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

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

javascript - Chrome Extension breaks web pages, making them seemingly load forever?

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...