Did you set up Safari to execute "do javascript" AppleScript command?
tell application "Safari"
make new document with properties {URL:"http://piyocast.com/as"}
end tell
If this script works, AppleScript itself works with Safari.
tell application "Safari"
set aRes to do JavaScript "var selObj = window.getSelection();
var selStr = (selObj).getRangeAt(0);
unescape(selStr);" in front document
end tell
display dialog aRes
If this script does not work, you have to allow Safari to execute "do JavaScript" command.
Safari v10 or later exhibit to execute "do JavaScript" command by default.
You have to enable "Develop" menu from Safari's preferences setting.
And....execute "Allow JavaScript from Apple Events" command from Safari'sDevelop menu (this operation require admin password).