简体   繁体   中英

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:

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

In main.js, If I try the following outside of the pageWorkers.Page() call:

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. If asked, I can add that code also.

Page workers, like tab attaching and unlike pageMods, don't have an onAttach function. Nor do they have an onReady , since the contentScriptFile is automatically attached when the HTML is ready.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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