Nick
Nick

Reputation: 1056

AppleScript set value to web form input field via JavaScript

I am trying to force a registration via Applescript. There is a form field requiring an email. I am successfully adding the email to the form field but it is still not recognized as it's "value". When I inspect the element the value is not set. But if I click in the form field and add a space then the value is recognized. I am not sure how to get around this. I have tried to use focus(), click(), multiple keystrokes and no matter what I do the value is never set using Applescript.

set email to the text returned of (display dialog "Enter in Your Email to Validate Your Purchase:" default answer "")

tell application "Safari"
        make new document at end of documents
        set URL of document 1 to "https://myurl.com"
        tell application "System Events" 

            set theScript to "document.getElementById('email').value= '" & email & "';"

        end tell

        delay 3 

        do JavaScript theScript in document 1

end tell

Upvotes: 2

Views: 1656

Answers (2)

wares
wares

Reputation: 1

Thanks for postings, Nick!

I needed to add a return. The code below is for a tab already opened to a webpage thus the url need not be set.

to inputByID(theId, theValue) -- creates the function

tell application "Safari" -- tells AppleScript to use Safari
    
    do JavaScript "  document.getElementById('" & theId & "').Focus();" in document 1
    
    delay 1
    
    do JavaScript "  document.getElementById('" & theId & "').Select();" in document 1
    
    delay 1
    
    do JavaScript "  document.getElementById('" & theId & "').value ='" & theValue & "';" in document 1
    
    delay 1
    
    tell application "System Events"
        keystroke space
        keystroke return
    end tell
    
end tell -- stops using safari

end inputByID --marks the end of the function

Upvotes: 0

Nick
Nick

Reputation: 1056

I found the answer:

tell application "Safari"
make new document at end of documents
set URL of document 1 to "https://www.myurl.com"

        delay 1
        do JavaScript "document.getElementById('email').focus();" in document 1
        delay 1
        do JavaScript "document.getElementById('email').select();" in document 1
        delay 1
        do JavaScript "document.getElementById('email').value = '" & email & "';" in document 1
        delay 1
        tell application "System Events"
            keystroke space
        end tell
end tell

Upvotes: 2

Related Questions