Applescript freezes upon first run when getting 'text of document 1 of application "Safari" '
I'm working on an applescript that searches the text of a Safari web page for specific text. The script freezes / hangs / times out ONLY during the "first run". By "first run" I mean the first time the script is run after a period of time has passed. If the script is run a 2nd, 3rd, or 4th time, etc soon thereafter it works perfectly. If you then wait an extended period of time again, the script freezes exactly as if it were a "first run". This appears to be independent of whether Safari is open or closed, i.e. the script freezes even if Safari remains open between the last working run and the "first run".
Details:
A web page is opened. I subsequently confirm the page is fully loaded with the following code set-up as a handler:
tell application "Safari"
repeat with i from 1 to 15
if (do JavaScript "document.readyState" in current tab of window 1) is "complete" then
exit repeat -- page loading is complete, exiting loop
else
delay 1
end if
end repeat
if i is greater than or equal to 15 then return false
if i is less than 15 then return true
end tell
The Applescript event log confirms loading is complete and returns a value of true. I can see the page is fully loaded, and in testing it is fully functional. All is good.
I then search the text of the fully loaded web page for specific text. It is this next step where Applescript hangs, but ONLY on the "first run":
set searchTerm to "find this"
if text of document 1 of application "Safari" contains (searchTerm as string) then
-- do stuff
end if
The event log shows that applescript starts to "get every text of document 1" and even returns the initial text of the web page but hangs. Applescrpt returns the following error: "Safari got an error: AppleEvent timed out. Error -1712". If I rerun the script at this point the full text of the web page is immediately displayed in the event log, and the script continues succesfully to the end. The "IF" statement is not the issue per se because I get the same error if I remove the IF and instead set a variable to the value of 'text of document 1 of application "Safari".
Bottom line - Applescript seems to hang while returning the text of the fully loaded web page, but ONLY on "first run". Any ideas?
Note: I've run this directly as an applescript and as a service via Automator. Same result. I also tried putting the computer to sleep briefly, wake and rerunning the script. This does not repeoduce the problem so while extended gaps in use cuases the problem, it does not appear that going to sleep during this time is sufficient to cause the issue.
Mac OS X (10.7.5)