Search code examples
safariclickapplescriptgetelementsbyname

AppleScript Safari : Click button after page has fully loaded


I have this script here which is loading a profile on an unfocused safari tab and saving the text I want in a variable

tell application "Safari" to set the URL of tab 2 of window 1 to "https://URLproduct/" & serialNumber & "/definition"
    delay 2.5

However some of the data is only available after a click on a button (this is a pop-up like overlay with a button, which make the another text not accessible until you press on "OK", also this button is not always here)

button HTML is :

<button class="btn btn-primary" autofocus="" ng-click="ok()" tabindex="0">OK</button>

which I press with this script :

do JavaScript "document.getElementsByClassName('btn btn-primary')[1].click();" in tab 2 of window 1 

Weirdly sometime is working sometime not and I can't add too much delay

Can I add a script which would wait for this button ('btn btn-primary') been availible (fully loaded) and then try again to get the text by with my 1st script?

-- May be I can add something like

tell application "Safari"


    tell document 1
        repeat until ("btn btn-primary" is in its source)
            delay 0.5
        end repeat
    end tell
end tell

then the click script?


Solution

  • yes, you can start executing your script after the page has loaded. This makes sure that the button is clickable (in case it appears at all).

    Put this code in to your script:

        tell application "Safari"
            repeat until (do JavaScript "document.readyState" in document 1) is "complete"
            end repeat
        end tell
    

    Happy scripting!