My Applescript has been encountering this error (sporadically) in Safari.
Result:
error "Safari got an error: Can’t get document \"DOC TITLE\"."
number -1728 from document "DOC TITLE"
I assumed this was because the page wasn't loaded, but I have a Javascript to check "complete" before continuing, as well as a try statement to delay another second on error.
Nevertheless, I'm still encountering this issue. It seems to be fairly random.
Any suggestions?
Applescript (entire Tell statement):
tell application "Safari"
set the URL of the front document to searchURL
delay 1
repeat
if (do JavaScript "document.readyState" in document 1) is "complete" then exit repeat
delay 1.5 -- wait a second before checking again
end repeat
try
set doc to document "DOC TITLE"
on error
delay 1
set doc to document "DOC TITLE"
end try
set theSource to source of doc
set t to theSource
end tell
There is room for flaws in your code. First you check readyState, how do you know you're checking the readyState of the right document? It could be the previously document. Delay 1 will significantly shorten the chance, but still it isn't secure. My first recommendation would be checking the readyState after checking page title.
Then when checking page title first creates also room for error, there is a chance that we're matching the page title of the previous page (if that was the same page, or has at least the same title). To make sure we're waiting for the correct page by it's title it's the most easiest way to set the page first to "about:blank".
Another thing, as you can see, what I've done is that every stage no longer waits than 20 seconds for a page to be loaded. Here is a more controlled way to load the page:
tell application "Safari"
-- first set the page to "about:blank"
set the URL of the front document to "about:blank"
set attempts to 1
repeat until "about:blank" is (name of front document)
set attempts to attempts + 1
if attempts > 20 then -- creating a timeout of 20 seconds
error "Timeout while waiting for blank page" number -128
end if
delay 1
end repeat
-- now we start from a blank page and open the right url and wait until page is loaded
set the URL of the front document to searchURL
set attempts to 1
repeat until "DOC TITLE" is (name of front document)
set attempts to attempts + 1
if attempts > 20 then -- creating a timeout of 20 seconds
error "Timeout while waiting for page" number -128
end if
delay 1
end repeat
-- now check the readystate of the document
set attempts to 1
repeat until (do JavaScript "document.readyState" in document 1) is "complete"
set attempts to attempts + 1
if attempts > 20 then -- creating a timeout of 20 seconds
error "Timeout while waiting for page" number -128
end if
delay 1
end repeat
-- page should be loaded completely now
set doc to document "DOC TITLE"
set theSource to source of doc
set t to theSource
end tell