Firefox SDK port.on and port.emit

So using the example in the SDK docs (below) doesn’t work in the sense that it doesn’t prevent the URL in the href from loading in the panel, and it doesn’t console log anything. I’m not sure as to why it’s not working the way it’s specified in the SDK docs, unless it’s outdated?

   var myScript = "window.addEventListener('click', function(event) {" +
               "  var t = event.target;" +
               "  if (t.nodeName == 'A')" +
               "    self.port.emit('click-link', t.toString());" +
               "}, false);"

var panel = require("sdk/panel").Panel({
  contentURL: "http://www.bbc.co.uk/mobile/index.html",
  contentScript: myScript
});

panel.port.on("click-link", function(url) {
  console.log(url);
});

panel.show();

Assuming this is in your main.js file, do you have the following line in it anywhere?


var window = require("window-utils").activeBrowserWindow;

I did not, thanks for pointing that out. I didn’t see it in the docs when reading about it. Quickly looking into it, it’s actually deprecated, https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/deprecated/window-utils.html.

And thank you for pointing out that it’s deprecated.

Time for me to look into changing some code before it breaks some scripts.

This is where I get stuck though, https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/guides/content-scripts/using-port.html says to use port for communicating. I also tried adding the “event/core” module, [URL=“https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/event/core.html”]https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/event/core.html to no avail while trying their examples to just get it to even work. :expressionless:

I don’t know what you mean by “stuck”. Code not working or understanding?

“port” is used “To enable add-on scripts and content scripts to communicate with each other”

I haven’t had the need to use event/core yet, but the docs say it “enables you to create APIs that broadcast events”

Maybe there is some overlap here, I would be interested in hearing from others as to the distinctions.

Stuck as in the code isn’t working thus leading me to not understand, I read the docs and understood it until I went to apply it. Then it doesn’t work. I know that port communicates the content scripts with the main add-on JavaScript and I need it to. I don’t know the where the event/core module would come in if it allows you to broad cast and listen for events, when “port” from what I read does that. I’ve tried including the event/core module with what I’m trying to do and without it, but I still can’t seem to get it to emit events. As I have said, I even copied the examples from the docs to test it after it didn’t work for me and it still doesn’t work testing it with the example in the docs.