Trigger Javascript function on webpage through Safari via Applescript

I am looking to trigger some Javascript through the “do JavaScript” command for Safari. The code is normally triggered via an onclick=“” in an html tag.

<a id='user38002' class='user' onclick="CSF.Login.select_user('greg zim');">
     <img class='default_icon' src='login_user_icon.png' alt='user icon'/>
     <span class='user_name'>gzim</span>

I would like to trigger the same function with something like

on doJavaScript()
	tell application "Safari"
		tell window 1
			do JavaScript "CSF.Login.select_user('greg zim');"
		end tell
	end tell
end doJavaScript

However that does not seem to work. Am I doing something obviously wrong?

Thanks in advance!

Browser: Safari 5.0.6 (5533.22.3)
Operating System: Mac OS X (10.6)

Try front document instead of window 1.

That worked. Thank you very much. Little things like that seem to trip me up often how can I learn the difference of something like that? Any Ideas?

With document-based applications such as Safari, a lot of the commands are for each document. Each window in Safari is actually a document, not just a window. The URL and web content of each window aren’t contained by the window, they are contained by the document. The document is contained by the window.

So to get the URL of a window, this will not work

tell application "Safari"
	set p to URL of front window
end tell

because the window doesn’t contain a URL. It contains a document.

This will work

tell application "Safari"
	set p to URL of front document
end tell

because the front document (in the front window) does contain a URL.

So basically, you have to treat Safari as a document-based application. Because it is. Just like you can’t tell TextEdit or Microsoft Word or Pages to get the text of the front window, you can’t expect to get anything from Safari’s front window either.

Look in the scripting dictionary for Safari. Reading the dictionary really helps. This is directly from the dictionary:

do JavaScriptv : Applies a string of JavaScript code to a document.

So in order for this to work, it has to be executed on a document.

Also, please note that each tab of a window contains a separate document. This is how to get the URL of a tab:

tell application "Safari"
	tell window 1
		tell tab 2
			set p to URL of it
		end tell
	end tell
end tell

I hope this answered your question. If you have more, just ask! :slight_smile:

I am at work and got a little busy so I can’t not look at this right now but thanks so much, I am guessing it will be helpful. Thank you for your time! God bless you sincerely in the name of The Lord Jesus! Thanks a ton!