问题
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);
回答1:
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
来源:https://stackoverflow.com/questions/26988053/chrome-extension-breaks-web-pages-making-them-seemingly-load-forever