getSelection() confusion in AS for Safari

Hi all,

I’m trying to programmatically get the selected text in Safari’s frontmost page.

This site http://www.quirksmode.org/js/selected.html# has a working Javascript (select something and click his “Get Selection” button).

Now, for my code. If I code:


tell application "Safari"
	do JavaScript "alert(window.getSelection());" in front document
end tell

I get a nice alert box in Safari with the correct text displayed. However, I just want the text, not the alert.

So I code


tell application "Safari"
	do JavaScript "window.getSelection();" in front document
end tell

Or many variants thereof, I always get the null string back.

I have tried everything I can think of. Does anyone know why these two code blocks give different results? Is there some sort of “convert selection object to string” that I am missing here, since window.getSelection() presumably returns a selection object.

Many thanks if anyone has any suggestions to try.

Hi, johnny.

I don’t know much about JavaScript, but this works for me:

tell application "Safari"
	set selectedText to (do JavaScript "\"\"+window.getSelection();" in front window)
end tell

I suspect that the selection function returns an array, which I believe I’ve concatenated to an empty string (as can be done in AppleScript). If no JavaScript experts come up with anything better, this should at least get you functioning…

Thanks so much!! Works perfectly. I would never have thought of that.

Cheers,
johnny