FF Addon (JPM) 将消息从 Panel 的脚本传递到主索引脚本

FF Addon (JPM) Pass message from Panel's script to main index script

我正在使用 JPM Addon 开发 FireFox 扩展。我正在从主 index.js 文件加载一个面板,就像这样...

var panel = require('sdk/panel');
var panel = panel.Panel({
    contentURL: url('pages/popup.html'),
    onHide: doHide
});

//and in another place...
panel.show({
            position: button
        });

pages/popup.html 文件引用了一个javascript 文件,我使用相对路径加载它。我需要弄清楚如何将消息从面板网页加载的 javascript 文件传递​​到插件的主要 index.js 脚本文件。

我尝试了 postMessage 以及 port.emit...

所以,要么

//index.js
panel = require("sdk/panel").Panel({
  onMessage: function(message) {
    console.log(message);
  }
});

//popup.js - panel file
panel.postMessage('something');

...或者...

//index.js
panel.on("message", function(text) {
  console.log(text);
});

//popup.js
self.port.emit('message', 'hello world');

不过,这两个好像都不行。求助!

您应该阅读“Scripting trusted panel content" in the MDN sdk/panel page部分。最相关的文字是:

Like a content script, these scripts can communicate with the add-on code using the postMessage() API or the port API. The crucial difference is that these scripts access the postMessage and port objects through the addon object, whereas content scripts access them through the self object.

因此,您的 popup.js 代码应为:

addon.port.emit('message', 'hello world');

还有你的index.js:

panel.port.on("message", function(text) {
  console.log(text);
});

Scripting trusted panel content”部分中有一个示例插件显示受信任面板(面板内容来自插件内部)和插件的主要后台脚本之间的双向通信-on.