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:
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 View → Developer → Allow 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!