使用上下文菜单和端口

时间:2011-12-13 12:26:30

标签: firefox firefox-addon firefox-addon-sdk

我在working with content scripts读到可以使用带上下文菜单的端口,但是下面的代码给出了一个错误: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);
});

2 个答案:

答案 0 :(得分:4)

引用the documentation

  

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

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

答案 1 :(得分:0)

请参阅:https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts/using_postMessage

  

作为端口的替代方案,内容模块支持内置消息事件。在大多数情况下,端口优先于消息事件。但是,上下文菜单模块不支持端口,因此要通过上下文菜单对象将消息从内容脚本发送到加载项,必须使用消息事件。