DEV Community

Franz Wong
Franz Wong

Posted on

3

Add a Context Menu Item to Chrome Extension

I tried adding a context menu item. But I failed to do that at first time.

The code itself is simple.

chrome.contextMenus.create({
  id: 'my_menu_item',
  title: 'Click me',
  contexts: ['selection']
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'my_menu_item') {
    console.log('hello');
  }
});
Enter fullscreen mode Exit fullscreen mode

The first question is where I should put it.

I should put it in background script. I added a background script to manifest.json. (I am using v3.) Of course, I should also give it permission to change context menu.

"permissions": ["contextMenus"],
"background": {
  "service_worker": "background.js"
}
Enter fullscreen mode Exit fullscreen mode

I put the code to background.js and reload it. Now it shows an error.

Unchecked runtime.lastError: Cannot create item with duplicate id my_menu_item
Enter fullscreen mode Exit fullscreen mode

I should add it once. But how? It turns out that I should put it in the runtime's installed event listener.

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'my_menu_item',
    title: 'Click me',
    contexts: ['selection']
  });
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'my_menu_item') {
    console.log('hello');
  }
});
Enter fullscreen mode Exit fullscreen mode

Now the context menu works as expected.

One last thing, there is another problem I encountered when I worked on a extension. We can't add the installed event listener in asynchronous way. The event is not caught.

The following doesn't work.

(async() {
  chrome.runtime.onInstalled.addListener(() => {
    chrome.contextMenus.create({
      id: 'my_menu_item',
      title: 'Click me',
      contexts: ['selection']
    });
  });
})();
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay