javascriptmessagefirefox-addon-sdkjpm

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


I am developing a FireFox extension using JPM Addon. I am loading a panel from the main index.js file like so...

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. 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.

I tried postMessage as well as 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!


Solution

  • You should read the section "Scripting trusted panel content" in the MDN sdk/panel page. 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. 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.

    So, your popup.js code should be:

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

    And your 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.