1.質問
拡張のcontent_scripts中のjsで、任意の外部jsファイルを読み込んで、そのjsファイルの中で任意のテキストをdocument.write();させるにはどうしたらよいでしょうか。
もう少し具体的に言うと、content_scriptsの中から外部のhttp://~/~.jsという外部jsを読み込ませたいのですが
その外部jsにdocument.write();が使われてしまっています。
元々、htmlの中にベタ書きする事を想定したブログパーツの様なもので、第三者が作られているので手を加える事が出来ません。
確かにhtmlの中に<script src="~~"></script>と書いておけばdocument.write();で何の問題も無いのですが
content_scriptsですとjavascriptから追加する必要があります。
manifest.json のcontent_scripts.run_atの値で実行されるタイミングが変わるので、もしかしてdocument.write();が効くタイミングがあるかも
と値document_idle、document_start,document_endにしてみたり
外部jsを呼び出す方法を
script = document.createElement("script");script.src = "http://~";document.body.appendChild(script);と
document.write('<script src="~"><'+'/script>');
の両方で試したのですが
タイミングが早いとdocument.bodyが無くてappendChildが成功しなかったり
タイミングが遅いとdocument.write();を実行した途端ページ内容がクリアされたりとどうもうまくいきません。
2.バグ発見?
また、content_scripts.run_atにdocument_startと指定して
実行させるcontentScriptに
document.write('from contentScript');
console.log("contentScriptが呼び出し",Math.random());
と指定すると、contentScriptは一度しか呼び出されないはずなのに
contentScriptが呼び出し 0.38785913377068937 contentScript.js:2
contentScriptが呼び出し 0.6574389105662704 contentScript.js:2
contentScriptが呼び出し 0.7338545499369502 contentScript.js:2
contentScriptが呼び出し 0.6709329732693732 contentScript.js:2
contentScriptが呼び出し 0.9620644422248006 contentScript.js:2
contentScriptが呼び出し 0.7930269243661314 contentScript.js:2
contentScriptが呼び出し 0.20299813826568425 contentScript.js:2
contentScriptが呼び出し 0.9966204478405416 contentScript.js:2
・・・と、何度もcontentScriptが呼び出されていまい
デベロッパーツールのelementsタブが
<html></html>
<html></html>
<html></html>
<html></html>
<html></html>
<html></html>
・・・とDOMが壊れてしまっています。
そもそもdocument_startでdocument.writeするなという事かもしれませんが・・・。
以上です。