Applescript / Javascript unable to fill Safari input box

Viewed 168

I have set my Safari homepage to a url that has a username and password form. My script should open Safari and set the username to a value. The script opens safari, the homepage is displayed, but no text added to input box.

tell application "Safari"
    activate
    tell window 1
        delay 3
        do JavaScript "document.getElementById('username').value = 'hello';"
    end tell
end tell

<input type="text" name="username" id="username" size="20" style="width: 150px;">

Can anyone suggest why?

1 Answers

You need to tell Safari where, e.g. tab n of window n or document n, etc.

Example AppleScript code:

tell application "Safari"
    tell current tab of window 1
        do JavaScript "document.getElementById('username').value = 'TheCoder';"
    end tell
end tell

Or:

tell application "Safari"
    do JavaScript "document.getElementById('username').value = 'TheCoder';" in document 1
end tell



Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

Related