Applescript / Javascript 无法填充 Safari 输入框

Applescript / Javascript unable to fill Safari input box

我已将我的 Safari 主页设置为 url,其中包含用户名和密码表单。我的脚本应该打开 Safari 并将用户名设置为一个值。脚本打开safari,显示首页,但输入框没有添加文字

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;">

谁能告诉我为什么?

您需要告诉 Safari 在哪里,例如tab n of window ndocument n,等等

示例 AppleScript 代码:

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

或:

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



注意:示例 AppleScript code 就是这样,没有包含任何 错误处理 不包含任何额外的 错误处理 可能是适当的。用户有责任根据需要添加任何 错误处理 。查看 try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay 命令 在适当的事件之间可能是必要的,例如delay 0.5,适当设置延迟