使用上下文菜单和端口

发布于 2024-12-21 02:38:25 字数 711 浏览 1 评论 0原文

我在 阅读使用内容脚本,可以将端口与上下文菜单一起使用,但以下代码给我一个错误: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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我乃一代侩神 2024-12-28 02:38:25

引用 文档

面板和页面工作人员对象直接集成工作人员 API。因此,要从与面板关联的内容脚本接收事件,请使用 panel.port.on()

您使用的既不是 panel 也不是 page-worker 而是 上下文菜单。并且 context-menu 包不允许与内容脚本进行双向通信。同样,如果您查看 文档:您只能接收内容脚本发送的消息,但不能向其发送消息。相反,消息 contextclick 会在适当的情况下自动发送到内容脚本。

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.

就此别过 2024-12-28 02:38:25

参考: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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文