在受信任的页面内容和加载项之间传递消息

Message passing between trusted page content and addon

本文关键字:加载项 之间 消息 信任      更新时间:2023-09-26

我无法在受信任的页面工作脚本和插件之间传递消息。

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,但没有成功。如果被要求,我也可以添加该代码。

页面工作程序,与选项卡附加不同,与pageMods不同,没有onAttach函数。它们也没有onReady,因为当HTML准备好时,contentScriptFile会自动附加。

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