Applescript,单击复选框并执行 JavaScript

Applescript, click checkbox with do JavaScript

我正在尝试在 AppleScript 中使用 do JavaScript 选中或取消选中复选框。复选框出现在名为 mainFrame 的 iframe 和名为 postForm 的表单中...这是复选框:

<input class="normal" id="apples" name="applesChk" value="<1>" style="visibility: visible" onclick="checkChk(this.checked, 1);" type="checkbox">

这是我的 AppleScript...这会有点尴尬:

tell application "System Events"
    tell process "Safari"

        set windowNumber to 1
        repeat the number of windows times
            if "(item)" is in name of window windowNumber then
                set tempWindowName to name of window windowNumber
            else
                set windowNumber to windowNumber + 1
            end if
        end repeat

    end tell
end tell

tell application "Safari"
    do JavaScript "document.['apples'].click()" in window tempWindowName
    do JavaScript "document.getElementsById('apples')[0].click()" in window tempWindowName
    do JavaScript "document.forms['postForm']['apples'].checked = true" in window tempWindowName
    do JavaScript "document.frames['mainFrame']['apples'].checked = true" in window tempWindowName
    do JavaScript "document.frames['mainFrame'].forms['postForm']['apples'].checked = true" in window tempWindowName
end tell

我通过查找包含特定短语的 window 名称获得 window,然后我使用它。然后您可以看到我五次尝试选中此框。我真的很难在这里成功地遵循其他示例......任何建议表示赞赏,我哪里出错了?提前致谢。

1:使用do javascript命令时必须指定documenttab,如下所示:

do JavaScript "some command" in document 1 -- not -->window 1
do JavaScript "some command" in (current tab of window 1)

2:您可以通过名称查找文档(或当前选项卡),如下所示:

tell application "Safari"
    set tDoc to first document whose name contains "(item)"
    do JavaScript "some command" in tDoc
    -- or 
    --set tTab to current tab of (first window whose name contains "(item)"
    --do JavaScript "some command" in tTab
end tell

3: frameswindow 的 属性,所以你必须使用 window.frames(不是 document.frames


4: document.getElementsById('apples')[0].click() 错误

  1. getElementsById 不是有效命令,请使用 getElementById
  2. getElementById return 一个元素,不是 数组 .
  3. document.getElementById('apples').click() 正确

如果您的信息正确,此脚本将起作用(如果 iframe 不在另一个 iframe 中):

tell application "Safari"
    set tDoc to first document whose name contains "(item)"
    do JavaScript "window.frames['mainFrame'].document.getElementById('apples').checked=true" in tDoc
end tell

此脚本已在包含 iframe (<iframe name="mainFrame" ...) 的 HTML 文档上进行了测试,此 iframe 包含表单 (<form action="demo_form.asp" name="postForm" ...),并且此表单包含复选框 ( <input class="normal" id="apples" ... type="checkbox">).