简体   繁体   English

在可信页面内容和插件之间传递消息

[英]Message passing between trusted page content and addon

I'm unable to pass messages between a trusted page-worker script, and the addon. 我无法在受信任的页面工作者脚本和插件之间传递消息。

main.js: 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: worker.html:

<html>
<head>
<script src="../js/worker.js"></script>
</head>
<body>
</body>
</html>

worker.js: worker.js:

    console.log("trying to emit message");
    addon.port.emit("message");
    addon.port.emit("message", "value");
    console.log("tried to emit message");

In main.js, If I try the following outside of the pageWorkers.Page() call: 在main.js中,如果我在pageWorkers.Page()调用之外尝试以下操作:

pageWorkers.port.on("message", function() {
        console.log("Message received");
});

I get the following exception: 我得到以下异常:

Message: TypeError: pageWorkers.port is undefined

Any help would be appreciated. 任何帮助,将不胜感激。 I have tried using postMessages to no avail. 我尝试使用postMessages无济于事。 If asked, I can add that code also. 如果需要,我也可以添加该代码。

Page workers, like tab attaching and unlike pageMods, don't have an onAttach function. 页面工作程序(如选项卡附加)和pageMods不同,没有onAttach函数。 Nor do they have an onReady , since the contentScriptFile is automatically attached when the HTML is ready. 它们也没有onReady ,因为当HTML准备就绪时,contentScriptFile会自动附加。

main.js main.js

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

worker.js worker.js

console.log("trying to emit message");
addon.port.emit("message");
console.log("trying to emit message1");
addon.port.emit("message1", "value");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM