Launching JavaScript using Applescript

Hi folks.

Looking for a way to launch a JavaScript .js file on a targeted web page I have loaded in Safari. This is what I have now, which runs, but doesn’t do anything:

tell application "Safari"
	set doc to document 1
	set ScriptFile to "Flash:Users:rich:RF:RF_scripts:JS:LL_reference.js" as alias
	do JavaScript ScriptFile in doc
end tell

Anybody know how I can target a web page with JS?



As you’ll see from Safari’s scripting dictionary, ‘do JavaScript’ takes a text argument, so you’ll need to read the file to get the text:

set scriptFile to "Flash:Users:rich:RF:RF_scripts:JS:LL_reference.js" as alias
-- Or if "rich" is your Home folder:
-- set scriptFile to ((path to home folder as text) & "RF:RF_scripts:JS:LL_reference.js") as alias
set JSCode to (read scriptFile from 1 as «class utf8»)

tell application "Safari"
	do JavaScript JSCode in document 1
end tell

What the dictionary doesn’t make clear is that ‘do JavaScript’ is disabled by default and has to be enabled with the “Allow JavaScript from Apple Events” item in Safari’s “Develop” menu. The menu in turn has to be enabled by checking the “Show Develop menu in menu bar” check box in the “Advanced” pane of Safari’s preferences. Once you’ve ticked the menu item, you can disabled the menu again (if you want to) and the setting will still hold.

Hi there,
As your question ends with “Anybody know how I can target a web page with JS?” - I’ll assume you need a bit of help getting started, then we can move to executing the file

When you run JavaScript through Applescript with a ‘do Javascript’ statement, if there is any runtime error, it will return null,and applescript doesn’t handle the error, so the return from the statement is literally nothing.

I also tend to prefer directing the script to a specific tab in safari so it doesn’t mess up if you don’t have the tab open (Maybe I’m the only crazy one that gets frustrated when he can’t work out why his script doesn’t work, only to realise that you had the wrong tab open)

you can catch the error and return it to applescript

tell application "Safari"

set theScriptResult to do javascript "

try {//enter run time code

thisvar = 12
thisvar = thisvar * 82
} catch(err) {//enter Error Handle
thisvar = err

" in tab 1 of window 1 

theScriptResult -- should return 984
end tell

In this case there’s no chance for error, but you can just replace the section that multiplies the number, with your script and you should be on your way.