使用Addon SDK我试图在每个页面加载时将脚本注入页面。为了测试,插件试图将变量添加到窗口对象,页面应该读取它。当我运行它时,我可以看到“注入”警报,但是页面给出了错误“未定义属性window.myVar”。我究竟做错了什么?顺便说一下,我不想使用unsafeWindow。
main.js:
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "*",
contentScriptFile: data.url("inject.js"),
contentScriptWhen: "start",
onAttach: function(worker) {
worker.port.emit("inject", "unused param");
}
});
inject.js
function inject(arg) {
var script = document.createElement("script");
script.innerHTML = 'alert("injecting"); window.myVar=54564;';
document.head.appendChild(script);
}
self.port.on("inject", inject);
page.html中
<html>
<head>
</head>
<body>
<script>
alert(window.myVar);
</script>
</body>
</html>
编辑: 我尝试了canuckistani的代码,它显示了一些奇怪的行为。顺便说一下,我在Firefox 31上。这是我的代码
function inject(arg) {
var myVar = 123;
unsafeWindow.myVar = cloneInto(myVar, unsafeWindow);
}
self.port.on("inject", inject);
和页面
<html>
<head>
</head>
<body>
<script>
alert(window.myVar); <!--This shows empty alert box-->
alert(window.myVar); <!--This shows alert box with right value (123)-->
</script>
</body>
</html>
答案 0 :(得分:0)
从Firefox 30开始(差不多2个版本!)你可以使用一些新的apis来做到这一点。这看起来像是:
let myVar = {1:2};
self.port.on("inject", function() {
unsafeWindow.myVar = cloneInto(myVar, unsafeWindow);
});
有关详细信息,请see this blog post: