scripting.unregisterContentScripts() - Mozilla

scripting.unregisterContentScripts()
====================================

Unregisters one or more content scripts.

**Note:** This method is available in Manifest V3 or higher in Chrome and Firefox 101. In Firefox 102+, this method is also available in Manifest V2.

To use this API you must have the `"scripting"` permission and permission for the page's URL, either explicitly as a host permission or using the activeTab permission.

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

Syntax
------

```js
await browser.scripting.unregisterContentScripts(
  scripts         // object
)
```

### Parameters

`scripts` Optional

`scripting.ContentScriptFilter`. A filter to identify the dynamic content scripts to unregistered. If not specified, all dynamic content scripts are unregistered.

### Return value

A `Promise` that fulfills with no arguments when all the scripts are unregistered. If any error occurs, the promise is rejected.

Examples
--------

This example unregisters a registered content script with ID `a-script`:

```js
try {
  await browser.scripting.unregisterContentScripts({
    ids: ["a-script"],
  });
} catch (err) {
  console.error(`failed to unregister content scripts: ${err}`);
}
```

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


scripting.getRegisteredContentScripts() - Mozilla

scripting.getRegisteredContentScripts()
=======================================

Returns all the content scripts registered with `scripting.registerContentScripts()` or a subset of the registered scripts when using a filter.

**Note:** This method is available in Manifest V3 or higher in Chrome and Firefox 101. In Firefox 102+, this method is also available in Manifest V2.

To use this API you must have the `"scripting"` permission and permission for the page's URL, either explicitly as a host permission or using the activeTab permission.

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

Syntax
------

```js
let scripts = await browser.scripting.getRegisteredContentScripts(
  filter          // object
)
```

### Parameters

`filter` Optional

`scripting.ContentScriptFilter`. A filter for the registered script details to return.

### Return value

A `Promise` that fulfills with an array of `scripting.RegisteredContentScript`. If any error occurs, the promise is rejected.

Examples
--------

This example returns all the registered content scripts:

```js
// Register two content scripts.
await browser.scripting.registerContentScripts([
  {
    id: "script-1",
    js: ["script-1.js"],
    matches: ["\*://example.com/\*"],
  },
  {
    id: "script-2",
    js: ["script-2.js"],
    matches: ["\*://example.com/\*"],
  },
]);

// Retrieve all content scripts.
let scripts = await browser.scripting.getRegisteredContentScripts();
console.log(scripts.map((script) => script.id)); // ["script-1", "script-2"]

// Only retrieve the second script.
scripts = await browser.scripting.getRegisteredContentScripts({
  ids: ["script-2"],
});
console.log(scripts.map((script) => script.id)); // ["script-2"]
```

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


userScripts.register() - Mozilla

userScripts.register()
======================

This method enables user scripts to be registered from an extension's pages (such as the background page).

This method is very similar to the `contentScripts.register()` API method (for example, they both return a promise that resolves to an API object with an `unregister()` method for unregistering the script). There are, however, differences in the options supported.

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

Syntax
------

```js
const registeredUserScript = await browser.userScripts.register(
  userScriptOptions       // object
);
// …
await registeredUserScript.unregister();
```

### Parameters

`userScriptOptions`

`object`. Represents the user scripts to register. It has similar syntax to `contentScripts.register()`.

The `UserScriptOptions` object has the following properties:

`scriptMetadata` Optional

A `JSON` object containing arbitrary metadata properties associated with the registered user scripts. However, while arbitrary, the object must be serializable, so it is compatible with the structured clone algorithm. This metadata is used to pass details from the script to the `API script`. For example, providing details of a subset of the APIs that need to be injected by the `API script`. The API does not use this metadata,

`allFrames` Optional

Same as `all_frames` in the `content_scripts` key.

`cookieStoreId` Optional

An array of cookie store ID strings or a string containing a cookie store ID. Registers the user script in the tabs that belong to the cookie store IDs. This enables scripts to be registered for all default or non-contextual identity tabs, private browsing tabs (if the extension is enabled in private browsing), the tabs of a contextual identity, or a combination of these.

`excludeGlobs` Optional

Same as `exclude_globs` in the `content_scripts` key.

`excludeMatches` Optional

Same as `exclude_matches` in the `content_scripts` key.

`includeGlobs` Optional

Same as `include_globs` in the `content_scripts` key.

`js`

An array of objects. Each object has either a property named `file`, which is a URL starting at the extension's manifest.json and pointing to a JavaScript file to register, or a property named `code`, which contains JavaScript code to register.

`matchAboutBlank` Optional

Same as `match_about_blank` in the `content_scripts` key.

`matches`

 Same as `matches` in the `content_scripts` key.
 The URL patterns provided in `matches` must be enabled by the host permissions defined in the manifest `permission` property or enabled by the user from the `optional_permissions` list. For example, if matches includes `https://mozilla.org/a` a script is only registered if host permissions include, for example, `https://mozilla.org/*`. If the URL pattern isn't enabled, the call to register fails with the error "Permission denied to register a user script for ORIGIN".

`runAt` Optional

Same as `run_at` in the `content_scripts` key.

Unlike content script options, the userScriptOptions object does not have a CSS property. Use `contentScripts.register()` to dynamically register and unregister stylesheets.

### Return value

A `Promise` that is fulfilled with a `RegisteredUserScript` object that is use to unregister the user scripts.

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

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

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

See also
--------

* `contentScripts.register()`
* `RegisteredUserScript.unregister()`


userScripts.onBeforeScript - Mozilla

userScripts.onBeforeScript
==========================

The `onBeforeScript` event of the `browser.userScripts` is fired before a user script is executed. It can only be included in the API script, the script registered in `"user_scripts"`, where it is used to detect that the custom API methods should be exported to the user script.

Syntax
------

```js
browser.userScripts.onBeforeScript.addListener(listener)
browser.userScripts.onBeforeScript.removeListener(listener)
browser.userScripts.onBeforeScript.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:

`script`

An `object` that represents the user script that matched a web page. Its properties and methods are as follows:

`defineGlobals`

A method that exports an object containing properties and methods available globally to the user script sandbox. This method must be called synchronously to guarantee that the user script has not executed.

`export`

A method that converts a value to one that the user script code can access. This method is used in API methods exported to the user script to result or resolve non-primitive values. The exported objects can also provide methods that the user script code can access and call.

`global`

An `object` that provides access to the sandbox for the user script.

`metadata`

The `scriptMetadata` property set when the user script was registered using `userScripts.register`.

Examples
--------

An example of how the listener might be used:

```js
browser.userScripts.onBeforeScript.addListener((script) => {
  script; // This is an API object that represents the user script
  // that is going to be executed.

  script.metadata; // Access the user script metadata (returns the
  // value of the scriptMetadata property from
  // the call to userScripts.register).

  // Export some global properties into the user script sandbox
  // (this method has to be called synchronously from the
  // listener, otherwise the user script may have executed).
  script.defineGlobals({
    aGlobalPropertyAccessibleFromUserScriptCode: "prop value",

    myCustomAPIMethod(param1, param2) {
      // Custom methods exported from the API script can use
      // the WebExtensions APIs available to content scripts.
      browser.runtime.sendMessage(/\* … \*/);
      // …

      return 123; // primitive values can be returned directly
      // …

      // Non primitive values have to be exported explicitly
      // using the export method provided by the script API
      // object
      return script.export({
        objKey1: {
          nestedProp: "nestedValue",
        },
        // Explicitly exported objects can also provide methods.
        objMethod() {
          /\* … \*/
        },
      });
    },

    async myAsyncMethod(param1, param2, param3) {
      // exported methods can also be declared as async
    },
  });
});
```

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

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

See also
--------

* `contentScripts`


UserScripts.UserScriptOptions - Mozilla

UserScripts.UserScriptOptions
=============================

The UserScriptOptions object represents the content scripts to register. It has similar syntax to the contentScript options supported by browser.contentScripts.register. The differences are:

* it does not support a CSS property (use browser.contentScripts.register to dynamically register/unregister stylesheets)
* It does support an optional scriptMetadata property (as a plain JSON object which contains some metadata properties associated to the registered userScripts)

The UserScriptOptions object has the following properties:

`allFrames` Optional

Same as `all_frames` in the `content_scripts` key.

`excludeGlobs` Optional

Same as `exclude_globs` in the `content_scripts` key.

`excludeMatches` Optional

Same as `exclude_matches` in the `content_scripts` key.

`includeGlobs` Optional

Same as `include_globs` in the `content_scripts` key.

`js` Optional

An array of objects. Each object has either a property named `file`, which is a URL starting at the extension's manifest.json and pointing to a JavaScript file to register, or a property named `code`, which is some JavaScript code to register.

`matchAboutBlank` Optional

Same as `match_about_blank` in the `content_scripts` key.

`matches`

Same as `matches` in the `content_scripts` key.

`runAt` Optional

Same as `run_at` in the `content_scripts` key.

`scriptMetadata` Optional

A user script metadata value

It has similar syntax to the contentScript options supported by browser.contentScripts.register.


Working with userScripts - Mozilla

Working with userScripts
========================

By implementing userScripts, extension developers can modify how sites look and/or work to better meet user needs.

Implement userScripts in your extension using the following steps:

1. Define the script in the extension's manifest using the `"user_scripts"` key.
2. Register the userScript
3. Implement the userScript functions

Let's step through the processes using a small sample web extension that illustrates the process. The example is available in the webextensions-examples repository on GitHub.

userScripts Manifest
--------------------

A user script is identified by the contents of the user\_scripts key of the extension's manifest. The minimum information for the `user_scripts` key would be:

```json
  "user\_scripts": {
    "api\_script": "customUserScriptAPIs.js"
  }
```

The "api\_script" property indicates the path to the JavaScript file that contains the code for the `userScript`.

Load the example extension
--------------------------

Once you have downloaded the example:

Navigate to about:debugging, click on **Load Temporary Add-on…** and double-click on the extension's manifest.

The default code included with the example allows you to load a `userScript` which will "eat" the content of pages matching the Hosts entry. Make any changes you want to make before clicking the **Register script** button at the bottom of the panel.

In the following image, the extension will "eat" the content of pages whose domain name ends in .org. This is the default behavior for this extension.

![User script example](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/userScripts/Working_with_userScripts/userscriptexample.png)

Nothing will happen until you click the **Register script** button. The button implements the user script according to the settings on this dialog. That means that you can experiment with the behavior of the script without having to implement an extensions yourself.

Register the userScript
-----------------------

Before a userScript can be executed, it must be registered using the `userScripts.register()` method. Here is the code to register the example extension:

```js
async function registerScript() {
  const params = {
    hosts: stringToArray(hostsInput.value),
    code: codeInput.value,
    excludeMatches: stringToArray(excludeMatchesInput.value),
    includeGlobs: stringToArray(includeGlobsInput.value),
    excludeGlobs: stringToArray(excludeGlobsInput.value),
    runAt: runAtInput.value,
    matchAboutBlank: stringToBool(matchAboutBlankInput.value),
    allFrames: stringToBool(allFramesInput.value),
    scriptMetadata: { name: scriptNameInput.value || null },
  };

  // Store the last submitted values to the extension storage
  // (so that they can be restored when the popup is opened
  // the next time).
  await browser.storage.local.set({
    lastSetValues: params,
  });

  try {
    // Clear the last userScripts.register result.
    lastResultEl.textContent = "";

    await browser.runtime.sendMessage(params);
    lastResultEl.textContent = "UserScript successfully registered";
    // Clear the last userScripts.register error.
    lastErrorEl.textContent = "";

    // Clear the last error stored.
    await browser.storage.local.remove("lastError");
  } catch (e) {
    // There was an error on registering the userScript,
    // let's show the error message in the popup and store
    // the last error into the extension storage.

    const lastError = `${e}`;
    // Show the last userScripts.register error.
    lastErrorEl.textContent = lastError;

    // Store the last error.
    await browser.storage.local.set({ lastError });
  }
}
```

This code first initializes the params object to pass values to the userScripts.register method.

Implement the userScript functions
----------------------------------

Once the script has been registered, navigate to a page whose domain name ends in .org, and you will see something like this:

![Status message indicating that websites ending in .org have been eaten: "This page has been eaten. {"OldStoredValue:" "website address", "NewStoredValue:" "website address"}"](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/userScripts/Working_with_userScripts/user_script_in_action.png)

See also
--------

* `userScripts`
* `userScripts.register()`
* `userScripts.onBeforeScript`


userScripts.RegisteredUserScript - Mozilla

userScripts.RegisteredUserScript
================================

A `RegisteredUserScript` object is returned by a call to `userScripts.register()` and represents the user scripts registered in that call.

The object defines a single method, `unregister()`, which is used to unregister the user scripts.

**Note:** If this object is destroyed (for example because it goes out of scope) then the associated scripts will be unregistered automatically, so you should keep a reference to this object for as long as you want the user scripts to stay registered.

Methods
-------

`unregister()`

Unregisters the user scripts represented by this object.

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

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


RegisteredUserScript.unregister() - Mozilla

RegisteredUserScript.unregister()
=================================

The `unregister()` method of the `RegisteredUserScript` object unregisters the user scripts represented by the object, user scripts that were registered using `userScripts.register()`.

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

Syntax
------

```js
const registeredUserScript = await browser.userScripts.register(
  userScriptOptions       // object
);
// …
await registeredUserScript.unregister()
```

### Parameters

None.

### Return value

A `Promise` that is resolved once the user scripts are unregistered. The promise does not return a value.

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

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

See also
--------

* `userScripts.register()`
* `RegisteredUserScript`


clipboard.setImageData() - Mozilla

clipboard.setImageData()
========================

Copies an image to the clipboard. The image is re-encoded before it is written to the clipboard. If the image is invalid, the clipboard is not modified.

The image is provided as an `ArrayBuffer` containing the encoded image. JPEG and PNG formats are supported.

Although this API is based on Chrome's `clipboard.setImageData()` API, there are some differences:

* The Chrome API is only for apps, not extensions.
* This API requires only the `"clipboardWrite"` permission, while the Chrome version also requires the `"clipboard"` permission.
* Chrome's API uses callbacks, and this API only supports promises.
* This API does not support the `additionalItems` parameter.

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

Syntax
------

```js
browser.clipboard.setImageData(imageData, imageType)
```

### Parameters

`imageData`

An `ArrayBuffer` containing the encoded image data to copy to the clipboard.

`imageType`

A string indicating the type of image contained in `imageData`: `"png"` or `"jpeg"`.

### Return value

A `Promise` that will be resolved with no arguments if the operation succeeded, or rejected if there was an error (for example, because the data did not represent a valid image).

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

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

Examples
--------

Copy a remote image:

```js
// requires:
// \* the host permission for "https://cdn.mdn.mozilla.net/\*"
// \* the API permission "clipboardWrite"

fetch("https://cdn.mdn.mozilla.net/static/img/favicon144.png")
  .then((response) => response.arrayBuffer())
  .then((buffer) => browser.clipboard.setImageData(buffer, "png"));
```

Copy an image that was bundled with the extension:

```js
// requires the API permission "clipboardWrite"

fetch(browser.runtime.getURL("image.png"))
  .then((response) => response.arrayBuffer())
  .then((buffer) => browser.clipboard.setImageData(buffer, "png"));
```

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


storage.session - Mozilla

storage.session
===============

 Represents the `session` storage area. Items in `session` storage are stored in memory for the duration of the browser session and are not persisted to disk.
 By default, it's not exposed to content scripts, but this behavior can be changed through `storage.session.setAccessLevel()`.

The amount of data that an extension can store in the session storage area is limited to 10 MB, unless stated otherwise in the browser compatibility table.

When the browser stops, all session storage is cleared. When the extension is uninstalled, its associated session storage is cleared.

Methods
-------

The `session` object implements the methods defined on the `storage.StorageArea` type:

`storage.session.get()`

Retrieves one or more items from the storage area.

`storage.session.getBytesInUse()`

Gets the amount of storage space (in bytes) used for one or more items in the storage area.

`storage.session.set()`

Stores one or more items in the storage area. If the item exists, its value is updated.

`storage.session.setAccessLevel()`

Sets the access level for the storage area.

`storage.session.remove()`

Removes one or more items from the storage area.

`storage.session.clear()`

Removes all items from the storage area.

Events
------

The `session` object implements the events defined on the `storage.StorageArea` type:

`storage.session.onChanged`

Fires when one or more items in the storage area change.

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


storage.StorageArea - Mozilla

storage.StorageArea
===================

StorageArea is an object representing a storage area.

Type
----

Values of this type are objects.

Methods
-------

`storage.StorageArea.get()`

Retrieves one or more items from the storage area.

`storage.StorageArea.getBytesInUse()`

Gets the amount of storage space (in bytes) used one or more items being stored in the storage area.

`storage.StorageArea.set()`

Stores one or more items in the storage area. If an item already exists, its value will be updated.

`storage.StorageArea.setAccessLevel()`

Sets the access level for the storage area.

`storage.StorageArea.remove()`

Removes one or more items from the storage area.

`storage.StorageArea.clear()`

Removes all items from the storage area.

Events
------

`storage.StorageArea.onChanged`

Fires when one or more items in the storage area change.

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


storage.managed - Mozilla

storage.managed
===============

A `storage.StorageArea` object that represents the `managed` storage area. Items in `managed` storage are set by the domain administrator or other native applications installed on the user's computer and are read-only for the extension. Trying to modify this storage area results in an error.

Provisioning managed storage
----------------------------

The procedure for provisioning managed storage varies between browsers. For Chrome instructions, see the "Manifest for storage areas" article.

For Firefox, you need to create a JSON manifest file in a specific format and location. For the details of manifest syntax and location, see Native manifests.

Here's an example manifest:

```json
{
  "name": "favourite-colour-examples@mozilla.org",
  "description": "ignored",
  "type": "storage",
  "data": {
    "colour": "management thinks it should be blue!"
  }
}
```

Given this manifest, the favourite-colour extension could access the data using code like this:

```js
let storageItem = browser.storage.managed.get("colour");
storageItem.then((res) => {
  console.log(`Managed colour is: ${res.colour}`);
});
```

Methods
-------

The `managed` object implements the methods defined on the `storage.StorageArea` type:

`storage.managed.get()`

Retrieves one or more items from the storage area.

`storage.managed.getBytesInUse()`

Gets the amount of storage space (in bytes) used for one or more items in the storage area.

Events
------

The `managed` object implements the events defined on the `storage.StorageArea` type:

`storage.managed.onChanged`

Fires when one or more items in the storage area change.

### Example extensions

* favourite-colour
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.storage` API. This documentation is derived from `storage.json` in the Chromium code.


storage.onChanged - Mozilla

storage.onChanged
=================

Fired when `storageArea.set`, `storageArea.remove`, or `storageArea.clear` executes against a storage area.

When this event is triggered by `storageArea.set`, it's possible to receive a callback when there is no change to the underlying data. Also, the information returned includes all keys within the storage area `storageArea.set` ran against. The extension can determine the changes that occurred by examining the content of the `changes` argument received by the `onChanged` listeners.

Syntax
------

```js
browser.storage.onChanged.addListener(listener)
browser.storage.onChanged.removeListener(listener)
browser.storage.onChanged.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:

`changes`

`object`. Object describing the change. This object contains properties for all the keys in the storage area included in the `storageArea.set` call, even if key values are unchanged. The name of each property is the name of each key. The value of each key is a `storage.StorageChange` object describing the change to that item.

`areaName`

`string`. The name of the storage area (`"sync"`, `"local"`, or `"managed"`) to which the changes were made.

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

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

Examples
--------

```js
/\*
Log the storage area that changed,
then for each item changed,
log its old value and its new value.
\*/
function logStorageChange(changes, area) {
  console.log(`Change in storage area: ${area}`);

  const changedItems = Object.keys(changes);

  for (const item of changedItems) {
    console.log(`${item} has changed:`);
    console.log("Old value: ", changes[item].oldValue);
    console.log("New value: ", changes[item].newValue);
  }
}

browser.storage.onChanged.addListener(logStorageChange);
```

### Example extensions

* proxy-blocker

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


storage.local - Mozilla

storage.local
=============

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

The browser may restrict the amount of data that an extension can store in the local storage area. For example:

* In Chrome, an extension is limited to storing 5MB of data using this API unless it has the `"unlimitedStorage"` permission.
* In Firefox, the amount of data an extension can store is subjected to the same storage limits as applied to IndexedDB databases. Extensions that intend to store more data than this limit need the "unlimitedStorage" permission. However, extensions with the "unlimitedStorage" permission may get a quota exceeded error when the disk space used by storage exceeds the global limit.

When the extension is uninstalled, its associated local storage is cleared.

Also, in Firefox, you can prevent the browser from clearing local storage on uninstall by visiting `about:config` and setting these browser preferences to `true`: `"keepUuidOnUninstall"` and `"keepStorageOnUninstall"`. This feature is provided to help developers test their extensions. Extensions themselves are not able to change these preferences.

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

Methods
-------

The `local` object implements the methods defined on the `storage.StorageArea` type:

`storage.local.get()`

Retrieves one or more items from the storage area.

`storage.local.getBytesInUse()`

Gets the amount of storage space (in bytes) used for one or more items in the storage area.

`storage.local.set()`

Stores one or more items in the storage area. If the item exists, its value is updated.

`storage.local.remove()`

Removes one or more items from the storage area.

`storage.local.clear()`

Removes all items from the storage area.

Events
------

The `local` object implements the events defined on the `storage.StorageArea` type:

`storage.local.onChanged`

Fires when one or more items in the storage area change.

### Example extensions

* annotate-page
* forget-it
* navigation-stats
* proxy-blocker
* quicknote
* stored-credentials
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.storage` API. This documentation is derived from `storage.json` in the Chromium code.


storage.sync - Mozilla

storage.sync
============

Represents the `sync` storage area. Items in `sync` storage are synced by the browser. The data is then available on all instances of the browser the user is logged into (for example, when using a Mozilla account on desktop versions of Firefox or a Google account on Chrome) across different devices.

For desktop Firefox, a user must have `Add-ons` selected in the "Sync" section in `"about:preferences"`. Firefox for Android does not synchronize data with the user's account. See Firefox bug 1316442.

The implementation of `storage.sync` in Firefox relies on the Add-on ID. If you use `storage.sync`, you must set an ID for your extension using the `browser_specific_settings` manifest.json key.

The main use case of this API is to store preferences about your extension and allow the user to sync them to different profiles.

Storage quotas for sync data
----------------------------

The browser enforces limits on the amount of data each extension is allowed to store in the sync area:

| Name | Description | Value in bytes |
| --- | --- | --- |
| Maximum total size |
 The maximum total amount of data that each extension is allowed to store
 in the sync storage area, as measured by the JSON stringification of
 every value plus every key's length.
  | 102400 |
| Maximum item size |
 The maximum size of any one item that each extension is allowed to store
 in the sync storage area, as measured by the JSON stringification of the
 item's value plus the length of its key.
  | 8192 |
| Maximum number of items |
 The maximum number of items that each extension can store in the sync storage
 area.
  | 512 |

If an extension attempts to store items that exceed these limits, calls to `storage.sync.set()` are rejected with an error. An extension can use `storage.sync.getBytesInUse()` to find out how much of its quota is in use.

Synchronization process
-----------------------

In Firefox, extension data is synced every 10 minutes or whenever the user selects **Sync Now** (in **Settings** > **Sync** or from the Mozilla account icon). When the browser performs a sync, for each key stored, it:

* compares the value on the server with the value at the last sync; if they are different, the value from the server is written to the key in the browser's sync storage.
* compares the browser's sync storage values with the value on the server; if they are different, writes the browser's key value to the server.

This means that, for each key, a change on the server takes precedence over a change in the browser's sync storage.

This mechanism is generally OK for data such as user preferences or other global settings changed by the user.

However, a key's value can be updated on one browser and synchronized then updated on a second browser before the second browser is synchronized, resulting in the local update being overwritten during sync. This mechanism is, therefore, not ideal for data aggregated across devices, such as a count of page views or how many times an option is used. To handle such cases, use `storage.sync.onChanged` to listen for sync updates from the server (for example, a count of page views on another browser instance). Then adjust the value locally to take the remote value into account (for example, update the total views based on the remote count and new local count).

Methods
-------

The `sync` object implements the methods defined on the `storage.StorageArea` type:

`storage.sync.get()`

Retrieves one or more items from the storage area.

`storage.sync.getBytesInUse()`

Gets the amount of storage space (in bytes) used for one or more items in the storage area.

`storage.sync.set()`

Stores one or more items in the storage area. If the item exists, its value is updated.

`storage.sync.remove()`

Removes one or more items from the storage area.

`storage.sync.clear()`

Removes all items from the storage area.

Events
------

The `sync` object implements the events defined on the `storage.StorageArea` type:

`storage.sync.onChanged`

Fires when one or more items in the storage area change.

### Example extensions

* favourite-colour
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.storage` API. This documentation is derived from `storage.json` in the Chromium code.


storage.StorageChange - Mozilla

storage.StorageChange
=====================

`StorageChange` is an object representing a change to a storage area.

Type
----

`StorageChange` objects contain the following properties:

`oldValue` Optional

The old value of the item, if there was an old value. This can be any data type.

`newValue` Optional

The new value of the item, if there is a new value. This can be any data 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.storage` API. This documentation is derived from `storage.json` in the Chromium code.


StorageArea.set() - Mozilla

StorageArea.set()
=================

Stores one or more items in the storage area or updates stored items.

When you store or update a value using this API, the `storage.onChanged` event fires.

Note that when storing items in the `sync` storage area, the browser enforces quotas on the amount of data each extension can store. See Storage quotas for sync data.

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

Syntax
------

```js
let settingItem = browser.storage.<storageType>.set(
  keys             // object
)
```

`<storageType>` is one of the writable storage types — `storage.local`, `storage.session`, or `storage.sync`.

### Parameters

`keys`

An object containing one or more key/value pairs to be stored. If an item is in storage, its value is updated.

Values can be primitive (such as a number, boolean, or string), `Array`, or `Object` types.

It's generally not possible to store other types, such as `Function`, `Date`, `RegExp`, `Set`, `Map`, `ArrayBuffer`, and so on. Some unsupported types restore as an empty object, while others cause `set()` to throw an error. The behavior is browser-specific.

**Note:** If you want to remove keys from storage, use `storage.storageArea.remove`. If you want to overwrite a value with a void value, use `null`, i.e., `key: null`.

### Return value

A `Promise` that is fulfilled with no arguments if the operation succeeds. If the operation fails, the promise is rejected with an error message.

Examples
--------

```js
function setItem() {
  console.log("OK");
}

function gotKitten(item) {
  console.log(`${item.kitten.name} has ${item.kitten.eyeCount} eyes`);
}

function gotMonster(item) {
  console.log(`${item.monster.name} has ${item.monster.eyeCount} eyes`);
}

function onError(error) {
  console.log(error);
}

// define 2 objects
let monster = {
  name: "Kraken",
  tentacles: true,
  eyeCount: 10,
};

let kitten = {
  name: "Moggy",
  tentacles: false,
  eyeCount: 2,
};

// store the objects
browser.storage.local.set({ kitten, monster }).then(setItem, onError);

browser.storage.local.get("kitten").then(gotKitten, onError);
browser.storage.local.get("monster").then(gotMonster, onError);
```

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


StorageArea.setAccessLevel() - Mozilla

StorageArea.setAccessLevel()
============================

Sets the access level for the storage area.

This method is only supported for the `storage.session` StorageArea.

Unlike other storage areas, `storage.session` is only available to privileged (trusted) extension contexts. This `setAccessLevel` method is used to expose the session storage area to content scripts too. By default, all other storage areas are exposed to all extension contexts, including content scripts.

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

Syntax
------

```js
await browser.storage.<storageType>.setAccessLevel(
  accessLevel             // string
)
```

`<storageType>` can be the `storage.session` storage type.

### Parameters

`accessLevel`

`String`. The access level of the storage area. Possible values are `TRUSTED_CONTEXTS` or `TRUSTED_AND_UNTRUSTED_CONTEXTS`.

### Return value

A `Promise` that is fulfilled with no arguments if the operation succeeded. If the operation failed, the promise is rejected with an error message.

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


StorageArea.clear() - Mozilla

StorageArea.clear()
===================

Removes all items from the storage area.

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

Syntax
------

```js
let clearing = browser.storage.<storageType>.clear()
```

`<storageType>` is one of the writable storage types — `storage.local`, `storage.session`, or `storage.sync`

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with no arguments if the operation succeeded. If the operation failed, the promise will be rejected with an error message.

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

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

Examples
--------

```js
function onCleared() {
  console.log("OK");
}

function onError(e) {
  console.log(e);
}

let clearStorage = browser.storage.local.clear();
clearStorage.then(onCleared, onError);
```

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


StorageArea.remove() - Mozilla

StorageArea.remove()
====================

Removes one or more items from the storage area.

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

Syntax
------

```js
let removingItem = browser.storage.<storageType>.remove(
  keys             // string, or array of strings
)
```

`<storageType>` is one of the writable storage types — `storage.local`, `storage.session`, or `storage.sync`.

### Parameters

`keys`

A string, or array of strings, representing the key(s) of the item(s) to be removed.

### Return value

A `Promise` that will be fulfilled with no arguments if the operation succeeded. If the operation failed, the promise will be rejected with an error message.

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

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

Examples
--------

Remove a single item:

```js
function onRemoved() {
  console.log("OK");
}

function onError(e) {
  console.log(e);
}

let removeKitten = browser.storage.sync.remove("kitten");
removeKitten.then(onRemoved, onError);
```

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


StorageArea.getBytesInUse() - Mozilla

StorageArea.getBytesInUse()
===========================

Gets the amount of storage space, in bytes, used one or more items being stored in the storage area.

 This function only exists in browser.storage.sync
 It does not exist in browser.storage.local
 See https://bugzil.la/1385832

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

Syntax
------

```js
let gettingSpace = browser.storage.<storageType>.getBytesInUse(
  keys                      // null, string, or array of strings
)
```

`<storageType>` can only be `storage.sync`, not `storage.local` because of this bug.

### Parameters

`keys`

A key (string) or keys (an array of strings) to identify the item(s) whose storage space you want to retrieve. If an empty array is passed in, 0 will be returned. If you pass `null` or `undefined` here, the function will return the space used by the entire storage area.

### Return value

A `Promise` that will be fulfilled with an integer, `bytesUsed`, representing the storage space used by the objects that were specified in `keys`. If the operation failed, the promise will be rejected with an error message.

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


storage.StorageArea.onChanged - Mozilla

storage.StorageArea.onChanged
=============================

Fires when one or more items in a storage area change. Compared to `storage.onChanged`, this event enables you to listen for changes in one of the storage areas: `local`, `managed`, `session`, and `sync`.

Syntax
------

```js
// local can also be sync, managed, or session
browser.storage.local.onChanged.addListener(listener)
browser.storage.local.onChanged.removeListener(listener)
browser.storage.local.onChanged.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

`changes`

`object`. Object describing the change. This contains one property for each key that changed. The name of the property is the name of the key that changed, and its value is a `storage.StorageChange` object describing the change to that item.

Examples
--------

```js
/\*
Log the old value and its new value of
changes in the local storage.
\*/
function logStorageChange(changes) {
  const changedItems = Object.keys(changes);

  for (const item of changedItems) {
    console.log(`${item} has changed:`);
    console.log("Old value: ", changes[item].oldValue);
    console.log("New value: ", changes[item].newValue);
  }
}

browser.storage.local.onChanged.addListener(logStorageChange);
```

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


StorageArea.get() - Mozilla

StorageArea.get()
=================

Retrieves one or more items from the storage area.

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

Syntax
------

```js
let results = browser.storage.<storageType>.get(
  keys    // null, string, object or array of strings
)
```

`<storageType>` will be one of the writable storage types — `sync`, `local`, or `managed`.

### Parameters

`keys`

A key (`string`) or keys (an array of strings, *or* an object specifying default values) to identify the item(s) to be retrieved from storage. If you pass an empty object or array here, an empty object will be retrieved. If you pass `null`, or an undefined value, the entire storage contents will be retrieved.

### Return value

A `Promise` that resolves to a `results` object, containing every object in `keys` that was found in the storage area. If `keys` is an object, keys that are not found in the storage area will have their values given by the `keys` object.

If the operation failed, the promise is rejected with an error message.

If managed storage is not set, `undefined` will be returned.

**Warning:** When used within a content script in Firefox versions prior to 52, the Promise returned by `browser.storage.local.get()` is fulfilled with an Array containing one Object. The Object in the Array contains the `keys` found in the storage area, as described above.

The Promise is correctly fulfilled with an Object when used in the background context (background scripts, popups, options pages, etc.).

When this API is used as `chrome.storage.local.get()`, it correctly passes an Object to the callback function.

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

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

Examples
--------

Suppose storage contains two items:

```js
// storage contains two items,
// "kitten" and "monster"
browser.storage.local.set({
  kitten: { name: "Mog", eats: "mice" },
  monster: { name: "Kraken", eats: "people" },
});
```

Define success and failure handlers for the promise:

```js
function onGot(item) {
  console.log(item);
}

function onError(error) {
  console.log(`Error: ${error}`);
}
```

With no `keys` argument, retrieve everything:

```js
let gettingItem = browser.storage.local.get();
gettingItem.then(onGot, onError);

// -> Object { kitten: Object, monster: Object }
```

With an empty `keys` argument, return nothing:

```js
// with an empty array, retrieve nothing
let gettingItem = browser.storage.local.get([]);
gettingItem.then(onGot, onError);

// -> Object { }
```

With the name of an object, retrieve the match:

```js
let gettingItem = browser.storage.local.get("kitten");
gettingItem.then(onGot, onError);

// -> Object { kitten: Object }
```

With an array of object names, retrieve all matches:

```js
let gettingItem = browser.storage.local.get([
  "kitten",
  "monster",
  "grapefruit",
]);
gettingItem.then(onGot, onError);

// -> Object { kitten: Object, monster: Object }
```

With an object with object names as keys and the default value as value:

```js
let gettingItem = browser.storage.local.get({
  kitten: "no kitten",
  monster: "no monster",
  grapefruit: {
    name: "Grape Fruit",
    eats: "Water",
  },
});

// -> Object { kitten: Object, monster: Object, grapefruit: Object }
```

### Chrome examples

```js
chrome.storage.local.get("kitten", (items) => {
  console.log(items.kitten); // -> {name:"Mog", eats:"mice"}
});
```

Or with an arrow function

```js
chrome.storage.local.get("kitten", (items) => {
  console.log(items.kitten); // -> {name:"Mog", eats:"mice"}
});
```

Or using a Promise

```js
let gettingItem = new Promise((resolve) =>
  chrome.storage.local.get("kitten", resolve),
);
gettingItem.then(onGot); // -> Object { kitten: Object }
```

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


BrowserSetting - Mozilla

BrowserSetting
==============

A `BrowserSetting` is an object representing a browser setting.

It provides methods to set and get the setting's underlying value, to clear any change you've made to it, and to listen for changes to its value.

Note that while this object is based on the ChromeSetting type, this object does not distinguish between setting the value in normal browsing windows and in private browsing windows. This means that all parts of the API relating to private browsing (such as the `scope` option to `ChromeSetting.set()`) are not implemented.

Methods
-------

`types.BrowserSetting.get()`

Get the current value of the setting, and an enumeration representing how the setting is currently controlled.

`types.BrowserSetting.set()`

Set the setting to a new value.

`types.BrowserSetting.clear()`

Clear any change made to the setting by this extension.

Events
------

`types.BrowserSetting.onChange`

Fired when the setting's value changes.

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


get() - Mozilla

get()
=====

The `BrowserSetting.get()` method gets the current value of the browser setting, and an enumeration indicating how the setting's value is currently controlled.

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

Syntax
------

```js
let getting = setting.get(
  details     // object
)
```

### Parameters

`details`

An empty object.

### Return value

A `Promise` that will be fulfilled with an object with the following properties:

`value`

The value of the setting. The type of this property is determined by the particular setting.

`levelOfControl`

`string`. This represents the way the setting is currently controlled. You can use it to check whether you can modify the setting. See `BrowserSetting.set()` for details. Its value may be any of the following:

|  |  |
| --- | --- |
| `"not_controllable"` | Extensions are not allowed to modify this setting. |
| `"controlled_by_other_extensions"` |
 Another extension that was installed after this one has modified this
 setting.
  |
| `"controllable_by_this_extension"` | This extension is allowed to modify the setting. |
| `"controlled_by_this_extension"` | This extension has already modified the setting. |

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

See `types.BrowserSetting`.

Example
-------

Log the value and level of control for the `networkPredictionEnabled` property of the `privacy.network` object, for private browsing windows. Note that this requires the "privacy" browser permission.

```js
let getting = browser.privacy.network.networkPredictionEnabled.get({});

getting.then((got) => {
  console.log(`Value: ${got.value}`);
  console.log(`Control: ${got.levelOfControl}`);
});
```

**Note:**

This API is based on Chromium's `chrome.types` API.


BrowserSetting.onChange - Mozilla

BrowserSetting.onChange
=======================

The `BrowserSetting.onChange` event is fired when the setting is changed.

On Firefox, it doesn't fire if the change has been made through `about:config`.

Syntax
------

```js
BrowserSetting.onChange.addListener(listener)
BrowserSetting.onChange.removeListener(listener)
BrowserSetting.onChange.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:

`details`

An `object` containing details of the change that occurred. Its properties are as follows:

`value`

The new value of the setting. The type of this property is determined by the particular setting.

`levelOfControl`

`string`. This represents the way the setting is currently controlled. You can use it to check whether you can modify the setting. See `BrowserSetting.set()` for details. Its value may be any of the following:

|  |  |
| --- | --- |
| `"not_controllable"` | Extensions are not allowed to modify this setting. |
| `"controlled_by_other_extensions"` |
 Another extension that was installed after this one has modified this
 setting.
  |
| `"controllable_by_this_extension"` | This extension is allowed to modify the setting. |
| `controlled_by_this_extension"` | This extension has already modified the setting. |

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

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

Examples
--------

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


clear() - Mozilla

clear()
=======

Use `BrowserSetting.clear()` to clear any changes the extension has made to the browser setting. The browser setting will revert to its previous value.

The extension will also give up control of the setting, allowing an extension with lower precedence (that is, an extension that was installed before this one) to modify the setting. See `BrowserSetting.set()` to learn more about controlling settings.

This is an asynchronous function that returns a `Promise`. If clearing the value failed, the promise resolves to `false`. If clearing the value succeeded it resolves to `true`.

Syntax
------

```js
let clearing = setting.clear(
  details     // object
)
```

### Parameters

`details`

An empty object.

### Return value

A `Promise` that will be fulfilled with a `boolean`: `true` if the setting was cleared, `false` otherwise.

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

See `types.BrowserSetting`.

Example
-------

Clear the `webRTCIPHandlingPolicy` setting:

```js
function onCleared(result) {
  if (result) {
    console.log("Setting was cleared");
  } else {
    console.log("Setting was not cleared");
  }
}

let clearing = browser.privacy.network.webRTCIPHandlingPolicy.clear({});
clearing.then(onCleared);
```

**Note:**

This API is based on Chromium's `chrome.types` API.


set() - Mozilla

set()
=====

Use `BrowserSetting.set()` to change the browser setting to a new value.

There are some rules that can restrict when extensions are able to change settings:

* some settings are locked, so they can't be changed by extensions at all
* if multiple extensions try to modify the same setting, then extensions are given a precedence ordering based on when they were installed. More-recently installed extensions have precedence over less-recently installed extension.

This means that if extension X tries to change a setting:

1. If the setting is locked, then the setting is not changed. However, X's change is remembered, and it is stored in a queue, ordered by X's precedence relative to any other extensions that tried to change the setting. If the setting becomes unlocked later on, the first extension in the queue gets to change the setting.
2. Otherwise, if no other extension has already changed the setting, then X succeeds in changing the setting, and is then said to "control" the setting.
3. Otherwise, if a lower-precedence extension Y has already changed the setting, then X succeeds in changing the setting, and now controls the setting. However, Y's change is remembered, and is stored in a queue in precedence order. If X subsequently clears its value, or if X is disabled or uninstalled, the first extension in the queue gets to make its change to the setting.
4. Otherwise, if a higher-precedence extension Z has already changed the setting, then X does not succeed in changing the setting, but its change is queued. If Z subsequently clears its value, or if Z is disabled or uninstalled, the first extension in the queue gets to make its change to the setting.

An extension can find out which of these scenarios applies by examining the "`levelOfControl`" property returned from a call to `BrowserSetting.get()`.

The `BrowserSetting.set()` method returns a Promise that resolves to a boolean: if an attempt to change a setting actually results in the setting being changed (scenarios 2 and 3 above) the boolean is `true`: otherwise it is `false`.

Syntax
------

```js
let setting = setting.set(
  details     // object
)
```

### Parameters

`details`

An object that must contain the following property:

`value`

`any`. The value you want to change the setting to. Its type depends on the particular setting.

### Return value

A `Promise` that will be fulfilled with a `boolean`: `true` if the setting was modified, `false` otherwise (for example, because the extension did not control the setting).

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

See `types.BrowserSetting`.

Example
-------

Modify the `hyperlinkAuditingEnabled` setting (this requires the "privacy" permission):

```js
function onSet(result) {
  if (result) {
    console.log("Value was updated");
  } else {
    console.log("Value was not updated");
  }
}

browser.browserAction.onClicked.addListener(() => {
  let setting = browser.privacy.websites.hyperlinkAuditingEnabled.set({
    value: false,
  });
  setting.then(onSet);
});
```

**Note:**

This API is based on Chromium's `chrome.types` API.


extension.onRequestExternal - Mozilla

extension.onRequestExternal
===========================

**Warning:** This is not implemented in Firefox because it has been deprecated since Chrome 33. Please use runtime.onMessageExternal instead.

Fired when a request is sent from another extension.

Syntax
------

```js
chrome.extension.onRequestExternal.addListener(function(
  request,      // optional any
  sender,       // runtime.MessageSender
  sendResponse, // function
) { })
chrome.extension.onRequestExternal.removeListener(listener)
chrome.extension.onRequestExternal.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:

`request`

`any`. The request sent by the calling script.

`sender`

`runtime.MessageSender`.

`sendResponse`

`function`. Function to call when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response.

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


extension.lastError - Mozilla

extension.lastError
===================

**Warning:** This function is deprecated, use `runtime.lastError` instead.

An alias for `runtime.lastError`.

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


extension.ViewType - Mozilla

extension.ViewType
==================

The type of extension view.

Type
----

Values of this type are strings. Possible values are: `"tab"`, `"popup"`, `"sidebar"`.

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


extension.setUpdateUrlData() - Mozilla

extension.setUpdateUrlData()
============================

Sets parameters for the extension's update URL. This value is ignored for extensions that are hosted in the browser vendor's store.

Syntax
------

```js
browser.extension.setUpdateUrlData(
  data // string
)
```

### Parameters

`data`

`string`.

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

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

Examples
--------

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


extension.getViews() - Mozilla

extension.getViews()
====================

Returns an array of the Window objects for each of the pages running inside the current extension. This includes, for example:

* the background page, if one is defined
* any popup pages, if defined and loaded
* any options pages, if defined and loaded
* any browser tabs that host content packaged with the extension

In Firefox, if this method is called from a page that is part of a private browsing window, such as a sidebar in a private window or a popup opened from a private window, then its return value will not include the extension's background page.

Syntax
------

```js
let windows = browser.extension.getViews(
  fetchProperties // optional object
)
```

### Parameters

`fetchProperties` Optional

An object with the following properties:

`type` Optional

`string`. An `extension.ViewType` indicating the type of view to get. If omitted, this function returns all views.

`windowId` Optional

`integer`. The window to restrict the search to. If omitted, this function returns all views. In Firefox version 92 and earlier, sidebar views are not matched and, therefore, not returned.

### Return value

`array` of `object`. Array of Window objects.

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

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

Examples
--------

Get all windows belonging to this extension, and log their URLs:

```js
const windows = browser.extension.getViews();

for (const extensionWindow of windows) {
  console.log(extensionWindow.location.href);
}
```

Get only windows in browser tabs hosting content packaged with the extension:

```js
const windows = browser.extension.getViews({ type: "tab" });
```

Get only windows in popups:

```js
const windows = browser.extension.getViews({ type: "popup" });
```

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


extension.isAllowedFileSchemeAccess() - Mozilla

extension.isAllowedFileSchemeAccess()
=====================================

Returns `true` if the extension can access the "file://" scheme, `false` otherwise.

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

Syntax
------

```js
let isAllowed = browser.extension.isAllowedFileSchemeAccess()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with a boolean: `true` if the extension is allowed access to "file://" URLs, `false` otherwise.

Firefox will always return `false`.

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

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

Examples
--------

```js
function logIsAllowed(answer) {
  console.log(`Is allowed: ${answer}`);
}

let isAllowed = browser.extension.isAllowedFileSchemeAccess();
isAllowed.then(logIsAllowed);
```

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


extension.getBackgroundPage() - Mozilla

extension.getBackgroundPage()
=============================

Returns the Window of the background page if the background script is running. If the script is not running, null is returned.

This a synchronous function.

**Note:** This method cannot be used in Private Browsing mode — it always returns null. Consider using `runtime.sendMessage()` or `runtime.connect()`. See Firefox bug 1329304 for more information.

Syntax
------

```js
let page = browser.extension.getBackgroundPage()
```

### Parameters

None.

### Return value

`object`. Window of the background page or null.

Examples
--------

Suppose a background script defines a function `foo()`:

```js
// background.js

function foo() {
  console.log("I'm defined in background.js");
}
```

A script running in a popup can call this function directly like this:

```js
// popup.js

let page = browser.extension.getBackgroundPage();
page.foo(); // -> "I'm defined in background.js"
```

### Example extensions

* find-across-tabs
* user-agent-rewriter
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.extension` API. This documentation is derived from `extension.json` in the Chromium code.


extension.isAllowedIncognitoAccess() - Mozilla

extension.isAllowedIncognitoAccess()
====================================

Check whether the extension is allowed access to tabs opened in "private browsing" mode.

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

Syntax
------

```js
let isAllowed = browser.extension.isAllowedIncognitoAccess()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with a boolean: `true` if the extension is allowed access to private tabs, `false` otherwise.

Examples
--------

```js
function logIsAllowed(answer) {
  console.log(`Is allowed: ${answer}`);
}

let isAllowed = browser.extension.isAllowedIncognitoAccess();
isAllowed.then(logIsAllowed);
```

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


extension.getExtensionTabs() - Mozilla

extension.getExtensionTabs()
============================

**Warning:** This method has been deprecated. Use `extension.getViews()` instead.

Returns an array of the JavaScript Window objects for each of the tabs running inside the current extension. If `windowId` is specified, returns only the Window objects of tabs attached to the specified window.

Syntax
------

```js
chrome.extension.getExtensionTabs(
  windowId // optional integer
)
```

This API is also available as `browser.extension.getExtensionTabs()`.

### Parameters

`windowId` Optional

`integer`.

### Return value

`array` of `object`. Array of global window objects

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


extension.onRequest - Mozilla

extension.onRequest
===================

**Warning:** This is not implemented in Firefox because it has been deprecated since Chrome 33. Please use runtime.onMessage instead.

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

Syntax
------

```js
chrome.extension.onRequest.addListener(function(
  request,         // optional any
  sender,          // runtime.MessageSender
  () => {/\* … \*/}  // function
) {/\* … \*/})
chrome.extension.onRequest.removeListener(listener)
chrome.extension.onRequest.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:

`request`

`any`. The request sent by the calling script.

`sender`

`runtime.MessageSender`.

`sendResponse`

`function`. Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one `onRequest` listener in the same document, then only one may send a response.

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


extension.getURL() - Mozilla

extension.getURL()
==================

**Warning:** This function is deprecated. Please use `runtime.getURL`.

Converts a relative path within an extension's install directory to a fully-qualified URL.

Syntax
------

```js
browser.extension.getURL(
  path // string
)
```

### Parameters

`path`

`string`. A path to a resource within an extension expressed relative to its install directory.

### Return value

`string`. The fully-qualified URL to the resource.

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

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

Examples
--------

Given a file packaged with the add-on at "beasts/frog.html", get the full URL like this:

```js
let fullURL = browser.extension.getURL("beasts/frog.html");

// -> something like:
// moz-extension://2c127fa4-62c7-7e4f-90e5-472b45eecfdc/beasts/frog.html
```

### Example extensions

* beastify
* cookie-bg-picker
* imagify
* notify-link-clicks-i18n
* proxy-blocker

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


extension.sendRequest() - Mozilla

extension.sendRequest()
=======================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Warning:** This method has been deprecated. Use `runtime.sendMessage` instead.

Sends a request to other listeners within the extension. Similar to `runtime.connect`, but only sends a request with an optional response. The `extension.onRequest` event fires in each page of the extension.

Syntax
------

```js
chrome.extension.sendRequest(
  extensionId,             // optional string
  request,                 // any
  (response) => {/\* … \*/}  // optional function
)
```

This API is also available as `browser.extension.sendRequest()` in a version that returns a promise.

### Parameters

`extensionId` Optional

`string`. The extension ID of the extension you want to connect to. If omitted, default is your own extension.

`request`

`any`.

`responseCallback` Optional

`function`. The function is passed these arguments:

`response`

`any`. The JSON response object sent by the handler of the request. If an error occurs while connecting to the extension, the callback will be called with no arguments and `runtime.lastError` will be set to the error message.

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


extension.inIncognitoContext - Mozilla

extension.inIncognitoContext
============================

Boolean value, `true` for content scripts running inside private browsing tabs and for extension pages running inside a private browsing process.

Syntax
------

```js
let isPrivate = browser.extension.inIncognitoContext;  // true or false
```

### Value

A *boolean* value indicate if the current script is running in a private tab or process.

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


contextualIdentities.onUpdated - Mozilla

contextualIdentities.onUpdated
==============================

Fired when the properties of a contextual identity, such as its name, icon, or color, are changed. Contextual identities may be updated by extensions using the `contextualIdentities` API, or directly by the user, using the browser's user interface.

Syntax
------

```js
browser.contextualIdentities.onUpdated.addListener(listener)
browser.contextualIdentities.onUpdated.removeListener(listener)
browser.contextualIdentities.onUpdated.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 this argument:

`changeInfo`

`object`. An object that contains a single property, `contextualIdentity`, which is a `contextualIdentities.ContextualIdentity` object representing the identity whose properties were updated.

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

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

Examples
--------

```js
function handleUpdated(changeInfo) {
  console.log(`Updated: ${changeInfo.contextualIdentity.name}`);
}

browser.contextualIdentities.onUpdated.addListener(handleUpdated);
```


contextualIdentities.get() - Mozilla

contextualIdentities.get()
==========================

Gets information about a contextual identity, given its cookie store ID.

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

Syntax
------

```js
let getContext = browser.contextualIdentities.get(
  cookieStoreId                  // string
)
```

### Parameters

`cookieStoreId`

`string`. The ID of this contextual identity's cookie store. Because contextual identities each have their own cookie store, this serves as an identifier for the contextual identity itself.

### Return value

A `Promise` that will be fulfilled with a `ContextualIdentity` that describes the identity. If the identity could not be found or the contextual identities feature is not enabled, the promise is rejected.

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

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

Examples
--------

This example tries to retrieve the contextual identity whose ID is "firefox-container-1":

```js
function onGot(context) {
  if (!context) {
    console.error("Context not found");
  } else {
    console.log(`Name: ${context.name}`);
  }
}

function onError(e) {
  console.error(e);
}

browser.contextualIdentities.get("firefox-container-1").then(onGot, onError);
```


contextualIdentities.create() - Mozilla

contextualIdentities.create()
=============================

Creates a new contextual identity. Once created, the user will be able to create new tabs belonging to this contextual identity, just as they can with the built-in identities.

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

Syntax
------

```js
let createContext = browser.contextualIdentities.create(
  details                  // object
)
```

### Parameters

`details`

`object`. An object containing properties for the new contextual identity. This contains the following properties:

`name`

`string`. The name of the new identity. This will be displayed in the browser's UI, enabling them to open a new tab belonging to the identity. It will also be displayed in the URL bar for tabs belonging to this identity.

`color`

`string`. The color associated with the new identity. This will be used to highlight tabs belonging to this identity. You can supply any of the following values here:

* "blue"
* "turquoise"
* "green"
* "yellow"
* "orange"
* "red"
* "pink"
* "purple"
* "toolbar"

`icon`

`string`. The name of an icon to display in the URL bar for tabs belonging to this identity. You can supply any of the following values here:

* "fingerprint"
* "briefcase"
* "dollar"
* "cart"
* "circle"
* "gift"
* "vacation"
* "food"
* "fruit"
* "pet"
* "tree"
* "chill"
* "fence"

### Return value

A `Promise` that will be fulfilled with a `ContextualIdentity` that describes the new identity. If the contextual identities feature is not enabled, the promise is rejected.

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

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

Examples
--------

This example creates a new contextual identity and logs its cookie store ID:

```js
function onCreated(context) {
  console.log(`New identity's ID: ${context.cookieStoreId}.`);
}

function onError(e) {
  console.error(e);
}

browser.contextualIdentities
  .create({
    name: "my-thing",
    color: "purple",
    icon: "briefcase",
  })
  .then(onCreated, onError);
```


contextualIdentities.onRemoved - Mozilla

contextualIdentities.onRemoved
==============================

Fired when a new contextual identity is removed. Contextual identities may be removed by extensions using the `contextualIdentities` API, or directly by the user, using the browser's user interface.

Syntax
------

```js
browser.contextualIdentities.onRemoved.addListener(listener)
browser.contextualIdentities.onRemoved.removeListener(listener)
browser.contextualIdentities.onRemoved.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 this argument:

`changeInfo`

`object`. An object that contains a single property, `contextualIdentity`, which is a `contextualIdentities.ContextualIdentity` object representing the identity that was removed.

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

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

Examples
--------

```js
function handleRemoved(changeInfo) {
  console.log(`Removed: ${changeInfo.contextualIdentity.name}`);
}

browser.contextualIdentities.onRemoved.addListener(handleRemoved);
```


contextualIdentities.remove() - Mozilla

contextualIdentities.remove()
=============================

Removes a contextual identity, given its cookie store ID.

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

Syntax
------

```js
let removeContext = browser.contextualIdentities.remove(
  cookieStoreId                  // string
)
```

### Parameters

`cookieStoreId`

`string`. The ID of the contextual identity's cookie store. Because contextual identities each have their own cookie store, this serves as an identifier for the contextual identity itself.

### Return value

A `Promise` that will be fulfilled with a `ContextualIdentity` that describes the identity that was removed. If the identity could not be found or the contextual identities feature is not enabled, the promise is rejected.

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

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

Examples
--------

This example tries to remove the contextual identity whose ID is "firefox-container-1":

```js
function onRemoved(context) {
  if (!context) {
    console.error("Context not found");
  } else {
    console.log(`Removed identity: ${context.cookieStoreId}.`);
  }
}

function onError(e) {
  console.error(e);
}

browser.contextualIdentities
  .remove("firefox-container-1")
  .then(onRemoved, onError);
```


contextualIdentities.query() - Mozilla

contextualIdentities.query()
============================

Gets information about all contextual identities, or about those contextual identities that match a given filter argument.

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

Syntax
------

```js
let getContext = browser.contextualIdentities.query(
  details                  // object
)
```

### Parameters

`details`

`object`. An object that can be used to filter the contextual identities returned. This may contain any of the following properties:

`name` Optional

`string`. Return only contextual identities with this name.

### Return value

A `Promise` that will be fulfilled with an array of `ContextualIdentity` objects, each describing a single identity. If the contextual identities feature is not enabled, the promise is rejected.

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

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

Examples
--------

Retrieve all contextual identities, and log their names:

```js
function onGot(contexts) {
  for (const context of contexts) {
    console.log(`Name: ${context.name}`);
  }
}

function onError(error) {
  console.error(error);
}

browser.contextualIdentities.query({}).then(onGot, onError);
```

Retrieve all contextual identities whose names are "my-thing", and log their names:

```js
function onGot(contexts) {
  for (const context of contexts) {
    console.log(`Name: ${context.name}`);
  }
}

function onError(error) {
  console.error(error);
}

browser.contextualIdentities
  .query({
    name: "my-thing",
  })
  .then(onGot, onError);
```

### Example extensions

* contextual-identities


contextualIdentities.update() - Mozilla

contextualIdentities.update()
=============================

Updates properties of a contextual identity, given its cookie store ID.

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

Syntax
------

```js
let createContext = browser.contextualIdentities.update(
  cookieStoreId,           // string
  details                  // object
)
```

### Parameters

`cookieStoreId`

`string`. The ID of this contextual identity's cookie store. Because contextual identities each have their own cookie store, this serves as an identifier for the contextual identity itself.

`details`

`object`. An object containing new values for the properties that you wish to change. This may contain any of the following properties:

`name` Optional

`string`. A new name for the identity. This will be displayed in the browser's UI, enabling them to open a new tab in the identity. It will also be displayed in the URL bar for tabs belonging to this identity.

`color` Optional

`string`. A new color for the identity. This will be used to highlight tabs belonging to this identity. You can supply any of the following values here:

* "blue"
* "turquoise"
* "green"
* "yellow"
* "orange"
* "red"
* "pink"
* "purple"
* "toolbar"

`icon` Optional

`string`. A new icon for the identity. You can supply any of the following values here:

* "fingerprint"
* "briefcase"
* "dollar"
* "cart"
* "circle"
* "gift"
* "vacation"
* "food"
* "fruit"
* "pet"
* "tree"
* "chill"
* "fence"

### Return value

A `Promise` that will be fulfilled with a `ContextualIdentity` that describes the updated identity. If the identity could not be found or the contextual identities feature is not enabled, the promise is rejected.

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

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

Examples
--------

This example updates the contextual identity whose ID is "firefox-container-1" to have a new name, color, and icon:

```js
function onUpdated(context) {
  console.log(`New identity's name: ${context.name}.`);
}

function onError(e) {
  console.error(e);
}

browser.contextualIdentities
  .update("firefox-container-1", {
    name: "my-thing",
    color: "purple",
    icon: "briefcase",
  })
  .then(onUpdated, onError);
```


contextualIdentities.onCreated - Mozilla

contextualIdentities.onCreated
==============================

Fired when a new contextual identity is created. Contextual identities may be created by extensions using the `contextualIdentities` API, or directly by the user, using the browser's user interface.

Syntax
------

```js
browser.contextualIdentities.onCreated.addListener(listener)
browser.contextualIdentities.onCreated.removeListener(listener)
browser.contextualIdentities.onCreated.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 this argument:

`changeInfo`

`object`. An object that contains a single property, `contextualIdentity`, which is a `contextualIdentities.ContextualIdentity` object, representing the identity that was created.

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

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

Examples
--------

```js
function handleCreated(changeInfo) {
  console.log(`Created: ${changeInfo.contextualIdentity.name}`);
}

browser.contextualIdentities.onCreated.addListener(handleCreated);
```


contextualIdentities.ContextualIdentity - Mozilla

contextualIdentities.ContextualIdentity
=======================================

The **`contextualIdentities.ContextualIdentity`** type describes a single contextual identity.

Type
----

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

`cookieStoreId`

`string`. The cookie store ID for the identity. Since contextual identities don't share cookie stores, this serves as a unique identifier.

`color`

`string`. The color for the identity. This will be shown in tabs belonging to this identity. The following values are valid:

* "blue"
* "turquoise"
* "green"
* "yellow"
* "orange"
* "red"
* "pink"
* "purple"
* "toolbar"

The value "toolbar" represents a theme-dependent color. Identities with color "toolbar" will be displayed in the same color as text in the toolbar (corresponding to the theme key `"toolbar_field_text"`).

`colorCode`

`string`. A hex code representing the exact color used for the identity. For example: `"#37adff"`. In the special case of the "toolbar" color, `colorCode` is always `"#7c7c7d"`, regardless of the displayed color.

`icon`

`string`. The name of an icon for the identity. This will be shown in the URL bar for tabs belonging to this identity. The following values are valid:

* "fingerprint"
* "briefcase"
* "dollar"
* "cart"
* "circle"
* "gift"
* "vacation"
* "food"
* "fruit"
* "pet"
* "tree"
* "chill"
* "fence"

`iconUrl`

`string`. A full resource:// URL pointing to the identity's icon. For example: "resource://usercontext-content/fingerprint.svg".

`name`

`string`. Name of the identity. This will be shown in the URL bar for tabs belonging to this identity. Note that names don't have to be unique.

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

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


contextualIdentities.move() - Mozilla

contextualIdentities.move()
===========================

Moves one or more contextual identities to a new position within the list of contextual identities.

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

Syntax
------

```js
let moveContainers = browser.contextualIdentities.move(
  cookieStoreIds,                  // string or array of string
  position                         // integer
)
```

### Parameters

`cookieStoreIds`

`string` or `array` of `string`. An ordered list of the contextual identity cookie store IDs to move.

`position`

`integer`. The position to move `cookieStoreIds` to in the list of contextual identities. Zero-based; `0` indicates the first position. `-1` indicates that the items are moved to the end of the list.

### Return value

A `Promise` that is fulfilled when the contextual identities are reordered. The promise is rejected if the request is for an invalid move or the contextual identities feature is not enabled.

Examples
--------

This example moves the first identity to the end and then back to the start.

```js
let identities = await browser.contextualIdentities.query({});
let firstId = identities[0].cookieStoreId;

// Moves first identity to the end.
await browser.contextualIdentities.move(firstId, -1);

// Move identity to the start again.
await browser.contextualIdentities.move(firstId, 0);
```

Another way of moving the first identity to the end is by moving all other identities to the start.

```js
let identities = await browser.contextualIdentities.query({});
let ids = identities.map((identity) => identity.cookieStoreId);
// Create an array without the first item:
let otherIds = ids.slice(1);

// Move other identities to the start,
// effectively putting the first identity at the end.
await browser.contextualIdentities.move(otherIds, 0);
```

This example moves the "Personal" identity to before "Work". The example assumes containers with these names to exist. This may not be the case in customized or localized (non-English) Firefox instances.

```js
let identities = await browser.contextualIdentities.query({});

// Find the index and ID of the container with the name "Personal".
let personalIndex = identities.findIndex((ci) => ci.name === "Personal");
if (personalIndex === -1) {
  throw new Error("Personal container not found");
}
let personalId = identities[personalIndex].cookieStoreId;

// Find the index of the container with the name "Work".
let workIndex = identities.findIndex((identity) => identity.name === "Work");
if (workIndex === -1) {
  throw new Error("Work container not found!");
}

if (personalIndex < workIndex) {
  // When the Personal identity moves, all following
  // identities shift to the left by one. To place
  // the Personal identity before the Work identity,
  // we should therefore subtract one.
  workIndex--;
}
await browser.contextualIdentities.move(personalId, workIndex);
```

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

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


dns.resolve() - Mozilla

dns.resolve()
=============

Resolves the given hostname to a DNS record.

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

Syntax
------

```js
let resolving = browser.dns.resolve(
  hostname,    // string
  flags        // array of string
)
```

### Parameters

`hostname`

`string`. The hostname to resolve.

`flags` Optional

`array` of `string`. Flags to modify the way the hostname is resolved. Any omitted flags default to `false`. You can pass zero or more of the following flags:

* `"allow_name_collisions"`: Allow name collision results which are normally filtered out.
* `"bypass_cache"`: Suppresses the internal DNS lookup cache.
* `"canonical_name"`: The canonical name of the specified host will be queried.
* `"disable_ipv4"`: Only IPv6 addresses will be returned.
* `"disable_ipv6"`: Only IPv4 addresses will be returned.
* `"disable_trr"`: Do not use the Trusted Recursive Resolver (TRR) for resolving the host name. A TRR enables resolving of host names using a dedicated DNS-over-HTTPS server.
* `"offline"`: Only literals and cached entries will be returned.
* `"priority_low"`: The request is given lower priority. If "priority\_medium" is also given, the query is given medium priority.
* `"priority_medium"`: The request is given medium priority. If "priority\_low" is also given, the query is given medium priority.
* `"speculate"`: Indicates that the request is speculative. Speculative requests return errors if prefetching is disabled by the browser's configuration.

### Return value

A `Promise` that will be fulfilled with a `DNSRecord` object. This object can contain the following properties:

`addresses`

`array` of `string`. The IP addresses associated with this DNS record.

`canonicalName`

`string`. The canonical name for this record. This is only included in the response if the `"canonical_name"` flag was passed to `resolve()`.

`isTRR`

`boolean`: `true` if the record was retrieved using a Trusted Recursive Resolver (TRR).

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

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

Examples
--------

```js
function resolved(record) {
  console.log(record.addresses);
}

let resolving = browser.dns.resolve("example.com");
resolving.then(resolved);

// > e.g. Array [ "192.0.2.172" ]
```

Bypass the cache, and ask for the canonical name:

```js
function resolved(record) {
  console.log(record.canonicalName);
  console.log(record.addresses);
}

let resolving = browser.dns.resolve("developer.mozilla.org", [
  "bypass\_cache",
  "canonical\_name",
]);
resolving.then(resolved);

// > e.g. xyz.us-west-2.elb.amazonaws.com
// > e.g. Array [ "192.0.2.172", "198.51.100.45" ]
```


i18n.detectLanguage() - Mozilla

i18n.detectLanguage()
=====================

Detects the language of the provided text using the Compact Language Detector (CLD).

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

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

Syntax
------

```js
let detectingLanguages = browser.i18n.detectLanguage(
  text                  // string
)
```

### Parameters

`text`

`string`. User input string to be translated.

### Return value

A `Promise` that will be fulfilled with a result object. The result object has two properties:

`isReliable`

`boolean`. Whether the language was detected reliably.

`languages`

`array` of objects, each of which has two properties:

`language`

`i18n.LanguageCode`. The detected language.

`percentage`

`integer`. The percentage of the input string that was in the detected language.

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

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

Examples
--------

```js
function onLanguageDetected(langInfo) {
  for (const lang of langInfo.languages) {
    console.log(`Language is: ${lang.language}`);
    console.log(`Percentage is: ${lang.percentage}`);
  }
}

let text = "L'homme est né libre, et partout il est dans les fers.";

let detecting = browser.i18n.detectLanguage(text);
detecting.then(onLanguageDetected);
```

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


i18n.getMessage() - Mozilla

i18n.getMessage()
=================

Gets the localized string for the specified message.

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

Syntax
------

```js
browser.i18n.getMessage(
  messageName,  // string
  substitutions // optional any
)
```

### Parameters

`messageName`

`string`. The name of the message, as specified in the messages.json file. If the message can't be found in messages.json:

* Firefox returns "" and logs an error.
* Chrome returns "" and does not log an error.

`substitutions` Optional

`string` or `array` of `string`. A single substitution string, or an array of substitution strings.

In Chrome, if you supply more than 9 substitution strings, `getMessage()` will return `undefined`.

### Return value

`string`. Message localized for current locale.

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

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

Examples
--------

Get the localized string for `"messageContent"`, with `target.url` substituted:

```js
let message = browser.i18n.getMessage("messageContent", target.url);
console.log(message);
```

This would work with a \_locales/en/messages.json file containing:

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

If `target.url` is "https://developer.mozilla.org", then the value of message, in the "en" locale, would be:
```

"You clicked https://developer.mozilla.org."
```

### Example extensions

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

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


i18n.LanguageCode - Mozilla

i18n.LanguageCode
=================

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

Type
----

Values of this type are strings.

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