I’m trying to automate some repetitive tasks I need to do. This seems like a simple question but has stumped me for days.
I have Safari open with just one window and the page has a button I would like my script to press. I first tested using the element inspector and entered my code in the console too click the button and it worked.
var button1 = document.getElementById(‘msku-custom-option-link’)
< undefined
button1.click()
< undefined
I’m now trying to do the same button click from a script file and I do not get the button click action. My script code is as follows
tell application “Safari”
delay 3
do JavaScript “document.getElementById(‘msku-custom-option-link’).click() ;” in document 1
do JavaScript “document.getElementById(‘msku-custom-option-link’).click();”
to clickID(theId) --creates a function that we can use over and over again instead of writing this code over and over again
tell application "Safari" -- lets AppleScript know what program to controll
do JavaScript "document.getElementById('" & theId & "').click();" in document 1 -- performs JavaScript code that clicks on the element of a specific id
end tell -- tells Applescript you are done talking to Safari
end clickID -- lets AppleScript know we are done with the function
I tried following the suggestion copying the code and modifying for my particular button
The script is
to clickID(theId) --creates a function that we can use over and over again instead of writing this code over and over again
tell application "Safari" -- lets AppleScript know what program to controll
display dialog "Start"
display dialog theId
do JavaScript "document.getElementById('" & theId & "').click();" in document 1 -- performs JavaScript code that clicks on the element of a specific id
display dialog "End"
end tell -- tells Applescript you are done talking to Safari
end clickID -- lets AppleScript know we are done with the function
on run
I get the display dialog messages but no button click

Adding the activate did not help. I did inspect the output of the Inspect Element and see that the button is part of an iframe. I’m thinking my reference to the button is not proper.
I’ve included a screen shot of the Inspect Element output. The button I wish to programatically click is within the iframe.
I use a bunch of do JavaScript scripts in Safari.
I don’t see any issues with what you showed. Nevertheless, I would suggest you do something in your script.
I normally write the JavaScript script separately and then send it to Safari, but this should not be an issue, just a matter of style. However, I always check that I got what I want before executing the command, something you did outside the AppleScript.
set jscrpt to “var bttn= document.getElementById(‘msku-custom-option-link’).;console.log(bttn); bttn.click();” tellapplication “Safari” totelldocument 1 todo JavaScript jscrpt
You can check in console window whether or not you are getting what you want.