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;
// …
}
});
添加回答
舉報