Passing variable using do Javascript

I’m begining to think, that this may not be possible:


tell application "Safari"
	activate
	delay 1
	--open URL in safari
	open location "http://www.mysite.com"
	delay 1
	--set link #1 from page to variable
	set MyLink to do JavaScript "document.links[1].href" in document 1
	delay 1
	--alert variable in javascript window
	do JavaScript "alert(" & MyLink & ");" in document 1
end tell

Any ideas?

Thank you!
:smiley:

Hi bladeMX,

You should post what you’re trying to do. What’s not possible?

gl,

oh, sorry!

Setting this variable:

set MyLink to do JavaScript "document.links[1].href" in document 1

Doesn’t seem to pass back into this:

do JavaScript "alert(" & MyLink & ");" in document 1

I’m fairly new to applescript, so any help is greatly appreciated.

Thank you!

Hi bladeMx,

Actually more info might have been better, because someone might know a lot about AppleScript and maybe a little javascript, but might have to review what ‘alert’ means. Mainly me! I ran this:

tell app “Safari”
activate
do JavaScript “alert(” & “hello” & “);” in document 1
end tell

and I get a dialog with javascript undefined and it looks like an error.

I don’t see anywhere in Safari javascript that you can run javascript. It seems that a function has to be embedded in a page. You could use AppleScript’s ‘display dialog’.

tell application “Safari”
activate
display dialog “hello” buttons {“OK”} default button “OK”
end tell

gl,

Oh wait. I think I found what is wrong. The text has to be quoted.

Yeah, this works:


tell application "Safari"
	activate
	do JavaScript "alert(\"" & "hello" & "\");" in document 1
end tell

gl,

Was that it?

Thanks kel!

Your code works with passing a string.

Here is the code for passing a variable:

tell application "Safari"
	activate
	delay 1
	--open URL in safari
	open location "http://www.mysite.com"
	delay 1
	--set link #1 from page to variable
	set MyLink to do JavaScript "document.links[3].href" in document 1
	delay 1
	--alert variable in javascript window
	do JavaScript "alert(\"" & MyLink & "\");" in document 1
end tell

If it’s of any interest, JavaScript also accepts single quotes, which saves having to escape double quotes. I don’t think they have any particular advantage apart from that.