如何使用javascript和applescript替换网页上的文本

时间:2016-08-12 05:52:13

标签: javascript macos applescript

以下javascript代码来自对此question的回答,并且非常适合替换网页上的文字。在Safari和Chrome中使用javascript控制台取得了成功的结果。

function replaceTextOnPage(from, to){
    getAllTextNodes().forEach(function(node){
        node.nodeValue = node.nodeValue.replace(new RegExp(quote(from), 'g'), to);
    });

    function getAllTextNodes(){
        var result = [];

        (function scanSubTree(node){
            if(node.childNodes.length) 
                for(var i = 0; i < node.childNodes.length; i++) 
                    scanSubTree(node.childNodes[i]);
            else if(node.nodeType == Node.TEXT_NODE) 
                result.push(node);
        })(document);

        return result;
    }

    function quote(str){
        return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    }
}

replaceTextOnPage('oldtext', 'newtext');

但是当我将其保存为 replace_text.js 并尝试使用Applescript运行时,在Safari和Chrome中都会返回 缺失值

tell application "Safari"
    activate
    tell the current tab of window 1 to do JavaScript "/Users/Me/ScriptFolder/replace_text.js"
end tell

我还尝试直接从脚本编辑器中的tell块运行javascript,在转义引号并转义转义后,而不是使用replace_text.js文件,但这也会导致 缺少值 即可。

当我将javascript代码直接复制并粘贴到脚本编辑器中并尝试使用javascript运行器运行时,我得到错误-2700:脚本错误。

  

第15行出错:ReferenceError:无法找到变量:document

如果我在脚本中将文档定义为document = "http://example.com",我会收到错误:

  

第12行出错:TypeError:undefined不是对象(评估&#39; node.childNodes.length&#39;)

有人能告诉我我做错了什么吗?如何使用Applescript运行相同的javascript代码?

由于

1 个答案:

答案 0 :(得分:1)

do JavaScript命令需要一个包含 JavaScript 代码的字符串,而不是文件路径。

所以,你可以使用:

set myJS to read "/Users/Me/ScriptFolder/replace_text.js" as «class utf8» -- encoding of the file is "utf-8"
tell application "Safari"
    tell the current tab of window 1 to do JavaScript myJS
end tell

或者这个:

set myJS to "function replaceTextOnPage(from, to){
    getAllTextNodes().forEach(function(node){
        node.nodeValue = node.nodeValue.replace(new RegExp(quote(from), 'g'), to);
    });
    return 'replaceTextOnPage(), Done' // just for testing, to avoid the missing value from the do JavaScript command
    function getAllTextNodes(){
        var result = [];
        (function scanSubTree(node){
            if(node.childNodes.length) 
                for(var i = 0; i < node.childNodes.length; i++) 
                    scanSubTree(node.childNodes[i]);
            else if(node.nodeType == Node.TEXT_NODE) 
                result.push(node);
        })(document);
        return result;
    }
    function quote(str){
        return (str+'').replace(/([.?*+^$[\\]\\(){}|-])/g, \"\\$1\");
    }
}
replaceTextOnPage('oldtext', 'newtext');"

tell application "Safari"
    activate
    tell the current tab of window 1 to do JavaScript myJS
end tell

do JavaScript命令在函数不返回任何内容时返回缺失值replaceTextOnPage函数不返回任何内容),这是正常行为。

相关问题