DEV Community

Franz Wong
Franz Wong

Posted on

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

Top comments (0)