MacOS – Applescript error: “Connection is invalid” when app quits

applescriptmacos

I'm working on some code to check on the currently open tabs/windows in my installed web browsers, like so:

on checkbrowser()

    if application "Safari" is running then
        tell application "Safari"
            set windowList to (every window)
            # do some stuff
        end tell
    end if

end checkbrowser


repeat while 1 = 1
    checkbrowser()
end repeat

This works perfectly as long as Safari stays open. If Safari is ever closed while the script is running, I get this message:

error "Safari got an error: Connection is invalid." number -609

The problem is something to do with (every window). If Safari quits, shouldn't the if statement prevent the script from even going to that line of the code? But that is where it throws the error.

Any ideas? Thanks!


Edit: Found the solution here.

Best Answer

The key was to put the problematic code inside a try block. Like this:

    if application "Safari" is running then
        tell application "Safari"
            try
                set windowList to (every window)
                # do some stuff
            on error number -609
            end try
        end tell
    end if

This way, the script ignores the error -609 and just moves along, which is what I wanted.