Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppleScript - JavaScript execution on Firefox

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.

like image 551
erkanyildiz Avatar asked Mar 31 '26 06:03

erkanyildiz


2 Answers

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.

like image 85
Johnsidi Avatar answered Apr 02 '26 19:04

Johnsidi


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 :)

like image 29
sv_in Avatar answered Apr 02 '26 19:04

sv_in