stackQA stackQA - 1 month ago 5x
Javascript Question

Applescript waiting for a page to load

I have tried various solutions to poll for elementID before continuing on with the applescript execution. I prefer to poll rather than to have a arbitrary delay.

set pageNotLoaded to true
set doForThisID to do JavaScript "document.getElementById(‘thisElementID‘);"

repeat while pageNotLoaded is true
if (doForThisID contains "thisElementID") then
set pageNotLoaded to false
end if
end try
end repeat

I have tried various solutions offered on the web but to no avail. Can anyone offer any suggestions to make this code work ?


Some of your logic is off, confusing things. Also, best practice is to have the javascript pass the boolean value, by nesting a .contains. Here's a script that uses three methods to test if a page is loaded:

a javascript document.readyState

a javascript document.contains

a simple Safari call for document text to look for a string.

You can alter this script to use just one of these.

property testingID : "login"
property testingString : "Username:"

set pageLoaded to false
tell application "Safari"
    repeat while pageLoaded is false
        set readyState to (do JavaScript "document.readyState" in document 1)
        set foundID to (do JavaScript "document.contains(document.getElementById(" & quoted form of testingID & "))" in document 1)
        set pageText to text of document 1

        if (readyState is "complete") and (foundID is true) and (pageText contains testingString) then set pageLoaded to true
        delay 0.2
    end repeat
end tell
display dialog "Ready state of page: " & readyState & return & ¬
    "ID is loaded: " & foundID & return & ¬
    "Test string is loaded: " & testingString