内容脚本无法通过 send.port.emit 发送消息

Content script unable to send messages via send.port.emit

我在我目前正在处理的 SDK 扩展中遇到了未记录的行为,非常感谢社区的帮助以找到修复或解决方法。

仅当在选项卡中打开嵌入在扩展程序中的HTML页面时才会出现此问题,如下所示:

tabs.open(data.url("html/test.html"));

请注意,上面的 test.html 将驻留在扩展根目录的 data/html 中。

我正在注入内容脚本并侦听如下所示发出的消息:

tabs.once("open", function (tab) {
  var w = tab.attach({ contentScriptFile: [ data.url("js/embed.js") ]});

  w.port.once("init", function () {
    console.log("content script initialised");
  });
});

内容脚本 data/js/embed.js 包含以下内容:

console.log("attaching embedded script");
self.port.emit("init");

问题是,如果内容脚本附加到 data HTML 页面(扩展中嵌入的页面),则内容脚本发送的消息是抑制

我的扩展程序打开一个嵌入式 HTML 页面并且能够从扩展程序接收消息和向其发送消息是绝对重要的。我怎样才能克服这个限制?


我创建了一个可以清楚地重现问题的小扩展。你可以找到它 here.

找到了一种绕过限制的方法,但它相当笨拙。它包括抓取选项卡的内容 window 对象,然后依赖 Window 的 postMessage API。像这样:

var tabs = require("sdk/tabs"),
    self = require("sdk/self"),
    data = self.data,
    utils = require("sdk/tabs/utils"),
    {viewFor} = require("sdk/view/core");

tabs.once("ready", function (tab) {
  var window = utils.getTabContentWindow(viewFor(tab));
  window.addEventListener("message", function (ev) {
    console.log("message received: ", ev.data);
  });
});

tabs.open(data.url("html/test.html"));

然后在 由 HTML 页面 加载的脚本中,将执行类似于以下内容的操作:

window.postMessage({ method: "init", state: true }, origin);

我还是想知道为什么不能使用原生 self.port.emit API?或者为什么它 安静地 抑制发送消息的尝试。

正如 here 指出的那样,答案是在 ready 事件中发出消息(而不是 open)。