AppleScript – Executing JavaScript in Safari and Chrome

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

Google

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:

  1. AppleScript.app autocorrects the second example to a lowercase JavaScript, but either should work.
  2. Safari requires that a document is specified
  3. If you’re using Firefox, it’s currently not possible to execute JavaScript with AppleScript

4 thoughts on “AppleScript – Executing JavaScript in Safari and Chrome

    1. Kevin Post author

      Thanks, you’re right. The if statement needs to be on one line or include an end if. I updated the code example.

      Reply
  1. John

    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!

    Reply

Leave a Reply to John Cancel reply

Your email address will not be published. Required fields are marked *