javascript (applescript) : 查找文本并突出显示

javascript (applescript) : find text and highlight

我试图找到某些文本的每个实例并在 Safari 浏览器中突出显示它们,无论它们是什么选项卡。

这是目前为止的代码:

set myList to {"ask", "yesterday", "more random e.g"}
try
    tell application "Safari"
        do JavaScript "document.designMode = 'on';" in tab 1 of window 1


        repeat with thisText in myList
            do JavaScript "var sel = window.getSelection();
                    sel.collapse(document.body, 0);
                    while (window.find('" & thisText & "', true)) {document.execCommand('HiliteColor', false, '#5cdf64');}
                    sel.collapseToEnd()" in tab 1 of window 1
        end repeat
        do JavaScript "document.designMode = 'off';" in tab 1 of window 1

    end tell
on error
    --
end try

此代码有问题:

你可以做一个循环来处理最前面的所有选项卡 window 像这样:

set myList to {{"ask","#5cdf64"}, {"yesterday", "#FFFF00"}, {"more random e.g", "#FF0000"}}
tell application "Safari"
    activate
    set theWindow to front window
    tell theWindow
        set tabCount to count of tabs
        repeat with tabIndex from 1 to tabCount
            set current tab to tab tabIndex
                tell current tab
                    repeat with colourPair in myList
                        do JavaScript "document.designMode = 'on'"
                        do JavaScript "var sel = window.getSelection(); sel.collapse(document.body, 0); while (window.find('" & (item 1 of colourPair) & "', true)) {document.execCommand('HiliteColor', false, '" & (item 2 of colourPair) & "');}"
                        do JavaScript "document.designMode = 'off'"
                    end repeat
                end tell
        end repeat
    end tell
end tell

您的 JavaScript 将指向正确的选项卡,而无需硬编码对 window 和选项卡的引用。

您为 myList 中的每个实例分配不同颜色的要求由 'list of lists' 和成对的搜索词和颜色代码处理。

我认为滚动与 sel.collapseToEnd() 有关,我认为您不需要。