0x499602D2 0x499602D2 - 1 year ago 96
Javascript Question

Javascript .replace command replace page text?

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 (example cake instead of pie).

Answer Source

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.

Do This

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--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
    // 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 Do This

While you can use string operations on .innerText and .innerHTML properties, those properties are not standardized parts of the DOM API, and their use is more or less deprecated; they also have some performance and reliability problems. However, the shortest version of this, and a version that works in most browsers, uses just that property.

// the innerHTML property of any DOM node is a string
document.body.innerHTML = document.body.innerHTML.replace(/cake/g,'pie')

Note that to some user agents, this 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download