3

Safari and Chrome can execute JavaScript via AppleScript

Safari:

 tell application "Safari"
    open location "http://example.com"
    activate
    do JavaScript "alert('example');" in current tab of first window
end tell

Chrome:

tell application "Google Chrome"
    open location "http://example.com"
    activate
    execute front window's active tab javascript "alert('example');"
end tell

Is there a way to do this in Firefox?

Note: Same question for Opera is here: AppleScript - JavaScript execution on Opera

I thought about asking them together, but I decided to ask two separate questions to be able to accept answers separately.

2 Answers 2

4

I have found a way to execute arbitrary javascript code on the current tab using the following AppleScript:

tell application "Firefox"
    activate
    set the clipboard to "(function(){alert(document.title)})();"

    tell application "System Events"
        keystroke "k" using {command down, option down} -- open console     
        delay 2
        keystroke "v" using {command down}
        keystroke return
        delay 1
        keystroke "i" using {command down, option down} -- close dev tools
        
    end tell
end tell

The above script shows the title of the current web page.

To execute your own code you just need to replace the javascript snippet between the curly braces:

alert(document.title)

with your own.

Sign up to request clarification or add additional context in comments.

Comments

2

Running javascript using AppleScript in Firefox has not been implemented. Bug Story.
It is in New state and with no assignees. You could take that up :)

1 Comment

OMG. "Assigned To: Nobody; OK to take it and work on it." I don't think I will go that far.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.