The following applescript waits for a page to load before continuing with the do javascript "document.body.innerText"
part of the script. It seems to work really well except for one thing. If Safari is running but no window is currently open, running this script results in
error "Safari got an error: Connection is invalid." number -609
Yet if I run this when Safari is closed it launches Safari, goes to the specified URL and once the page loads, runs the javascript portion. I don't understand why it gets an error if Safari is running with no windows open.
tell application "Safari"
activate
if not (exists document 1) then reopen
tell front document
set URL to "http://example.com"
repeat until length of (source as text) is not 0
delay 0.5
end repeat
do javascript "document.body.innerText"
end tell
end tell
The error always highlights the source as text
part of the script. I tried changing length of (source as text) is not 0
to repeat until name is "example domain"
but the error still occurs if no windows are open and Safari is running.