Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using a chrome extension to inject code into web pages to change parts of the text if they match a certain string. It replaces the text correctly, but seems to hold the web page in an endless state of loading, and messes up certain elements on sites like Facebook.

    var actualCode = '(' + function() {
    document.body.innerHTML = document.body.innerHTML.replace(/10:00/g, "11:00 AM");
    } + ')();';
    var script = document.createElement('script');
    script.textContent = actualCode;
    (document.head||document.documentElement).appendChild(script);
    script.parentNode.removeChild(script);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
222 views
Welcome To Ask or Share your Answers For Others

1 Answer

Replacing the innerHTML will also replace attributes and text within script tags. To replace only text nodes inside non-script tags, use a TreeWalker.

var treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT),
    textNode;

while(textNode = treeWalker.nextNode()) {
  if(textNode.parentElement.tagName !== 'SCRIPT') {
    textNode.nodeValue = textNode.nodeValue.replace(/10:00/g, "11:00 AM");
  }
}

Also, you don't need to append a script to the DOM to be able to access its contents. Content scripts can modify the DOM.

JSBin Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...