替换网站中的文字

Num*_*ica 4 html javascript

我正在寻找使用JavaScript替换网页(我想要运行它的任何网页)中的文本.我不是JavaScript的专家,所以我有点迷茫.如果我可以帮助它,我想避免使用jQuery.

通过谷歌,我发现了这个 stackoverflow问题.但是,当我注入document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');网页时,它会混淆页面.它似乎使页面恢复为基本文本和格式.

另外,我想知道是否可以使用此处的正则表达式代码.再说一次,我真的不确定如何使用它.它的作用是只替换网页文本 - 而不是链接或文件名.

我正在使用重要的Google Chrome浏览器.

Pau*_*aul 10

您可以在DOM中的所有文本节点上执行您的补充:

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");
  }
}
Run Code Online (Sandbox Code Playgroud)

引用函数借用了这个答案.

用法:

replaceTextOnPage('hello', 'hi');
Run Code Online (Sandbox Code Playgroud)

请注意,您需要在旧版浏览器中使用SHIM forEach,或者使用如下循环替换该代码:

var nodes = getAllTextNodes();
for(var i = 0; i < nodes.length; i++){
    nodes[i].nodeValue = nodes[i].nodeValue.replace(new RegExp(quote(from), 'g'), to);
}
Run Code Online (Sandbox Code Playgroud)