Working with context-menu and port

被刻印的时光 ゝ 提交于 2019-12-11 05:21:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!