Search code examples
firefox-addonfirefox-addon-sdk

Can't recieve port message from main.js in content script


I am trying to send a message via port from my main.js to my content script for my panel. I've tried many things without luck, however sending a message from the content script to main.js works perfectly.

Here is what my main.js looks like:

var data = require("self").data;
var setting = require("panel").Panel({
  width: 250,
  height: 130,
  contentURL: data.url("www.google.com"),
  contentScriptFile: data.url("script.js")
});
require("widget").Widget({
  id: "sorter1",
  label: "Search Result Sorting",
  contentURL: data.url("icon.ico"),
  panel: setting
});
setting.port.emit("message");

And here is my content script:

self.on("message", function(addonMessage) {
  document.innerHTML = "Got Message"
});

Solution

  • I had this figured out a few days ago, just haven't had the time to post here.

    A few things to keep in mind when using panels:

    • Pannel page is loaded when extension is loaded, not when it is shown.
    • Content script of the panel page is injected into the panel page when the page is shown.(when contentScriptWhen property is default)
    • Content scripts dont have access to add-on SDK resources.

    This is how I implemented it

    In main.js

    panel.on("show", function() {
         panel.port.emit("message");
    });
    

    In panel content script

    self.port.on("message", function() {
        //doThings
    });
    

    port.emit() doesn't need a second argument, though second argument is what will be passed to the content script for

    function(secondArg) {
    }