Tengo un Servicio de sistema personalizado en mi Mac, titulado Búsqueda de Google , que coloca el texto seleccionado dentro de una URL definida y luego abre la URL en una nueva pestaña (adyacente a la pestaña actual) en Google Chrome.
Mi Servicio recibe seleccionado text
en any application
. El Servicio se activa exclusivamente a través del menú contextual del botón derecho del ratón para el texto seleccionado, en todo el sistema y en todas las aplicaciones. No se trata de una aplicación de terceros ni de un atajo de teclado.
De forma predeterminada, cada vez que se hace clic en un enlace que abre una nueva pestaña en Chrome mientras se mantiene presionado ⌘ command, la pestaña actual en Chrome no cambia. La nueva pestaña se abre a la derecha e inmediatamente adyacente a la pestaña actual, pero la nueva pestaña no se convierte en la pestaña activa.
Me gustaría que la ⌘ command clave tuviera el mismo efecto cuando ejecuto mi Servicio. De modo que:
if <the command key is being pressed when the Service is triggered> then
Open URL in a new, adjacent tab.
(Do not change the active tab.)
else
Open URL in a new, adjacent tab.
Change the active tab to the new tab.
Mi servicio consta de una acción "Ejecutar AppleScript". Aquí está el código completo:
on run {input, parameters}
(*
When triggering this Service in applications other than Google Chrome, such as TextEdit, the Chrome window opens in the background. This command brings the Chrome window to the foreground:
*)
activate application "Google Chrome"
(*
Converting the selected text to plain text to remove any formatting:
From: http://lifehacker.com/127683/clear-text-formatting-on-os-x
*)
set selectedText to input
set selectedText to (selectedText as text)
(*
Removing any line breaks and indentations in the selected text:
From: http://stackoverflow.com/a/12546965
*)
set AppleScript's text item delimiters to {return & linefeed, return, linefeed, character id 8233, character id 8232}
set plainTextSelectedText to text items of (selectedText as text)
set AppleScript's text item delimiters to {" "}
set plainTextSelectedText to plainTextSelectedText as text
(* Assigning variables: *)
set baseURL to "https://www.google.com/search?q="
set finalLink to baseURL & plainTextSelectedText
(* Opening webpage in Chrome: *)
(*
The following tell block creates a new tab, located immediately after the currently open tab, which is what I want to occur.
From: http://apple.stackexchange.com/questions/271702/applescript-how-to-open-a-link-in-google-chrome-in-a-new-adjacent-tab/271709#271709
*)
tell application "Google Chrome"
activate
tell front window to make new tab at after (get active tab) with properties {URL:finalLink} -- open a new tab after the current tab
end tell
end run
Mi queja con el código anterior es que establece la pestaña actual en la nueva pestaña, incluso si ⌘ commandse mantiene presionada cuando se inicia el Servicio.
¿Es posible que la pestaña actual no se cambie a la nueva pestaña si y solo si el usuario mantiene presionado ⌘ commandcuando se ejecuta el Servicio?
Solo espero que la ⌘ commandfuncionalidad clave funcione cuando se hace clic en el menú contextual del botón derecho en Chrome.app. Por ejemplo, si este Servicio se activa desde Preview.app, aunque sería bueno tener a mi disposición la capacidad de usar la ⌘ commandtecla para no cambiar la pestaña activa de la ventana de Chrome, entiendo que esto probablemente esté solicitando demasiado.
Entiendo que AppleScript no tiene ningún mecanismo para verificar si se presiona una tecla en medio del guión. Sin embargo, me pregunto si hay un método alternativo para crear una nueva pestaña en AppleScript que haga que Chrome escuche todo para que Chrome pueda responder ⌘ commandcomo lo hace de forma natural.
Creo que esto hará lo que estás pidiendo. Modifiqué su código original para ver qué proceso está al frente en el momento en que se ejecuta , para bifurcarlo y probarlo adecuadamente según las condiciones expresadas en su pregunta mediante el uso de checkModifierKeys
*. para ver si ⌘ commandse presionó la tecla cuando Google Chrome es el proceso principal en el momento en que se ejecuta el servicio . * (No tengo afiliación con el blog de Charles Poynton o checkModifierKeys de Stefan Klieme, aparte de haber estado usando este programa durante algunos años sin problemas).
Tal como está codificado, asume que checkModifierKeys
está ubicado en /usr/local/bin/
. Modifique según sea necesario.
Ver los comentarios en el if theFrontmostProcessWhenRun is "Google Chrome" then
bloque para su flujo lógico .
on run {input, parameters}
-- # Get the name of frontmost process at the time the services was run.
-- #
-- # This is used later in an if statement block for when if Google Chrome was frontmost process when run
-- # to check that the value returned from checkModifierKeys was for the command key being pressed.
tell application "System Events"
set theFrontmostProcessWhenRun to get name of process 1 where frontmost is true
end tell
(*
When triggering this Service in applications other than Google Chrome, such as TextEdit, the Chrome window opens in the background. This command brings the Chrome window to the foreground:
*)
activate application "Google Chrome"
(*
Converting the selected text to plain text to remove any formatting:
From: http://lifehacker.com/127683/clear-text-formatting-on-os-x
*)
set selectedText to input
set selectedText to (selectedText as text)
(*
Removing any line breaks and indentations in the selected text:
From: http://stackoverflow.com/a/12546965
*)
set AppleScript's text item delimiters to {return & linefeed, return, linefeed, character id 8233, character id 8232}
set plainTextSelectedText to text items of (selectedText as text)
set AppleScript's text item delimiters to {" "}
set plainTextSelectedText to plainTextSelectedText as text
(* Assigning variables: *)
set baseURL to "https://www.google.com/search?q="
set finalLink to baseURL & plainTextSelectedText
(* Opening webpage in Chrome: *)
(*
The following tell block creates a new tab, located immediately after the currently open tab, which is what I want to occur.
From: http://apple.stackexchange.com/questions/271702/applescript-how-to-open-a-link-in-google-chrome-in-a-new-adjacent-tab/271709#271709
*)
if theFrontmostProcessWhenRun is "Google Chrome" then
-- # Google Chrome was the frontmost process when the service was run.
if ((do shell script "/usr/local/bin/checkModifierKeys") as integer) is equal to 256 then
-- # The command key was pressed when the service was run.
tell application "Google Chrome"
-- # See Note: below.
set activeTab to active tab index of front window
tell front window to make new tab at after (get active tab) with properties {URL:finalLink} -- open a new tab after the current tab
set active tab index of front window to activeTab
end tell
else
tell application "Google Chrome"
tell front window to make new tab at after (get active tab) with properties {URL:finalLink} -- open a new tab after the current tab
end tell
end if
else
-- # Google Chrome was not the frontmost process when the service was run.
tell application "Google Chrome"
tell front window to make new tab at after (get active tab) with properties {URL:finalLink} -- open a new tab after the current tab
end tell
end if
end run
Nota: cuando Google Chrome está al frente en el momento en que se ejecuta el servicio y se presiona la tecla, obtiene el actual y lo vuelve a configurar después de crear la nueva pestaña . Esto pretende ser una solución alternativa, ya que es un poco confuso, pero mejor que nada hasta que se pueda encontrar una solución más elegante a un problema.⌘ commandactive tab index
checkModifierKeys
tu solución; tiene que ver con cómo AppleScript abre una pestaña de fondo en Chrome. ¿Hay otro método para abrir una pestaña de Chrome en segundo plano en AppleScript? Esa pregunta probablemente merece su propia publicación separada...active tab index
para restablecerlo después de que el foco se haya configurado en la nueva pestaña desde su creación.checkModifierKeys
.)
esfera de rubik