I haven’t used AppleScript much, but I was recently working on a script to automate a workflow and I was surprised to discover that each browser uses different commands to execute JavaScript.
Specifically, Safari uses do JavaScript "add code here" in document X
and Chrome requires execute javascript "add code here"
Here’s an example of each:
Safari
tell application "Safari"
open location "https://google.com"
if (do JavaScript "document.readyState" in document 1) is "complete" then set pageLoaded to true
display dialog pageLoaded as string
end tell
tell application "Google Chrome"
open location "https://google.com"
if (execute javascript "document.readyState") is "complete" then set pageLoaded to true
display dialog pageLoaded as string
end tell
A couple notes:
- AppleScript.app autocorrects the second example to a lowercase JavaScript, but either should work.
- Safari requires that a document is specified
- If you’re using Firefox, it’s currently not possible to execute JavaScript with AppleScript
I needed and end if after set pageLoaded to true to get it to work.
Thanks, you’re right. The
if
statement needs to be on one line or include anend if
. I updated the code example.Thanks Kevin, but you’re doing it wrong. You can, and should, specify the tab to use in both browsers! And the way to get the “active tab of active window” differs between browsers. I’ll contribute both methods here for your readers.
—-
In AppleScript there is a handy feature called “Open Dictionary” and this is what Chrome says:
execute v : Execute a piece of javascript.
execute specifier : The tab to execute the command in.
javascript text : The javascript code to execute.
→ any
So the format is as follows :
tell application “Google Chrome”
execute active tab of front window javascript “alert(‘Hello World’)”
end tell
That will tell the current tab in the frontmost window to run the code.
——
The equivalent for Safari is:
do JavaScript v : Applies a string of JavaScript code to a document.
do JavaScript text : The JavaScript code to evaluate.
[in tab] : The tab that the JavaScript should be evaluated in.
→ any
tell application “Safari”
do JavaScript “alert(‘Hello World’)” in front document
end tell
Where “front document” means the active tab in the frontmost window.
—–
There you have it! A way to ensure your code runs in the correct tab!
John, thanks for the tip! I’ll try updating my local scripts.