简体   繁体   English

Firefox扩展阻止Javascript运行

[英]Firefox Extension is Preventing Javascript Running

I'm writing a simple Firefox web extension, which will replace certain words (eg acronyms) with expanded versions. 我正在编写一个简单的Firefox Web扩展,它将用扩展版本替换某些单词(例如首字母缩写词)。 My code is as follows: 我的代码如下:

var replacements = [];
replacements["example1"] = "My First Example";
replacements["example2"] = "Second Example";

if(!window.location.href.startsWith('https://ignore.thissite.com/')){
    for(key in replacements){
        replaceOnDocument(new RegExp('\\b'+key+'\\b', 'gi'), '{{{REPLACE_'+key+'}}}');
        document.body.innerHTML = document.body.innerHTML.replace(new RegExp('{{{REPLACE_'+key+'}}}', 'g'), '<abbr title="'+key+'">'+replacements[key]+'</abbr>');
    }
}

function replaceOnDocument(pattern, string){
    Array.from(document.querySelectorAll("body, body *:not(script):not(noscript):not(style):not(code):not(pre)"))
        .forEach(someNode => Array.from(someNode.childNodes)
        .filter(childNode => childNode.nodeType == 3)
        .forEach(textNode => textNode.textContent = textNode.textContent.replace(pattern, string)));
}

This seems to replace all the instances as expected, but I've noticed that Javascript doesn't seem to run correctly on pages that the script has run on. 这似乎可以按预期替换所有实例,但是我注意到Javascript似乎无法在运行脚本的页面上正确运行。 I've been staring at the code for half an hour now and can't work out why that would be the case. 我已经盯着代码半个小时了,无法弄清楚为什么会这样。 To make things worse, the problem seems to be intermittent (although happens more often than not). 更糟的是,这个问题似乎是断断续续的(尽管这种情况经常发生)。

Any ideas as to why my code would prevent Javascript running as expected? 关于我的代码为何会阻止Javascript按预期运行的任何想法?

I already speculated that replacing the content of body.innerHTML may cause issues, so how about using the following approach for replacing text? 我已经推测替换body.innerHTML的内容可能会引起问题,那么如何使用以下方法替换文本呢? codepen example 代码笔示例

const walker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW_TEXT,
  {
    // filter / exclude tags
    acceptNode: function (node) {
      return node.parentElement.nodeName === "SCRIPT" ? NodeFilter.FILTER_SKIP : NodeFilter.FILTER_ACCEPT;
    }
  }
);

while (walker.nextNode()) {
  // replace every H with @
  walker.currentNode.nodeValue = walker.currentNode.nodeValue.replace("H", "@");
}

This iterates over every text node excluding script text nodes and replaces their content. 这会遍历除脚本文本节点之外的每个文本节点,并替换其内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM