我正在编写我的第一个 Firefox 附加扩展,它主要通过文本框上的右键单击上下文菜单来工作。
我希望能够根据用户执行右键单击事件的文本框中当前是否选择了任何文本来显示/隐藏单个选项。
我已经能够使用内容脚本和后台脚本之间的消息来了解它的基础知识...
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脚本,因此菜单项的可见性变得基于在先前状态,而不是当前状态。
是否有更好的方法来编写此内容,以便 contextMenu 项根据当前情况可见?
最佳答案
您可以使用 contexts
属性设置何时显示上下文菜单项。
就您而言,您似乎对网页上选定的文本感兴趣,因此有 selected
上下文(完整的上下文列表可以在 here 中找到)。
当单击菜单项时,所选文本将发送到菜单项的单击监听器,下面是一个示例:
browser.contextMenus.create({
id: "log-selection",
title: "Process Selection",
contexts: ["selection"],
onclick: (info, tab) => {
console.log(info.selectionText);
}
});
关于javascript - Firefox AddOn 扩展中 contextMenu 选项的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57027930/