1

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?

Xfce4
  • 557
  • 5
  • 28
  • 1
    If your extension is ManifestV3, you'll have to [keep the background script alive](https://stackoverflow.com/a/66618269), otherwise the message will be processed too late. – wOxxOm Dec 23 '21 at 17:43

1 Answers1

0

I definitely did not know how to configure manifest file correctly.

Added this block inside the manifest file and it worked:

"content_scripts": [
  {
    "js": ["content.js"],
    "matches": ["<all_urls>"]
  }
],
Xfce4
  • 557
  • 5
  • 28