首页 > 解决方案 > 用 Applescript 在线替换文本

问题描述

Applescript 的新手在这里。我正在尝试制作一个脚本,该脚本可以在线扫描文本编辑器中的文本并用其他单词替换单词。

在我的具体情况下,它用“”替换了一些 html 片段——即删除它们。

我当前的脚本收到以下错误消息…… “勇敢的浏览器出现错误:窗口 1 不理解“执行”消息。” 来自窗口 1 的数字 -1708

这是下面的脚本。有问题的行似乎是EditorField变量的来源。

有什么建议或想法可以让它发挥作用吗?谢谢。

    tell application "Brave Browser"
        activate
        my replaceWordWithStringInBodyText(" ", "")
        my replaceWordWithStringInBodyText("<span class=\"Apple-converted-space\">", "")
        my replaceWordWithStringInBodyText("<b>", "<strong>")
    end tell

    on replaceWordWithStringInBodyText(searchWord, replacementString)
        tell application "Brave Browser"
            activate
            tell window 1
                set EditorField to (execute javascript "document.getElementById('\"wp-content-editor-container\"')")
                tell EditorField
                    -- start at the end and go to the beginning
                    repeat with i from the (count of paragraphs) to 1 by -1
                        tell paragraph i
                            repeat
                                try
                                    if exists searchWord then
                                        set (last word where it is searchWord) to replacementString
                                    else
                                        exit repeat
                                    end if
                                on error errorMessage
                                    exit repeat
                                end try
                            end repeat
                        end tell
                    end repeat
                end tell
            end tell
            return true
        end tell
    end replaceWordWithStringInBodyText

标签: javascriptapplescript

解决方案


我假设在Brave浏览器中,您已在View > Developer菜单上单击Allow JavaScript from Apple Events以进行检查。

话虽如此,并且由于您没有包含用于测试代码的URL,所以让我举一个示例,说明如何单击右上角的“提问”按钮,如果我在勇敢的浏览器:

tell application "Brave Browser" to tell active tab of front window to execute javascript ¬
    "document.getElementsByClassName('ws-nowrap s-btn s-btn__primary')[0].click();"

如您所见,还必须与目标选项卡以及目标窗口进行通信。所以你需要相应地调整你的代码


推荐阅读