3 回答
TA贡献1744条经验 获得超4个赞
您无法添加到“真实”菜单,但您可以伪造它并且无需禁用常规菜单。
监听上下文菜单事件,在合理的位置显示一个按钮,只要上下文菜单被触发,它就会出现。我把它放在左边,但你可以尝试一下。然后,您只需在单击或模糊时将其隐藏即可。
// The element to whose context menu the item should be added.
const element = document.getElementById('example');
// The menu item that should be added.
const menuItem = document.getElementById('menuItem');
// ...so listen for the contextmenu event on this element
element.addEventListener('contextmenu', e => {
//e.menuItems.add(menuItem); // How to get it into the menu?
menuItem.style.left = (e.clientX - menuItem.getBoundingClientRect().width) + "px";
menuItem.style.top = (e.clientY - menuItem.getBoundingClientRect().height) + "px";
menuItem.style.visibility = 'visible';
menuItem.focus();
});
// ...do this when you click the button:
menuItem.addEventListener('mousedown', e => {
menuItem.style.visibility = 'hidden'
menuItem.blur();
alert('the menu item has been clicked');
});
// ...hide the button onblur
menuItem.addEventListener('blur', e => {
menuItem.style.visibility = 'hidden';
});
#example{border:thin solid;padding:1em;}
#menuItem{visibility:hidden;position:absolute;width:80px;height:35px;outline: none;box-shadow: none;}
<p id="example">
I want to add an item to the context menu
that opens on this paragraph.
</p>
<!--
the element below is supposed to show
in the context menu instead of inline.
-->
<button
id="menuItem">
Click me!
</button>
TA贡献1797条经验 获得超6个赞
如果不使用WebExtension就无法修改浏览器上下文菜单,最好的解决方案是使用e.preventDefault()
它停止浏览器上下文菜单显示,然后添加您自己的上下文菜单(例如弹出窗口)。
TA贡献1807条经验 获得超9个赞
"permissions": ["contextMenus"]
browser.contextMenus.create(
{
id: "log-selection",
title: browser.i18n.getMessage("contextMenuItemSelectionLogger"),
contexts: ["selection"],
},
onCreated
);
browser.contextMenus.onClicked.addListener((info, tab) => {
switch (info.menuItemId) {
case "log-selection":
console.log(info.selectionText);
break;
// …
}
});
添加回答
举报