0

I'm trying to create a google chrome extension that will allow me to highlight selected text.

The error I get is: Unchecked runtime.lastError: Cannot create item with duplicate id highlight-red

It's also not highlighting in any colors.

The JS code:

chrome.contextMenus.create({
  id: "highlight-red",
  title: "Highlight Red",
  contexts: ["selection"]
});

chrome.contextMenus.create({
  id: "highlight-green",
  title: "Highlight Green",
  contexts: ["selection"]
});

chrome.contextMenus.create({
  id: "highlight-blue",
  title: "Highlight Blue",
  contexts: ["selection"]
});



chrome.contextMenus.onClicked.addListener((info, tab) => {
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: setCheck,
    args: [info]
  });
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: highlightSelection,
    args: [info]
  });
});

function setCheck(info) {
  var check = true;
}

function highlightSelection(info) {
  var color = info.menuItemId;
  var selection = window.getSelection().toString();
  var range = window.getSelection().getRangeAt(0);
  var newNode = document.createElement("span");
  newNode.setAttribute("style", "background-color: " + color + ";");
  newNode.appendChild(range.extractContents());
  range.insertNode(newNode);
}

I'm trying to highlight texts

Rui
  • 11
  • Please see [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Norio Yamamoto Jan 21 '23 at 08:58
  • @mplungjan - Creating an mcve for an extension-related problem isn't hard at all. Some of my answers contain the complete source code for small extensions that demonstrate or solve a problem. – Thomas Mueller Jan 21 '23 at 11:28
  • @ThomasMueller Ok. I was pretty convinced that SO would not allow it to run due to sandboxing – mplungjan Jan 21 '23 at 11:30
  • @mplungjan - That's right, you can't run them directly in SO. You need to copy and paste the source code into local files and then load them as an unpacked extension via chrome://extensions/ – Thomas Mueller Jan 21 '23 at 11:33
  • So I was correct. And so were you – mplungjan Jan 21 '23 at 11:38

0 Answers0