docs.rodeo

MDN Web Docs mirror

menus.create()

{{AddonSidebar}} 

Creates a menu item using an options object defining properties for the item.

Unlike other asynchronous functions, this one does not return a promise, but uses an optional callback to communicate success or failure. This is because its return value is the ID of the new item.

For compatibility with other browsers, Firefox makes this method available in the contextMenus namespace and menus namespace. However, it’s not possible to create tools menu items (contexts: ["tools_menu"]) using the contextMenus namespace.

Creating menus in persistent and non-persistent extensions

How you create menu items depends on whether your extension uses:

See Initialize the extension on the background scripts page and Event-driven background scripts on Extension Workshop for more information.

Syntax

browser.menus.create(
  createProperties, // object
  () => {/* … */}   // optional function
)

Parameters

Return value

integer or string. The ID of the newly created item.

Examples

This example creates a context menu item that’s shown when the user has selected some text in the page. It just logs the selected text to the console:

browser.menus.create({
  id: "log-selection",
  title: "Log '%s' to the console",
  contexts: ["selection"],
});

browser.menus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "log-selection") {
    console.log(info.selectionText);
  }
});

This example adds two radio items, which you can use to choose whether to apply a green or a blue border to the page. Note that this example will need the activeTab permission.

function onCreated() {
  if (browser.runtime.lastError) {
    console.log("error creating item:", browser.runtime.lastError);
  } else {
    console.log("item created successfully");
  }
}

browser.menus.create(
  {
    id: "radio-green",
    type: "radio",
    title: "Make it green",
    contexts: ["all"],
    checked: false,
  },
  onCreated,
);

browser.menus.create(
  {
    id: "radio-blue",
    type: "radio",
    title: "Make it blue",
    contexts: ["all"],
    checked: false,
  },
  onCreated,
);

let makeItBlue = 'document.body.style.border = "5px solid blue"';
let makeItGreen = 'document.body.style.border = "5px solid green"';

browser.menus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "radio-blue") {
    browser.tabs.executeScript(tab.id, {
      code: makeItBlue,
    });
  } else if (info.menuItemId === "radio-green") {
    browser.tabs.executeScript(tab.id, {
      code: makeItGreen,
    });
  }
});

{{WebExtExamples}} 

Browser compatibility

{{Compat}} 

[!NOTE] This API is based on Chromium’s chrome.contextMenus API. This documentation is derived from context_menus.json in the Chromium code.

In this article

View on MDN