【发布时间】:2015-06-17 04:05:39
【问题描述】:
我已阅读此问题 Is it possible to inject a javascript code that OVERRIDES the one existing in a DOM? 并且该解决方案大部分时间都运行良好,但有时页面中的 JavaScript 代码似乎会先运行,然后是 content_scripts。
这有时会使“OVVERRIDES”失败。
我的测试代码如下:
//manifest.json
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["js_injector.js"],
"run_at": "document_start"
}
//js_injector.js
function injectJs(link) {
var scr = document.createElement('script');
scr.type="text/javascript";
scr.src=link;
document.documentElement.appendChild(scr);
}
injectJs(chrome.extension.getURL('my.js'));
//my.js
console.log("in my.js");
function foo() {
console.log("in my.js foo");
}
//test.html (view this page in chrome)
<html>
<script type="text/javascript">
console.log("I am here 1110");
foo()
console.log("I am here 1111");
</script>
</html>
通常,我会得到以下日志:
in my.js my.js:114
I am here 1110 test.html:4
in my.js foo my.js:116
I am here 1111 test.html:6
但有时,会得到以下日志:
I am here 1110 test.html:4
Uncaught ReferenceError: foo is not defined test.html:5
in my.js test.js:114
似乎在页面和内容脚本中运行代码的顺序是随机的? 我的目的是让目标页面运行在内容脚本中定义的 js api。 有人知道如何解决吗? 谢谢!
【问题讨论】:
标签: javascript google-chrome-extension