Javascript .replace command replace page text?

后端 未结 3 1748
孤独总比滥情好
孤独总比滥情好 2020-11-27 07:54

Can the JavaScript command .replace replace text in any webpage? I want to create a Chrome extension that replaces specific words in any webpage to say something else (examp

3条回答
  •  佛祖请我去吃肉
    2020-11-27 08:29

    The .replace method is a string operation, so it's not immediately simple to run the operation on HTML documents, which are composed of DOM Node objects.

    Use TreeWalker API

    The best way to go through every node in a DOM and replace text in it is to use the document.createTreeWalker method to create a TreeWalker object. This is a practice that is used in a number of Chrome extensions!

    // create a TreeWalker of all text nodes
    var allTextNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT),
        // some temp references for performance
        tmptxt,
        tmpnode,
        // compile the RE and cache the replace string, for performance
        cakeRE = /cake/g,
        replaceValue = "pie";
    
    // iterate through all text nodes
    while (allTextNodes.nextNode()) {
        tmpnode = allTextNodes.currentNode;
        tmptxt = tmpnode.nodeValue;
        tmpnode.nodeValue = tmptxt.replace(cakeRE, replaceValue);
    }
    

    Don't use innerHTML or innerText or jQuery .html()

    // the innerHTML property of any DOM node is a string
    document.body.innerHTML = document.body.innerHTML.replace(/cake/g,'pie')
    
    • It's generally slower (especially on mobile devices).
    • It effectively removes and replaces the entire DOM, which is not awesome and could have some side effects: it destroys all event listeners attached in JavaScript code (via addEventListener or .onxxxx properties) thus breaking the functionality partially/completely.
    • This is, however, a common, quick, and very dirty way to do it.

提交回复
热议问题