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

谁说我不能喝 提交于 2020-01-06 15:57:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!