Add contextmenu items to a Chrome extension's browser action button (Manifest v3)

Viewed 2080

I know the answer for manifest v2: Add contextmenu items to a Chrome extension's browser action button

It's been working fine until migrating manifest from v2 to v3.

My current manifest.json:

{
  "manifest_version": 3,
  "version": "0.1.1",
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "all_frames": false,
      "matches": ["http://*/*", "https://*/*"],
      "js": ["content.js"]
    }
  ],
  "permissions": ["contextMenus"],
   ...
}

And now this doesn't add a context menu item to my extension's browser action button:

chrome.contextMenus.create({
  id: 'foo',
  title: 'first',
  contexts: ['browser_action'],
  onclick: function () {
    alert('first')
  }
})

I checked that 'selection' context properly adds a context menu to the selected text on a web page. Is there something I have to do to migrate from v2 to v3?

1 Answers

Found a solution myself. The context should be 'action' instead of 'browser_action'. And it looks like onclick property has been deprecated. So, it should be something like:

chrome.contextMenus.create({
  id: 'foo',
  title: 'first',
  contexts: ['action']
})

function contextClick(info, tab) {
  const { menuItemId } = info

  if (menuItemId === 'foo') {
    // do something
  }
}

chrome.contextMenus.onClicked.addListener(contextClick)
Related