Edit line: I am using manifest v3.
chrome.contextMenus.create(...parameters...)
is used in background script (background.js) to add new items to context menu (right-click menu).
What I would like to do is to update the context menu item title when some text is selected on the page. When no text is selected, the title should revert to the original/ default state.
Normally this can be done with eventListeners. But, one problem I encountered while using eventListeners in background.js is that background.js runs before window.document
(even window
) object is built/ available.
So, as mentioned in another SO answer, I tried exploiting content scripts like this:
// THIS BLOCK IS INSIDE content-script.js
document.addEventListener("selectionchange", function(e) {
chrome.runtime.sendMessage({selection: getSelection().toString()});
});
And,
// THIS BLOCK is inside background.js
chrome.runtime.onMessage.addListener(updateTitle);
function updateTitle(msg) {
if ("selection" in msg)
{
chrome.contextMenus.update("#menuitemID", {title: "New Title"});
}
};
However, for whatever reason, the title does not update.
What am I doing wrong?