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.
Best Answer
You need to swap the position of the
activate
line of code with theif not (exists document 1) then reopen
line of code.Example:
The screenshot of the Script Editor, below, was run with Safari open and without any windows opened.
First I had to check "[√] Show Develop menu in menu bar" (Safari > Preferences… > Advanced) and then on the Develop menu click "Allow JavaScript from Apple Events". Next I copied and pasted your AppleScript code in Script Editor and clicked the Run the Script button and it ran without error and returned the text of the http://example.com web page. However Safari was closed when I ran the script the first time.
After reading your question again, I was able to reproduce the error by having Safari open without any windows open. I then looked more throughly at your code and noticed
activate
was beforeif not (exists document 1) then reopen
andactivate
needs to be after it to avoid the error.