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

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

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