How to find a specific tab while multiple Google Chrome windows are open in AppleScript

Viewed 372
to clickClassName(theClassName, elementnum)
    tell application "Google Chrome"
        set youtubeTab to (the first tab of window 2 whose URL contains "youtube")
    end tell
    tell application "Google Chrome"
        execute youtubeTab javascript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();"
    end tell
end clickClassName

clickClassName("ytp-play-button ytp-button", 0)

I have two windows open on my MacBook. One on the MacBook itself another one on the external display. I would like to play/pause YouTube videos playing on the external display while taking notes on my MacBook. Above script works only if the windows on the MacBook is activated because it is specifically pointing to the other window via window 2.

I think I need to find all windows and somehow use the repeat operator so that I can play/pause the video regardless of which window is activated. But I am not sure how to approach.

Any help is appreciated!

PS. I have added this script as a Service and assigned a specific key combination. So when I am taking notes on my MacBook I can quickly play/pause the video.

1 Answers

The following example AppleScript code will click the Play/Pause button on a YouTube video in any (every) tab of Google Chrome whose URL contains youtube:

tell application "Google Chrome"
    set YouTubeTabs to a reference to ¬
        (tabs of windows whose URL contains "youtube")
    repeat with aTab in YouTubeTabs
        tell aTab to ¬
            execute javascript ¬
                "document.getElementsByClassName('ytp-play-button ytp-button')[0].click();"
    end repeat
end tell

Assuming you only have one tab in Google Chrome that has a YouTube video to play/pause, this will certainly do it for you.

Related