Chrome扩展程序打破网页,使他们似乎永远加载? [英] Chrome Extension breaks web pages, making them seemingly load forever?

查看:104
本文介绍了Chrome扩展程序打破网页,使他们似乎永远加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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。



JSBin Demo


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.

JSBin Demo

这篇关于Chrome扩展程序打破网页,使他们似乎永远加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆