So I want to have a script that presses a button for me and if the button doesn't exist, it keeps clicking until the button exists.
Here is a method that I would use and should work. I say should as I cannot test based on the element being getQualities. However, I did test the code using a known element on the page of this question and it worked.
Example AppleScript code:
set theElementExists to false
repeat until theElementExists
tell application "Google Chrome" to ¬
set theElementExists to ¬
execute front window's active tab javascript ¬
"document.body.contains(document.getElementById('getQualities'));"
delay 1
end repeat
if theElementExists then
tell application "Google Chrome" to ¬
execute front window's active tab javascript ¬
"document.getElementById('getQualities'}.click();"
end if
Notes:
I'm not a big fan of using endless loops constructs, but when I do, I typically add additional code to terminate the script after a reasonable time out period. (Which of course makes them not an endless loop.)
Example AppleScript code:
set theElementExists to false
set i to 0
repeat until theElementExists
tell application "Google Chrome" to ¬
set theElementExists to ¬
execute front window's active tab javascript ¬
"document.body.contains(document.getElementById('getQualities'));"
delay 1
set i to i + 1
if i ≥ 10 then return
end repeat
As coded this would run for up to 10 seconds.
The document.body.contains() method returns a Boolean value.
Note that the second if statement if theElementExists then is not really necessary per se, and I've included it mainly for coding clarity.
In case you are wondering how I tested it, I used the following within my code, which targets the Ask Question button on this page:
"document.body.contains(document.getElementsByClassName('ws-nowrap s-btn s-btn__primary')[0]);"
And:
"document.getElementsByClassName('ws-nowrap s-btn s-btn__primary')[0].click();"
While manually setting focus to a different page first, then manually setting focus back to this page and it clicked the Ask Question button.