使用上下文菜单和端口
我在 阅读使用内容脚本,可以将端口与上下文菜单一起使用,但以下代码给我一个错误:cm.port 未定义。当我发出事件时,相同的代码适用于 require("panel")
,但不适用于上下文菜单。我做错了什么?
这是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");
这个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);
});
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);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
引用 文档:
您使用的既不是
panel
也不是page-worker
而是上下文菜单
。并且context-menu
包不允许与内容脚本进行双向通信。同样,如果您查看 文档:您只能接收内容脚本发送的消息,但不能向其发送消息。相反,消息context
和click
会在适当的情况下自动发送到内容脚本。To quote the documentation:
What you are using is neither
panel
norpage-worker
butcontext-menu
. And thecontext-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 messagescontext
andclick
are sent to the content script automatically in appropriate situations.参考:https://developer.mozilla.org/ en-US/Add-ons/SDK/Guides/Content_Scripts/using_postMessage
Refer to:https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts/using_postMessage