MacOS – Keyboard shortcut for AppleScript works only when preferences window is open

applescriptautomatormacos

I created this AppleScript to play/pause Youtube videos running on Chrome:

on run {input, parameters}

    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('ytp-play-button ytp-button')[0].click();"
    end tell

    return input
end run

It works fine when I run it from Automator. I saved the service and added a keyboard shortcut +J for running the service. I also added Automator to the Accessibility settings (following this SO answer).

Now here's the strange part: it works when I have the System Preferences window on focus. If I close it, or switch to any other window, the shortcut doesn't work. I noticed that it's working because there's a menu item in System Preferences window that corresponds to the shortcut, and that is getting triggered when I press the shortcut.

Please help. Thanks in advance.

Best Answer

As I mentioned in my comment to wch1zpink's answer "Making sure the Service's settings are correct and the shortcut key sequence is not in use by another is the first step" and mentioned afterwards by jackjr300 in his comment. Changing the keyboard shortcut to one that is not used by anything else in the system or any application (that is if 'Services receives no input in any application' is set), works for me, whether or not System Preferences is open, when using the code, as is, in the OP and a non-conflicting key sequence.

There also is no need to have any applications set in System Preferences > Security & Privacy > Privacy > Accessibility for this particular use case, whether running from Automator or when using a non-conflicting keyboard shortcut in System Preferences > Keyboard > Shortcuts > Services > (Name You Gave The Service).

To resolve your issue, you must use a keyboard shortcut that is not already assigned elsewhere in the system and or any applications.

You might have to use a three or four key sequence as there are very few, if any, two key combos that aren't already in use.


On a side note, return input is not at all needed in the code in this particular use case.