I need to make an AppleScript that opens a specific URL and acts as a “fake” anchor link of sorts. During my research I’m often linking to URLs but I also want specific areas of an URL’s web page to show up in Safari and preferably some specific text highlighted as well.
This jumbled mess of a script I’ve put together accounts for the webpage to load up first and works fine, but the only way I got it to work properly every time is with some delays added and other mess I commented within the code below.
set theURL to "https://en.wikipedia.org/wiki/The_Rolling_Stones"
set theTEXT to "Mick and I thought these songs were really puerile"
tell application "Safari" to activate
open location theURL
tell application "Safari"
activate
delay 1
repeat
if (do JavaScript "document.readyState" in document 1) is "complete" then exit repeat
delay 1 -- wait a second before checking again
end repeat
delay 1
end tell
tell application "System Events"
tell process "Safari" to keystroke "f" using command down
-- If I don't hit delete key twice and find dialog previously open it fails on some websites
keystroke (ASCII character 127)
keystroke (ASCII character 127)
keystroke theTEXT
-- If I don't hit enter key often jumbles first letters of theTEXT if find dialog previously open
key code 36
-- to close the Find dialog and leave blue highighted text I'd like to to use this following keystroke
-- keystroke "." using command down
-- unfortunately this makes the highlighted text unhighlight entirely on some longer websites
end tell
-- But if I put it down here like this it works :/
tell application "System Events"
tell process "Safari" to keystroke "." using command down
end tell
Please show me a better, faster way that’s reliable. This DOES work and it IS reliable on various websites after all my silly tweaks, but it’s slow and I’m sure my script code looks ridiculous.
Model: MacBook Pro
AppleScript: 2.9
Browser: Safari 10.0.1
Operating System: Mac OS X (10.10)