1

I read at working with content scripts that one can use port with context-menu, but the following code gives me an error: cm.port is undefined. The same code works with require("panel") when I emit an event, but not with context menu. What am doing wrong?

This is main.js

const data = require('self').data;
var cm = require("context-menu").Item({
label: "asdasd",
  contentScriptFile: data.url("panel.js")
});

cm.port.emit("myEvent", "panel is showing");

this panel.js

console.log("entering the panel.js file...");
self.on("click", function(node,data) {
self.port.emit("asd");
});

self.port.on("myEvent", function(data) {
    console.log(data);
});
  • The error message doesn't match your code. Do you mean "cm.port is undefined"? – Wladimir Palant Dec 13 '11 at 17:42
  • FTR, one can communicate with the page by associating the cm to a pageMod as per http://stackoverflow.com/a/11768820/271577 (for a workaround to https://bugzilla.mozilla.org/show_bug.cgi?id=824348 ) – Brett Zamir Jul 03 '14 at 00:20

2 Answers2

4

To quote the documentation:

The panel and page-worker objects integrate the worker API directly. So to receive events from a content script associated with a panel you use panel.port.on()

What you are using is neither panel nor page-worker but context-menu. And the context-menu package doesn't allow bi-directional communication with the content script. Again, if you look at the documentation: you can only receive messages sent by the content script but not send messages to it. Instead, the messages context and click are sent to the content script automatically in appropriate situations.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
  • 1
    What was not obvious to those of us who don't read all the docs first is that the solution is to use `postMessage()` from the content script and onMessage within the context menu item (`cm`). – Brett Zamir Nov 11 '12 at 14:17
  • 2
    @iND: Yes, Mozilla removed documentation for old SDK versions for some reason. I've updated the links to current version. – Wladimir Palant Dec 28 '12 at 13:37
0

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

As an alternative to port, content modules support the built-in message event. In most cases port is preferable to message events. However, the context-menu module does not support port, so to send messages from a content script to the add-on via a context menu object, you must use message events.

iericzhou
  • 620
  • 8
  • 11