Search code examples
firefox-addon-sdk

Using port.emit and port.on in a firefox extension


Can someone please explain the context in which port.on and port.emit are used in a firefox extension?

From the official documentation I imagine that this should work:

//main.js
var someData = "Message received"; 

self.port.emit("myMessage", someData);
self.port.on("myMessage", alert(someData));

but I get

Error: self is not defined.

After attaching this to a defined object like this:

var self = require("sdk/self"); 
self.port.emit("myMessage", someData);

I get

Error: port is not defined.


Solution

  • If you use the page-mod module to inject a content script into a web page, you then use self.port in the content script to communicate back with main.js. For example:

    main.js:

    var data = require('sdk/self').data;
    
    require('sdk/page-mod').PageMod({
      include: ["*"],
      contentScriptFile: [data.url('cs.js')],
      attachTo: ["existing", "top"],
      onAttach: function(worker) {
        worker.port.emit('attached', true);
      }
    });
    

    cs.js:

    self.port.on('attached', function() {
      console.log('attached...');
    });
    

    For the related documentation, start here:

    https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts