i18n.getUILanguage() - Mozilla

i18n.getUILanguage()
====================

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

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

Syntax
------

```js
browser.i18n.getUILanguage()
```

### Parameters

None.

### Return value

`string`. The browser UI language code as an `i18n.LanguageCode`.

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

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

Examples
--------

```js
let uiLanguage = browser.i18n.getUILanguage();
console.log(uiLanguage);

//e.g. "fr"
```

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


Locale-specific message reference - Mozilla

Locale-specific message reference
=================================

Each internationalized extension has at least one file named `messages.json` that provides locale-specific strings. This page describes the format of `messages.json` files.

**Note:** For information on how to internationalize your extensions, see our i18n guide.

messages.json example
---------------------

The following code shows an example `messages.json file`, taken from our notify-link-clicks-i18n example extension. Only the "*name*" and "message" fields are required.

```json
{
  "extensionName": {
    "message": "Notify link clicks i18n",
    "description": "Name of the extension."
  },

  "extensionDescription": {
    "message": "Shows a notification when the user clicks on links.",
    "description": "Description of the extension."
  },

  "notificationTitle": {
    "message": "Click notification",
    "description": "Title of the click notification."
  },

  "notificationContent": {
    "message": "You clicked $URL$.",
    "description": "Tells the user which link they clicked.",
    "placeholders": {
      "url": {
        "content": "$1",
        "example": "https://developer.mozilla.org"
      }
    }
  }
}
```

Placement
---------

Your `messages.json` files need to be placed inside directories named after the locale each one is supporting — `en`, `de`, `ja`, etc. These in turn need to be placed inside a directory called `_locales`, inside the root of your extension.

Member details
--------------

This section describes each member that can appear in a `messages.json` file.

### name

Each top-level member is named after the name of the message string you are localizing, for example `"extensionName"` or `"notificationContent"` in the example above. Each name is case-insensitive, and acts as a key allowing you to retrieve the localized message text.

The name can include the following characters:

* A-Z
* a-z
* 0-9
* \_ (underscore)
* @

**Note:** You shouldn't define names that start with @@. Such names are reserved for predefined messages.

### message

At least this property must be set for every string. The `"message"` member contains a localized string that can contain placeholders. You can use:

* *$placeholder\_name$* (case insensitive) to insert a particular placeholder (for example $URL$ in the example above) into your string.
* `$1`, `$2`, `$3`, etc. to directly insert values obtained from a `i18n.getMessage()` call into your string.

Other points to note:

* Any number of consecutive dollar signs appearing in strings are replaced by the same number of dollar signs minus one. So, $$ > $, $$$ > $$, etc.
* When the locale file is read, tokens matching `/\$([a-z0-9_@]+)\$/i` are replaced with the matching value from the string's "placeholders" object. These substitutions happen prior to processing any `/\$\d/` tokens in the message.
* When a locale string is used, tokens matching `/\$\d+/` are replaced with the replacements passed to `i18n.getMessage()`.
* `getMessage()` won't process calls with more than 9 placeholders/substitutions.
### description

Optional
The `"description"` member should contain a description of the message string's contents, aimed to provide a translator with help to create the best translation possible of the string.

### placeholders

Optional
The `"placeholders"` member defines one or more placeholder substrings to be used within the message — these can be used to hardcode items that you don't want translated, or refer to variables.

Each placeholder substring definition has a number of values of its own:

```json
"url" : {
  "content" : "$1",
  "example" : "https://developer.mozilla.org"
}
```

#### placeholder name

The placeholder name is used to represent the placeholder in the substitution string (e.g. `"url"` becomes `$url$`). It is case insensitive and can contain the same characters as a message string name.

#### content

The "content" item defines the content of the placeholder. This can be a hardcoded string, such as "My placeholder", but it can also include values obtained from a `i18n.getMessage()` call. This property is required. For more information, see Retrieving message strings from JavaScript.

#### example

Optional
The optional "example" item is again intended to help translators by showing them an example of how the placeholder would appear to end users, allowing them to make the best choice when localizing the file.


i18n.getAcceptLanguages() - Mozilla

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`.

This is an asynchronous function that returns a `Promise`.

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

Syntax
------

```js
let gettingAcceptLanguages = browser.i18n.getAcceptLanguages()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an `array` of ``i18n.LanguageCode`` objects.

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

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

Examples
--------

```js
function onGot(languages) {
  console.log(languages);
  //e.g. Array [ "en-US", "en" ]
}

let gettingAcceptLanguages = browser.i18n.getAcceptLanguages();
gettingAcceptLanguages.then(onGot);
```

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


search.query() - Mozilla

search.query()
==============

Perform a search using the browser's default search engine.

The results are displayed in the current tab, a new tab, or a new window according to the `disposition` property or in the tab specified in the `tabId` property. If neither is specified, the results display in the current tab.

To use this function, your extension must have the `"search"` manifest permission.

Syntax
------

```js
browser.search.query(
  queryInfo             // object
)
```

### Parameters

`queryInfo`

`object`. An object with the following properties:

`disposition` Optional

`string`. The location where the search results are displayed. Valid values are `CURRENT_TAB`, `NEW_TAB`, and `NEW_WINDOW`. Defaults to `CURRENT_TAB`. Cannot be specified with `tabId`.

`tabId` Optional

`integer`. An optional identifier for the tab you want to execute the search in. If this property is omitted, the search results are displayed in a new tab. Cannot be specified with `disposition`.

`text`

`string`. The search query.

### Return value

None.

Examples
--------

A search with the results shown in the current tab (default):

```js
function search() {
  browser.search.query({
    text: "styracosaurus",
  });
}

browser.browserAction.onClicked.addListener(search);
```

A search with the results shown in a new window:

```js
function search() {
  browser.search.query({
    text: "styracosaurus",
    disposition: "NEW\_WINDOW",
  });
}

browser.browserAction.onClicked.addListener(search);
```

A search with the results shown in a specific tab:

```js
function search(tab) {
  browser.search.query({
    query: "styracosaurus",
    tabId: tab.id,
  });
}

browser.browserAction.onClicked.addListener(search);
```

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

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


search.get() - Mozilla

search.get()
============

Gets an array of all installed search engines.

Each search engine returned is identified with a name, which you can pass into `search.search()` to use that particular engine to make a search.

This is an asynchronous function that returns a `Promise`.

Syntax
------

```js
let gettingEngines = browser.search.get()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an array of search engine objects. Each search engine object may contain the following properties:

`name`

`string`. The search engine's name.

`isDefault`

`boolean`. `true` if the search engine is the default. Only one search engine can be the default at any given time.

`alias` Optional

`string`. If a search engine has an alias, the user can search with a particular search engine by entering the alias in address bar before the search term. For example, if the Wikipedia engine has an alias "wk", the user can search Wikipedia for pandas by entering "wk pandas" in the address bar. The alias is sometimes also called a "keyword".

`favIconUrl` Optional

`string`. The search engine's icon, as a data: URL.

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

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

Examples
--------

Get all installed search engines:

```js
function retrieved(results) {
  console.log(`There were: ${results.length} search engines retrieved.`);
  for (const searchEngine of results) {
    console.log(JSON.stringify(searchEngine.name));
  }
}

browser.search.get().then(retrieved);
```

### Example extensions

* menu-search


search.search() - Mozilla

search.search()
===============

Perform a search using the search engine specified or the default search engine if no search engine is specified.

The results are displayed in the current tab, a new tab, or a new window according to the `disposition` property or in the tab specified in the `tabId` property. If neither is specified, the results display in a new tab.

To use this function, your extension must have the `"search"` manifest permission.

To get the installed search engines, use `search.get()`.

Syntax
------

```js
browser.search.search(
  searchProperties       // object
)
```

### Parameters

`searchProperties`

`object`. An object with the following properties:

`disposition` Optional

`string`. The location where the search results are displayed. Valid values are `CURRENT_TAB`, `NEW_TAB`, and `NEW_WINDOW`. Defaults to `NEW_TAB`. Cannot be specified with `tabId`.

`engine` Optional

`string`. The name of the search engine. If the search engine name doesn't exist, the function rejects the call with an error. If this property is omitted, the default search engine is used.

`query`

`string`. The search query.

`tabId` Optional

`integer`. An optional identifier for the tab you want to execute the search in. If this property is omitted, the search results are displayed in a new tab. Cannot be specified with `disposition`.

### Return value

None.

Examples
--------

A search using the default search engine with the results shown in the current tab (default):

```js
function search() {
  browser.search.search({
    query: "styracosaurus",
  });
}

browser.browserAction.onClicked.addListener(search);
```

A search using Wikipedia with the results shown in a new window:

```js
function search() {
  browser.search.search({
    query: "styracosaurus",
    engine: "Wikipedia (en)",
    disposition: "NEW\_WINDOW",
  });
}

browser.browserAction.onClicked.addListener(search);
```

A search using Wikipedia with the results shown in the current tab:

```js
function search(tab) {
  browser.search.search({
    query: "styracosaurus",
    engine: "Wikipedia (en)",
    tabId: tab.id,
  });
}

browser.browserAction.onClicked.addListener(search);
```

### Example extensions

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

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


menus.OnClickData - Mozilla

menus.OnClickData
=================

Information passed to the `menus.onClicked` event listener when a menu item is clicked.

Type
----

Values of this type are objects. They contain the following properties:

`bookmarkId` Optional

`string`. The ID of the bookmark where the context menu was clicked.

`button` Optional

`integer`. Which mouse button was pressed. The values are the same as for `MouseEvent.button`.

`checked` Optional

`boolean`. A flag indicating whether a checkbox or radio item was checked after it was clicked.

`editable`

`boolean`. A flag indicating whether the element is editable: for example, if it is a textarea.

`frameId` Optional

`integer`. The ID of the frame in which the item was clicked. The frame ID can be used in other APIs that accept frame IDs, such as `tabs.sendMessage()`. If the item was clicked in the top level document, `frameId` is zero. If the item was clicked outside the page entirely (for example, in the `tools_menu` or `tab` context), then `frameId` is `undefined`.

`frameUrl` Optional

`string`. The URL of the frame of the element where the context menu was clicked, if it was in a frame.

`linkText` Optional

`string`. If the element is a link, the text for the link. If the link contains no text, the URL itself is given here.

`linkUrl` Optional

`string`. If the element is a link, the URL it points to.

`mediaType` Optional

`string`. One of "image", "video", or "audio" if the context menu was activated on one of these types of elements.

`menuItemId`

`integer` or `string`. The ID of the menu item that was clicked.

`modifiers`

`array` of `string`. An array containing any modifier keys that were pressed when the item was clicked. Possible values are: "Alt", "Command", "Ctrl", "MacCtrl", and "Shift". On a Mac, if the user has the Control key pressed, then both "Ctrl" and "MacCtrl" are included.

`pageUrl` Optional

`string`. The URL of the page in which the menu item was clicked. This property is not present if the click occurred in a context where there is no current page, such as on a browser action.

`parentMenuItemId` Optional

`integer` or `string`. The parent ID, if any, for the item clicked.

`selectionText` Optional

`string`. If some text was selected in the page, this contains the selected text.

`srcUrl` Optional

`string`. If present, the `src` value for the media in the clicked element.

`targetElementId` Optional

`integer`. An identifier of the element, if any, over which the context menu was created. Use `menus.getTargetElement()` in the content script to locate the element. Note that this is not the id attribute of the page element.

`viewType` Optional

`ViewType`. The type of extension view.

`wasChecked` Optional

`boolean`. A flag indicating whether a checkbox or radio item was checked before it was clicked.

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.contextMenus` API. This documentation is derived from `context_menus.json` in the Chromium code.


menus.refresh() - Mozilla

menus.refresh()
===============

Refreshes a menu that's being shown.

Updates the extension's menu items in the menu that the browser is currently showing, including changes that have been made since the menu was shown. Has no effect if the menu is not being shown. Rebuilding a shown menu is an expensive operation, only invoke this method when necessary.

This would typically be called from inside a `menus.onShown` event handler, after the handler has made any updates to the menu.

Firefox makes this function available via the `contextMenus` namespace as well as the `menus` namespace.

This is an asynchronous function that returns a `Promise`.

Syntax
------

```js
browser.menus.refresh()
```

### Parameters

None.

### Return value

A `Promise` that is fulfilled with no arguments.

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

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

Examples
--------

This example listens for the context menu to be shown over a link, then updates the `openLabelledId` menu item with the link's hostname:

```js
function updateMenuItem(linkHostname) {
  browser.menus.update(openLabelledId, {
    title: `Open (${linkHostname})`,
  });
  browser.menus.refresh();
}

browser.menus.onShown.addListener((info) => {
  if (!info.linkUrl) {
    return;
  }
  let linkElement = document.createElement("a");
  linkElement.href = info.linkUrl;
  updateMenuItem(linkElement.hostname);
});
```

### Example extensions

* menu-labelled-open


menus.create() - Mozilla

menus.create()
==============

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:
>
>
> * non-persistent background pages (an event page), where menus persist across browser and extension restarts. You call `menus.create` (with a menu-specific ID) from within a `runtime.onInstalled` listener. This avoids repeated attempts to create the menu item when the pages restart, which would occur with a top-level call.
> * persistent background pages:
>     + in Chrome, menu items from persistent background pages are persisted. Create your menus in a `runtime.onInstalled` listener.
>     + in Firefox, menu items from persistent background pages are never persisted. Call `menus.create` unconditionally from the top level to register the menu items.
>
>
> See Initialize the extension on the background scripts page and Event-driven background scripts on Extension Workshop for more information.
>
>
>

Syntax
------

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

### Parameters

`createProperties`

`object`. Properties for the new menu item.

`checked` Optional

`boolean`. The initial state of a checkbox or radio item: `true` for selected and `false` for unselected. Only one radio item can be selected at a time in a given group of radio items.

`command` Optional

`string`. String describing an action that should be taken when the user clicks the item. The recognized values are:

* `"_execute_browser_action"`: simulate a click on the extension's browser action, opening its popup if it has one (Manifest V2 only)
* `"_execute_action"`: simulate a click on the extension's action, opening its popup if it has one (Manifest V3 only)
* `"_execute_page_action"`: simulate a click on the extension's page action, opening its popup if it has one
* `"_execute_sidebar_action"`: open the extension's sidebar

See the documentation of special shortcuts in the manifest.json key `commands` for details.

When one of the recognized values is specified, clicking the item does not trigger the `menus.onClicked` event; instead, the default action triggers, such as opening a pop-up. Otherwise, clicking the item triggers `menus.onClicked` and the event can be used to implement fallback behavior.

`contexts` Optional

`array` of ``menus.ContextType``. Array of contexts in which this menu item will appear. If this option is omitted:

* if the item's parent has contexts set, then this item will inherit its parent's contexts
* otherwise, the item is given a context array of ["page"].

`documentUrlPatterns` Optional

`array` of `string`. Lets you restrict the item to apply only to documents whose URL matches one of the given match patterns. This applies to frames as well.

`enabled` Optional

`boolean`. Whether this menu item is enabled or disabled. Defaults to `true`.

`icons` Optional

`object`. One or more custom icons to display next to the item. Custom icons can only be set for items appearing in submenus. This property is an object with one property for each supplied icon: the property's name should include the icon's size in pixels, and path is relative to the icon from the extension's root directory. The browser tries to choose a 16x16 pixel icon for a normal display or a 32x32 pixel icon for a high-density display. To avoid any scaling, you can specify icons like this:

```js
browser.menus.create({
  icons: {
    16: "path/to/geo-16.png",
    32: "path/to/geo-32.png",
  },
});
```

Alternatively, you can specify a single SVG icon, and it will be scaled appropriately:

```js
browser.menus.create({
  icons: {
    16: "path/to/geo.svg",
  },
});
```

**Note:** The top-level menu item uses the icons specified in the manifest rather than what is specified with this key.

`id` Optional

`string`. The unique ID to assign to this item. Is mandatory for non-persistent background (event) pages in Manifest V2 and in Manifest V3. Cannot be the same as another ID for this extension.

`onclick` Optional

`function`. The function called when the menu item is clicked. Event pages cannot use this: instead, they should register a listener for `menus.onClicked`.

`parentId` Optional

`integer` or `string`. The ID of a parent menu item; this makes the item a child of a previously added item. Note: If you have created more than one menu item, then the items will be placed in a submenu. The submenu's parent will be labeled with the name of the extension.

`targetUrlPatterns` Optional

`array` of `string`. Similar to `documentUrlPatterns`, but lets you filter based on the `href` of anchor tags and the `src` attribute of img/audio/video tags. This parameter supports any URL scheme, even those that are usually not allowed in a match pattern.

`title` Optional

`string`. The text to be displayed in the item. Mandatory unless `type` is "separator".

You can use "`%s`" in the string. If you do this in a menu item, and some text is selected in the page when the menu is shown, then the selected text will be interpolated into the title. For example, if `title` is "Translate '%s' to Pig Latin" and the user selects the word "cool", then activates the menu, then the menu item's title will be: "Translate 'cool' to Pig Latin".

If the title contains an ampersand "&" then the next character will be used as an access key for the item, and the ampersand will not be displayed. Exceptions to this are:

* If the next character is also an ampersand: then a single ampersand will be displayed and no access key will be set. In effect, "&&" is used to display a single ampersand.
* If the next characters are the interpolation directive "%s": then the ampersand will not be displayed and no access key will be set.
* If the ampersand is the last character in the title: then the ampersand will not be displayed and no access key will be set.

Only the first ampersand will be used to set an access key: subsequent ampersands will not be displayed but will not set keys. So "&A and &B" will be shown as "A and B" and set "A" as the access key.

In some localized versions of Firefox (Japanese and Chinese), the access key is surrounded by parentheses and appended to the menu label, *unless* the menu title itself already ends with the access key (`"toolkit(&K)"` for example). For more details, see Firefox bug 1647373.

`type` Optional

``menus.ItemType``. The type of menu item: "normal", "checkbox", "radio", "separator". Defaults to "normal".

`viewTypes` Optional

``extension.ViewType``. List of view types where the menu item will be shown. Defaults to any view, including those without a `viewType`.

`visible` Optional

`boolean`. Whether the item is shown in the menu. Defaults to `true`.

`callback` Optional

`function`. Called when the item has been created. If there were any problems creating the item, details will be available in `runtime.lastError`.

### 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:

```js
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.

```js
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,
    });
  }
});
```

### Example extensions

* menu-accesskey-visible
* menu-demo
* menu-labelled-open
* menu-remove-element
* menu-search
* session-state
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.contextMenus` API. This documentation is derived from `context_menus.json` in the Chromium code.


menus.onShown - Mozilla

menus.onShown
=============

Fired when the browser has shown a menu.

An extension can use this event to update its menu items using information that's only available once the menu is shown. Typically an extension will figure out the update in its `onShown` handler and then call `menus.refresh()` to update the menu itself.

The handler can add, remove, or update menu items.

For example, the menu-labelled-open example extension adds a menu item that's shown when the user clicks a link, and that, when clicked, just opens the link. It uses `onShown` and `refresh()` to annotate the menu item with the hostname for the link, so the user can easily see where they will go before they click.

Note that an extension should not take too much time before calling `refresh()`, or the update will be noticeable to the user.

The handler is passed some information about the menu and its contents, and some information from the page (such as the link and/or selection text). To get access to the information from the page, your extension must have the host permission for it.

If the `onShown` handler calls any asynchronous APIs, then it's possible that the menu has been closed again before the handler resumes execution. Because of this, if a handler calls any asynchronous APIs, it should check that the menu is still being displayed before it updates the menu. For example:

```js
let lastMenuInstanceId = 0;
let nextMenuInstanceId = 1;

browser.menus.onShown.addListener(async (info, tab) => {
  let menuInstanceId = nextMenuInstanceId++;
  lastMenuInstanceId = menuInstanceId;

  // Call an async function
  await /\* the function to call \*/ ;

  // After completing the async operation, check whether the menu is still shown.
  if (menuInstanceId !== lastMenuInstanceId) {
    return; // Menu was closed and shown again.
  }
  // Now use menus.create/update + menus.refresh.
});

browser.menus.onHidden.addListener(() => {
  lastMenuInstanceId = 0;
});
```

Note that it is possible to call menus API functions synchronously, and in this case you don't have to perform this check:

```js
browser.menus.onShown.addListener(async (info, tab) => {
  browser.menus.update(menuId /\*, …\*/);
  // Note: Not waiting for returned promise.
  browser.menus.refresh();
});
```

However, if you call these APIs asynchronously, then you do have to perform the check:

```js
browser.menus.onShown.addListener(async (info, tab) => {
  let menuInstanceId = nextMenuInstanceId++;
  lastMenuInstanceId = menuInstanceId;

  await browser.menus.update(menuId /\*, …\*/);
  // must now perform the check
  if (menuInstanceId !== lastMenuInstanceId) {
    return;
  }
  browser.menus.refresh();
});
```

Firefox makes this event available via the `contextMenus` namespace as well as the `menus` namespace.

Syntax
------

```js
browser.menus.onShown.addListener(listener)
browser.menus.onShown.removeListener(listener)
browser.menus.onShown.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

Stop listening to this event. The `listener` argument is the listener to remove.

`hasListener(listener)`

Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.

addListener syntax
------------------

### Parameters

`listener`

The function called when this event occurs. The function is passed these arguments:

`info`

`Object`. This is just like the `menus.OnClickData` object, except it contains two extra properties:

* `contexts`: an array of all the `contexts` that are applicable to this menu.
* `menuIds`: an array of IDs of all menu items belonging to this extension that are being shown in this menu.

Compared with `menus.OnClickData`, the `info` object also omits the `menuItemId` and `modifiers` properties, because of course these are not available until a menu item has been selected.

The `contexts`, `menuIds`, `frameId`, and `editable` properties are always provided. All the other properties in `info` are only provided if the extension has the host permission for the page.

`tab`

`tabs.Tab`. The details of the tab where the click took place. If the click did not take place in or on a tab, this parameter will be missing.

Examples
--------

This example listens for the context menu to be shown over a link, then updates the `openLabelledId` menu item with the link's hostname:

```js
function updateMenuItem(linkHostname) {
  browser.menus.update(openLabelledId, {
    title: `Open (${linkHostname})`,
  });
  browser.menus.refresh();
}

browser.menus.onShown.addListener((info) => {
  if (!info.linkUrl) {
    return;
  }
  let linkElement = document.createElement("a");
  linkElement.href = info.linkUrl;
  updateMenuItem(linkElement.hostname);
});
```

### Example extensions

* menu-labelled-open
Browser compatibility
---------------------

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


menus.ItemType - Mozilla

menus.ItemType
==============

The type of menu item.

Type
----

Values of this type are strings. Possible values are:

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 `menus.onClicked` 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 `menus.onClicked` 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.

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.contextMenus` API. This documentation is derived from `context_menus.json` in the Chromium code.


menus.remove() - Mozilla

menus.remove()
==============

Removes a menu item.

For compatibility with other browsers, Firefox makes this method available via the `contextMenus` namespace as well as the `menus` namespace.

This is an asynchronous function that returns a `Promise`.

Syntax
------

```js
let removing = browser.menus.remove(
  menuItemId      // integer or string
)
```

### Parameters

`menuItemId`

`integer` or `string`. The ID of the menu item to remove.

### Return value

A `Promise` that will be fulfilled with no arguments if removal was successful, or rejected with an error message if removal failed (for example, because the item could not be found).

Examples
--------

This extension adds a menu item labeled "Remove me!". If you click the item, the extension removes it.

```js
function onRemoved() {
  console.log("item removed successfully");
}

function onError() {
  console.log("error removing item:", browser.runtime.lastError);
}

browser.menus.create({
  id: "remove-me",
  title: "Remove me!",
  contexts: ["all"],
});

browser.menus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "remove-me") {
    let removing = browser.menus.remove(info.menuItemId);
    removing.then(onRemoved, onError);
  }
});
```

### Example extensions

* menu-demo
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.contextMenus` API. This documentation is derived from `context_menus.json` in the Chromium code.


menus.onHidden - Mozilla

menus.onHidden
==============

Fired when the browser stops displaying a menu: for example because the user clicked outside it or selected an item.

It is only triggered for menus that can be manipulated using the `menus` API itself: this includes the context menu, the browser's tools menu, and the bookmarks menu.

This is most likely to be used in combination with the `menus.onShown` and `menus.refresh()` APIs: an extension can update the menu when it is shown, then undo the changes when it is hidden.

Firefox makes this event available via the `contextMenus` namespace as well as the `menus` namespace.

Syntax
------

```js
browser.menus.onHidden.addListener(listener)
browser.menus.onHidden.removeListener(listener)
browser.menus.onHidden.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

Stop listening to this event. The `listener` argument is the listener to remove.

`hasListener(listener)`

Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.

addListener syntax
------------------

### Parameters

`listener`

The function called when this event occurs. The function is passed no parameters.

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

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

Examples
--------

This example just logs a message whenever a menu is hidden:

```js
function hidden() {
  console.log("Menu was hidden");
}

browser.menus.onHidden.addListener(hidden);
```


menus.onClicked - Mozilla

menus.onClicked
===============

Fired when a menu item is clicked.

For compatibility with other browsers, Firefox makes this event available via the `contextMenus` namespace as well as the `menus` namespace.

Syntax
------

```js
browser.menus.onClicked.addListener(listener)
browser.menus.onClicked.removeListener(listener)
browser.menus.onClicked.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

Stop listening to this event. The `listener` argument is the listener to remove.

`hasListener(listener)`

Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.

addListener syntax
------------------

### Parameters

`listener`

The function called when this event occurs. The function is passed these arguments:

`info`

`menus.OnClickData`. Information about the item clicked and the context where the click happened.

`tab`

`tabs.Tab`. The details of the tab where the click took place. If the click did not take place in or on a tab, this parameter will be missing.

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

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

Examples
--------

This example listens for clicks on a menu item, then log the item's ID and the tab ID:

```js
browser.menus.create({
  id: "click-me",
  title: "Click me!",
  contexts: ["all"],
});

browser.menus.onClicked.addListener((info, tab) => {
  console.log(`Item ${info.menuItemId} clicked in tab ${tab.id}`);
});
```

### Example extensions

* 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.


menus.update() - Mozilla

menus.update()
==============

Updates a previously created menu item.

For compatibility with other browsers, Firefox makes this method available via the `contextMenus` namespace as well as the `menus` namespace.

This is an asynchronous function that returns a `Promise`.

Syntax
------

```js
let updating = browser.menus.update(
  id,               // integer or string
  updateProperties // object
)
```

### Parameters

`id`

`integer` or `string`. The ID of the item to update.

`updateProperties`

`object`. The properties to update. The same as the `createProperties` object passed to `menus.create()`, except that `id` can't be set. In addition, `icons` can only be changed on menu commands, not on the top-level context menu. The top-level icon matches the extension's primary icon as declared in the extension's manifest file.

`checked` Optional

`boolean`. The initial state of a checkbox or radio item: `true` for selected and `false` for unselected. Only one radio item can be selected at a time in a given group of radio items.

`command` Optional

`string`. String describing an action that should be taken when the user clicks the item. The recognized values are:

* `"_execute_browser_action"`: simulate a click on the extension's browser action, opening its popup if it has one (Manifest V2 only)
* `"_execute_action"`: simulate a click on the extension's action, opening its popup if it has one (Manifest V3 only)
* `"_execute_page_action"`: simulate a click on the extension's page action, opening its popup if it has one
* `"_execute_sidebar_action"`: open the extension's sidebar

See the documentation of special shortcuts in the manifest.json key `commands` for details.

When one of the recognized values is specified, clicking the item does not trigger the `menus.onClicked` event; instead, the default action triggers, such as opening a pop-up. Otherwise, clicking the item triggers `menus.onClicked` and the event can be used to implement fallback behavior.

`contexts` Optional

`array` of ``menus.ContextType``. Array of contexts in which this menu item will appear. If this option is omitted:

* if the item's parent has contexts set, then this item will inherit its parent's contexts
* otherwise, the item is given a context array of ["page"].

`documentUrlPatterns` Optional

`array` of `string`. Lets you restrict the item to apply only to documents whose URL matches one of the given match patterns. This applies to frames as well.

`enabled` Optional

`boolean`. Whether this menu item is enabled or disabled. Defaults to `true`.

`icons` Optional

`object`. One or more custom icons to display next to the item. Custom icons can only be set for items appearing in submenus. This property is an object with one property for each supplied icon: the property's name should include the icon's size in pixels, and path is relative to the icon from the extension's root directory. The browser tries to choose a 16x16 pixel icon for a normal display or a 32x32 pixel icon for a high-density display. To avoid any scaling, you can specify icons like this:

```js
browser.menus.create({
  icons: {
    16: "path/to/geo-16.png",
    32: "path/to/geo-32.png",
  },
});
```

Alternatively, you can specify a single SVG icon, and it will be scaled appropriately:

```js
browser.menus.create({
  icons: {
    16: "path/to/geo.svg",
  },
});
```

**Note:** The top-level menu item uses the icons specified in the manifest rather than what is specified with this key.

`id` Optional

`string`. The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension.

`onclick` Optional

`function`. The function called when the menu item is clicked. Event pages cannot use this: instead, they should register a listener for `menus.onClicked`.

`parentId` Optional

`integer` or `string`. The ID of a parent menu item; this makes the item a child of a previously added item. Note: If you have created more than one menu item, then the items will be placed in a submenu. The submenu's parent will be labeled with the name of the extension.

`targetUrlPatterns` Optional

`array` of `string`. Similar to `documentUrlPatterns`, but lets you filter based on the `href` of anchor tags and the `src` attribute of img/audio/video tags. This parameter supports any URL scheme, even those that are usually not allowed in a match pattern.

`title` Optional

`string`. The text to be displayed in the item. Mandatory unless `type` is "separator".

You can use "`%s`" in the string. If you do this in a menu item, and some text is selected in the page when the menu is shown, then the selected text will be interpolated into the title. For example, if `title` is "Translate '%s' to Pig Latin" and the user selects the word "cool", then activates the menu, then the menu item's title will be: "Translate 'cool' to Pig Latin".

If the title contains an ampersand "&" then the next character will be used as an access key for the item, and the ampersand will not be displayed. Exceptions to this are:

* If the next character is also an ampersand: then a single ampersand will be displayed and no access key will be set. In effect, "&&" is used to display a single ampersand.
* If the next characters are the interpolation directive "%s": then the ampersand will not be displayed and no access key will be set.
* If the ampersand is the last character in the title: then the ampersand will not be displayed and no access key will be set.

Only the first ampersand will be used to set an access key: subsequent ampersands will not be displayed but will not set keys. So "&A and &B" will be shown as "A and B" and set "A" as the access key.

`type` Optional

``menus.ItemType``. The type of menu item: "normal", "checkbox", "radio", "separator". Defaults to "normal".

`viewTypes` Optional

``extension.ViewType``. List of view types where the menu item will be shown. Defaults to any view, including those without a `viewType`.

`visible` Optional

`boolean`. Whether the item is shown in the menu. Defaults to `true`.

### Return value

A `Promise` that will be fulfilled with no arguments if the update was successful, or rejected with an error message if the update failed.

Examples
--------

This example creates a menu item, then updates its title when the user clicks it:

```js
function onUpdated() {
  console.log("item updated successfully");
}

function onError() {
  console.log("error updating item:", browser.runtime.lastError);
}

browser.menus.create({
  id: "do-not-click-me",
  title: "Do not click this button",
  contexts: ["all"],
});

browser.menus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "do-not-click-me") {
    let updating = browser.menus.update(info.menuItemId, {
      title: "Do not click this button again",
    });
    updating.then(onUpdated, onError);
  }
});
```

### Example extensions

* menu-accesskey-visible
* menu-demo
* menu-labelled-open
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.contextMenus` API. This documentation is derived from `context_menus.json` in the Chromium code.


menus.ACTION_MENU_TOP_LEVEL_LIMIT - Mozilla

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". Any items beyond this limit will be ignored.

Its value is `6` on Firefox and Chrome.

For compatibility with other browsers, Firefox makes this property available via the `contextMenus` namespace as well as the `menus` namespace.

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.contextMenus` API. This documentation is derived from `context_menus.json` in the Chromium code.


menus.overrideContext() - Mozilla

menus.overrideContext()
=======================

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

The overrideContext method will cause the matching menu items from this extension to be shown instead of the default menu. This method should be called from a `contextmenu` DOM event handler, and only applies to the menu that opens after this event.

This interface requires the `menus.overrideContext` permission.

Syntax
------

```js
browser.menus.overrideContext(
  contextOptions // object
)
```

### Parameters

`contextOptions`

`object`. Options for how the context menus will be overridden.

`showDefaults` Optional

`boolean`. Whether to also include default menu items in the menu.

`context` Optional

`string`. ContextType to override, to allow menu items from other extensions in the menu. Currently only `'bookmark'` and `'tab'` are supported. `showDefaults` cannot be used with this option.

`bookmarkId` Optional

`string`. Required when context is `'bookmark'`. Requires 'bookmark' permission.

`tabId` Optional

`integer`. Required when context is `'tab'`. Requires 'tabs' permission.

Examples
--------

Open the tab context menu on your custom UI, in this case:

```js
document.addEventListener(
  "contextmenu",
  (event) => {
    const foo = event.target.closest(".foo");
    if (foo) {
      // When the context menu is opened on an element with the foo class
      // set the context to "opening a tab context menu".
      browser.menus.overrideContext({
        context: "tab",
        tabId: parseInt(foo.dataset.tabId),
      });
    }
  },
  { capture: true },
);
```

See this blog post for more details.

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

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


menus.ContextType - Mozilla

menus.ContextType
=================

The different contexts a menu item can appear in.

Type
----

Values of this type are strings. The item is displayed when the given context applies. Possible values are:

all

Specifying 'all' is equivalent to the combination of all other contexts except for 'bookmark', 'tab' and 'tools\_menu'.

action

Applies when the user context-clicks your browser action in a Manifest V3 extension. The maximum number of items that can be added to the top-level browser action context menu is `menus.ACTION_MENU_TOP_LEVEL_LIMIT`, but you can add any number of items to submenus.

audio

Applies when the user context-clicks an audio element.

bookmark

Applies when the user context-clicks a bookmark item in the bookmarks toolbar, bookmarks menu, bookmarks sidebar (`Ctrl`+`B`) and the Library window (`Ctrl`+`Shift`+`B`). The latter two are supported as of Firefox 66. Requires the "bookmarks" API permission in the manifest.

browser\_action

Applies when the user context-clicks your browser action in a Manifest V2 extension. The maximum number of items that can be added to the top-level browser action context menu is `menus.ACTION_MENU_TOP_LEVEL_LIMIT`, but you can add any number of items to submenus.

editable

Applies when the user context-clicks an editable element, like a textarea.

frame

Applies when the user context-clicks in a nested iframe.

image

Applies when the user context-clicks an image.

link

Applies when the user context-clicks on a link.

page

Applies when the user context-clicks in the page, but none of the other page contexts apply (for example, the click is not on an image or a nested iframe or a link).

page\_action

Applies when the user context-clicks your page action. The maximum number of items that can be added to the top-level page action context menu is `menus.ACTION_MENU_TOP_LEVEL_LIMIT`, but you can add any number of items to submenus.

password

Applies when the user context-clicks on a password input element.

selection

Applies when part of the page is selected.

tab

Applies when the user context-clicks on a tab (specifically, this refers to the tab-strip or other user interface element enabling the user to switch from one browser tab to another, not to the page itself).

From Firefox 63, clicking the menu item on a tab grants the activeTab permission for the tab clicked, even if that isn't the currently active tab.

tools\_menu

The item will be added to the browser's tools menu. Note that this is only available if you access `ContextType` through the `menus` namespace. It is not available if you access it through the `contextMenus` namespace.

video

Applies when the user context-clicks a video element.

Note that "launcher" is not supported.

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.contextMenus` API. This documentation is derived from `context_menus.json` in the Chromium code.


menus.getTargetElement() - Mozilla

menus.getTargetElement()
========================

Returns the element for a given `targetElementId`

This method is available to all extension script contexts (content scripts, background pages and other extension pages) and returns the element for a given `info.targetElementId`, provided that the element still exists in the document where the method is invoked.

The method only works in the document that includes the right-clicked element and the `targetElementId` expires when the user opens another context menu.

**Note:** `menus.getTargetElement` only return the requested element if called in the same context as the document that contains the element, for example using content scripts (as shown in the example below).

An extension requires the "menus" permission to use this API.

Syntax
------

```js
let elem = browser.menus.getTargetElement(targetElementId);
```

### Parameters

`targetElementId`

The property of the ``menus.OnClickData`` object passed to the ``menus.onClicked`` handler or ``menus.onShown`` event.

### Return value

The element referred to by the `targetElementId` parameter. If the `targetElementId` parameter is not valid, the method returns `null`.

Examples
--------

The following example uses the `getTargetElement` method to get the element referred to by the `info.targetElementId` property and then removes it.

```js
browser.menus.create({
  title: "Remove element",
  documentUrlPatterns: ["\*://\*/\*"],
  contexts: [
    "audio",
    "editable",
    "frame",
    "image",
    "link",
    "page",
    "password",
    "video",
  ],
  onclick(info, tab) {
    browser.tabs.executeScript(tab.id, {
      frameId: info.frameId,
      code: `browser.menus.getTargetElement(${info.targetElementId}).remove();`,
    });
  },
});
```

### Example extensions

* menu-remove-element
Browser compatibility
---------------------

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

See also
--------

* `menus.create`
* `menus.OnClickData`


menus.removeAll() - Mozilla

menus.removeAll()
=================

Removes all menu items added by the extension.

For compatibility with other browsers, Firefox makes this method available via the `contextMenus` namespace as well as the `menus` namespace.

This is an asynchronous function that returns a `Promise`.

Syntax
------

```js
let removing = browser.menus.removeAll()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with no arguments when all items have been removed.

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

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

Examples
--------

This example adds two menu items. When the user clicks the item labeled "Remove all!", the extension removes both items using `removeAll()`.

```js
function onRemoved() {
  console.log("items removed successfully");
}

browser.menus.create({
  id: "click-me",
  title: "Click me!",
  contexts: ["all"],
});

browser.menus.create({
  id: "remove-all",
  title: "Remove all!",
  contexts: ["all"],
});

browser.menus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "remove-all") {
    let removing = browser.menus.removeAll();
    removing.then(onRemoved);
  }
});
```

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


identity.launchWebAuthFlow - Mozilla

identity.launchWebAuthFlow
==========================

Performs the first part of an OAuth2 flow, including user authentication and client authorization.

This function's only mandatory parameter is the service provider's authorization URL, which must contain a number of URL parameters including the redirect URL and the extension's client ID. The service provider then:

* authenticates the user with the service provider, if necessary (that is: if they are not already signed in)
* asks the user to authorize the extension to access the requested data, if necessary (that is: if the user has not already authorized the extension)

Note that if neither authentication or authorization are needed, then this function will complete silently, without any user interaction.

This function also takes an optional parameter `interactive`: if this is omitted or set to false, then the flow is forced to complete silently. In this case, if the user has to authenticate or authorize, then the operation will just fail.

This function returns a `Promise`: if authentication and authorization were successful, the promise is fulfilled with a redirect URL that contains a number of URL parameters. Depending on the OAuth2 flow implemented by the service provider in question, the extension will need to go through further steps to get a valid access code, which it can then use to access the user's data.

If there's any error, the promise is rejected with an error message. Error conditions may include:

* the service provider's URL could not be reached
* the client ID did not match the ID of a registered client
* the redirect URL did not match any redirect URLs registered for this client
* the user did not authenticate successfully
* the user did not authorize the extension
* the `interactive` parameter was omitted or false, but user interaction would have been needed to authorize the extension.
Syntax
------

```js
let authorizing = browser.identity.launchWebAuthFlow(
  details   // object
)
```

### Parameters

`details`

`object`. Options for the flow, containing the following properties:

`url`

`string`. The URL offered by the OAuth2 service provider to get an access token. The details of this URL should be given in the documentation for the service provider in question, but the URL parameters should always include:

`redirect_uri` Optional

`string`. This represents the URI your extension is redirected to when the flow has finished. Not required for the flow to work on the browser side if it matches the generated redirect URL. See Getting the redirect URL.

`interactive` Optional

`boolean`. If omitted or `false`, forces the flow to complete silently, without any user interaction.

If the user is already signed in and has already granted access for the extension, then `launchWebAuthFlow()` can complete silently, without any user interaction. Otherwise (if the service provider needs the user to sign in, or to authorize the extension), then `launchWebAuthFlow()` will prompt the user: that is, the flow will be interactive.

Extensions should not launch interactive flows except in response to a user action. However, sometimes extensions still want to access the user's data without a direct user action (for example, imagine an extension that wants to access data when the browser launches).

This is the purpose of `interactive`: if you omit `interactive` or set it to `false`, then the flow is forced to conclude silently: if the service provider needs to interact with the user, the flow will just fail. So as a general rule: set `interactive` to `true` if you're launching the flow in response to a user action, and omit it otherwise.

### Return value

A `Promise`. If the extension is authorized successfully, this will be fulfilled with a string containing the redirect URL. The URL will include a parameter that either is an access token or can be exchanged for an access token, using the documented flow for the particular service provider.

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

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

Examples
--------

This function authorizes an extension to access a user's Google data, according to the documentation at https://developers.google.com/identity/protocols/OAuth2UserAgent. Validation of the returned access token isn't shown here:

```js
function validate(redirectURL) {
  // validate the access token
}

function authorize() {
  const redirectURL = browser.identity.getRedirectURL();
  const clientID =
    "664583959686-fhvksj46jkd9j5v96vsmvs406jgndmic.apps.googleusercontent.com";
  const scopes = ["openid", "email", "profile"];
  let authURL = "https://accounts.google.com/o/oauth2/auth";
  authURL += `?client\_id=${clientID}`;
  authURL += `&response\_type=token`;
  authURL += `&redirect\_uri=${encodeURIComponent(redirectURL)}`;
  authURL += `&scope=${encodeURIComponent(scopes.join(" "))}`;

  return browser.identity.launchWebAuthFlow({
    interactive: true,
    url: authURL,
  });
}

function getAccessToken() {
  return authorize().then(validate);
}
```

### Example extensions

* google-userinfo

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


identity.getRedirectURL() - Mozilla

identity.getRedirectURL()
=========================

Generates a URL that you can use as a redirect URL.

The URL is derived from your extension's ID, so if you use this function you should probably set your extension's ID explicitly using the `browser_specific_settings` key (otherwise, each time you temporarily install the extension, you'll get a different redirect URL).

See Getting a redirect URL for more information on redirect URLs.

Syntax
------

```js
let redirectURL = browser.identity.getRedirectURL()
```

### Parameters

None.

### Return value

A string containing a redirect URL value.

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

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

Examples
--------

Get the redirect URL:

```js
let redirectURL = browser.identity.getRedirectURL();
```

### Example extensions

* google-userinfo

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


webRequest.CertificateInfo - Mozilla

webRequest.CertificateInfo
==========================

An object describing a single X.509 certificate.

The `SecurityInfo` object returned from the `webRequest.getSecurityInfo()` API includes a `certificates` property which is an array of these objects.

Type
----

Values of this type are objects. They contain the following properties:

`fingerprint`

`Object`. An object with the following properties:

`sha1`

`String`. SHA-1 hash of the certificate's DER encoding.

`sha256`

`String`. SHA-256 hash of the certificate's DER encoding.

`isBuiltInRoot`

`Boolean`. `true` if the certificate is one of the trust roots installed in the browser, `false` otherwise.

`issuer`

`String`. Name of the organization that issued this certificate, represented as a Distinguished Name and formatted as a comma-separated list of Relative Distinguished Names, each of the form "type=value".

For example: "CN=DigiCert SHA2 Secure Server CA,O=DigiCert Inc,C=US".

`rawDER`

`Array` of `Number`. If `webRequest.getSecurityInfo()` was called with the `rawDER` option present and set to `true`, this will contain the DER encoding of the certificate.

`serialNumber`

`String`. The certificate's serial number.

`subject`

`String`. Name of the organization that issued this certificate, represented as a Distinguished Name and formatted as a comma-separated list of Relative Distinguished Names, each of the form "type=value".

For example: "CN=\*.cdn.mozilla.net,O=Mozilla Corporation,L=Mountain View,ST=California,C=US".

`subjectPublicKeyInfoDigest`

`Object`. An object containing the following properties:

`sha256`

`String`. Base64 encoded SHA-256 hash of the DER-encoded public key info.

`validity`

`Object`. Validity period for the certificate. An object containing the following properties:

`start`

`Number`. The start of the certificate's validity period, in milliseconds since the epoch.

`end`

`Number`. The end of the certificate's validity period, in milliseconds since the epoch.

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

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


webRequest.filterResponseData() - Mozilla

webRequest.filterResponseData()
===============================

Use this function to create a `webRequest.StreamFilter` object for a request. The stream filter gives the web extension full control over the stream, with the ability to monitor and modify the response. It's the extension's responsibility to write and close or disconnect the stream, as the default behavior is to keep the request open without a response.

You typically call this function from a `webRequest` event listener.

Firefox uses an optimized byte cache for script requests. This optimized byte cache overrides the normal request caching. Data from this cache is not available in a form useful to extensions. If your extension needs to filter scripts, create your filter in `webRequest.onBeforeRequest`. Doing this ensures that the filter is created prior to the attempt to load from cache, thereby avoiding the optimized cache.

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

To use this API, you must have the `"webRequest"` and `"webRequestBlocking"` API permissions, and for the event listener, the host permission for the host. In addition:

* From Firefox 95, to use this API to intercept requests related to the loading of service worker scripts, the `"webRequestFilterResponse.serviceWorkerScript"` permission is also required.
* From Firefox 110, Manifest V3 extensions must also request the `"webRequestFilterResponse"` permission to use this API.
Syntax
------

```js
let filter = browser.webRequest.filterResponseData(
  requestId       // string
)
```

### Parameters

`requestId`

`string`. ID of the request to filter. You can get this from the `details` object that is passed into any `webRequest` event listeners.

### Return value

A `webRequest.StreamFilter` object that you can use to monitor and modify the response.

Examples
--------

This example shows a minimal implementation that passes through the stream data and closes the filter stream when the stream finishes receiving data. The code would be called from a `webRequest` event listener and the event listener provides `details`.

```js
let filter = browser.webRequest.filterResponseData(details.requestId);
filter.ondata = (event) => {
  console.log(`filter.ondata received ${event.data.byteLength} bytes`);
  filter.write(event.data);
};
filter.onstop = (event) => {
  // The extension should always call filter.close() or filter.disconnect()
  // after creating the StreamFilter, otherwise the response is kept alive forever.
  // If processing of the response data is finished, use close. If any remaining
  // response data should be processed by Firefox, use disconnect.
  filter.close();
};
```

This example, taken from the http-response example extension, creates a filter in `webRequest.onBeforeRequest` and uses it, to modify the first chunk of the response:

```js
function listener(details) {
  let filter = browser.webRequest.filterResponseData(details.requestId);
  let decoder = new TextDecoder("utf-8");
  let encoder = new TextEncoder();

  filter.ondata = (event) => {
    let str = decoder.decode(event.data, { stream: true });
    // Just change any instance of Example in the HTTP response
    // to WebExtension Example.
    str = str.replace(/Example/g, "WebExtension Example");
    filter.write(encoder.encode(str));
    filter.disconnect();
  };

  return {};
}

browser.webRequest.onBeforeRequest.addListener(
  listener,
  { urls: ["https://example.com/\*"], types: ["main\_frame"] },
  ["blocking"],
);
```

### Example extensions

* http-response

**Note:** The example above only works for small requests that aren't chunked or streamed. More advanced examples are documented with `webRequest.StreamFilter.ondata`.

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

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


webRequest.onSendHeaders - Mozilla

webRequest.onSendHeaders
========================

This event is fired just before sending headers. If your extension or some other extension modified headers in ``onBeforeSendHeaders``, you'll see the modified version here.

This event is informational only.

Syntax
------

```js
browser.webRequest.onSendHeaders.addListener(
  listener,             // function
  filter,               // object
  extraInfoSpec         // optional array of strings
)
browser.webRequest.onSendHeaders.removeListener(listener)
browser.webRequest.onSendHeaders.hasListener(listener)
```

Events have three functions:

`addListener(listener, filter, extraInfoSpec)`

Adds a listener to this event.

`removeListener(listener)`

Stop listening to this event. The `listener` argument is the listener to remove.

`hasListener(listener)`

Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.

addListener syntax
------------------

### Parameters

`listener`

The function called when this event occurs. The function is passed this argument:

`details`

`object`. Details about the request. See the details section for more information.

`filter`

`webRequest.RequestFilter`. A filter that restricts the events that is sent to this listener.

`extraInfoSpec` Optional

`array` of `string`. Extra options for the event. You can only pass one value here:

* `"requestHeaders"`: include the request headers in the `details` object passed to the listener

Additional objects
------------------

### details

`cookieStoreId`

`string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See Work with contextual identities for more information.

`documentUrl`

`string`. URL of the document in which the resource will be loaded. For example, if the web page at "https://example.com" contains an image or an iframe, then the `documentUrl` for the image or iframe will be "https://example.com". For a top-level document, `documentUrl` is undefined.

`frameId`

`integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab

`incognito`

`boolean`. Whether the request is from a private browsing window.

`method`

`string`. Standard HTTP method: for example, "GET" or "POST".

`originUrl`

`string`. URL of the resource which triggered the request. For example, if "https://example.com" contains a link, and the user clicks the link, then the `originUrl` for the resulting request is "https://example.com".

The `originUrl` is often but not always the same as the `documentUrl`. For example, if a page contains an iframe, and the iframe contains a link that loads a new document into the iframe, then the `documentUrl` for the resulting request will be the iframe's parent document, but the `originUrl` will be the URL of the document in the iframe that contained the link.

`parentFrameId`

`integer`. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists.

`proxyInfo`

`object`. This property is present only if the request is being proxied. It contains the following properties:

`host`

`string`. The hostname of the proxy server.

`port`

`integer`. The port number of the proxy server.

`type`

`string`. The type of proxy server. One of:

* "http": HTTP proxy (or SSL CONNECT for HTTPS)
* "https": HTTP proxying over TLS connection to proxy
* "socks": SOCKS v5 proxy
* "socks4": SOCKS v4 proxy
* "direct": no proxy
* "unknown": unknown proxy

`username`

`string`. Username for the proxy service.

`proxyDNS`

`boolean`. True if the proxy will perform domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup.

`failoverTimeout`

`integer`. Failover timeout in seconds. If the proxy connection fails, the proxy will not be used again for this period.

`requestId`

`string`. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request.

`requestHeaders` Optional

`webRequest.HttpHeaders`. The HTTP request headers that have been sent out with this request.

`tabId`

`integer`. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.

`thirdParty`

`boolean`. Indicates whether the request and its content window hierarchy are third party.

`timeStamp`

`number`. The time when this event fired, in milliseconds since the epoch.

`type`

`webRequest.ResourceType`. The type of resource being requested: for example, "image", "script", "stylesheet".

`url`

`string`. Target of the request.

`urlClassification`

`object`. The type of tracking associated with the request, if with the request has been classified by Firefox Tracking Protection. This is an object with the following properties:

`firstParty`

`array` of `strings`. Classification flags for the request's first party.

`thirdParty`

`array` of `strings`. Classification flags for the request or its window hierarchy's third parties.

The classification flags include:

* `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin that has been found to fingerprint but is not considered to participate in tracking, such as a payment provider.
* `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources.
* `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request, the `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker.
* `any_basic_tracking`: a meta flag that combines any tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`.
* `any_strict_tracking`: a meta flag that combines any tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`.
* `any_social_tracking`: a meta flag that combines any social tracking flags.

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

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

Examples
--------

This code logs all cookies that will be sent in making requests to the target match pattern:

```js
// The target match pattern
let targetPage = "\*://\*.google.ca/\*";

// Log cookies sent with this request
function logCookies(e) {
  for (const header of e.requestHeaders) {
    if (header.name === "Cookie") {
      console.log(header.value);
    }
  }
}

// Listen for onSendHeaders, and pass
// "requestHeaders" so we get the headers
browser.webRequest.onSendHeaders.addListener(
  logCookies,
  { urls: [targetPage] },
  ["requestHeaders"],
);
```

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


webRequest.ResourceType - Mozilla

webRequest.ResourceType
=======================

This type is a string, which represents the context in which a resource was fetched in a web request.

It's used to filter the requests you listen to using the webRequest API. For example: you can listen to requests only for images, or only for scripts.

Type
----

Values of this type are strings. Possible values are:

`beacon`

Requests sent through the Beacon API.

`csp_report`

Requests sent to the `report-uri` given in the `Content-Security-Policy` header, when an attempt to violate the policy is detected.

`font`

Web fonts loaded for a `@font-face` CSS rule.

`image`

Resources loaded to be rendered as image, except for `imageset` on browsers that support that type (see browser compatibility below).

`imageset`

Images loaded by a `<picture>` element or given in an `<img>` element's `srcset` attribute.

`main_frame`

Top-level documents loaded into a tab.

`media`

Resources loaded by a `<video>` or `<audio>` element.

`object`

Resources loaded by an `<object>` or `<embed>` element.

Browsers that don't have a dedicated `object_subrequest` type (see browser compatibility below), also label subsequent requests sent by the plugin as `object`.

`object_subrequest`

Requests sent by plugins.

`ping`

Requests sent to the URL given in a hyperlink's `ping` attribute, when the hyperlink is followed.

Browsers that don't have a dedicated `beacon` type (see browser compatibility below), also label requests sent through the Beacon API as `ping`.

`script`

Code that is loaded to be executed by a `<script>` element or running in a Worker.

`speculative`

In a speculative connection, the browser has determined that a request to a URI may be coming soon, so it starts a TCP and/or TLS handshake immediately, so it is ready more quickly when the resource is actually requested. Note that this type of connection does not provide valid tab information, so request details such as `tabId`, `frameId`, `parentFrameId`, etc. are inaccurate.

`stylesheet`

CSS stylesheets loaded to describe the representation of a document.

`sub_frame`

Documents loaded into an `<iframe>` or `<frame>` element.

`web_manifest`

Web App Manifests loaded for websites that can be installed to the homescreen.

`websocket`

Requests initiating a connection to a server through the WebSocket API.

`xml_dtd`

DTDs loaded for an XML document.

`xmlhttprequest`

Requests sent by an `XMLHttpRequest` object or through the Fetch API.

`xslt`

XSLT stylesheets loaded for transforming an XML document.

`other`

Resources that aren't covered by any other available type.

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.webRequest` API. This documentation is derived from `web_request.json` in the Chromium code.


webRequest.RequestFilter - Mozilla

webRequest.RequestFilter
========================

An object describing filters to apply to webRequest events.

Type
----

Values of this type are objects. They contain the following properties:

`urls`

`array` of `string`. An array of match patterns. The listener will only be called for requests whose targets match any of the given patterns. Only requests made using HTTP or HTTPS will trigger events, other protocols (such as data: and file:) supported by pattern matching do not trigger events. `view-source:` requests may be matched based on its inner URL.

`types` Optional

`array` of ``webRequest.ResourceType``. A list of resource types (for example, stylesheets, images, scripts). The listener will only be called for requests for resources which are one of the given types.

`tabId` Optional

`integer`. The listener will only be called for requests from the `tab` identified by this ID.

`windowId` Optional

`integer`. The listener will only be called for requests from the `window` identified by this ID.

`incognito` Optional

`boolean`. If provided, requests that do not match the incognito state (`true` or `false`) will be filtered out.

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.webRequest` API. This documentation is derived from `web_request.json` in the Chromium code.


webRequest.BlockingResponse - Mozilla

webRequest.BlockingResponse
===========================

An object of this type is returned by event listeners that have set `"blocking"` in their `extraInfoSpec` argument.

By setting particular properties in `BlockingResponse`, the listener can modify network requests.

Note that you can't set all this object's properties in every listener: the properties you can set are dependent on the event that triggered this listener, as detailed below.

Type
----

Values of this type are objects. They contain the following properties:

`authCredentials` Optional

`object`. If set, the request is made using the given credentials. You can only set this property in `onAuthRequired`. The `authCredentials` property is an object with the following properties:

`username`

`string`. Username to supply.

`password`

`string`. Password to supply.

`cancel` Optional

`boolean`. If `true`, the request is cancelled. You can only set this property in `onBeforeRequest`, `onBeforeSendHeaders`, `onHeadersReceived`, and `onAuthRequired`.

`redirectUrl` Optional

`string`. This is a URL, and if set, the original request is redirected to that URL. You can only set this property in `onBeforeRequest` or `onHeadersReceived`.

Redirections to non-HTTP schemes such as data: are allowed, but they are not currently supported (Firefox bug 707624). Redirects use the same request method as the original request unless initiated from `onHeadersReceived` stage, in which case the redirect uses the GET method.

If an extension wants to redirect a public (e.g. HTTPS) URL to an extension page, the extension's manifest.json file must contain a web\_accessible\_resources key that lists the URL for the extension page.

`requestHeaders` Optional

`webRequest.HttpHeaders`. This is an `HttpHeaders` object, an array in which each object represents a header. If set, the request is made with these headers rather than the original headers. You can only set this property in `onBeforeSendHeaders` .

`responseHeaders` Optional

`webRequest.HttpHeaders`. This is an `HttpHeaders` object, an array in which each object represents a header. If set, the server is assumed to have responded with these response headers instead of the originals. You can only set this property in `onHeadersReceived`. If multiple extensions attempt to set the same header (for example, `Content-Security-Policy`), only one of the changes will be successful.

`upgradeToSecure` Optional

`boolean`. If set to `true` and the original request is an HTTP request, this will prevent the original request from being sent and instead make a secure (HTTPS) request. If any extension returns `redirectUrl` in `onBeforeRequest`, then `upgradeToSecure` will be ignored for that request. You can only set this property in `onBeforeRequest`.

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.webRequest` API. This documentation is derived from `web_request.json` in the Chromium code.


webRequest.StreamFilter - Mozilla

webRequest.StreamFilter
=======================

A `StreamFilter` is an object you use to monitor and modify HTTP responses.

To create a `StreamFilter`, call `webRequest.filterResponseData()`, passing the ID of the web request you want to filter.

You can think of the stream filter as sitting between the networking stack and the browser's rendering engine. The filter is passed HTTP response data as it's received from the network. It can examine and modify the data before passing it along to the rendering engine, where it is parsed and rendered. The filter has full control over the response body, and the default behavior without any listeners or write calls is to have a stream without content that never closes.

The filter generates four different events:

* `onstart` when the filter is about to start receiving response data.
* `ondata` when some response data has been received by the filter and is available to be examined or modified.
* `onstop` when the filter has finished receiving response data.
* `onerror` if an error has occurred in initializing and operating the filter.

You can listen to each event by assigning a listener function to its attribute:

```js
filter.onstart = (event) => {
  console.log("started");
};
```

Note that the request is blocked during the execution of any event listeners.

The filter provides a `write()` function. At any time from the `onstart` event onwards you can use this function to write data to the output stream.

If you assign listeners to any of the filter's events, all the response data passed to the rendering engine is supplied through calls you make to `write()`. So, if you add a listener and don't call `write()` the rendered page is blank.

Once you have finished interacting with the response, call either of the following:

* `disconnect()`: This disconnects the filter from the request, so the rest of the response is processed normally.
* `close()`: This closes the request, so no additional response data will be processed.

The filter also provides functions to `suspend()` and `resume()` the request.

Methods
-------

`webRequest.StreamFilter.close()`

Closes the request.

`webRequest.StreamFilter.disconnect()`

Disconnects the filter from the request.

`webRequest.StreamFilter.resume()`

Resumes processing of the request.

`webRequest.StreamFilter.suspend()`

Suspends processing of the request.

`webRequest.StreamFilter.write()`

Writes some data to the output stream.

Properties
----------

`webRequest.StreamFilter.ondata`

Event handler which is called when incoming data is available.

`webRequest.StreamFilter.onerror`

Event handler which is called when an error has occurred.

`webRequest.StreamFilter.onstart`

Event handler which is called when the stream is about to start receiving data.

`webRequest.StreamFilter.onstop`

Event handler which is called when the stream has no more data to deliver and has closed.

`webRequest.StreamFilter.error`

When `webRequest.StreamFilter.onerror` is called, this will describe the error.

`webRequest.StreamFilter.status`

Describes the current status of the stream.

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

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

Examples
--------

This code listens for `onstart`, `ondata`, and `onstop`. It logs those events, and the response data as an `ArrayBuffer` itself:

```js
function listener(details) {
  let filter = browser.webRequest.filterResponseData(details.requestId);

  filter.onstart = (event) => {
    console.log("started");
  };

  filter.ondata = (event) => {
    console.log(event.data);
    filter.write(event.data);
  };

  filter.onstop = (event) => {
    console.log("finished");
    filter.disconnect();
  };

  //return {}; // not needed
}

browser.webRequest.onBeforeRequest.addListener(
  listener,
  { urls: ["https://example.org/"], types: ["main\_frame"] },
  ["blocking"],
);
```


webRequest.onBeforeRequest - Mozilla

webRequest.onBeforeRequest
==========================

This event is triggered when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel or redirect the request.

To cancel or redirect the request, first include `"blocking"` in the `extraInfoSpec` array argument to `addListener()`. Then, in the listener function, return a `BlockingResponse` object, setting the appropriate property:

* to cancel the request, include a property `cancel` with the value `true`.
* to redirect the request, include a property `redirectUrl` with the value set to the URL to which you want to redirect.

If an extension wants to redirect a public (e.g. HTTPS) URL to an extension page, the extension's manifest.json file must contain a web\_accessible\_resources key that lists the URL for the extension page.

When multiple blocking handlers modify a request, only one set of modifications take effect. Redirects and cancellations have the same precedence. So if you canceled a request, you might see another request with the same `requestId` again if another blocking handler redirected the request.

From Firefox 52 onwards, instead of returning `BlockingResponse`, the listener can return a `Promise` which is resolved with a `BlockingResponse`. This enables the listener to process the request asynchronously.

If you use `"blocking"`, you must have the "webRequestBlocking" API permission in your manifest.json.

Syntax
------

```js
browser.webRequest.onBeforeRequest.addListener(
  listener,             // function
  filter,               // object
  extraInfoSpec         // optional array of strings
)
browser.webRequest.onBeforeRequest.removeListener(listener)
browser.webRequest.onBeforeRequest.hasListener(listener)
```

Events have three functions:

`addListener(listener, filter, extraInfoSpec)`

Adds a listener to this event.

`removeListener(listener)`

Stop listening to this event. The `listener` argument is the listener to remove.

`hasListener(listener)`

Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.

addListener syntax
------------------

### Parameters

`listener`

The function called when this event occurs. The function is passed this argument:

`details`

`object`. Details about the request. See the details section for more information.

Returns: `webRequest.BlockingResponse`. If `"blocking"` is specified in the `extraInfoSpec` parameter, the event listener should return a `BlockingResponse` object, and can set either its `cancel` or its `redirectUrl` properties. From Firefox 52 onwards, instead of returning `BlockingResponse`, the listener can return a `Promise` which is resolved with a `BlockingResponse`. This enables the listener to process the request asynchronously.

`filter`

`webRequest.RequestFilter`. A filter that restricts the events that is sent to this listener.

`extraInfoSpec` Optional

`array` of `string`. Extra options for the event. You can pass any of the following values:

* `"blocking"`: make the request synchronous, so you can cancel or redirect the request
* `"requestBody"`: include `requestBody` in the `details` object passed to the listener

Additional objects
------------------

### details

`cookieStoreId`

`string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See Work with contextual identities for more information.

`documentUrl`

`string`. URL of the document in which the resource will be loaded. For example, if the web page at "https://example.com" contains an image or an iframe, then the `documentUrl` for the image or iframe will be "https://example.com". For a top-level document, `documentUrl` is undefined.

`frameAncestors`

`array`. Contains information for each document in the frame hierarchy up to the top-level document. The first element in the array contains information about the immediate parent of the document being requested, and the last element contains information about the top-level document. If the load is actually for the top-level document, then this array is empty.

`url`

`string`. The URL that the document was loaded from.

`frameId`

`integer`. The `frameId` of the document. `details.frameAncestors[0].frameId` is the same as `details.parentFrameId`.

`frameId`

`integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.

`incognito`

`boolean`. Whether the request is from a private browsing window.

`method`

`string`. Standard HTTP method: for example, "GET" or "POST".

`originUrl`

`string`. URL of the resource which triggered the request. For example, if "https://example.com" contains a link, and the user clicks the link, then the `originUrl` for the resulting request is "https://example.com".

The `originUrl` is often but not always the same as the `documentUrl`. For example, if a page contains an iframe, and the iframe contains a link that loads a new document into the iframe, then the `documentUrl` for the resulting request will be the iframe's parent document, but the `originUrl` will be the URL of the document in the iframe that contained the link.

`parentFrameId`

`integer`. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists.

`proxyInfo`

`object`. This property is present only if the request is being proxied. It contains the following properties:

`host`

`string`. The hostname of the proxy server.

`port`

`integer`. The port number of the proxy server.

`type`

`string`. The type of proxy server. One of:

* "http": HTTP proxy (or SSL CONNECT for HTTPS)
* "https": HTTP proxying over TLS connection to proxy
* "socks": SOCKS v5 proxy
* "socks4": SOCKS v4 proxy
* "direct": no proxy
* "unknown": unknown proxy

`username`

`string`. Username for the proxy service.

`proxyDNS`

`boolean`. True if the proxy will perform domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup.

`failoverTimeout`

`integer`. Failover timeout in seconds. If the proxy connection fails, the proxy will not be used again for this period.

`requestBody` Optional

`object`. Contains the HTTP request body data. Only provided if `extraInfoSpec` contains `"requestBody"`.

`error` Optional

`string`. This is set if any errors were encountered when obtaining request body data.

`formData` Optional

`object`. This object is present if the request method is POST and the body is a sequence of key-value pairs encoded in UTF-8 as either "multipart/form-data" or "application/x-www-form-urlencoded".

It is a dictionary in which each key contains the list of all values for that key. For example: `{'key': ['value1', 'value2']}`. If the data is of another media type, or if it is malformed, the object is not present.

`raw` Optional

`array` of ``webRequest.UploadData``. If the request method is PUT or POST, and the body is not already parsed in `formData`, then this array contains the unparsed request body elements.

`requestId`

`string`. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request.

`tabId`

`integer`. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.

`thirdParty`

`boolean`. Indicates whether the request and its content window hierarchy are third party.

`timeStamp`

`number`. The time when this event fired, in milliseconds since the epoch.

`type`

`webRequest.ResourceType`. The type of resource being requested: for example, "image", "script", "stylesheet".

`url`

`string`. Target of the request.

`urlClassification`

`object`. The type of tracking associated with the request, if with the request has been classified by Firefox Tracking Protection. This is an object with the following properties:

`firstParty`

`array` of `strings`. Classification flags for the request's first party.

`thirdParty`

`array` of `strings`. Classification flags for the request or its window hierarchy's third parties.

The classification flags include:

* `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin that has been found to fingerprint but is not considered to participate in tracking, such as a payment provider.
* `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources.
* `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request, the `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker.
* `any_basic_tracking`: a meta flag that combines any tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`.
* `any_strict_tracking`: a meta flag that combines any tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`.
* `any_social_tracking`: a meta flag that combines any social tracking flags.

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

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

### DNS resolution ordering when BlockingResponse is used

Regarding DNS resolution when BlockingResponse is used with OnBeforeRequest: In HTTP Channel, onBeforeRequest with blocking response does happen prior to DNS resolution and also prior to speculative connect. For other channels, speculative connect may cause DNS requests to happen before onBeforeRequest. This ordering is not something an extension developer ought to rely on as it may vary across browsers, and from one browser version to another, let alone one request channel to another. Refer BugZilla issue clarification provided by Mozilla developers on DNS resolution ordering

Examples
--------

This code logs the URL for every resource requested which matches the <all\_urls> pattern:

```js
function logURL(requestDetails) {
  console.log(`Loading: ${requestDetails.url}`);
}

browser.webRequest.onBeforeRequest.addListener(logURL, {
  urls: ["<all\_urls>"],
});
```

This code cancels requests for images that are made to URLs under "https://developer.mozilla.org/" (to see the effect, visit any page on MDN that contains images, such as webRequest):

```js
// match pattern for the URLs to redirect
let pattern = "https://developer.mozilla.org/\*";

// cancel function returns an object
// which contains a property `cancel` set to `true`
function cancel(requestDetails) {
  console.log(`Canceling: ${requestDetails.url}`);
  return { cancel: true };
}

// add the listener,
// passing the filter argument and "blocking"
browser.webRequest.onBeforeRequest.addListener(
  cancel,
  { urls: [pattern], types: ["image"] },
  ["blocking"],
);
```

This code replaces, by redirection, all network requests for images that are made to URLs under "https://developer.mozilla.org/" (to see the effect, visit any page on MDN that contains images, such as webRequest):

```js
// match pattern for the URLs to redirect
let pattern = "https://developer.mozilla.org/\*";

// redirect function
// returns an object with a property `redirectURL`
// set to the new URL
function redirect(requestDetails) {
  console.log(`Redirecting: ${requestDetails.url}`);
  return {
    redirectUrl:
      "https://38.media.tumblr.com/tumblr\_ldbj01lZiP1qe0eclo1\_500.gif",
  };
}

// add the listener,
// passing the filter argument and "blocking"
browser.webRequest.onBeforeRequest.addListener(
  redirect,
  { urls: [pattern], types: ["image"] },
  ["blocking"],
);
```

This code is exactly like the previous example, except that the listener handles the request asynchronously. It returns a `Promise` that sets a timer, and resolves with the redirect URL when the timer expires:

```js
// match pattern for the URLs to redirect
let pattern = "https://developer.mozilla.org/\*";

// URL we will redirect to
let redirectUrl =
  "https://38.media.tumblr.com/tumblr\_ldbj01lZiP1qe0eclo1\_500.gif";

// redirect function returns a Promise
// which is resolved with the redirect URL when a timer expires
function redirectAsync(requestDetails) {
  console.log(`Redirecting async: ${requestDetails.url}`);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ redirectUrl });
    }, 2000);
  });
}

// add the listener,
// passing the filter argument and "blocking"
browser.webRequest.onBeforeRequest.addListener(
  redirectAsync,
  { urls: [pattern], types: ["image"] },
  ["blocking"],
);
```

Another example, that redirects all images to a data URL:

```js
let pattern = "https://developer.mozilla.org/\*";

let image = `
 <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
 <rect style="stroke-width: 10; stroke: #666;" width="100%" height="100%" fill="#d4d0c8" />
 <text transform="translate(0, 9)" x="50%" y="50%" width="100%" fill="#666" height="100%" style="text-anchor: middle; font: bold 10pt 'Segoe UI', Arial, Helvetica, Sans-serif;">Blocked</text>
 </svg>
`;

function listener(details) {
  const redirectUrl = `data:image/svg+xml,${encodeURIComponent(image)}`;
  return { redirectUrl };
}

browser.webRequest.onBeforeRequest.addListener(
  listener,
  { urls: [pattern], types: ["image"] },
  ["blocking"],
);
```

Here's another version:

```js
function randomColor() {
  return `#${Math.floor(Math.random() \* 16777215).toString(16)}`;
}

const pattern = "https://developer.mozilla.org/\*";

let image = `
 <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
 <rect width="100%" height="100%" fill="${randomColor()}"/>
 </svg>
`;

function listener(details) {
  const redirectUrl = `data:image/svg+xml,${encodeURIComponent(image)}`;
  return { redirectUrl };
}

browser.webRequest.onBeforeRequest.addListener(
  listener,
  { urls: [pattern], types: ["image"] },
  ["blocking"],
);
```

### Example extensions

* http-response

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