Chrome扩展程序打破网页,使他们似乎永远加载? [英] Chrome Extension breaks web pages, making them seemingly load forever?
问题描述
我使用chrome扩展将代码注入到网页中,以便在文本匹配特定字符串时更改部分文本。它正确地取代了文本,但似乎使网页处于无限的加载状态,并在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);
替换 innerHTML code>也会替换
脚本
标签中的属性和文本。要仅替换非脚本标记中的文本节点,请使用 TreeWalker
。
var treeWalker = document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),
textNode; (textNode = treeWalker.nextNode()){
if(textNode.parentElement.tagName!=='SCRIPT'){
textNode.nodeValue = textNode.nodeValue。
while(textNode =更换(/ 10:00 / g,上午11:00);
$ / code $ / pre
另外,你不需要附加脚本到DOM能够访问其内容。内容脚本可以修改DOM。
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);
解决方案 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.
这篇关于Chrome扩展程序打破网页,使他们似乎永远加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!