简体   繁体   English

FF插件(JPM)从面板脚本传递消息到主索引脚本

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

I am developing a FireFox extension using JPM Addon. 我正在使用JPM插件开发FireFox扩展。 I am loading a panel from the main index.js file like so... 我正在像这样从主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
        });

The pages/popup.html file references a javascript file and I use the relative path to load it. pages / popup.html文件引用了一个javascript文件,我使用相对路径来加载它。 I need to figure out how to pass a message from this javascript file, loaded by the panel web page, to the main index.js script file of the addon. 我需要弄清楚如何将消息从面板页面加载的此javascript文件传递到插件的主要index.js脚本文件。

I tried postMessage as well as port.emit... 我尝试了postMessage以及port.emit ...

So, either 所以,要么

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

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

...or... ...要么...

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

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

However, both of these don't seem to work. 但是,这两个似乎都不起作用。 Help! 救命!

You should read the section " Scripting trusted panel content " in the MDN sdk/panel page . 您应该阅读MDN sdk / panel页面中的“ 脚本编写受信任的面板内容 ”部分。 The most relevant text is: 最相关的文本是:

Like a content script, these scripts can communicate with the add-on code using the postMessage() API or the port API. 与内容脚本一样,这些脚本可以使用postMessage() API或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. 关键的区别是这些脚本通过addon对象访问postMessageport对象,而内容脚本通过self对象访问它们。

So, your popup.js code should be: 因此,您的popup.js代码应为:

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

And your index.js : 还有你的index.js

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

There is an example add-on in the " Scripting trusted panel content " section showing communication in both directions between the trusted panel (panel content comes from within the add-on) and the main background script of the add-on. 脚本化受信任面板内容 ”部分中有一个示例附加组件,显示了受信任面板(面板内容来自附加组件内部)和附加组件的主要背景脚本之间双向通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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