Run Real JavaScript on a certain webpage

So I'd like to run this JS code in Chrome when I press the '-' key:

(async () => {
stores.toggleAudio()
returnToBTT('foo');
})();

This code works when I run it in Chrome's console, but nothing happens when I press '-' in Chrome. How to debug this?

The real java script action does not have anything to do with Chrome (this runs completely in BTT) :slight_smile:

For running Java Script in Chrome, you need to use Apple Script, have a look here:
google chrome - Can AppleScript access browser tabs and execute javascript in them? - Stack Overflow

Thanks! Was a bit confused.

This is important:

Note: As of August 2018, you may need to navigate to ViewDeveloperAllow JavaScript from Apple Events for execute javascript to work

2 Likes

I had a similar challenge getting a BTT trigger to click a certain button via JavaScript in Chrome.
Here's the target button I wanted to click without reaching for my mouse:

<button aria-label="Go back" class="_afxv _al46 _al47" tabindex="-1"><div class=" _9zm2"></div></button>

This is the Apple Script & JavaScript I used:

tell application "Google Chrome"
    set activeTabIndex to active tab index of window 1
    set theTab to tab activeTabIndex of window 1
    execute theTab javascript "
    var button = document.querySelector('button[aria-label=\"Go back\"]._afxv._al46._al47');
    if (button) {
        button.click();
    } else {
        console.log('Button not found');
    }
    "
end tell

I tried executing this script in BTT several ways without success. I confirmed that the JavaScript was correct by executing the JS in Chrome's console.
(Echoing @Andreas_Hegenberg, make sure you've selected ViewDeveloperAllow JavaScript from Apple Events in Chrome.)

What finally worked was saving the Apple Script to a .scpt file, then having BTT "Execute Terminal Command (Async/non-blocking)", and providing BTT this terminal command:

osascript ~/myScripts/click_back_button.scpt 

If you don't want to save it as a file, you can format the Terminal command using a heredoc with EOF syntax like so :

osascript <<EOF
tell application "Google Chrome"
    set activeTabIndex to active tab index of window 1
    set theTab to tab activeTabIndex of window 1
    execute theTab javascript "
    var button = document.querySelector('button[aria-label=\"Go back\"]._afxv._al46._al47');
    if (button) {
        button.click();
    } else {
        console.log('Button not found');
    }
    "
end tell
EOF

Hope this helps someone out there save time and/or reduce mouse usage!