簡體   English   中英

在可信頁面內容和插件之間傳遞消息

[英]Message passing between trusted page content and 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");

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM