Firefox AddOn 扩展中 contextMenu 选项的可见性

Visibility of contextMenu option in Firefox AddOn extension

我正在编写我的第一个 Firefox 附加扩展,它主要通过文本框上的右键单击上下文菜单工作。

我希望能够 show/hide 根据当前是否在用户执行右键单击事件的文本框中选择了任何文本的个人选项。

我已经能够使用内容脚本和背景脚本之间的消息来了解它的基本工作...

content.js...
window.oncontextmenu = function(e) {
  if (e && e.target && (e.target.nodeName == "TEXTAREA" || (e.target.nodeName == "INPUT" && e.target.type == "text"))) {
    var selectedText = "";
    if (e.target.selectionStart < e.target.selectionEnd) {
      selectedText = e.target.value.substring(e.target.selectionStart, e.target.selectionEnd);
    }
    browser.runtime.sendMessage({ "action": "additemvisible", "selectedText": selectedText});
  }
};

background.js...
browser.runtime.onMessage.addListener(function(message) {
  if (message && message.action) {
    if (message.action == "additemvisible") {
      addSelectedText = message.selectedText;
      browser.menus.update("addtextitem", { visible: addSelectedText != "" });
    }
  }
});

问题 消息似乎是通过 background.js 脚本在显示上下文菜单后 ,因此菜单项的可见性将基于 之前的 状态,而不是当前状态。

是否有更好的方法来编写此内容,以便根据当前情况显示上下文菜单项?

您可以使用 contexts 属性 设置何时显示上下文菜单项。 在您的情况下,您似乎对网页上选定的文本感兴趣,有 selected 上下文(可以找到完整的上下文列表 here)。

当菜单项被点击时,选中的文本会被发送到菜单项的点击监听器,这里是一个例子:

browser.contextMenus.create({
  id: "log-selection",
  title: "Process Selection",
  contexts: ["selection"],
  onclick: (info, tab) => {
    console.log(info.selectionText);
  }
});