Creating a keyboard shortcut to pause Youtube video in a Google Chrome tab

automatorgoogle-chromekeyboardyoutube

Here is what I want to do: hook up a keyboard shortcut with an action to play/pause the video that is currently open in a Google Chrome tab. Would it be possible on Mac OS X?

I was thinking about keeping Youtube always in a particular tab (e.g. the first one) and creating Automator script with a keyboard shortcut. I know it would be possible by simulating user actions (switch to particular tab, simulate click, go back to last tab) but I'm looking for more smooth way.

Best Answer

You could assign a shortcut to a script like this:

tell application "Google Chrome"
    repeat with t in tabs of windows
        tell t
            if URL starts with "http://www.youtube.com" then
                execute javascript "player = document.querySelectorAll('#watch7-player embed')[0]
if (player) {
    player.getPlayerState() == 1 ? player.pauseVideo() : player.playVideo()
} else { // if youtube.com/html5 is enabled
    document.querySelectorAll('.html5-player-chrome > button:first-child')[0].click()
}"
                exit repeat
            end if
        end tell
    end repeat
end tell

For Safari, replace execute javascript with do JavaScript.