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

1

6

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?

Nonrecognition answered 3/12, 2021 at 2:23 Comment(0)
N
27

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)
Nonrecognition answered 3/12, 2021 at 3:4 Comment(2)
does anyone know in manifest v3, how to have multiple contextMenu items (i.e. different ids) with multiple onclick listeners that execute different functions? or is there a way to pass the id of the contextMenu object when calling a single addListener() ? All the examples I've seen seem pretty base case, with only one contextMenu, while many applications have several contextMenus that may have different onclick functions. (This wasn't an issue in v2 because in v2 you could just declare the onclick function as an object within each contextMenus object).Delora
wesinat0r, the context menu's ID is passed in the "info" variable of the onclick function.Whorled

© 2022 - 2024 — McMap. All rights reserved.