我无法在受信任的页面工作者脚本和插件之间传递消息。
main.js:
var pageWorkers = require("sdk/page-worker");
var self = require("sdk/self");
// Create a page worker that loads Wikipedia:
pageWorkers.Page({
contentURL: self.data.url("html/worker.html"),
onAttach: function(worker) {
console.log("within onAttach");
worker.port.on("message", function() {
console.log("Message received");
});
worker.port.on("message", function(message) {
console.log("Message received1");
});
},
onReady: function(worker) {
console.log("within onReady");
worker.port.on("message", function() {
console.log("Message received");
});
}
});
worker.html:
<html>
<head>
<script src="../js/worker.js"></script>
</head>
<body>
</body>
</html>
worker.js:
console.log("trying to emit message");
addon.port.emit("message");
addon.port.emit("message", "value");
console.log("tried to emit message");
在main.js中,如果我在pageWorkers.Page()
电话之外尝试以下内容:
pageWorkers.port.on("message", function() {
console.log("Message received");
});
我得到以下异常:
Message: TypeError: pageWorkers.port is undefined
任何帮助将不胜感激。我试过使用postMessages无济于事。如果被问到,我也可以添加该代码。
答案 0 :(得分:4)
页面工作者,如标签附加,与pageMods不同,没有onAttach
功能。它们也没有onReady
,因为在HTML准备好后会自动附加contentScriptFile。
var worker = pageWorkers.Page({
contentURL: self.data.url("html/worker.html")
});
worker.port.on("message", function() {
console.log("Message received");
});
//If your events have the same name then they're the same event,
//irrespective of arguments passed
worker.port.on("message1", function(message) {
console.log("Message received1");
});
console.log("trying to emit message");
addon.port.emit("message");
console.log("trying to emit message1");
addon.port.emit("message1", "value");