Connection is invalid error when running Applescript and Safari

Solution 1:

You need to swap the position of the activate line of code with the if not (exists document 1) then reopen line of code.

Example:

tell application "Safari"
    if not (exists document 1) then reopen
    activate
    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 screenshot of the Script Editor, below, was run with Safari open and without any windows opened.

Script Editor window

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 before if not (exists document 1) then reopen and activate needs to be after it to avoid the error.