2017-12-18 9 views
0

FirefoxのWeb拡張機能を使用していますが、一部の言葉(頭字語など)を拡張版に置き換えています。次のように私のコードは次のとおりです。Firefoxの拡張機能がJavaScriptの実行を妨げている

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))); 
} 

これは期待通りにすべてのインスタンスを置き換えるようだが、私はJavascriptがスクリプトが動作しているページ上で正しく実行するようには思えないことに気付きました。私は今30分のコードを見つめていて、それがなぜそのようになるのかを考え出すことはできません。事態を悪化させるために、問題は間欠的であるように思われます(ただし、頻繁に起こることはありません)。

私のコードがJavascriptが期待通りに動作しないようにする理由はありますか?

+0

スクリプトタグを含む可能性のあるbody.innerHTML全体を置き換えるので、必要な関数名や変数も置き換えられることがあります。これが問題ではないとしても、全身の内容を置き換えることは私に危険なようです。 – Robbendebiene

+0

divのinnerHTMLを使用した[scriptタグの作成]が重複している可能性があります](https://stackoverflow.com/questions/13390588/script-tag-create-with-innerhtml-of-a-div-doesnt-work ) – the8472

答えて

1

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", "@"); 
} 

スクリプトのテキストノードを除くすべてのテキストノードの上にこの反復処理し、それらの内容を置き換えます。

関連する問題