********** SOLUÇÃO ATUALIZADA **********
Esta atualização é uma solução direta para a pergunta original do OP.
O código AppleScript a seguir adicionará um item de menu de status "Reproduzir / pausar YouTube" com as opções para reproduzir ou pausar qualquer vídeo do YouTube no Google Chrome ou Safari, independentemente de os navegadores serem visíveis ou não. Salve este código AppleScript a seguir como um aplicativo "fique aberto" no Script Editor.app.
use framework "Foundation"
use framework "AppKit"
use scripting additions
property StatusItem : missing value
property selectedMenu : ""
property defaults : class "NSUserDefaults"
property internalMenuItem : class "NSMenuItem"
property externalMenuItem : class "NSMenuItem"
property newMenu : class "NSMenu"
my makeStatusBar()
my makeMenus()
on makeStatusBar()
set bar to current application's NSStatusBar's systemStatusBar
set StatusItem to bar's statusItemWithLength:-1.0
-- set up the initial NSStatusBars title
StatusItem's setTitle:"Play/Pause YouTube"
-- set up the initial NSMenu of the statusbar
set newMenu to current application's NSMenu's alloc()'s initWithTitle:"Custom"
newMenu's setDelegate:me (*
Requied delegation for when the Status bar Menu is clicked the menu will use the delegates method (menuNeedsUpdate:(menu)) to run dynamically update.*)
StatusItem's setMenu:newMenu
end makeStatusBar
on makeMenus()
newMenu's removeAllItems() -- remove existing menu items
set someListInstances to {"Play/Pause YouTube - Safari", "Play/Pause YouTube - Chrome", "Quit"}
repeat with i from 1 to number of items in someListInstances
set this_item to item i of someListInstances
set thisMenuItem to (current application's NSMenuItem's alloc()'s initWithTitle:this_item action:("someAction" & (i as text) & ":") keyEquivalent:"")
(newMenu's addItem:thisMenuItem)
(thisMenuItem's setTarget:me) -- required for enabling the menu item
end repeat
end makeMenus
on someAction1:sender
clickClassName2("ytp-play-button ytp-button", 0)
end someAction1:
on someAction2:sender
clickClassName("ytp-play-button ytp-button", 0)
end someAction2:
on someAction3:sender
quit me
end someAction3:
to clickClassName2(theClassName, elementnum)
if application "Safari" is running then
try
tell application "Safari"
tell window 1 to set current tab to tab 1 whose URL contains "youtube"
do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
end tell
end try
end if
end clickClassName2
to clickClassName(theClassName, elementnum)
tell application "Google Chrome" to (tabs of window 1 whose URL contains "youtube")
set youtubeTabs to item 1 of the result
tell application "Google Chrome"
execute youtubeTabs javascript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();"
end tell
end clickClassName
Se você deseja que seu novo ... Reproduzir Pausar YouTube Status Menu.app seja visível apenas no menu de status e não no Dock, clique com o botão direito do mouse no aplicativo no Finder e selecione a opção "Mostrar conteúdo do pacote". Na pasta Conteúdo, abra o arquivo Info.plist em qualquer editor de texto e adicione as duas linhas a seguir. Em seguida, salve e feche esse arquivo.
<key>LSBackgroundOnly</key>
<true/>
Se você não estiver satisfeito com a edição direta do arquivo .plist, o código AppleScript a seguir permitirá que você escolha o aplicativo a ser oculto no Dock quando estiver em execução.
Se o aplicativo escolhido já estiver definido como oculto no Dock, a única opção que você terá é ocultar o aplicativo de ficar visível no Dock enquanto estiver em execução ... E vice-versa.
Esse script é especialmente útil para ocultar "aplicativos abertos", com os ícones de aplicativos dos manipuladores ociosos aparecendo no Dock durante a execução.
property fileTypes : {"com.apple.application-bundle"}
property plistFileItem : " <key>LSBackgroundOnly</key>" & linefeed & " <true/>"
activate
set chosenApp to (choose application with prompt ¬
"Choose The Application You Want Hidden From The Dock While It Is Running" as alias)
tell application "System Events" to set appName to name of chosenApp
set plistFile to ((POSIX path of chosenApp) & "/Contents/info.plist") as string
set plistFileContents to (read plistFile)
set plistFileItemExists to plistFileItem is in plistFileContents
if plistFileItemExists then
activate
set theChoice to button returned of (display dialog ¬
"Would you like to un-hide " & quote & appName & quote & ¬
" from the Dock while it's running?" buttons {"Cancel", "Un-Hide"} ¬
default button 2 cancel button 1 with title "Make A Choice")
else
activate
set theChoice to button returned of (display dialog ¬
"Would you like to hide " & quote & appName & quote & ¬
" from the Dock while it's running?" buttons {"Cancel", "Hide"} ¬
default button 2 cancel button 1 with title "Make A Choice")
end if
if theChoice is "Hide" then
tell application "System Events" to tell contents of property list file plistFile ¬
to make new property list item at end with properties ¬
{kind:string, name:"LSBackgroundOnly", value:true}
else if theChoice is "Un-Hide" then
tell application "System Events" to tell contents of property list file plistFile ¬
to make new property list item at end with properties ¬
{kind:string, name:"LSBackgroundOnly", value:false}
else
return
end if
************ SOLUÇÃO ORIGINAL ************
Este script clicará no botão Reproduzir / Pausar em um vídeo reproduzido no YouTube no Google Chrome, estando o Google Chrome visível ou não.
to clickClassName(theClassName, elementnum)
tell application "Google Chrome" to (tabs of window 1 whose URL contains "youtube")
set youtubeTabs to item 1 of the result
tell application "Google Chrome"
execute youtubeTabs javascript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();"
end tell
end clickClassName
clickClassName("ytp-play-button ytp-button", 0)
Esta é a versão do script para trabalhar com o Safari
to clickClassName2(theClassName, elementnum)
tell application "Safari"
tell window 1 to set current tab to tab 1 whose URL contains "youtube"
do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
end tell
end clickClassName2
clickClassName2("ytp-play-button ytp-button", 0)
Em um esforço para fornecer ao OP uma solução AppleScript completa, levei minha resposta original um passo adiante.
ATUALIZAR
Eu finalmente descobri. Eu criei um aplicativo AppleScript no Xcode. Originalmente, meu projeto começava apenas com uma janela de um botão para controlar os vídeos do YouTube atualmente ativos no Chrome ou Safari. Este projeto cresceu um pouco para um aplicativo que contém vários utilitários. Este GIF mostra o botão Pausa do YouTube que controla o YouTube no Chrome e Safari. Vinculei as ações do botão ao AppleScript que originalmente escrevi no editor de scripts.
Esta é uma captura instantânea do aplicativo Xcode Trabalhando no arquivo AppDelegate.applescript.
Aqui está o código nesse arquivo que eu criei para fazer o programa funcionar.
script AppDelegate
property parent : class "NSObject"
-- IBOutlets
property theWindow : missing value
to clickClassName(theClassName, elementnum) -- Handler for pausing YouTube in Chrome
if application "Google Chrome" is running then
try
tell application "Google Chrome" to (tabs of window 1 whose URL contains "youtube")
set youtubeTabs to item 1 of the result
tell application "Google Chrome"
execute youtubeTabs javascript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();"
end tell
end try
end if
end clickClassName
to clickClassName2(theClassName, elementnum) -- Handler for pausing YouTube in Safari
if application "Safari" is running then
try
tell application "Safari"
tell window 1 to set current tab to tab 1 whose URL contains "youtube"
do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
end tell
end try
end if
end clickClassName2
on doSomething:sender -- Calls the Chrome YouTube Handler
clickClassName("ytp-play-button ytp-button", 0)
end doSomething:
on doSomething14:sender -- Calls the Safari YouTube Handler
clickClassName2("ytp-play-button ytp-button", 0)
end doSomething14:
on doSomething2:sender -- Hide and or show the Menu Bar
tell application "System Preferences"
reveal pane id "com.apple.preference.general"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "General"
click checkbox "Automatically hide and show the menu bar"
end tell
delay 1
quit application "System Preferences"
end doSomething2:
on doSomething3:sender -- Sets Display resolution to the second lowest setting (15 inch Built In Retina Display - MBP)
tell application "System Preferences"
reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
click radio button "Scaled" of radio group 1 of tab group 1
click radio button 2 of radio group 1 of group 1 of tab group 1
end tell
quit application "System Preferences"
end doSomething3:
on doSomething4:sender -- Sets Display resolution to the second highest setting (15 inch Built In Retina Display - MBP)
tell application "System Preferences"
reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
click radio button "Scaled" of radio group 1 of tab group 1
click radio button 4 of radio group 1 of group 1 of tab group 1
end tell
quit application "System Preferences"
end doSomething4:
on doSomething5:sender -- Sets Display resolution to the highest setting (15 inch Built In Retina Display - MBP)
tell application "System Preferences"
reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
click radio button "Scaled" of radio group 1 of tab group 1
click radio button 5 of radio group 1 of group 1 of tab group 1
end tell
quit application "System Preferences"
end doSomething5:
on doSomething6:sender -- Sets Display resolution to the lowest setting (15 inch Built In Retina Display - MBP)
tell application "System Preferences"
reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
click radio button "Scaled" of radio group 1 of tab group 1
click radio button 1 of radio group 1 of group 1 of tab group 1
delay 0.1
click button "OK" of sheet 1
quit application "System Preferences"
end tell
end doSomething6:
on doSomething7:sender -- Displays a dialog with your current IP
tell current application to display dialog (do shell script "curl ifconfig.io") with icon 2 buttons "OK" default button 1 with title "Your Current IP Address Is.." giving up after 5
end doSomething7:
on doSomething8:sender -- Shows hidden files in Finder
do shell script "defaults write com.apple.finder AppleShowAllFiles TRUE\nkillall Finder"
end doSomething8:
on doSomething9:sender -- Hides hidden files in Finder if they are showing
do shell script "defaults write com.apple.finder AppleShowAllFiles FALSE\nkillall Finder"
end doSomething9:
on doSomething10:sender -- Brightness Highest
tell application "System Preferences"
reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
set value of value indicator 1 of slider 1 of group 2 of tab group 1 to 12
end tell
quit application "System Preferences"
end doSomething10:
on doSomething11:sender -- Brightness Lowest
tell application "System Preferences"
reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
set value of value indicator 1 of slider 1 of group 2 of tab group 1 to 0.1
end tell
quit application "System Preferences"
end doSomething11:
on doSomething12:sender -- Zoom
tell application "System Events"
key code 28 using {command down, option down}
end tell
end doSomething12:
on doSomething13:sender -- Dictation On/Off
tell application "System Events"
keystroke "x" using {option down}
end tell
end doSomething13:
on doSomething15:sender -- Enables Screensaver as Desktop background
tell application "System Events"
do shell script "/System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine -background"
end tell
end doSomething15:
on doSomething16:sender -- Kills Screensaver Desktop background
try
tell application id "com.apple.ScreenSaver.Engine" to quit
end try
end doSomething16:
on applicationWillFinishLaunching:aNotification
-- Insert code here to initialize your application before any files are opened
end applicationWillFinishLaunching:
on applicationShouldTerminate:sender
-- Insert code here to do any housekeeping before your application quits
return current application's NSTerminateNow
end applicationShouldTerminate:
on applicationShouldTerminateAfterLastWindowClosed:sender -- Quits app when clicking red x
return TRUE
end applicationShouldTerminateAfterLastWindowClosed:
end script
Atualizei o código para que a guia YouTube no Chrome não precise ser a guia visível ou ativa ao clicar no botão de pausa do YouTube criado no Xcode
Aqui está um link para baixar todo o projeto do Xcode
AVISO: A função de proteção de tela da área de trabalho congelará o aplicativo. Depois de sair e abrir novamente, a função de proteção de tela da área de trabalho para sair do protetor de tela ativo funcionará.
Pensamentos posteriores: eu provavelmente deveria ter incluído cada um dos códigos AppleScript nas instruções "try" para evitar todo tipo de mensagem de erro para quem está jogando com este projeto, que não possui o mesmo sistema e tipo de computador que eu. (MacBook Pro 15 "OS Sierra 10.12.6)
Para a função de zoom Para funcionar, ela deve estar ativada nas preferências do sistema.
Para que a alternância de “Ditado ativado / desativado” funcione corretamente, o atalho para ativar os comandos de ditado nas preferências do sistema deve corresponder ao atalho usado no script
on doSomething13:sender -- Dictation On/Off
tell application "System Events"
keystroke "x" using {option down}
end tell
end doSomething13:
Atualmente, estou trabalhando na capacidade de alternar entre o aplicativo em execução somente na janela ou na barra de menus