Skip to content
Advertisement

Why is my chrome Context Menu button not working when clicked?

New to extensions development here. I’m trying to build a simple extension where if the user highlights some text on the webpage and clicks on the defined context menu option then an alert message message is displayed. However, when the context menu option is clicked nothing happens. Not sure where I’m going wrong. Please help. Thanks!

Here is my code:

hello.js `

chrome.contextMenus.create(
    {
        id: "foo",
        "title": "click",
        "contexts": ["selection"]
    }
);

chrome.contextMenus.onClicked.addListener(
    (info, tab) => {
        alert("Hello");
        console.log("Hello");
    }
);

manifest.json `

{
    "manifest_version": 3,
    "name": "bar",
    "description": "Base Level Extension",
    "version": "1.0",

    "background": { 
      "service_worker": "hello.js"
    },

    "permissions": [
      "contextMenus"
    ]

}

Advertisement

Answer

I rewrote your program. I hope this works as you expected. Read the program comments carefully.

hello.js

chrome.runtime.onInstalled.addListener(() => {
  // If you call it directly, restarting Chrome will result in the following error.
  // Unchecked runtime.lastError: Cannot create item with duplicate id foo
  chrome.contextMenus.create({
    id: "foo",
    "title": "click",
    "contexts": ["selection"]
  });
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
  // Service worker cannot access the DOM, so alert() isn't available.
  //  alert("Hello");
  chrome.windows.create({
    width: 350,
    height: 250,
    top: 200,
    left: 400,
    type: "popup",
    url: "alert.html"
  });
  console.log("Hello");
});

alert.html

<!DOCTYPE html>
<html>
<style type="text/css">
  * {
    font-size: xx-large;
  }
</style>

<body>
  Hello
</body>

</html>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement