问题
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);
});
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/8489224/working-with-context-menu-and-port