Getting selected text from Safari documents

Text selected in a Safari document can be returned to a script by using the do JavaScript command to run a function called “window.getSelection()”. (I think it’s a Mozilla function that’s also supported by Safari.) The function apparently returns a “selection object”, so a little more JavaScript is needed to extract the text from it. The method that works in Safari is to concatenate the function result to an empty string (or an empty string to it). The result returned to AppleScript is Unicode text.

tell application "Safari"
	set selectedText to (do JavaScript "''+window.getSelection();" in front document) -- (Two single quotes before the plus sign.)
	-- or:
	set selectedText to (do JavaScript "window.getSelection()+'';" in front document)
	-- or:
	set selectedText to (do JavaScript "\"\"+window.getSelection();" in front document)
	-- or:
	set selectedText to (do JavaScript "window.getSelection()+\"\";" in front document)
end tell