Я хотел выполнить то же самое, что и в оригинальном сообщении, и смог заставить его работать, используя некоторую передачу сообщений.Независимо от того, является ли это плохой практикой или нет, я использовал включенное (true / false) свойство contextMenu, чтобы оставить свой параметр контекстного меню присутствующим, но затемненным.
Я создал контекстное меню.Важным свойством является идентификатор.Остальное в основном произвольное, потому что оно будет изменяться динамически.
В content.js
//This event listener will determine if the context menu should be updated
//based on if the right-button was clicked and if there is a selection or not
document.addEventListener("mousedown", function(event){
if (event.button !== 2) {
return false;
}
var selected = window.getSelection().toString();
if(event.button == 2 && selected != '') {
//get selected text and send request to bkgd page to create menu
chrome.extension.sendMessage({
'message': 'updateContextMenu',
'selection': true});
} else {
chrome.extension.sendMessage({
'message': 'updateContextMenu',
'selection': false});
}
}, true);
В background.js:
//add a message listener that will modify the context menu however you see fit
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.message == 'updateContextMenu') {
if (request.selection) {
chrome.contextMenus.update('contextMenuId',{
'title': 'New Title',
'enabled': true,
"contexts": ["all"],
'onclick': someFunction
});
} else {
chrome.contextMenus.update('contextMenuId',{
'title': 'Select some text first',
'enabled': false,
"contexts": ["all"]
});
}
} else {
sendResponse({});
}
});
//The original context menu. The important property is the id. The rest is mostly
//arbitrary because it will be changed dynamically by the listener above.
chrome.contextMenus.create({
'id': 'contextMenuId',
'enabled': false,
'title': 'Some Title',
"contexts": ["all"]
});