commands - Mozilla

commands
========

|  |  |
| --- | --- |
| Type | `Object` |
| Mandatory | No |
| Manifest version | 2 or higher |
| Example |
```json
"commands": {
  "toggle-feature": {
    "suggested\_key": {
      "default": "Ctrl+Shift+Y",
      "linux": "Ctrl+Shift+U"
    },
    "description": "Send a 'toggle-feature' event"
  }
}
```
 |

Use the **`commands`** key to define one or more keyboard shortcuts for your extension.

Each keyboard shortcut is defined with a **name**, a **combination of keys**, and a **description**. Once you've defined commands in your extension's `manifest.json`, you can listen for their associated key combinations with the `commands` JavaScript API.

Syntax
------

The `commands` key is an object, and each shortcut is a property of it. **The property's name is the name of the shortcut.**

Each shortcut's value is an object, with up to 2 properties:

1. `suggested_key`: the combination of keys that activate the shortcut.
2. `description`: a string that describes the shortcut; i.e. what it does.

The `suggested_key` property is an object with any of the following properties (all strings):

* `"default"`
* `"mac"`
* `"linux"`
* `"windows"`
* `"chromeos"`
* `"android"`
* `"ios"`

The value of each property is the keyboard shortcut for the command on that platform, as a string containing keys separated by "`+`". The value for `"default"` is used on all platforms that are not explicitly listed.

For example:

```json
"commands": {
  "toggle-feature": {
    "suggested\_key": {
      "default": "Alt+Shift+U",
      "linux": "Ctrl+Shift+U"
    },
    "description": "Send a 'toggle-feature' event to the extension"
  },
  "do-another-thing": {
    "suggested\_key": {
      "default": "Ctrl+Shift+Y"
    }
  }
}
```

This JSON defines 2 shortcuts:

1. `"toggle-feature"`, accessed with
 `Ctrl`
 +
 `Shift`
 +
 `U`
 on Linux, and
 `Alt`
 +
 `Shift`
 +
 `U`
 on all other platforms.
2. `"do-another-thing"`, accessed with
 `Ctrl`
 +
 `Shift`
 +
 `Y`
 on all platforms.

You could then listen for the `"toggle-feature"` command with code like this:

```js
browser.commands.onCommand.addListener((command) => {
  if (command === "toggle-feature") {
    console.log("Toggling the feature!");
  }
});
```

### Special shortcuts

There are these 4 **special shortcuts with default actions** for which the `commands.onCommand` event does not fire:

* `_execute_browser_action`: works like a click on a toolbar button created with `browserAction` or specified in the browser\_action key in the manifest.json key.
* `_execute_action`: works like a click on a toolbar button created with `action` or specified in the action key in the manifest.json key.
* `_execute_page_action`: works like a click on an address bar button created with `pageAction` or specified in the page\_action key in the manifest.json key.
* `_execute_sidebar_action`: opens the extension's sidebar specified in the sidebar\_action manifest.json key.

The availability of these special shortcuts varies between manifest versions and browsers, like this:

|  | Manifest V2 | Manifest V3 |
| --- | --- | --- |
| `_execute_browser_action` | Yes | No |
| `_execute_action` | No | Yes |
| `_execute_page_action` | Yes | Not available in Chromium-based browsers |
| `_execute_sidebar_action` | Firefox only | Firefox only |

For example, this JSON defines a key combination that clicks the extension's browser action:

```json
"commands": {
  "\_execute\_browser\_action": {
    "suggested\_key": {
      "default": "Ctrl+Shift+Y"
    }
  }
}
```

Shortcut values
---------------

There are two valid formats for shortcut keys: as a **key combination** or as a **media key**.

### Key combinations

**Note:** On Macs, `"Ctrl"` is interpreted as `"Command"`, so if you actually need `"Ctrl"`, specify `"MacCtrl"`.

Key combinations must consist of 2 or 3 keys:

1. **modifier** (mandatory, except for function keys). This can be any of: `"Ctrl"`, `"Alt"`, `"Command"`, or `"MacCtrl"`.
2. **secondary modifier** (optional). If supplied, this must be either `"Shift"` or (for Firefox ≥ 63) any one of `"Ctrl"`, `"Alt"`, `"Command"`, or `"MacCtrl"`. Must not be the modifier already used as the main modifier.
3. **key** (mandatory). This can be any one of:
    * the letters `A` – `Z`
    * the numbers `0` – `9`
    * the function keys `F1` – `F12`
    * `Comma`, `Period`, `Home`, `End`, `PageUp`, `PageDown`, `Space`, `Insert`, `Delete`, `Up`, `Down`, `Left`, `Right`

The key is then given as a string containing the set of key values, in the order listed above, separated by "`+`". For example, `"Ctrl+Shift+Z"`.

If a key combination is already used by the browser (like `"Ctrl+P"`) or by an existing add-on, then you can't override it. You can define it, but your event handler will not be called when the user presses the key combination.

### Media keys

Alternatively, the shortcut may be specified as one of the following media keys:

* `"MediaNextTrack"`
* `"MediaPlayPause"`
* `"MediaPrevTrack"`
* `"MediaStop"`
Updating shortcuts
------------------

Shortcuts can be updated via `commands.update()`. Users can also update shortcuts via the "Manage Extension Shortcuts" option at `about:addons` in Firefox, as shown in this video. In Chrome, users can change shortcuts at `chrome://extensions/shortcuts`.

Example
-------

Define a single keyboard shortcut, using only the default key combination:

```json
"commands": {
  "toggle-feature": {
    "suggested\_key": {
      "default": "Ctrl+Shift+Y"
    },
    "description": "Send a 'toggle-feature' event"
  }
}
```

Define two keyboard shortcuts, one with a platform-specific key combination:

```json
"commands": {
  "toggle-feature": {
    "suggested\_key": {
      "default": "Alt+Shift+U",
      "linux": "Ctrl+Shift+U"
    },
    "description": "Send a 'toggle-feature' event"
  },
  "do-another-thing": {
    "suggested\_key": {
      "default": "Ctrl+Shift+Y"
    }
  }
}
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


incognito - Mozilla

incognito
=========

|  |  |
| --- | --- |
| Type | `String` |
| Mandatory | No |
| Manifest version | 2 or higher |
| Example |
```json
"incognito": "spanning"
```

```json
"incognito": "split"
```

```json
"incognito": "not\_allowed"
```
 |

Use the `incognito` key to control how the extension works with private browsing windows.

**Note:** By default, extensions do not run in private browsing windows. Whether an extension can access private browsing windows is under user control. For details, see Extensions in Private Browsing. Your extension can check whether it can access private browsing windows using `extension.isAllowedIncognitoAccess`.

This is a string that can take any of these values:

* "spanning" (the default): the extension will see events from private and non-private windows and tabs. Windows and tabs will get an `incognito` property in the `Window` or `Tab` that represents them. This property indicates whether or not the object is private:

```js
browser.windows.getLastFocused().then((windowInfo) => {
  console.log(`Window is private: ${windowInfo.incognito}`);
});
```

* "split": the extension will be split between private and non-private windows. There are effectively two copies of the extension running: one sees only non-private windows, the other sees only private windows. Each copy has isolated access to Web APIs (so, for example, `localStorage` is not shared). However, the WebExtension API `storage.local` is shared. (**Note:** this setting is not supported by Firefox.)
* "not\_allowed": private tabs and windows are invisible to the extension.
Example
-------

```json
"incognito": "spanning"
```

```json
"incognito": "split"
```

```json
"incognito": "not\_allowed"
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


declarative_net_request - Mozilla

declarative\_net\_request
=========================

|  |  |
| --- | --- |
| Type | `Object` |
| Mandatory | No |
| Manifest version | 2 or higher |
| Example |
```json
"declarative\_net\_request" : {
  "rule\_resources" : [{
    "id": "ruleset",
    "enabled": true,
    "path": "rules.json"
  }]
}
```
 |

Specify static rulesets for use with `declarativeNetRequest`. See Permissions for more information on permission requirements.

Syntax
------

The `"declarative_net_request"` key is an object that must contain the `"rule_resources"` property, an array that must include at least one object with these properties:

| Name | Type | Description |
| --- | --- | --- |
| `"id"` | `String` | A non-empty string uniquely identifying the ruleset. IDs beginning with '\_' are reserved for internal use. |
| `"enabled"` | `Boolean` | Whether the ruleset is enabled by default. The `declarativeNetRequest.updateEnabledRulesets` method can be used to enable or disable a ruleset at runtime. |
| `"path"` | `String` | The path of the JSON ruleset relative to the extension directory. See the Rules section of the `declarativeNetRequest` API for information on the content of the ruleset JSON file. |

Example
-------

```json
"declarative\_net\_request" : {
  "rule\_resources" : [{
    "id": "ruleset\_1",
    "enabled": true,
    "path": "rules\_1.json"
  }, {
    "id": "ruleset\_2",
    "enabled": false,
    "path": "rules\_2.json"
  }]
}
```

Example extensions
------------------

* dnr-block-only
* dnr-redirect-url
Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


manifest_version - Mozilla

manifest\_version
=================

|  |  |
| --- | --- |
| Type | `Number` |
| Mandatory | Yes |
| Example |
```json
"manifest\_version": 3
```
 |

This key specifies the version of manifest.json used by this extension.

Example
-------

```json
"manifest\_version": 3
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Legacy Version Formats - Mozilla

Legacy Version Formats
======================

This page describes legacy web extension version string formats. See the manifest version key documentation for information on the current version string format.

Firefox legacy version number
-----------------------------

A **version string** consists of one or more *version parts*, separated by dots.

Each **version part** is parsed as a sequence of four parts: `<number-a><string-b><number-c><string-d>`. Each of the parts is optional. Numbers are integers base 10 (may be negative), and strings are non-numeric ASCII characters.

Here are a few examples of valid version parts:

* `0` (as in `1.0`): `<number-a>=0`
* `5a` (as in `1.5a`): `<number-a>=5`, `<string-b>=a`
* `5pre4` (as in `3.5pre4`): `<number-a>=5`, `<string-b>=pre`, `<number-c>=4`
* `*` (as in `1.0.*`): `<string-b>=*`

A few special parsing rules are applied for backward compatibility and readability:

* if the version part is a single asterisk, it is interpreted as an infinitely-large number:
 `1.5.0.*` is the same as `1.5.0.(infinity)`
* if string-b is a plus sign, number-a is incremented to be compatible with the Firefox 1.0.x version format:
 `1.0+` is the same as `1.1pre`

The rationale behind splitting a version part into a sequence of strings and numbers is that when comparing version parts, the numeric parts are compared as numbers, for example, '1.0pre1' < '1.0pre10', while the strings are compared byte-wise. See the next section for details on how versions are compared.

From Firefox 108, web extensions using this version string trigger a warning on installation.

Comparing versions
------------------

When two version strings are compared, their version parts are compared left to right. An empty or missing version part is equivalent to `0`.

If at some point, a version part of one version string is greater than the corresponding version part of another version string, then the first version string is greater than the other one.

Otherwise, the version strings are equal. As missing version parts are treated as if they were `0`, these version strings are equal: `1`, `1.0`, `1.0.`, `1.0.0`, and even `1.0..`.

### Comparing version parts

Version parts are also compared left to right; parts A and C are compared as numbers, while parts B and D are compared byte-wise. A string part that exists is always less than a string part that doesn't exist (`1.6a` is less than `1.6`).

Examples
--------
```

1.-1
< 1 == 1. == 1.0 == 1.0.0
< 1.1a < 1.1aa < 1.1ab < 1.1b < 1.1c
< 1.1pre == 1.1pre0 == 1.0+
< 1.1pre1a < 1.1pre1aa < 1.1pre1b < 1.1pre1
< 1.1pre2
< 1.1pre10
< 1.1.-1
< 1.1 == 1.1.0 == 1.1.00
< 1.10
< 1.* < 1.*.1
< 2.0
```


i18n - Mozilla

i18n
====

Functions to internationalize your extension. You can use these APIs to get localized strings from locale files packaged with your extension, find out the browser's current language, and find out the value of its Accept-Language header.

See the Internationalization page for a guide on using this API.

Types
-----

`i18n.LanguageCode`

A language tag such as `"en-US"` or "`fr`".

Functions
---------

`i18n.getAcceptLanguages()`

Gets the accept-languages of the browser. This is different from the locale used by the browser. To get the locale, use `i18n.getUILanguage`.

`i18n.getMessage()`

Gets the localized string for the specified message.

`i18n.getUILanguage()`

Gets the UI language of the browser. This is different from `i18n.getAcceptLanguages` which returns the preferred user languages.

`i18n.detectLanguage()`

Detects the language of the provided text using the Compact Language Detector.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* menu-accesskey-visible
* menu-demo
* notify-link-clicks-i18n

**Note:** This API is based on Chromium's `chrome.i18n` API. This documentation is derived from `i18n.json` in the Chromium code.

See also
--------

* Internationalization: a guide to using the WebExtension i18n system.
* Locale-Specific Message reference: extensions supply locale-specific strings in files called `messages.json`. This page describes the format of `messages.json`.


webNavigation - Mozilla

webNavigation
=============

Add event listeners for the various stages of a navigation. A navigation consists of a frame in the browser transitioning from one URL to another, usually (but not always) in response to a user action like clicking a link or entering a URL in the location bar.

Compared with the `webRequest` API: navigations usually result in the browser making web requests, but the webRequest API is concerned with the lower-level view from the HTTP layer, while the webNavigation API is more concerned with the view from the browser UI itself.

Each event corresponds to a particular stage in the navigation. The sequence of events is like this:

![Visualization of the primary flow and additional flows described below.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation/we-flow.png)

* The primary flow is:
    + ``onBeforeNavigate``
    + ``onCommitted``
    + ``onDOMContentLoaded``
    + ``onCompleted``.
* Additionally:
    + ``onCreatedNavigationTarget`` is fired before `onBeforeNavigate` if the browser needed to create a new tab or window for the navigation (for example, because the user opened a link in a new tab).
    + `onHistoryStateUpdated` is fired if a page uses the history API (2011) to update the URL displayed in the browser's location bar.
    + `onReferenceFragmentUpdated` is fired if the fragment identifier for a page is changed.
    + `onErrorOccurred` can be fired at any point.

Each navigation is a URL transition in a particular browser frame. The browser frame is identified by a tab ID and a frame ID. The frame may be the top-level browsing context in the tab, or may be a nested browsing context implemented as an iframe.

Each event's `addListener()` call accepts an optional filter parameter. The filter will specify one or more URL patterns, and the event will then only be fired for navigations in which the target URL matches one of the patterns.

The `onCommitted` event listener is passed two additional properties: a `TransitionType` indicating the cause of the navigation (for example, because the user clicked a link, or because the user selected a bookmark), and a `TransitionQualifier` providing further information about the navigation.

To use this API you need to have the "webNavigation" permission.

Types
-----

`webNavigation.TransitionType`

Cause of the navigation: for example, the user clicked a link, or typed an address, or clicked a bookmark.

`webNavigation.TransitionQualifier`

Extra information about a transition.

Functions
---------

`webNavigation.getFrame()`

Retrieves information about a particular frame. A frame may be the top-level frame in a tab or a nested iframe, and is uniquely identified by a tab ID and a frame ID.

`webNavigation.getAllFrames()`

Given a tab ID, retrieves information about all the frames it contains.

Events
------

`webNavigation.onBeforeNavigate`

Fired when the browser is about to start a navigation event.

`webNavigation.onCommitted`

Fired when a navigation is committed. At least part of the new document has been received from the server and the browser has decided to switch to the new document.

`webNavigation.onDOMContentLoaded`

Fired when the DOMContentLoaded event is fired in the page.

`webNavigation.onCompleted`

Fired when a document, including the resources it refers to, is completely loaded and initialized. This is equivalent to the DOM `load` event.

`webNavigation.onErrorOccurred`

Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, or the user aborted the navigation.

`webNavigation.onCreatedNavigationTarget`

Fired when a new window, or a new tab in an existing window, is created to host a navigation: for example, if the user opens a link in a new tab.

`webNavigation.onReferenceFragmentUpdated`

Fired if the fragment identifier for a page is changed.

`webNavigation.onTabReplaced`

Fired when the contents of the tab is replaced by a different (usually previously pre-rendered) tab.

`webNavigation.onHistoryStateUpdated`

Fired when the page used the history API (2011) to update the URL displayed in the browser's location bar.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* navigation-stats

**Note:** This API is based on Chromium's `chrome.webNavigation` API. This documentation is derived from `web_navigation.json` in the Chromium code.


browserSettings - Mozilla

browserSettings
===============

Enables an extension to modify certain global browser settings. Each property of this API is a `BrowserSetting` object, providing the ability to modify a particular setting.

Because these are global settings, it's possible for extensions to conflict. See the documentation for `BrowserSetting.set()` for details of how conflicts are handled.

To use this API you need to have the "browserSettings" permission.

Properties
----------

`browserSettings.allowPopupsForUserEvents`

Determines whether code running in web pages can display popups in response to user events.

`browserSettings.cacheEnabled`

Determines whether the browser cache is enabled or not.

`browserSettings.closeTabsByDoubleClick`

Determines whether the selected tab can be closed with a double click.

`browserSettings.colorManagement`

Determines various settings for color management.

`browserSettings.contextMenuShowEvent`

Determines the mouse event that triggers a context menu popup.

`browserSettings.ftpProtocolEnabled`

Determines whether the FTP protocol is enabled.

`browserSettings.homepageOverride`

Read the value of the browser's home page.

`browserSettings.imageAnimationBehavior`

Determines how the browser treats animated images.

`browserSettings.newTabPageOverride`

Reads the value of the browser's new tab page.

`browserSettings.newTabPosition`

Controls the position of newly opened tabs relative to already open tabs.

`browserSettings.openBookmarksInNewTabs`

Determines whether bookmarks are opened in the current tab or a new tab.

`browserSettings.openSearchResultsInNewTabs`

Determines whether search results are opened in the current tab or a new tab.

`browserSettings.openUrlbarResultsInNewTabs`

Determines whether address bar autocomplete suggestions are opened in the current tab or a new tab.

`browserSettings.overrideContentColorScheme`

Controls whether to override the browser theme (light or dark) when setting pages' preferred color scheme.

`browserSettings.overrideDocumentColors`

Controls whether the user-chosen colors override the page's colors.

`browserSettings.tlsVersionRestrictionConfig`

Read the highest and lowest versions of TLS supported by the browser.

`browserSettings.useDocumentFonts`

Controls whether the browser will use the fonts specified by a web page or use only built-in fonts.

`browserSettings.webNotificationsDisabled`

Prevents websites from showing notifications using the `Notification` Web API.

`browserSettings.zoomFullPage`

Controls whether zoom is applied to the entire page or to text only.

`browserSettings.zoomSiteSpecific`

Controls whether page zoom is applied on a per-site or per-tab basis. If `privacy.websites``.resistFingerprinting` is true, this setting has no effect and zoom is applied on a per-tab basis.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


sessions - Mozilla

sessions
========

Use the sessions API to list, and restore, tabs and windows that have been closed while the browser has been running.

The `sessions.getRecentlyClosed()` function returns an array of `tabs.Tab` and `windows.Window` objects, representing tabs and windows that have been closed since the browser was running, up to the maximum defined in `sessions.MAX_SESSION_RESULTS`.

You can then restore a window or tab using the `sessions.restore()` function. Restoring doesn't just reopen the tab: it also restores the tab's navigation history so the back/forward buttons will work.

This API also provides a group of functions that enable an extension to store additional state associated with a tab or a window. Then, if the tab or window is closed and subsequently restored, the extension can retrieve the state. For example, a tab grouping extension might use this to remember which group a tab is in, so as to restore it into the right group if the user restores the tab.

To use the sessions API you must have the "sessions" API permission.

Types
-----

`sessions.Filter`

Enables you to restrict the number of `Session` objects returned by a call to `sessions.getRecentlyClosed()`.

`sessions.Session`

Represents a tab or window that the user has closed in the current browsing session.

Properties
----------

`sessions.MAX_SESSION_RESULTS`

The maximum number of sessions that will be returned by a call to `sessions.getRecentlyClosed()`.

Functions
---------

`sessions.forgetClosedTab()`

Removes a closed tab from the browser's list of recently closed tabs.

`sessions.forgetClosedWindow()`

Removes a closed window from the browser's list of recently closed windows.

`sessions.getRecentlyClosed()`

Returns an array of `Session` objects, representing windows and tabs that were closed in the current browsing session (that is: the time since the browser was started).

`sessions.restore()`

Restores a closed tab or window.

`sessions.setTabValue()`

Store a key/value pair associated with a given tab.

`sessions.getTabValue()`

Retrieve a previously stored value for a given tab, given its key.

`sessions.removeTabValue()`

Remove a key/value pair from a given tab.

`sessions.setWindowValue()`

Store a key/value pair associated with a given window.

`sessions.getWindowValue()`

Retrieve a previously stored value for a given window, given its key.

`sessions.removeWindowValue()`

Remove a key/value pair from a given window.

Events
------

`sessions.onChanged`

Fired when a tab or window is closed.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* session-state

**Note:** This API is based on Chromium's `chrome.sessions` API.


search - Mozilla

search
======

Use the search API to retrieve the installed search engines and execute searches.

To use this API you need to have the `"search"` permission.

When choosing between `search.query()` and `search.search()`, consider the following:

* `search.query()` is available in most major browsers, making it ideal for use in cross-browser extensions. However, it can only issue searches against the browser's default search engine.
* `search.search()` is available only in Firefox. However, it has the advantage of being able to issue a search against any search engine installed in the browser.
Functions
---------

`search.get()`

Retrieve all search engines.

`search.query()`

Search using the browser's default search engine.

`search.search()`

Search using a specified search engine.

Example extensions
------------------

* menu-search
Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


menus - Mozilla

menus
=====

Add items to the browser's menu system.

This API is modeled on Chrome's "contextMenus" API, which enables Chrome extensions to add items to the browser's context menu. The `browser.menus` API adds a few features to Chrome's API.

Before Firefox 55 this API was also originally named `contextMenus`, and that name has been retained as an alias, so you can use `contextMenus` to write code that works in Firefox and also in other browsers.

To use this API you need to have the `menus` permission. You may also use the `contextMenus` alias instead of `menus`, but if you do, the APIs must be accessed as `browser.contextMenus` instead.

Except for `menus.getTargetElement()`, this API cannot be used from content scripts.

Creating menu items
-------------------

To create a menu item call the `menus.create()` method. You pass this method an object containing options for the item, including the item ID, item type, and the contexts in which it should be shown.

In a Firefox extension using non-persistent background pages (Event pages) or in any Chrome extension, you call `menus.create` from within a `runtime.onInstalled` listener. In a Firefox extension using persistent background pages, you make a top-level call. See `menus.create()` for more information.

Listen for clicks on your menu item by adding a listener to the `menus.onClicked` event. This listener will be passed a `menus.OnClickData` object containing the event's details.

You can create four different types of menu item, based on the value of the `type` property you supply in the options to `create()`:

* "normal": a menu item that just displays a label
* "checkbox": a menu item that represents a binary state. It displays a checkmark next to the label. Clicking the item toggles the checkmark. The click listener will be passed two extra properties: "checked", indicating whether the item is checked now, and "wasChecked", indicating whether the item was checked before the click event.
* "radio": a menu item that represents one of a group of choices. Just like a checkbox, this also displays a checkmark next to the label, and its click listener is passed "checked" and "wasChecked". However, if you create more than one radio item, then the items function as a group of radio items: only one item in the group can be checked, and clicking an item makes it the checked item.
* "separator": a line separating a group of items.

If you have created more than one context menu item or more than one tools menu item, then the items will be placed in a submenu. The submenu's parent will be labeled with the name of the extension. For example, here's an extension called "Menu demo" that's added two context menu items:

![Context menu with two items labeled click me, and click me too!](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/menus-1.png)

Icons
-----

If you've specified icons for your extension using the "icons" manifest key, your menu item will display the specified icon next to its label. The browser will try to choose a 16x16 pixel icon for a normal display or a 32x32 pixel icon for a high-density display:

![Context menu with two items labeled click me, and click me too!](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/menus-2.png)

Only for items in a submenu, you can specify custom icons by passing the `icons` option to `menus.create()`:

![Context menu with two items labeled click me, and click me too!. The click me option is labeled with a green paint can icon. The click me too option is labeled with a blue paint can icon.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/menus-3.png)

Example
-------

Here's a context menu containing 4 items: a normal item, two radio items with separators on each side, and a checkbox. The radio items are given custom icons.

![Context menu with four items labeled remove me, Greenify, Bluify, and uncheck me. Greenify and Bluify are radio buttons given custom icons.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/menus-4.png)

You could create a submenu like this using code like:

```js
browser.menus.create(
  {
    id: "remove-me",
    title: browser.i18n.getMessage("menuItemRemoveMe"),
    contexts: ["all"],
  },
  onCreated,
);

browser.menus.create(
  {
    id: "separator-1",
    type: "separator",
    contexts: ["all"],
  },
  onCreated,
);

browser.menus.create(
  {
    id: "greenify",
    type: "radio",
    title: browser.i18n.getMessage("menuItemGreenify"),
    contexts: ["all"],
    checked: true,
    icons: {
      16: "icons/paint-green-16.png",
      32: "icons/paint-green-32.png",
    },
  },
  onCreated,
);

browser.menus.create(
  {
    id: "bluify",
    type: "radio",
    title: browser.i18n.getMessage("menuItemBluify"),
    contexts: ["all"],
    checked: false,
    icons: {
      16: "icons/paint-blue-16.png",
      32: "icons/paint-blue-32.png",
    },
  },
  onCreated,
);

browser.menus.create(
  {
    id: "separator-2",
    type: "separator",
    contexts: ["all"],
  },
  onCreated,
);

let checkedState = true;

browser.menus.create(
  {
    id: "check-uncheck",
    type: "checkbox",
    title: browser.i18n.getMessage("menuItemUncheckMe"),
    contexts: ["all"],
    checked: checkedState,
  },
  onCreated,
);
```

Types
-----

`menus.ContextType`

The different contexts a menu can appear in.

`menus.ItemType`

The type of menu item: "normal", "checkbox", "radio", "separator".

`menus.OnClickData`

Information sent when a menu item is clicked.

Properties
----------

`menus.ACTION_MENU_TOP_LEVEL_LIMIT`

The maximum number of top level extension items that can be added to a menu item whose ContextType is "browser\_action" or "page\_action".

Functions
---------

`menus.create()`

Creates a new menu item.

`menus.getTargetElement()`

Returns the element for a given `info.targetElementId`.

`menus.overrideContext()`

Hide all default Firefox menu items in favor of providing a custom context menu UI.

`menus.refresh()`

Update a menu that's currently being displayed.

`menus.remove()`

Removes a menu item.

`menus.removeAll()`

Removes all menu items added by this extension.

`menus.update()`

Updates a previously created menu item.

Events
------

`menus.onClicked`

Fired when a menu item is clicked.

`menus.onHidden`

Fired when the browser hides a menu.

`menus.onShown`

Fired when the browser shows a menu.

Browser compatibility
---------------------

Example extensions
------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

* menu-accesskey-visible
* menu-demo
* menu-labelled-open
* menu-remove-element
* menu-search
* session-state

**Note:**

This API is based on Chromium's `chrome.contextMenus` API. This documentation is derived from `context_menus.json` in the Chromium code.


pageAction - Mozilla

pageAction
==========

The API to control address bar button.

![Paw print icon representing a page action](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction/page-action.png)

You can listen for clicks on the icon in a background script, or specify a popup that opens when the icon is clicked.

If you specify a popup, you define its contents and behavior using HTML, CSS, and JavaScript. JavaScript running in the popup gets access to all the same WebExtension APIs as your background scripts. Despite being named `pageAction`, the action code doesn't get access to web page content. To access web page DOM, you need to add a content script and interact with it.

The button also has a context menu, and you can add items to this menu with the `menus` API using the `page_action` `menus.ContextType`.

You can define most of a page action's properties declaratively using the `page_action` key in your `manifest.json`, and redefine them programmatically using this API.

Page actions are for actions that are only relevant to particular pages (such as "bookmark the current tab"). If they are relevant to the browser as a whole (such as "show all bookmarks"), use a browser action instead.

Types
-----

`pageAction.ImageDataType`

Pixel data for an image.

Functions
---------

`pageAction.show()`

Shows the page action for a given tab.

`pageAction.hide()`

Hides the page action for a given tab.

`pageAction.isShown()`

Checks whether the page action is shown or not.

`pageAction.setTitle()`

Sets the page action's title. This is displayed in a tooltip over the page action.

`pageAction.getTitle()`

Gets the page action's title.

`pageAction.setIcon()`

Sets the page action's icon.

`pageAction.setPopup()`

Sets the URL for the page action's popup.

`pageAction.getPopup()`

Gets the URL for the page action's popup.

`pageAction.openPopup()`

Opens the page action's popup.

Events
------

`pageAction.onClicked`

Fired when a page action icon is clicked. This event will not fire if the page action has a popup.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* apply-css
* chill-out
* history-deleter
* menu-remove-element

**Note:** This API is based on Chromium's `chrome.pageAction` API. This documentation is derived from `page_action.json` in the Chromium code.


windows - Mozilla

windows
=======

Interact with browser windows. You can use this API to get information about open windows and to open, modify, and close windows. You can also listen for window open, close, and activate events.

Types
-----

`windows.WindowType`

The type of browser window this is.

`windows.WindowState`

The state of this browser window.

`windows.Window`

Contains information about a browser window.

`windows.CreateType`

Specifies the type of browser window to create.

Constants
---------

`windows.WINDOW_ID_NONE`

The `windowId` value that represents the absence of a browser window.

`windows.WINDOW_ID_CURRENT`

A value that can be used in place of a `windowId` in some APIs to represent the current window.

Methods
-------

`windows.get()`

Gets details about a window, given its ID.

`windows.getCurrent()`

Gets the current window.

`windows.getLastFocused()`

Gets the window that was most recently focused — typically the window 'on top'.

`windows.getAll()`

Gets all windows.

`windows.create()`

Creates a new window.

`windows.update()`

Updates the properties of a window. Use this to move, resize, and (un)focus a window, etc.

`windows.remove()`

Closes a window, and all its tabs.

Events
------

`windows.onCreated`

Fired when a window is created.

`windows.onRemoved`

Fired when a window is closed.

`windows.onFocusChanged`

Fired when the currently focused window changes.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* annotate-page
* bookmark-it
* private-browsing-theme
* store-collected-images
* theme-integrated-sidebar
* window-manipulator

**Note:** This API is based on Chromium's `chrome.windows` API. This documentation is derived from `windows.json` in the Chromium code.


contentScripts - Mozilla

contentScripts
==============

Use this API to register content scripts. Registering a content script instructs the browser to insert the given content scripts into pages that match the given URL patterns.

**Note:** When using Manifest V3 or higher, use `scripting.registerContentScripts()` to register scripts.

This API is very similar to the `"content_scripts"` `manifest.json` key, except that with `"content_scripts"`, the set of content scripts and associated patterns is fixed at install time. With the `contentScripts` API, an extension can register and unregister scripts at runtime.

To use the API, call `contentScripts.register()` passing in an object defining the scripts to register, the URL patterns, and other options. This returns a `Promise` that is resolved with a `contentScripts.RegisteredContentScript` object.

The `RegisteredContentScript` object represents the scripts that were registered in the `register()` call. It defines an `unregister()` method that you can use to unregister the content scripts. Content scripts are also unregistered automatically when the page that created them is destroyed. For example, if they are registered from the background page they will be unregistered automatically when the background page is destroyed, and if they are registered from a sidebar or a popup, they will be unregistered automatically when the sidebar or popup is closed.

There is no `contentScripts` API permission, but an extension must have the appropriate host permissions for any patterns it passes to `register()`.

Types
-----

`contentScripts.RegisteredContentScript`

An object of this type is returned by the `contentScripts.register()` function. It represents the content scripts that were registered by that call, and can be used to unregister the content script.

Functions
---------

`contentScripts.register()`

Registers the given content scripts.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* content-script-register


alarms - Mozilla

alarms
======

Schedule code to run at a specific time in the future. This is like `setTimeout()` and `setInterval()`, except that those functions don't work with background pages that are loaded on demand.

Alarms do not persist across browser sessions. They are created globally across all contexts of a single extension. E.g. alarm created in background script will fire `onAlarm` event in background script, options page, popup page and extension tabs (and vice versa). Alarms API is not available in `Content scripts`.

To use this API you need to have the "alarms" permission.

Types
-----

`alarms.Alarm`

Information about a particular alarm.

Methods
-------

`alarms.clear()`

Clear a specific alarm, given its name.

`alarms.clearAll()`

Clear all scheduled alarms.

`alarms.create()`

Create a new alarm.

`alarms.get()`

Retrieves a specific alarm, given its name.

`alarms.getAll()`

Retrieve all scheduled alarms.

Events
------

`alarms.onAlarm`

Fired when an alarm goes off.

Example extensions
------------------

* chill-out
* dynamic-theme
Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.alarms` API.


identity - Mozilla

identity
========

Use the identity API to get an OAuth2 authorization code or access token, which an extension can then use to access user data from a service that supports OAuth2 access (such as Google or Facebook).

OAuth2 flows vary between service provider so, to use this API with a particular service provider, consult their documentation. For example:

* Google
* GitHub

The identity API provides the `identity.launchWebAuthFlow()` function. This authenticates the user with the service, if necessary, and asks the user to authorize the extension to access data, if necessary. The function completes with an access token or authorization code, depending on the provider.

The extension then completes the OAuth2 flow to get a validated access token, and uses the token in HTTPS requests to access the user's data according to the authorization the user gave.

To use this API, you must have the "identity" API permission.

Setup
-----

There's some setup you must do before publishing your extension.

### Getting the redirect URL

The redirect URL represents the end point of `identity.launchWebAuthFlow()`, in which the access token or authorization code is delivered to the extension. The browser extracts the result from the redirect URL without loading its response.

You get the redirect URL by calling `identity.getRedirectURL()`. This function derives a redirect URL from the add-on's ID. To simplify testing, set your add-on's ID explicitly using the `browser_specific_settings` key (otherwise, each time you temporarily install the add-on, you get a different redirect URL).

`identity.getRedirectURL()` returns a URL at a fixed domain name and a subdomain derived from the add-on's ID. Some OAuth servers (such as Google) only accept domains with a verified ownership as the redirect URL. As the dummy domain cannot be controlled by extension developers, the default domain cannot always be used.

However, loopback addresses are an accepted alternative that do not require domain validation (based on RFC 8252, section 7.3). Starting from Firefox 86, a loopback address with the format `http://127.0.0.1/mozoauth2/[subdomain of URL returned by identity.getRedirectURL()]` is permitted as a value for the redirect URL.

**Note:** Starting with Firefox 75, you must use the redirect URL returned by `identity.getRedirectURL()`. Earlier versions allowed you to supply any redirect URL.

Starting with Firefox 86, the special loopback address described above can be used too.

You'll use the redirect URL in two places:

* supply it when registering your extension as an OAuth2 client.
* pass it into `identity.launchWebAuthFlow()`, as a URL parameter added to that function's `url` argument.
### Registering your extension

Before you use OAuth2 with a service provider, you must register the extension with the provider as an OAuth2 client.

This will tend to be specific to the service provider, but in general it means creating an entry for your extension on the provider's website. In this process you supply your redirect URL, and receive a client ID (and sometimes also a secret). You need to pass both of these into `identity.launchWebAuthFlow()`.

Functions
---------

`identity.getRedirectURL()`

Gets the redirect URL.

`identity.launchWebAuthFlow()`

Launches WAF.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* google-userinfo

**Note:** This API is based on Chromium's `chrome.identity` API.


tabs - Mozilla

tabs
====

Interact with the browser's tab system.

**Note:** When using Manifest V3 or higher, the methods to execute scripts, insert CSS, and remove CSS are provided by the `scripting` API through the `scripting.executeScript()`, `scripting.insertCSS()` and `scripting.removeCSS()` methods.

You can use this API to get a list of opened tabs, filtered by various criteria, and to open, update, move, reload, and remove tabs. You can't directly access the content hosted by tabs using this API, but you can insert JavaScript and CSS into tabs using the `tabs.executeScript()` or `tabs.insertCSS()` APIs.

You can use most of this API without any special permission. However:

* To access `Tab.url`, `Tab.title`, and `Tab.favIconUrl` (or to filter by these properties via `tabs.query()`), you need to have the `"tabs"` permission, or have host permissions that match `Tab.url`.
    + Access to these properties by host permissions is supported since Firefox 86 and Chrome 50. In Firefox 85 and earlier, the "tabs" permission was required instead.
* To use `tabs.executeScript()` or `tabs.insertCSS()`, you must have the host permission for the tab

Alternatively, you can get these permissions temporarily, only for the currently active tab and only in response to an explicit user action, by asking for the `"activeTab"` permission.

Many tab operations use a Tab `id`. Tab `id`s are guaranteed to be unique to a single tab only within a browser session. If the browser is restarted, then it can and will reuse tab `id`s. To associate information with a tab across browser restarts, use `sessions.setTabValue()`.

Types
-----

`tabs.MutedInfoReason`

Specifies the reason a tab was muted or unmuted.

`tabs.MutedInfo`

This object contains a boolean indicating whether the tab is muted, and the reason for the last state change.

`tabs.PageSettings`

Used to control how a tab is rendered as a PDF by the `tabs.saveAsPDF()` method.

`tabs.Tab`

This type contains information about a tab.

`tabs.TabStatus`

Indicates whether the tab has finished loading.

`tabs.WindowType`

The type of window that hosts this tab.

`tabs.ZoomSettingsMode`

Defines whether zoom changes are handled by the browser, by the extension, or are disabled.

`tabs.ZoomSettingsScope`

Defines whether zoom changes will persist for the page's origin, or only take effect in this tab.

`tabs.ZoomSettings`

Defines zoom settings `mode`, `scope`, and default zoom factor.

Properties
----------

`tabs.TAB_ID_NONE`

A special ID value given to tabs that are not browser tabs (for example, tabs in devtools windows).

Functions
---------

`tabs.captureTab()`

Creates a data URL encoding an image of the visible area of the given tab.

`tabs.captureVisibleTab()`

Creates a data URL encoding an image of the visible area of the currently active tab in the specified window.

`tabs.connect()`

Sets up a messaging connection between the extension's background scripts (or other privileged scripts, such as popup scripts or options page scripts) and any content scripts running in the specified tab.

`tabs.create()`

Creates a new tab.

`tabs.detectLanguage()`

Detects the primary language of the content in a tab.

`tabs.discard()`

Discards one or more tabs.

`tabs.duplicate()`

Duplicates a tab.

`tabs.executeScript()` (Manifest V2 only)

Injects JavaScript code into a page.

`tabs.get()`

Retrieves details about the specified tab.

`tabs.getAllInWindow()`
Deprecated

Gets details about all tabs in the specified window.

`tabs.getCurrent()`

Gets information about the tab that this script is running in, as a `tabs.Tab` object.

`tabs.getSelected()`
Deprecated

Gets the tab that is selected in the specified window. **Deprecated: use `tabs.query({active: true})` instead.**

`tabs.getZoom()`

Gets the current zoom factor of the specified tab.

`tabs.getZoomSettings()`

Gets the current zoom settings for the specified tab.

`tabs.goForward()`

Go forward to the next page, if one is available.

`tabs.goBack()`

Go back to the previous page, if one is available.

`tabs.hide()`
Experimental

Hides one or more tabs.

`tabs.highlight()`

Highlights one or more tabs.

`tabs.insertCSS()` (Manifest V2 only)

Injects CSS into a page.

`tabs.move()`

Moves one or more tabs to a new position in the same window or to a different window.

`tabs.moveInSuccession()`

Modifies the succession relationship for a group of tabs.

`tabs.print()`

Prints the contents of the active tab.

`tabs.printPreview()`

Opens print preview for the active tab.

`tabs.query()`

Gets all tabs that have the specified properties, or all tabs if no properties are specified.

`tabs.reload()`

Reload a tab, optionally bypassing the local web cache.

`tabs.remove()`

Closes one or more tabs.

`tabs.removeCSS()` (Manifest V2 only)

Removes from a page CSS which was previously injected by calling `tabs.insertCSS()`.

`tabs.saveAsPDF()`

Saves the current page as a PDF.

`tabs.sendMessage()`

Sends a single message to the content script(s) in the specified tab.

`tabs.sendRequest()`
Deprecated

Sends a single request to the content script(s) in the specified tab. **Deprecated**: use `tabs.sendMessage()` instead.

`tabs.setZoom()`

Zooms the specified tab.

`tabs.setZoomSettings()`

Sets the zoom settings for the specified tab.

`tabs.show()`
Experimental

Shows one or more tabs that have been `hidden`.

`tabs.toggleReaderMode()`

Toggles Reader mode for the specified tab.

`tabs.update()`

Navigate the tab to a new URL, or modify other properties of the tab.

`tabs.warmup()`

Prepare the tab to make a potential following switch faster.

Events
------

`tabs.onActivated`

Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired.

`tabs.onActiveChanged`
Deprecated

Fires when the selected tab in a window changes. **Deprecated:** use `tabs.onActivated` instead.

`tabs.onAttached`

Fired when a tab is attached to a window, for example because it was moved between windows.

`tabs.onCreated`

Fired when a tab is created. Note that the tab's URL may not be set at the time this event fired.

`tabs.onDetached`

Fired when a tab is detached from a window, for example because it is being moved between windows.

`tabs.onHighlightChanged`
Deprecated

Fired when the highlighted or selected tabs in a window change. **Deprecated:** use `tabs.onHighlighted` instead.

`tabs.onHighlighted`

Fired when the highlighted or selected tabs in a window change.

`tabs.onMoved`

Fired when a tab is moved within a window.

`tabs.onRemoved`

Fired when a tab is closed.

`tabs.onReplaced`

Fired when a tab is replaced with another tab due to prerendering.

`tabs.onSelectionChanged`
Deprecated

Fires when the selected tab in a window changes. **Deprecated:** use `tabs.onActivated` instead.

`tabs.onUpdated`

Fired when a tab is updated.

`tabs.onZoomChange`

Fired when a tab is zoomed.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* annotate-page
* apply-css
* beastify
* bookmark-it
* chill-out
* commands
* context-menu-copy-link-with-types
* contextual-identities
* cookie-bg-picker
* devtools-panels
* find-across-tabs
* firefox-code-search
* history-deleter
* imagify
* list-cookies
* menu-demo
* menu-labelled-open
* menu-remove-element
* open-my-page-button
* permissions
* session-state
* store-collected-images
* tabs-tabs-tabs

**Note:** This API is based on Chromium's `chrome.tabs` API. This documentation is derived from `tabs.json` in the Chromium code.


bookmarks - Mozilla

bookmarks
=========

The WebExtensions `bookmarks` API lets an extension interact with and manipulate the browser's bookmarking system. You can use it to bookmark pages, retrieve existing bookmarks, and edit, remove, and organize bookmarks.

To use this API, an extension must request the "bookmarks" permission in its `manifest.json` file.

Extensions cannot create, modify, or delete bookmarks in the root node of the bookmarks tree. Doing so causes an error with the message: "*The bookmark root cannot be modified*"

Types
-----

`bookmarks.BookmarkTreeNode`

Represents a bookmark or folder in the bookmarks tree.

`bookmarks.BookmarkTreeNodeType`

A `String` enum which describes whether a node in the tree is a bookmark, a folder, or a separator.

`bookmarks.BookmarkTreeNodeUnmodifiable`

A `String` enum which specifies why a bookmark or folder is unmodifiable.

`bookmarks.CreateDetails`

Contains information which is passed to the `bookmarks.create()` function when creating a new bookmark.

Functions
---------

`bookmarks.create()`

Creates a bookmark or folder.

`bookmarks.get()`

Retrieves one or more `BookmarkTreeNode`s, given a bookmark's ID or an array of bookmark IDs.

`bookmarks.getChildren()`

Retrieves the children of the specified `BookmarkTreeNode`.

`bookmarks.getRecent()`

Retrieves a requested number of recently added bookmarks.

`bookmarks.getSubTree()`

Retrieves part of the bookmarks tree, starting at the specified node.

`bookmarks.getTree()`

Retrieves the entire bookmarks tree into an array of `BookmarkTreeNode` objects.

`bookmarks.move()`

Moves the specified `BookmarkTreeNode` to a new location in the bookmark tree.

`bookmarks.remove()`

Removes a bookmark or an empty bookmark folder, given the node's ID.

`bookmarks.removeTree()`

Recursively removes a bookmark folder; that is, given the ID of a folder node, removes that node and all its descendants.

`bookmarks.search()`

Searches for `BookmarkTreeNode`s matching a specified set of criteria.

`bookmarks.update()`

Updates the title and/or URL of a bookmark, or the name of a bookmark folder, given the bookmark's ID.

Events
------

`bookmarks.onCreated`

Fired when a bookmark or folder is created.

`bookmarks.onRemoved`

Fired when a bookmark or folder is removed. When a folder is removed recursively, a single notification is fired for the folder, and none for its contents.

`bookmarks.onChanged`

Fired when a bookmark or folder changes. Currently, only `title` and `url` changes trigger this.

`bookmarks.onMoved`

Fired when a bookmark or folder is moved to a different parent folder or to a new offset within its folder.

`bookmarks.onChildrenReordered`

Fired when the user has sorted the children of a folder in the browser's UI. This is not called as a result of a `move()`.

`bookmarks.onImportBegan`

Fired when a bookmark import session is begun. Expensive observers should ignore `bookmarks.onCreated` updates until `bookmarks.onImportEnded` is fired. Observers should still handle other notifications immediately.

`bookmarks.onImportEnded`

Fired when a bookmark import session has finished.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* bookmark-it

**Note:** This API is based on Chromium's `chrome.bookmarks` API. This documentation is derived from `bookmarks.json` in the Chromium code.


cookies - Mozilla

cookies
=======

Enables extensions to get and set cookies, and be notified when they change.

Permissions
-----------

To use this API, an add-on must specify the "cookies" API permission in its manifest.json file, along with host permissions for any sites for which it wishes to access cookies. The add-on may read or write any cookies which could be read or written by a URL matching the host permissions. For example:

`http://*.example.com/`

An add-on with this host permission may:

* Read a non-secure cookie for `www.example.com`, with any path.
* Write a secure or non-secure cookie for `www.example.com`, with any path.

It may *not*:

* Read a secure cookie for `www.example.com`.

`http://www.example.com/`

An add-on with this host permission may:

* Read a non-secure cookie for `www.example.com`, with any path.
* Read a non-secure cookie for `.example.com`, with any path.
* Write a secure or non-secure cookie for `www.example.com` with any path.
* Write a secure or non-secure cookie for `.example.com` with any path.

It may *not*:

* Read or write a cookie for `foo.example.com`.
* Read or write a cookie for `foo.www.example.com`.

`*://*.example.com/`

An add-on with this host permission may:

* Read or write a secure or non-secure cookie for `www.example.com` with any path.

Tracking protection
-------------------

Trackers use third-party cookies, that is, cookies set by a website other than the one you are on, to identify the websites you visit. For example:

1. You visit `a-shopping-site.com`, which uses `ad-tracker.com` to deliver its adverts on the web. `ad-tracker.com` sets a cookie associated with the `ad-tracker.com` domain. While you are on `a-shopping-site.com`, `ad-tracker.com` receives information about the products you browse.
2. You now visit `a-news-site.com` that uses `ad-tracker.com` to deliver adverts. `ad-tracker.com` read its cookie and use the information collected from `a-shopping-site.com` to decide which adverts to display to you.

Firefox includes features to prevent tracking. These features separate cookies so that trackers cannot make an association between websites visited. So, in the preceding example, `ad-tracker.com` cannot see the cookie created on `a-news-site.com` when visiting `a-shopping-site.com`. The first iteration of this protection was first-party isolation which is now being superseded by dynamic partitioning.

**Note:** First-party isolation and dynamic partitioning will not be active at the same time. If the user or an extension turns on first-party isolation, it takes precedence over dynamic partitioning. However, when private browsing uses dynamic partitioning, normal browsing may not be partitioning cookies. See Status of partitioning in Firefox, for details.

### Storage partitioning

When using dynamic partitioning, Firefox partitions the storage accessible to JavaScript APIs by top-level site while providing appropriate access to unpartitioned storage to enable common use cases. This feature is being rolled out progressively. See Status of partitioning in Firefox, for implementation details.

Storage partitions are keyed by the schemeful URL of the top-level website and, when dynamic partitioning is active, the key value is available through the `partitionKey.topLevelSite` property in the cookies API, for example, `partitionKey: {topLevelSite: "http://site"}`.

Generally, top-level documents are in unpartitioned storage, while third-party iframes are in partitioned storage. If a partition key cannot be determined, the default (unpartitioned storage) is used. For example, while all HTTP(S) sites can be used as a partition key, `moz-extension:-` URLs cannot. Therefore, iframes in Firefox's extension documents do not use partitioned storage.

By default, `cookies.get()`, `cookies.getAll()`, `cookies.set()`, and `cookies.remove()` work with cookies in unpartitioned storage. To work with cookies in partitioned storage in these APIs, `topLevelSite` in `partitionKey` must be set. The exception is `getAll` where setting `partitionKey` without `topLevelSite` returns cookies in partitioned and unpartitioned storage. `cookies.onChanged` fires for any cookie that the extension can access, including cookies in partitioned storage. To ensure that the correct cookie is modified, extensions should read the `cookie.partitionKey` property from the event and pass its value to `cookies.set()` and `cookies.remove()`.

### First-party isolation

When first-party isolation is on, cookies are qualified by the domain of the original page the user visited (essentially, the domain shown to the user in the URL bar, also known as the "first party domain").

First-party isolation can be enabled by the user by adjusting the browser's configuration and set by extensions using the `firstPartyIsolate` setting in the `privacy` API. Note that first-party isolation is enabled by default in Tor Browser.

In the `cookies` API, the first party domain is represented using the `firstPartyDomain` attribute. All cookies set while first-party isolation is on have this attribute set to the domain of the original page. In the preceding example, this is `a-shopping-site.com` for one cookie and `a-news-site.com` for the other. When first-party isolation is off, all cookies set by websites have this property set to an empty string.

The `cookies.get()`, `cookies.getAll()`, `cookies.set()` and `cookies.remove()` APIs all accept a `firstPartyDomain` option.

When first-party isolation is on, you must provide this option or the API call will fail and return a rejected promise. For `get()`, `set()`, and `remove()` you must pass a string value. For `getAll()`, you may also pass `null` here, and this will get all cookies, whether or not they have a non-empty value for `firstPartyDomain`.

When first-party isolation is off, the `firstPartyDomain` parameter is optional and defaults to an empty string. A non-empty string can be used to retrieve or modify first-party isolation cookies. Likewise, passing `null` as `firstPartyDomain` to `getAll()` will return all cookies.

Types
-----

`cookies.Cookie`

Represents information about an HTTP cookie.

`cookies.CookieStore`

Represents a cookie store in the browser.

`cookies.OnChangedCause`

Represents the reason a cookie changed.

`cookies.SameSiteStatus`

Represents the same-site status of the cookie.

Methods
-------

`cookies.get()`

Retrieves information about a single cookie.

`cookies.getAll()`

Retrieves all cookies that match a given set of filters.

`cookies.set()`

Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.

`cookies.remove()`

Deletes a cookie by name.

`cookies.getAllCookieStores()`

Lists all existing cookie stores.

Event handlers
--------------

`cookies.onChanged`

Fired when a cookie is set or removed.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* cookie-bg-picker
* list-cookies

**Note:** This API is based on Chromium's `chrome.cookies` API. This documentation is derived from `cookies.json` in the Chromium code.


storage - Mozilla

storage
=======

Enables extensions to store and retrieve data, and listen for changes to stored items.

The storage system is based on the Web Storage API, with a few differences. Among other differences, these include:

* It's asynchronous.
* Values are scoped to the extension, not to a specific domain (i.e. the same set of key/value pairs are available to all scripts in the background context and content scripts).
* The values stored can be any JSON-ifiable value, not just `String`. Among other things, this includes: `Array` and `Object`, but only when their contents can be represented as JSON, which does not include DOM nodes. You don't need to convert your values to JSON `Strings` prior to storing them, but they are represented as JSON internally, thus the requirement that they be JSON-ifiable.
* Multiple key/value pairs can be set or retrieved in the same API call.

To use this API you need to include the `"storage"` permission in your `manifest.json` file.

Each extension has its own storage area, which can be split into different types of storage.

Although this API is similar to `Window.localStorage` it is recommended that you don't use `Window.localStorage` in the extension code to store extension-related data. Firefox will clear data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons, while data saved using the `storage.local` API will be correctly persisted in these scenarios.

You can examine the stored data under the Extension Storage item in the Storage Inspector tab of the developer toolbox, accessible from `about:debugging`.

**Note:** The storage area is not encrypted and shouldn't be used for storing confidential user information.

Types
-----

`storage.StorageArea`

An object representing a storage area.

`storage.StorageChange`

An object representing a change to a storage area.

Properties
----------

`storage` has four properties, which represent the different types of available storage area.

`storage.local`

Represents the `local` storage area. Items in `local` storage are local to the machine the extension was installed on.

`storage.managed`

Represents the `managed` storage area. Items in `managed` storage are set by the domain administrator and are read-only for the extension. Trying to modify this namespace results in an error.

`storage.session`

Represents the `session` storage area. Items in `session` storage are stored in memory and are not persisted to disk.

`storage.sync`

Represents the `sync` storage area. Items in `sync` storage are synced by the browser, and are available across all instances of that browser that the user is logged into, across different devices.

Events
------

`storage.onChanged`

Fired when one or more items change in any of the storage areas.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* annotate-page
* favourite-colour
* forget-it
* navigation-stats
* proxy-blocker
* quicknote
* stored-credentials

**Note:** This API is based on Chromium's `chrome.storage` API. This documentation is derived from `storage.json` in the Chromium code.


notifications - Mozilla

notifications
=============

Display notifications to the user, using the underlying operating system's notification mechanism. Because this API uses the operating system's notification mechanism, the details of how notifications appear and behave may differ according to the operating system and the user's settings.

To use this API you need to have the "notifications" permission.

The notification looks the same on all desktop operating systems. Something like:

![Example notification with a bold title and regular text](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications/notification.png)

Types
-----

`notifications.NotificationOptions`

Defines the content of a notification.

`notifications.TemplateType`

The type of notification. For example, this defines whether the notification can contain an image.

Functions
---------

`notifications.clear()`

Clear a specific notification, given its ID.

`notifications.create()`

Create and display a new notification.

`notifications.getAll()`

Get all notifications.

`notifications.update()`

Update a notification.

Events
------

`notifications.onButtonClicked`

Fired when the user clicked a button in the notification.

`notifications.onClicked`

Fired when the user clicked the notification, but not on a button.

`notifications.onClosed`

Fired when a notification closed, either by the system or because the user dismissed it.

`notifications.onShown`

Fired immediately after a notification has been shown.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* export-helpers
* forget-it
* google-userinfo
* notify-link-clicks-i18n
* runtime-examples

**Note:** This API is based on Chromium's `chrome.notifications` API.


privacy - Mozilla

privacy
=======

Access and modify various privacy-related browser settings.

To use the privacy API, you must have the "privacy" API permission.

Properties
----------

`privacy.network`

Access and modify privacy settings relating to the network.

`privacy.services`

Access and modify privacy settings relating to the services provided by the browser or third parties.

`privacy.websites`

Access and modify privacy settings relating to the behavior of websites.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.privacy` API.


dom - Mozilla

dom
===

Access special extension only DOM features.

Functions
---------

`dom.openOrClosedShadowRoot()`

Gets the open shadow root or the closed shadow root hosted by the specified element. If the shadow root isn't attached to the element, it will return `null`.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


proxy - Mozilla

proxy
=====

Use the proxy API to proxy web requests. You can use the `proxy.onRequest` event listener to intercept web requests, and return an object that describes whether and how to proxy them.

The advantage of the `proxy.onRequest` approach is that the code that implements your proxy policy runs in your extension's background script, so it gets full access to the WebExtension APIs available to your extension (including, for example, access to your extension's `storage` and networking APIs like `dns`).

Apart from this API, extensions can also use the `browserSettings.proxyConfig` property to configure global proxy settings.

Google Chrome provides an extension API also called "proxy" which is functionally similar to this API, in that extensions can use it to implement a proxying policy. However, the design of the Chrome API is completely different to this API. Because this API is incompatible with the Chrome `proxy` API, this API is only available through the `browser` namespace.

To use this API you need to have the "proxy" permission. Also, where you want to intercept requests, you also need host permission for the URLs of intercepted requests.

**Note:** The "proxy" permission requires `"strict_min_version"` to be set to "91.1.0" or above. To use this permission, add or update the `"browser_specific_settings"` key in your manifest.json to specify a minimum Firefox version. See Securing the proxy API for Firefox add-ons for more information.

**Note:** The browser can make speculative connections, where it determines that a request to a URI may be coming soon. This type of connection does not provide valid tab information, so request details such as `tabId`, `frameId`, `parentFrameId`, etc. are inaccurate. These connections have a `webRequest.ResourceType` of `speculative`.

Types
-----

`proxy.ProxyInfo`

Describes a proxy.

`proxy.RequestDetails`

Contains information about a web request that the browser is about to make.

Properties
----------

`proxy.settings`

Get and set proxy settings.

Events
------

`proxy.onError`

Fired when the system encounters an error running the PAC script or the `onRequest` listener.

`proxy.onRequest`

Fired when a web request is about to be made, giving the extension an opportunity to proxy it.

Example extensions
------------------

* proxy-blocker
Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


sidebarAction - Mozilla

sidebarAction
=============

Gets and sets properties of an extension's sidebar.

A sidebar is a pane that is displayed at the left-hand or right-hand side of the browser window, next to the web page. The browser provides a UI that enables the user to see the currently available sidebars and to select a sidebar to display. Using the `sidebar_action` manifest.json key, an extension can define its own sidebar. Using the `sidebarAction` API described here, an extension can get and set the sidebar's properties.

The `sidebarAction` API is closely modeled on the `browserAction` API.

The sidebarAction API is based on Opera's sidebarAction API. However, note that the following are not yet supported: `setBadgeText()`, `getBadgeText()`, `setBadgeBackgroundColor()`, `getBadgeBackgroundColor()`, `onFocus`, `onBlur`.

Types
-----

`sidebarAction.ImageDataType`

Pixel data for an image. Must be an `ImageData` object (for example, from a `<canvas>` element).

Functions
---------

`sidebarAction.close()`

Closes the sidebar.

`sidebarAction.getPanel()`

Gets the sidebar's panel.

`sidebarAction.getTitle()`

Gets the sidebar's title.

`sidebarAction.isOpen()`

Checks whether the sidebar is open or not.

`sidebarAction.open()`

Opens the sidebar.

`sidebarAction.setIcon()`

Sets the sidebar's icon.

`sidebarAction.setPanel()`

Sets the sidebar's panel.

`sidebarAction.setTitle()`

Sets the sidebar's title. This will be displayed in any UI provided by the browser to list sidebars, such as a menu.

`sidebarAction.toggle()`

Toggles the visibility of the sidebar.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example add-ons
---------------

* annotate-page

**Note:** This API is based on Opera's `chrome.sidebarAction` API.


userScripts - Mozilla

userScripts
===========

Use this API to register user scripts, third-party scripts designed to manipulate webpages or provide new features. Registering a user script instructs the browser to attach the script to pages that match the URL patterns specified during registration.

**Note:** When using Manifest V3 or higher, use `scripting.registerContentScripts()` to register scripts.

This API offers similar capabilities to `contentScripts` but with features suited to handling third-party scripts:

* execution is in an isolated sandbox: each user script is run in an isolated sandbox within the web content processes, preventing accidental or deliberate interference among scripts.
* access to the `window` and `document` global values related to the webpage the user script is attached to.
* no access to WebExtension APIs or associated permissions granted to the extension: the API script, which inherits the extension's permissions, can provide packaged WebExtension APIs to registered user scripts. An API script is declared in the extension's manifest file using the "user\_scripts" manifest key.

**Warning:** This API requires the presence of the `user_scripts` key in the manifest.json, even if no API script is specified. For example. `user_scripts: {}`.

To use the API, call ``register()`` passing in an object defining the scripts to register. The method returns a Promise that is resolved with a ``RegisteredUserScript`` object.

**Note:** User scripts are unregistered when the related extension page (from which the user scripts were registered) is unloaded, so you should register a user script from an extension page that persists at least as long as you want the user scripts to stay registered.

Types
-----

`userScripts.RegisteredUserScript`

The `object` returned by the `register()` method. It represents the registered user scripts and is used to deregister the user scripts.

Methods
-------

`userScripts.register()`

Registers user scripts.

Events
------

`userScripts.onBeforeScript`

An event available to the API script, registered in`"user_scripts"`, that execute before a user script executes. Use it to trigger the export of the additional APIs provided by the API script, so they are available to the user script.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Working with `userScripts`
* `browser.contentScripts`


contextualIdentities - Mozilla

contextualIdentities
====================

Work with contextual identities: list, create, remove, and update contextual identities.

"Contextual identities", also known as "containers", are a browser feature that lets users assume multiple identities when browsing the web, and maintain some separation between these identities. For example, a user might consider their "work identity" separate from their "personal identity", and not want to share cookies between these two contexts.

With the contextual identities feature, each contextual identity has a name, a color, and an icon. New tabs can be assigned to an identity, and the name, icon, and color appears in the address bar. Internally, each identity gets a cookie store that is not shared with other tabs. This cookie store is identified by the `cookieStoreId` in this and other APIs.

![A context menu with "open in new container tab" submenu highlighted. The submenu shows personal, work, banking, and shopping contextual identities.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/contextualIdentities/containers.png)Contextual identities are an experimental feature in Firefox and are only enabled by default in Firefox Nightly. To enable them in other versions of Firefox, set the `privacy.userContext.enabled` preference to `true`. Note that although contextual identities are available in Firefox for Android, there's no UI to work with them in this version of the browser.

Before Firefox 57, the `contextualIdentities` API is only available if the contextual identities feature is itself enabled. If an extension tried to use the `contextualIdentities` API without the feature being enabled, then method calls would resolve their promises with `false`.

From Firefox 57 onwards, if an extension that uses the `contextualIdentities` API is installed, then the contextual identities feature will be enabled automatically. Note though that it's still possible for the user to disable the feature using the "privacy.userContext.enabled" preference. If this happens, then `contextualIdentities` method calls will reject their promises with an error message.

See Work with contextual identities for more information.

Contextual identities are not supported in any other browsers.

To use this API you need to include the "contextualIdentities" and "cookies" permissions in your manifest.json file.

Types
-----

`contextualIdentities.ContextualIdentity`

Contains information about a contextual identity.

Functions
---------

`contextualIdentities.create()`

Creates a new contextual identity.

`contextualIdentities.get()`

Retrieves a contextual identity, given its cookie store ID.

`contextualIdentities.move()`

Moves one or more contextual identities within the list of contextual identities.

`contextualIdentities.query()`

Retrieves all contextual identities, or all contextual identities with a particular name.

`contextualIdentities.update()`

Updates properties of an existing contextual identity.

`contextualIdentities.remove()`

Deletes a contextual identity.

Events
------

`contextualIdentities.onCreated`

Fired when a contextual identity is created.

`contextualIdentities.onRemoved`

Fired when a contextual identity is removed.

`contextualIdentities.onUpdated`

Fired when one or more properties of a contextual identity is updated.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* contextual-identities


runtime - Mozilla

runtime
=======

This module provides information about your extension and the environment it's running in.

It also provides messaging APIs enabling you to:

* Communicate between different parts of your extension. For advice on choosing between the messaging options, see Choosing between one-off messages and connection-based messaging.
* Communicate with other extensions.
* Communicate with native applications.
Types
-----

`runtime.Port`

Represents one end of a connection between two specific contexts, which can be used to exchange messages.

`runtime.MessageSender`

Contains information about the sender of a message or connection request.

`runtime.PlatformOs`

Identifies the browser's operating system.

`runtime.PlatformArch`

Identifies the browser's processor architecture.

`runtime.PlatformInfo`

Contains information about the platform the browser is running on.

`runtime.RequestUpdateCheckStatus`

Result of a call to `runtime.requestUpdateCheck()`.

`runtime.OnInstalledReason`

The reason that the `runtime.onInstalled` event is being dispatched.

`runtime.OnRestartRequiredReason`

The reason that the `runtime.onRestartRequired` event is being dispatched.

Properties
----------

`runtime.lastError`

This value is set when an asynchronous function has an error condition that it needs to report to its caller.

`runtime.id`

The ID of the extension.

Functions
---------

`runtime.getBackgroundPage()`

Retrieves the Window object for the background page running inside the current extension.

`runtime.openOptionsPage()`

Opens your extension's options page.

`runtime.getFrameId()`

Gets the frame ID of any window global or frame element.

`runtime.getManifest()`

Gets the complete manifest.json file, serialized as an object.

`runtime.getURL()`

Given a relative path from the manifest.json to a resource packaged with the extension, returns a fully-qualified URL.

`runtime.setUninstallURL()`

Sets a URL to be visited when the extension is uninstalled.

`runtime.reload()`

Reloads the extension.

`runtime.requestUpdateCheck()`

Checks for updates to this extension.

`runtime.connect()`

Establishes a connection from a content script to the main extension process, or from one extension to a different extension.

`runtime.connectNative()`

Connects the extension to a native application on the user's computer.

`runtime.sendMessage()`

Sends a single message to event listeners within your extension or a different extension. Similar to `runtime.connect` but only sends a single message, with an optional response.

`runtime.sendNativeMessage()`

Sends a single message from an extension to a native application.

`runtime.getPlatformInfo()`

Returns information about the current platform.

`runtime.getBrowserInfo()`

Returns information about the browser in which this extension is installed.

`runtime.getPackageDirectoryEntry()`

Returns a DirectoryEntry for the package directory.

Events
------

`runtime.onStartup`

Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started.

`runtime.onInstalled`

Fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version.

`runtime.onSuspend`

Sent to the event page just before the extension is unloaded. This gives the extension an opportunity to do some cleanup.

`runtime.onSuspendCanceled`

Sent after `runtime.onSuspend` to indicate that the extension won't be unloaded after all.

`runtime.onUpdateAvailable`

Fired when an update is available, but isn't installed immediately because the extension is currently running.

`runtime.onBrowserUpdateAvailable`
Deprecated

Fired when an update for the browser is available, but isn't installed immediately because a browser restart is required.

`runtime.onConnect`

Fired when a connection is made with either an extension process or a content script.

`runtime.onConnectExternal`

Fired when a connection is made with another extension.

`runtime.onMessage`

Fired when a message is sent from either an extension process or a content script.

`runtime.onMessageExternal`

Fired when a message is sent from another extension. Cannot be used in a content script.

`runtime.onRestartRequired`

Fired when the device needs to be restarted.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* beastify
* content-script-register
* cookie-bg-picker
* devtools-panels
* export-helpers
* favourite-colour
* find-across-tabs
* imagify
* menu-demo
* mocha-client-tests
* native-messaging
* notify-link-clicks-i18n
* permissions
* runtime-examples
* store-collected-images
* user-script-register
* webpack-modules

**Note:** This API is based on Chromium's `chrome.runtime` API. This documentation is derived from `runtime.json` in the Chromium code.


browserAction - Mozilla

browserAction
=============

Adds a button to the browser's toolbar.

A browser action is a button in the browser's toolbar.

You can associate a popup with the button. Like a web page, the popup is specified using HTML, CSS, and JavaScript. JavaScript running in the popup gets access to all the same WebExtension APIs as your background scripts, but its global context is the popup, not the current page displayed in the browser. To affect web pages, you need to communicate with them via messages.

If you specify a popup, it is shown — and the content loaded — when the user clicks the icon. If you do not specify a popup, an event is dispatched to your extension when the user clicks the icon.

The button also has a context menu, and you can add items to this menu with the `menus` API using the `browser_action` `menus.ContextType`.

You can define most of a browser action's properties declaratively using the `browser_action` key in the manifest.json.

With the `browserAction` API, you can:

* use `browserAction.onClicked` to listen for clicks on the icon.
* get and set the icon's properties — icon, title, popup, and so on. You can get and set these globally across all tabs or for a tab by passing the tab ID as an additional argument.
Types
-----

`browserAction.ColorArray`

An array of four integers in the range 0-255 defining an RGBA color.

`browserAction.ImageDataType`

Pixel data for an image. Must be an `ImageData` object (for example, from a `<canvas>` element).

Functions
---------

`browserAction.setTitle()`

Sets the browser action's title. This will be displayed in a tooltip.

`browserAction.getTitle()`

Gets the browser action's title.

`browserAction.setIcon()`

Sets the browser action's icon.

`browserAction.setPopup()`

Sets the HTML document to be opened as a popup when the user clicks on the browser action's icon.

`browserAction.getPopup()`

Gets the HTML document set as the browser action's popup.

`browserAction.openPopup()`

Open the browser action's popup.

`browserAction.setBadgeText()`

Sets the browser action's badge text. The badge is displayed on top of the icon.

`browserAction.getBadgeText()`

Gets the browser action's badge text.

`browserAction.setBadgeBackgroundColor()`

Sets the badge's background color.

`browserAction.getBadgeBackgroundColor()`

Gets the badge's background color.

`browserAction.setBadgeTextColor()`

Sets the badge's text color.

`browserAction.getBadgeTextColor()`

Gets the badge's text color.

`browserAction.enable()`

Enables the browser action for a tab. By default, browser actions are enabled for all tabs.

`browserAction.disable()`

Disables the browser action for a tab, meaning that it cannot be clicked when that tab is active.

`browserAction.isEnabled()`

Checks whether the browser action is enabled or not.

Events
------

`browserAction.onClicked`

Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Example extensions
------------------

* bookmark-it
* favourite-colour
* find-across-tabs
* forget-it
* google-userinfo
* native-messaging
* open-my-page-button
* permissions
* runtime-examples
* store-collected-images
* tabs-tabs-tabs

**Note:** This API is based on Chromium's `chrome.browserAction` API. This documentation is derived from `browser_action.json` in the Chromium code.


permissions - Mozilla

permissions
===========

Enables extensions to request extra permissions at runtime, after they have been installed.

Extensions need permissions to access more powerful WebExtension APIs. They can ask for permissions at install time, by including the permissions they need in the `permissions` manifest.json key. The main advantages of asking for permissions at install time are:

* The user is only asked once, so it's less disruptive for them, and a simpler decision.
* The extension can rely on the access to the APIs it needs, because if already running, the permissions have been granted.

In most major browsers, users can see if their installed extensions request advanced permissions through the browser's extensions manager.

With the permissions API, an extension can ask for additional permissions at runtime. These permissions need to be listed in the `optional_permissions` manifest.json key. Note that some permissions are not allowed in `optional_permissions`. The main advantages of this are:

* The extension can run with a smaller set of permissions, except when it actually needs them.
* The extension can handle permission denial in a graceful manner, instead of presenting the user with a global "all or nothing" choice at install time. You can still get a lot out of that map extension, without giving it access to your location, for example.
* The extension may need host permissions, but not know at install time which host permissions it needs. For example, the list of hosts may be a user setting. In this scenario, asking for a more specific range of hosts at runtime, can be an alternative to asking for "<all\_urls>" at install time.

To use the permissions API, decide which permissions your extension can request at runtime, and list them in `optional_permissions`. After this, you can request any permissions that were included in `optional_permissions`. Requests may only be made in the handler for a user action (for example, a click handler).

Starting with Firefox 84, users will be able to manage optional permissions of installed extensions from the Add-ons Manager. Extensions that use optional permissions should listen for browser.permissions.onAdded and browser.permissions.onRemoved API events to know when a user grants or revokes these permissions.

For advice on designing your request for runtime permissions, to maximize the likelihood that users grant them, see Request permissions at runtime.

Types
-----

`permissions.Permissions`

Represents a set of permissions.

Methods
-------

`permissions.contains()`

Discover an extension's given set of permissions.

`permissions.getAll()`

Get all the permissions this extension currently has.

`permissions.remove()`

Give up a set of permissions.

`permissions.request()`

Ask for a set of permissions.

Event handlers
--------------

`permissions.onAdded`

Fired when a new permission is granted.

`permissions.onRemoved`

Fired when a permission is removed.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `manifest.json` `permissions` property
* `manifest.json` `optional_permissions` property
Example extensions
------------------

* dnr-dynamic-with-options
* dnr-redirect-url
* permissions

**Note:** This API is based on Chromium's `chrome.permissions` API.