runtime.OnRestartRequiredReason - Mozilla

runtime.OnRestartRequiredReason
===============================

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

Type
----

Values of this type are strings. Possible values are:

* `"app_update"`: The application is being updated to a newer version.
* `"os_update"`: The browser/OS is updated to a newer version.
* `"periodic"`: The system has run for more than the permitted uptime set in the enterprise policy.
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.runtime` API. This documentation is derived from `runtime.json` in the Chromium code.


runtime.onInstalled - Mozilla

runtime.onInstalled
===================

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

Note that `runtime.onInstalled` is not the same as `management.onInstalled`. The `runtime.onInstalled` event is fired only for your extension. The `browser.management.onInstalled` event is fired for any extensions.

Syntax
------

```js
browser.runtime.onInstalled.addListener(listener)
browser.runtime.onInstalled.removeListener(listener)
browser.runtime.onInstalled.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)`

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

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

### Parameters

`function`

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

`details`

An object with the following properties:

`id` Optional

`string`. The ID of the imported shared module extension that updated. This is present only if the `reason` value is `shared_module_update`.

`previousVersion` Optional

`string`. The previous version of the extension just updated. This is only present if the `reason` value is `update`.

`reason`

An `runtime.OnInstalledReason` value, stating the reason that this event is being dispatched.

`temporary`

`boolean`. True if the add-on was installed temporarily. For example, using the "about:debugging" page in Firefox or using web-ext run. False otherwise.

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

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

Examples
--------

When the extension is installed, log the install reason and open https://example.com:

```js
function handleInstalled(details) {
  console.log(details.reason);
  browser.tabs.create({
    url: "https://example.com",
  });
}

browser.runtime.onInstalled.addListener(handleInstalled);
```

### Example extensions

* runtime-examples

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


runtime.Port - Mozilla

runtime.Port
============

A `Port` object represents one end of a connection between two specific contexts, which can be used to exchange messages.

One side initiates the connection, using a `connect()` API. This returns a `Port` object. The other side listens for connection attempts using an `onConnect` listener. This is passed a corresponding `Port` object.

Once both sides have `Port` objects, they can exchange messages using `Port.postMessage()` and `Port.onMessage`. When they are finished, either end can disconnect using `Port.disconnect()`, which will generate a `Port.onDisconnect` event at the other end, enabling the other end to do any cleanup required.

A `Port` can also become disconnected in response to various events. See Lifecycle.

You can use this pattern to communicate between:

* different parts of your extension (for example, between content scripts and background scripts)
* between your extension and a native application running on the user's computer.
* between your extension and a different extension

You need to use different connection APIs for different sorts of connections, as detailed in the table below.

| Connection type | Initiate connection attempt | Handle connection attempt |
| --- | --- | --- |
| Background script to content script | `tabs.connect()` | `runtime.onConnect` |
| Content script to background script | `runtime.connect()` | `runtime.onConnect` |
| Extension to native application | `runtime.connectNative()` |
 Not applicable (see
 Native messaging).
  |
| Extension to Extension | `runtime.connect()` | `runtime.onConnectExternal` |

Type
----

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

`name`

`string`. The port's name, defined in the `runtime.connect()` or `tabs.connect()` call that created it. If this port is connected to a native application, its name is the name of the native application.

`disconnect`

`function`. Disconnects a port. Either end can call this when they have finished with the port. It will cause `onDisconnect` to be fired at the other end. This is useful if the other end is maintaining some state relating to this port, which can be cleaned up on disconnect. If this port is connected to a native application, this function will close the native application.

`error`

`object`. If the port was disconnected due to an error, this will be set to an object with a string property `message`, giving you more information about the error. See `onDisconnect`.

`onDisconnect`

`object`. This contains the `addListener()` and `removeListener()` functions common to all events for extensions built using WebExtension APIs. Listener functions will be called when the other end has called `Port.disconnect()`. This event will only be fired once for each port. The listener function will be passed the `Port` object. If the port was disconnected due to an error, then the `Port` argument will contain an `error` property giving more information about the error:

```js
port.onDisconnect.addListener((p) => {
  if (p.error) {
    console.log(`Disconnected due to an error: ${p.error.message}`);
  }
});
```

Note that in Google Chrome `port.error` is not supported: instead, use `runtime.lastError` to get the error message.

`onMessage`

`object`. This contains the `addListener()` and `removeListener()` functions common to all events for extensions built using WebExtension APIs. Listener functions will be called when the other end has sent this port a message. The listener will be passed the value that the other end sent.

`postMessage`

`function`. Send a message to the other end. This takes one argument, which is a serializable value (see Data cloning algorithm) representing the message to send. It will be delivered to any script listening to the port's `onMessage` event, or to the native application if this port is connected to a native application.

`sender` Optional

`runtime.MessageSender`. Contains information about the sender of the message. This property will only be present on ports passed to `onConnect`/`onConnectExternal` listeners.

Lifecycle
---------

The lifecycle of a `Port` is described in the Chrome docs.

There is, however, one important difference between Firefox and Chrome, stemming from the fact that the `runtime.connect` and `tabs.connect` APIs are broadcast channels. This means that there may be potentially more than one recipient, and this results in ambiguity when one of the contexts with a `runtime.onConnect` call is closed. In Chrome, a port stays active as long as there is any other recipient. In Firefox, the port closes when any of the contexts unloads. In other words, the disconnection condition,

* All frames that received the port (via `runtime.onConnect`) have unloaded.

which holds in Chrome, is replaced by

* *Any* frame that received the port (via `runtime.onConnect`) has unloaded.

in Firefox (see bug 1465514).

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

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

Examples
--------

### Connecting from content scripts

This content script:

* connects to the background script and stores the `Port` in a variable called `myPort`.
* listens for messages on `myPort` and logs them.
* sends messages to the background script, using `myPort`, when the user clicks the document.

```js
// content-script.js

let myPort = browser.runtime.connect({ name: "port-from-cs" });
myPort.postMessage({ greeting: "hello from content script" });

myPort.onMessage.addListener((m) => {
  console.log("In content script, received message from background script: ");
  console.log(m.greeting);
});

document.body.addEventListener("click", () => {
  myPort.postMessage({ greeting: "they clicked the page!" });
});
```

The corresponding background script:

* listens for connection attempts from the content script.
* when it receives a connection attempt:
    + stores the port in a variable named `portFromCS`.
    + sends the content script a message using the port.
    + starts listening to messages received on the port, and logs them.
* sends messages to the content script, using `portFromCS`, when the user clicks the extension's browser action.

```js
// background-script.js

let portFromCS;

function connected(p) {
  portFromCS = p;
  portFromCS.postMessage({ greeting: "hi there content script!" });
  portFromCS.onMessage.addListener((m) => {
    console.log("In background script, received message from content script");
    console.log(m.greeting);
  });
}

browser.runtime.onConnect.addListener(connected);

browser.browserAction.onClicked.addListener(() => {
  portFromCS.postMessage({ greeting: "they clicked the button!" });
});
```

#### Multiple content scripts

If you have multiple content scripts communicating at the same time, you might want to store each connection in an array.

```js
// background-script.js

let ports = [];

function connected(p) {
  ports[p.sender.tab.id] = p;
  // …
}

browser.runtime.onConnect.addListener(connected);

browser.browserAction.onClicked.addListener(() => {
  ports.forEach((p) => {
    p.postMessage({ greeting: "they clicked the button!" });
  });
});
```

### Connecting to native applications

This example connects to the native application "ping\_pong" and starts listening for messages from it. It also sends the native application a message when the user clicks a browser action icon:

```js
/\*
On startup, connect to the "ping\_pong" app.
\*/
let port = browser.runtime.connectNative("ping\_pong");

/\*
Listen for messages from the app.
\*/
port.onMessage.addListener((response) => {
  console.log(`Received: ${response}`);
});

/\*
On a click on the browser action, send the app a message.
\*/
browser.browserAction.onClicked.addListener(() => {
  console.log("Sending: ping");
  port.postMessage("ping");
});
```

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


runtime.sendMessage() - Mozilla

runtime.sendMessage()
=====================

Sends a single message to event listeners within your extension or a different extension.

If sending to your extension, omit the `extensionId` argument. The `runtime.onMessage` event will be fired in each page in your extension, except for the frame that called `runtime.sendMessage`.

If sending to a different extension, include the `extensionId` argument set to the other extension's ID. `runtime.onMessageExternal` will be fired in the other extension. By default, your extension can exchange messages with itself and any other extension (defined by `extensionId`). However, the `externally_connectable` manifest key can be used to limit communication to specific extensions.

Extensions cannot send messages to content scripts using this method. To send messages to content scripts, use `tabs.sendMessage`.

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

**Note:** You can also use a connection-based approach to exchange messages.

Syntax
------

```js
let sending = browser.runtime.sendMessage(
  extensionId,             // optional string
  message,                 // any
  options                  // optional object
)
```

### Parameters

`extensionId` Optional

`string`. The ID of the extension to send the message to. Include this to send the message to a different extension. If the intended recipient has set an ID explicitly using the browser\_specific\_settings key in manifest.json, then `extensionId` should have that value. Otherwise it should have the ID that was generated for the intended recipient.

If `extensionId` is omitted, the message is sent to your extension.

`message`

`any`. An object that can be structured clone serialized (see Data cloning algorithm).

`options` Optional

`object`.

`includeTlsChannelId` Optional

`boolean`. Whether the TLS channel ID will be passed into `runtime.onMessageExternal` for processes that are listening for the connection event.

This option is only supported in Chromium-based browsers.

Depending on the arguments it is given, this API is sometimes ambiguous. The following rules are used:

* **if one argument is given**, it is the message to send, and the message will be sent internally.
* **if two arguments are given:**
    + the arguments are interpreted as `(message, options)`, and the message is sent internally, if the second argument is any of the following:
        1. a valid `options` object (meaning, it is an object which contains only the properties of `options` that the browser supports)
        2. null
        3. undefined
    + otherwise, the arguments are interpreted as `(extensionId, message)`. The message will be sent to the extension identified by `extensionId`.
* **if three arguments are given**, the arguments are interpreted as `(extensionId, message, options)`. The message will be sent to the extension identified by `extensionId`.

Note that before Firefox 55, the rules were different in the 2-argument case. Under the old rules, if the first argument was a string, it was treated as the `extensionId`, with the message as the second argument. This meant that if you called `sendMessage()` with arguments like `("my-message", {})`, then it would send an empty message to the extension identified by "my-message". Under the new rules, with these arguments you would send the message "my-message" internally, with an empty options object.

### Return value

A `Promise`. If the receiver sent a response, this will be fulfilled with the response. Otherwise it will be fulfilled with no arguments. If an error occurs while connecting to the extension, 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
--------

Here's a content script that sends a message to the background script when the user clicks the content window. The message payload is `{greeting: "Greeting from the content script"}`, and the sender also expects to get a response, which is handled in the `handleResponse` function:

```js
// content-script.js

function handleResponse(message) {
  console.log(`Message from the background script: ${message.response}`);
}

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

function notifyBackgroundPage(e) {
  const sending = browser.runtime.sendMessage({
    greeting: "Greeting from the content script",
  });
  sending.then(handleResponse, handleError);
}

window.addEventListener("click", notifyBackgroundPage);
```

The corresponding background script looks like this:

```js
// background-script.js
function handleMessage(request, sender, sendResponse) {
  console.log(`A content script sent a message: ${request.greeting}`);
  sendResponse({ response: "Response from background script" });
}

browser.runtime.onMessage.addListener(handleMessage);
```

**Note:** Instead of using `sendResponse()`, returning a `Promise` is the recommended approach for Firefox add-ons.
 Examples using a Promise are available in the examples section of the `runtime.onMessage` listener.

### Example extensions

* content-script-register
* devtools-panels
* export-helpers
* find-across-tabs
* mocha-client-tests
* notify-link-clicks-i18n
* store-collected-images
* user-script-register
* webpack-modules

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


runtime.onRestartRequired - Mozilla

runtime.onRestartRequired
=========================

Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at its earliest convenience to let the restart happen. If the app does nothing, a restart will be enforced after a 24-hour grace period has passed. Currently, this event is only fired for ChromeOS kiosk apps.

Syntax
------

```js
browser.runtime.onRestartRequired.addListener(listener)
browser.runtime.onRestartRequired.removeListener(listener)
browser.runtime.onRestartRequired.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)`

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

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

### Parameters

`function`

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

`reason`

A `runtime.OnRestartRequiredReason` value — the reason that the event is being dispatched.

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


runtime.connect() - Mozilla

runtime.connect()
=================

Make a connection between different contexts inside the extension.

You can call this:

* in an extension's content scripts, to establish a connection with the extension's background scripts (or similarly privileged scripts, like popup scripts or options page scripts).
* in an extension's background scripts (or similarly privileged scripts), to establish a connection with a different extension.

Note that you can't use this function to connect an extension to its content scripts. To do this, use `tabs.connect()`.

By default, this connection enables the extension to exchange messages with itself or any other extension (if `extensionId` is specified). However, the `externally_connectable` manifest key can be used to limit communication to specific extensions and enable communication with websites. Connections within the extension trigger the `runtime.onConnect` event, connections from other extensions or web pages trigger the `runtime.onConnectExternal` event.

Syntax
------

```js
let port = browser.runtime.connect(
  extensionId, // optional string
  connectInfo  // optional object
)
```

### Parameters

`extensionId` Optional

`string`. The ID of the extension to connect to. If the target has set an ID explicitly using the browser\_specific\_settings key in manifest.json, then `extensionId` should have that value. Otherwise it should have the ID that was generated for the target.

`connectInfo` Optional

`object`. Details of the connection:

`name` Optional

`string`. Will be passed into `runtime.onConnect` for processes that are listening for the connection event.

`includeTlsChannelId` Optional

`boolean`. Whether the TLS channel ID will be passed into `runtime.onConnectExternal` for processes that are listening for the connection event.

### Return value

`runtime.Port`. Port through which messages can be sent and received. The port's `onDisconnect` event is fired if the extension does not exist.

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

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

Examples
--------

This content script:

* connects to the background script and stores the `Port` in a variable called `myPort`.
* listens for messages on `myPort` and logs them.
* sends messages to the background script, using `myPort`, when the user clicks the document.

```js
// content-script.js

let myPort = browser.runtime.connect({ name: "port-from-cs" });
myPort.postMessage({ greeting: "hello from content script" });

myPort.onMessage.addListener((m) => {
  console.log("In content script, received message from background script: ");
  console.log(m.greeting);
});

document.body.addEventListener("click", () => {
  myPort.postMessage({ greeting: "they clicked the page!" });
});
```

The corresponding background script:

* listens for connection attempts from the content script.
* when it receives a connection attempt:
    + stores the port in a variable named `portFromCS`.
    + sends the content script a message using the port.
    + starts listening to messages received on the port, and logs them.
* sends messages to the content script, using `portFromCS`, when the user clicks the extension's browser action.

```js
// background-script.js

let portFromCS;

function connected(p) {
  portFromCS = p;
  portFromCS.postMessage({ greeting: "hi there content script!" });
  portFromCS.onMessage.addListener((m) => {
    console.log("In background script, received message from content script");
    console.log(m.greeting);
  });
}

browser.runtime.onConnect.addListener(connected);

browser.browserAction.onClicked.addListener(() => {
  portFromCS.postMessage({ greeting: "they clicked the button!" });
});
```

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


runtime.onSuspendCanceled - Mozilla

runtime.onSuspendCanceled
=========================

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

Syntax
------

```js
browser.runtime.onSuspendCanceled.addListener(listener)
browser.runtime.onSuspendCanceled.removeListener(listener)
browser.runtime.onSuspendCanceled.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)`

Checks whether a `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.

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

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

Examples
--------

Listen for `SuspendCanceled` events:

```js
function handleSuspendCanceled() {
  console.log("Suspend canceled");
}

browser.runtime.onSuspendCanceled.addListener(handleSuspendCanceled);
```

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


runtime.lastError - Mozilla

runtime.lastError
=================

This value is used to report an error message from an asynchronous API, when the asynchronous API is given a callback. This is useful for extensions that are using the callback-based version of the WebExtension APIs.

You don't need to check this property if you are using the promise-based version of the APIs: instead, pass an error handler to the promise:

```js
const gettingCookies = browser.cookies.getAll();
gettingCookies.then(onGot, onError);
```

The `runtime.lastError` property is set when an asynchronous function has an error condition that it needs to report to its caller.

If you call an asynchronous function that may set `lastError`, you are expected to check for the error when you handle the result of the function. If `lastError` has been set and you don't check it within the callback function, then an error will be raised.

Syntax
------

```js
let myError = browser.runtime.lastError;  // null or Error object
```

### Value

An `Error` object representing the error. The `message` property is a `string` with a human-readable description of the error. If `lastError` has not been set, the value is `null`.

Examples
--------

Set a cookie, using a callback to log the new cookie or report an error:

```js
function logCookie(c) {
  if (browser.runtime.lastError) {
    console.error(browser.runtime.lastError);
  } else {
    console.log(c);
  }
}

browser.cookies.set({ url: "https://developer.mozilla.org/" }, logCookie);
```

The same, but using a promise to handle the result of `setCookie()`:

```js
function logCookie(c) {
  console.log(c);
}

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

const setCookie = browser.cookies.set({
  url: "https://developer.mozilla.org/",
});

setCookie.then(logCookie, logError);
```

**Note:** `runtime.lastError` is an alias for `extension.lastError`. They are set together, and checking either one will work.

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

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

### Example extensions

* menu-demo

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


runtime.PlatformNaclArch - Mozilla

runtime.PlatformNaclArch
========================

The native client architecture. This may be different from arch on some platforms.

Type
----

Values of this type are strings. Possible values are: `"arm"`, `"x86-32"`, `"x86-64"`.

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


runtime.getPackageDirectoryEntry() - Mozilla

runtime.getPackageDirectoryEntry()
==================================

Returns a `DirectoryEntry` object representing the package directory.

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

Syntax
------

```js
let gettingEntry = browser.runtime.getPackageDirectoryEntry()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with a `DirectoryEntry` object representing the package directory.

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

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

Examples
--------

```js
function gotDirectoryEntry(directoryEntry) {
  console.log(directoryEntry);
}

let gettingEntry = browser.runtime.getPackageDirectoryEntry();
gettingEntry.then(gotDirectoryEntry);
```

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


runtime.openOptionsPage() - Mozilla

runtime.openOptionsPage()
=========================

If your extension has an options page defined, this method opens it.

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

Syntax
------

```js
let openingPage = browser.runtime.openOptionsPage()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with no arguments when the options page has been created successfully, or rejected with an error message if the operation failed.

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

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

Examples
--------

Open the options page when the user clicks a browser action's icon:

```js
function onOpened() {
  console.log(`Options page opened`);
}

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

let opening = browser.runtime.openOptionsPage();
opening.then(onOpened, onError);
```

### Example extensions

* favourite-colour

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


runtime.PlatformArch - Mozilla

runtime.PlatformArch
====================

The machine's processor architecture.

Type
----

Values of this type are strings. Possible values are:

`"arm"`

The platform is based on arm architecture.

`"x86-32"`

The platform is based on x86 32-bit architecture.

`"x86-64"`

The platform is based on x86 64-bit architecture.

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


runtime.onConnectExternal - Mozilla

runtime.onConnectExternal
=========================

Fired when an extension receives a connection request from a different extension.

To send a message which will be received by the `onConnectExternal` listener, use `runtime.connect()`, passing the ID of the recipient in the `extensionId` parameter.

The listener is passed a `runtime.Port` object which it can then use to send and receive messages. The `Port` object also contains a `sender` property, which is a `runtime.MessageSender` object, and which the recipient can use to check the sender's ID.

Syntax
------

```js
browser.runtime.onConnectExternal.addListener(listener)
browser.runtime.onConnectExternal.removeListener(listener)
browser.runtime.onConnectExternal.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)`

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

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

### Parameters

`function`

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

`port`

A `runtime.Port` object connecting the current script to the other extension it is connecting to.

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

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

Examples
--------

In this example the extension Hansel connects to the extension Gretel:

```js
console.log("connecting to Gretel");
let myPort = browser.runtime.connect("gretel@mozilla.org");

myPort.onMessage.addListener((message) => {
  console.log(`From Gretel: ${message.content}`);
});

browser.browserAction.onClicked.addListener(() => {
  myPort.postMessage({ content: "Hello from Hansel" });
});
```

Gretel listens for the connection and checks that the sender is really Hansel:

```js
let portFromHansel;

browser.runtime.onConnectExternal.addListener((port) => {
  console.log(port);
  if (port.sender.id === "hansel@mozilla.org") {
    console.log("connection attempt from Hansel");
    portFromHansel = port;
    portFromHansel.onMessage.addListener((message) => {
      console.log(`From Hansel: ${message.content}`);
    });
  }
});

browser.browserAction.onClicked.addListener(() => {
  portFromHansel.postMessage({ content: "Message from Gretel" });
});
```

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


declarativeNetRequest.onRuleMatchedDebug - Mozilla

declarativeNetRequest.onRuleMatchedDebug
========================================

Fired when a rule is matched with a request. Only available extensions with the `"declarativeNetRequestFeedback"` permission, as this is intended for debugging purposes only. See Testing for details on how testing is enabled in each browser.

Syntax
------

```js
browser.declarativeNetRequest.onRuleMatchedDebug.addListener(listener)
browser.declarativeNetRequest.onRuleMatchedDebug.removeListener(listener)
browser.declarativeNetRequest.onRuleMatchedDebug.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`

An object containing information about the request the rule matched.

`documentId` Optional

A `string`. The unique identifier for the frame's document, if this request is for a frame.

`documentLifecycle` Optional

A `string`. The lifecycle of the frame's document, if this request is for a frame. Possible values are: `"prerender"`, `"active"`, `"cached"`, or `"pending_deletion"`.

`frameId`

A `number`. The value `0` indicates that the request happens in the main frame. A positive value indicates the ID of a subframe where the request happens. If the document of a (sub-)frame is loaded (type is `main_frame` or `sub_frame`), `frameId` indicates this frame's ID, not the outer frame's ID. Frame IDs are unique within a tab.

`frameType` Optional

A `string`. The type of the frame, if this request is for a frame. Possible values are: `"outermost_frame"`, `"fenced_frame"`, or `"sub_frame"`.

`initiator` Optional

A `string`. The origin where the request was initiated. This does not change through redirects. The string 'null' is used if this is an opaque origin.

`method`

A `string`. A standard HTTP method.

`parentDocumentId` Optional

A `string`. The unique identifier for the frame's parent document, if this request is for a frame and has a parent.

`parentFrameId`

A `number`. The ID of the frame that wraps the frame which sent the request. Set to `-1` if there is no parent frame.

`requestId`

A `string`. The ID of the request. Request IDs are unique within a browser session.

`tabId`

A `number`. The ID of the tab in which the request takes place. Set to `-1` if the request is not related to a tab.

`type`

`ResourceType`. The resource type of the request.

`url`

A `string`. The URL of the request.

`rule`

`MatchedRule`. Details of a matched rule.

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

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


declarativeNetRequest.GUARANTEED_MINIMUM_STATIC_RULES - Mozilla

declarativeNetRequest.GUARANTEED\_MINIMUM\_STATIC\_RULES
========================================================

The minimum number of static rules guaranteed to an extension across its enabled static rulesets. Any rules above this limit are count towards the global static rule limit.

Its value is `30000` on Chrome.

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

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


declarativeNetRequest.testMatchOutcome - Mozilla

declarativeNetRequest.testMatchOutcome
======================================

Checks if any of the extension's `declarativeNetRequest` rules would match a hypothetical request. Only available while testing, as this is intended to be used during extension development. See Testing for details on how testing is enabled in each browser.

Syntax
------

```js
let result = await browser.declarativeNetRequest.testMatchOutcome(
    request,                // object
    options                 // optional object
);
```

### Parameters

`request`

The details of the request to test.

`initiator` Optional

A `string`. The initiator URL (if any) for the hypothetical request.

`method` Optional

A `string`. The standard (lower case) HTTP method of the hypothetical request. Defaults to `"get"` for HTTP requests and is ignored for non-HTTP requests.

`tabId` Optional

A `number`. The ID of the tab the hypothetical request takes place in. Does not need to correspond to a real tab ID. Default is `-1`, meaning that the request isn't related to a tab.

`type`

`declarativeNetRequest.ResourceType`. The resource type of the hypothetical request.

`url`

A `string`. The URL of the hypothetical request.

`options` Optional

Details of options for the request.

`includeOtherExtensions` Optional

A `boolean`. Whether matching rules from other extensions are included in `matchedRules`. When rules from other extensions match, the resulting `matchedRule` has an `extensionId` property. Defaults to `false`.

### Return value

A `Promise` that fulfills with an object with these properties:

`matchedRules`

`declarativeNetRequest.MatchedRule`. Details of the rules (if any) that match the hypothetical request.

If no rules match, the `matchedRules` array is empty. If the request fails, the promise is rejected with an error message.

Examples
--------

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

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


declarativeNetRequest.DYNAMIC_RULESET_ID - Mozilla

declarativeNetRequest.DYNAMIC\_RULESET\_ID
==========================================

Ruleset ID for the dynamic rules added by the extension using `updateDynamicRules`.

Its value is `"_dynamic"`.

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

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


declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES - Mozilla

declarativeNetRequest.MAX\_NUMBER\_OF\_DYNAMIC\_AND\_SESSION\_RULES
===================================================================

The maximum number of combined dynamic and session scoped rules an extension can add.

In Chrome, this limit is enforced for the combination of dynamic and session scoped rules.

In Firefox, each ruleset has its own quota.

Its value is `5000`.

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

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


declarativeNetRequest.MAX_NUMBER_OF_ENABLED_STATIC_RULESETS - Mozilla

declarativeNetRequest.MAX\_NUMBER\_OF\_ENABLED\_STATIC\_RULESETS
================================================================

The maximum number of static rulesets an extension can have enabled, i.e., the number of values in the `declarative_net_request.rule_resources` manifest key with `"enabled"` set to `true`. Static rulesets exceeding the limit are ignored.

An extension can change the number of enabled rulesets using the `updateEnabledRulesets` method.

Its value is `10`.

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

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


declarativeNetRequest.MatchedRule - Mozilla

declarativeNetRequest.MatchedRule
=================================

An object describing the matched rule. This type may be returned by the `declarativeNetRequest.getMatchedRules` or `declarativeNetRequest.testMatchOutcome` methods, or observed through the `declarativeNetRequest.onRuleMatchedDebug` event.

Type
----

Values of this type are objects. They contain these properties:

`extensionId`

A `string`. The ID of the extension, if this rule belongs to a different extension. This property is only available when used with `declarativeNetRequest.testMatchOutcome`, with the `includeOtherExtensions` option set to `true`.

`ruleId`

A `number`. The matching rule's ID.

`rulesetId`

A `string`. The ID of the ruleset this rule belongs to. The value returned is:

* For a rule originating from the set of static rules, the value specified in the "id" key of the ruleset in the `declarative_net_request.rule_resources` manifest key.
* For a rule originating from the set of dynamic rules, the value defined in `declarativeNetRequest.DYNAMIC_RULESET_ID`, i.e., `"_dynamic"`.
* For a rule originating from the set of session rules, the value defined in `declarativeNetRequest.SESSION_RULESET_ID`, i.e., `"_session"`.

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

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


declarativeNetRequest.ResourceType - Mozilla

declarativeNetRequest.ResourceType
==================================

The resource type of a request. Comparable to `webRequest.ResourceType`.

Type
----

Values of this type are strings. Possible values are:

`beacon`

Requests sent through the Beacon API.

`csp_report`

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

`font`

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

`image`

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

`imageset`

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

`main_frame`

Top-level documents loaded into a tab.

`media`

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

`object`

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

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

`object_subrequest`

Requests sent by plugins.

`ping`

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

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

`script`

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

`speculative`

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

`stylesheet`

CSS stylesheets loaded to describe the representation of a document.

`sub_frame`

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

`web_manifest`

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

`webbundle`

Requests initiating a connection to a server through a Web Bundle or packaged website.

`websocket`

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

`webtransport`

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

`xml_dtd`

DTDs loaded for an XML document.

`xmlhttprequest`

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

`xslt`

XSLT stylesheets loaded for transforming an XML document.

`other`

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

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

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


declarativeNetRequest.getDynamicRules - Mozilla

declarativeNetRequest.getDynamicRules
=====================================

Returns the set of dynamic rules for the extension.

Syntax
------

```js
let gettingDynamicRules = browser.declarativeNetRequest.getDynamicRules();
```

### Parameters

This function takes no parameters.

### Return value

A `Promise` is fulfilled with an array of `declarativeNetRequest.Rule` objects. Each of these represents a rule that belongs to the extension. If no rules are active, the array is empty. If the request fails, the promise is rejected with an error message.

Examples
--------

### Example extensions

* dnr-dynamic-with-options
Browser compatibility
---------------------

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


declarativeNetRequest.setExtensionActionOptions - Mozilla

declarativeNetRequest.setExtensionActionOptions
===============================================

Configures whether the action count for tabs is displayed as the extension action's badge text and provides a way for the action count to be incremented.

Syntax
------

```js
let count = browser.declarativeNetRequest.setExtensionActionOptions(
    extensionActionOptions, // object
);
```

### Parameters

`extensionActionOptions`

An object containing the configuration details for the action count for tabs.

`displayActionCountAsBadgeText` Optional

`boolean` Whether to automatically display the action count for a page as the extension's badge text. This preference persists across sessions.

`tabUpdate` Optional

`object`. Details of how the tab's action count should be adjusted. See the tabUpdate section for more details.

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

### tabUpdate

`increment`

`number` The amount to increment the tab's action count by. Negative values decrement the count.

`tabId`

`number` The tab to update the action count for.

### Return value

A `Promise` that fulfills with no arguments. If the request fails, the promise is rejected with an error message.

Examples
--------

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

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


declarativeNetRequest.getAvailableStaticRuleCount - Mozilla

declarativeNetRequest.getAvailableStaticRuleCount
=================================================

Returns the number of static rules that can be activated before the global static rule limit is reached.

Syntax
------

```js
let count = await browser.declarativeNetRequest.getAvailableStaticRuleCount();
```

### Parameters

This function takes no parameters.

### Return value

A `Promise` fulfilled with a number that indicates how many static rules can enable before the global static rule limit is reached. If the request fails, the promise is rejected with an error message.

Examples
--------

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

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


declarativeNetRequest.MAX_NUMBER_OF_STATIC_RULESETS - Mozilla

declarativeNetRequest.MAX\_NUMBER\_OF\_STATIC\_RULESETS
=======================================================

The maximum number of static rulesets an extension can specify as part of the `declarative_net_request.rule_resources` manifest key.

Its value is `50`.

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

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


declarativeNetRequest.RuleCondition - Mozilla

declarativeNetRequest.RuleCondition
===================================

Details of the condition that determines whether a rule matches a request, as the `condition` property of a `declarativeNetRequest.Rule`.

Type
----

Values of this type are objects. They contain these properties:

`domainType` Optional

A `string`. Specifies whether the network request is first-party or third-party to the domain from where it originated. If omitted, all requests are accepted. Possible values are `"firstParty"` and `"thirdParty"`.

`domains`
Deprecated
 Optional

An array of `string`. Use `initiatorDomains` instead. The rule only matches network requests originating from this list of domains.

`excludedDomains`
Deprecated
 Optional

An array of `string`. Use `excludedInitiatorDomains` instead. The rule does not match network requests originating from this list of domains.

`initiatorDomains` Optional

An array of `string`. The rule only matches network requests originating from this list of domains. If the list is omitted, the rule is applied to requests from all domains. An empty list is not allowed. A canonical domain should be used. This matches against the request initiator and not the request URL.

`excludedInitiatorDomains` Optional

An array of `string`. The rule does not match network requests originating from this list of domains. If the list is empty or omitted, no domains are excluded. This takes precedence over `initiatorDomains`. A canonical domain should be used. This matches against the request initiator and not the request URL.

`isUrlFilterCaseSensitive` Optional

A `boolean`. Whether the `urlFilter` or `regexFilter` (whichever is specified) is case sensitive. While there is consensus on defaulting to `false` across browsers in WECG issue 269, the value used to be `true` in (older) versions of Chrome and Safari. See Browser compatibility for details.

`regexFilter` Optional

A `string`. Regular expression to match against the network request URL. Note that:

* The supported format is not stable and varies across browsers, see "Regular expressions in DNR API (regexFilter)" in WECG issue 344 for details.
* Only one of `urlFilter` or `regexFilter` can be specified.
* The `regexFilter` must be composed of only ASCII characters. This is matched against a URL where the host is encoded in the punycode format (in case of internationalized domains) and any other non-ascii characters are URL encoded in utf-8.

`requestDomains` Optional

An array of `string`. The rule only matches network requests when the domain matches one from this list. If the list is omitted, the rule is applied to requests from all domains. An empty list is not allowed. A canonical domain should be used.

`excludedRequestDomains` Optional

An array of `string`. The rule does not match network requests when the domains matches one from this list. If the list is empty or omitted, no domains are excluded. This takes precedence over `requestDomains`. A canonical domain should be used.

`requestMethods` Optional

An array of `string`. List of HTTP request methods that the rule matches. An empty list is not allowed. Specifying a `requestMethods` rule condition also excludes non-HTTP(s) requests, whereas specifying `excludedRequestMethods` does not.

`excludedRequestMethods` Optional

An array of `string`. List of request methods that the rule does not match on. Only one of `requestMethods` and `excludedRequestMethods` should be specified. If neither of them is specified, all request methods are matched.

`resourceTypes` Optional

An array of `declarativeNetRequest.ResourceType`. List of resource types that the rule matches with. An empty list is not allowed. This must be specified for `"allowAllRequests"` rules and may only include the `"sub_frame"` and `"main_frame"` resource types.

`excludedResourceTypes` Optional

An array of `declarativeNetRequest.ResourceType`. List of resource types that the rule does not match on. Only one of `resourceTypes` and `excludedResourceTypes` should be specified. If neither of them is specified, all resource types except `"main_frame"` are blocked.

`tabIds` Optional

An array of `number`. List of `tabs.Tab`.`id` that the rule should match. An ID of `tabs.TAB_ID_NONE` matches requests that don't originate from a tab. An empty list is not allowed. Only supported for session-scoped rules.

`excludedTabIds` Optional

An array of `number`. List of `tabs.Tab`.`id` that the rule should not match. An ID of `tabs.TAB_ID_NONE` excludes requests that do not originate from a tab. Only supported for session-scoped rules.

`urlFilter` Optional

A `string`. The pattern that is matched against the network request URL. Supported constructs:

* `*` : Wildcard: Matches any number of characters.
* `|` : Left or right anchor: If used at either end of the pattern, specifies the beginning or end of the URL respectively.
* `||` : Domain name anchor: If used at the beginning of the pattern, specifies the start of a (sub-)domain of the URL.
* `^` : Separator character: This matches anything except a letter, a digit, or one of `_`, `-`, `.`, or `%`. The last `^` may also match the end of the URL instead of a separator character.

`urlFilter` is composed of the following parts: (optional left/domain name anchor) + pattern + (optional right anchor).
 If omitted, all URLs are matched. An empty string is not allowed.
 A pattern beginning with `||*` is not allowed. Use `*` instead.
 Note that:

* Only one of `urlFilter` or `regexFilter` can be specified.
* The `urlFilter` must be composed of only ASCII characters. This is matched against a URL where the host is encoded in the punycode format (in case of internationalized domains) and any other non-ASCII characters are URL encoded in utf-8. For example, when the request URL is `http://abc.рф?q=ф`, the `urlFilter` is matched against the URL `http://abc.xn--p1ai/?q=%D1%84`.

### Canonical domain

Domains specified in `initiatorDomains`, `excludedInitiatorDomains`, `requestDomains`, or `excludedRequestDomains` should comply with the following:

* Sub-domains such as "a.example.com" are allowed.
* The entries must consist of only *lowercase* ASCII characters.
* Use Punycode encoding for internationalized domains.
* IPv4 addresses must be represented as 4 numbers separated by a dot.
* IPv6 addresses should be represented in their canonical form, wrapped in square brackets.

To programmatically generate the canonical domain for a URL, use the URL API and read its `hostname` property, i.e., `new URL(url).hostname`.

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

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

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


declarativeNetRequest.SESSION_RULESET_ID - Mozilla

declarativeNetRequest.SESSION\_RULESET\_ID
==========================================

The ruleset ID for the session-scoped rules added by the extension.

Its value is `"_session"`.

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

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


declarativeNetRequest.getSessionRules - Mozilla

declarativeNetRequest.getSessionRules
=====================================

Returns the active set of session scoped rules for the extension.

Syntax
------

```js
let sessionRules = await browser.declarativeNetRequest.getSessionRules();
```

### Parameters

This function takes no parameters.

### Return value

A `Promise` fulfilled with an array of `declarativeNetRequest.Rule` objects. If no rules are active, the object is empty. If the request fails, the promise is rejected with an error message

Examples
--------

### Example extensions

* dnr-dynamic-with-options
Browser compatibility
---------------------

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


declarativeNetRequest.Redirect - Mozilla

declarativeNetRequest.Redirect
==============================

Details describing how a redirect should be performed, as the `redirect` property of a `RuleAction`. Only valid for redirect rules.

**Note:**
 A redirect action does not redirect the request, and the request continues as usual when:

* the action does not change the request.
* the redirect URL is invalid (e.g., the value of `redirect.regexSubstitution` is not a valid URL).

Type
----

Values of this type are objects. They contain these properties:

`extensionPath` Optional

A `string`. The path relative to the extension directory. Should start with '/'. The initiator of the request can only follow the redirect when the resource is listed in `web_accessible_resources`.

`regexSubstitution` Optional

A `string`. The substitution pattern for rules that specify a `regexFilter`. The first match of `regexFilter` within the URL is replaced with this pattern. Within `regexSubstitution`, backslash-escaped digits (`\1` to `\9`) are used to insert the corresponding capture groups. `\0` refers to the entire matching text.

`transform` Optional

`declarativeNetRequest.URLTransform`. The URL transformations to perform.

`url` Optional

A `string`. The redirect URL. Redirects to JavaScript URLs are not allowed.

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

* dnr-redirect-url
Browser compatibility
---------------------

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


declarativeNetRequest.getMatchedRules - Mozilla

declarativeNetRequest.getMatchedRules
=====================================

Returns all the rules matched for the extension. Callers can filter the list of matched rules by specifying a `filter`. This method is only available to extensions with the `"declarativeNetRequestFeedback"` permission or that have the `"activeTab"` permission granted for the `tabId` specified in `filter`. Rules not associated with an active document that were matched more than five minutes ago are not returned.

Syntax
------

```js
let gettingMatchedRules = browser.declarativeNetRequest.getMatchedRules(
    filter                // object
);
```

### Parameters

`filter` Optional

An object to filter the list of matched rules.

`minTimeStamp` Optional

A `number`. If specified, only matches rules after the specified timestamp.

`tabId` Optional

A `number`. If specified, only matches rules for the specified tab. Matches rules not associated with any active tab if set to `-1`.

### Return value

A `Promise` that fulfills with an object with these properties:

`rule`

`declarativeNetRequest.MatchedRule`. Details of a matched rule.

`tabId`

`number` The `tabId` of the tab the request originated from if the tab is still active. Otherwise, `-1`.

`timeStamp`

`number` The time the rule was matched. Timestamps correspond to the JavaScript convention for times, i.e. the number of milliseconds since the epoch.

If no rules are matched, the object is empty. If the request fail, the promise is rejected with an error message

Examples
--------

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

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


declarativeNetRequest.getEnabledRulesets - Mozilla

declarativeNetRequest.getEnabledRulesets
========================================

Returns the IDs for the set of activated static rulesets.

Syntax
------

```js
let rulesetIds = await browser.declarativeNetRequest.getEnabledRulesets();
```

### Parameters

This function takes no parameters.

### Return value

A `Promise` fulfilled with an array of string containing static rulesets IDs. If no rules are active, the array is empty. If the request fails, the promise is rejected with an error message.

Examples
--------

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

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


declarativeNetRequest.isRegexSupported - Mozilla

declarativeNetRequest.isRegexSupported
======================================

Checks if a regular expression is supported as a `declarativeNetRequest.RuleCondition``.regexFilter` rule condition.

Syntax
------

```js
let count = browser.declarativeNetRequest.isRegexSupported(
    regexOptions                // object
);
```

### Parameters

`regexOptions`

An object containing the regular expression to check.

`isCaseSensitive` Optional

`boolean` Whether the regex specified is case sensitive. Default is `true`.

`regex`

`string` The regular expression to check.

`requireCapturing` Optional

`boolean` Whether the regex specified requires capturing. Capturing is only required for redirect rules that specify a regexSubstitution action. The default is false.

### Return value

A `Promise` that fulfills with an object with these properties:

`isSupported`

`boolean` Whether the regular expression is supported.

`reason` Optional

`string` Specifies the reason why the regular expression is not supported. Possible values are `"syntaxError"` and `"memoryLimitExceeded"`. Only provided if `isSupported` is false.

If the request fails, the promise is rejected with an error message.

Examples
--------

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

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


declarativeNetRequest.Rule - Mozilla

declarativeNetRequest.Rule
==========================

The object describing the actions to take for matching requests. These can be specified in the static rule resources linked by the manifest.json's `declarative_net_request` key, or more dynamically through the `declarativeNetRequest.updateDynamicRules` or `declarativeNetRequest.updateSessionRules` methods.

See Rules on the API overview page for more information about rules.

Type
----

Values of this type are objects. They contain these properties:

`action`

`declarativeNetRequest.RuleAction`. The action to take if this rule is matched.

`condition`

`declarativeNetRequest.RuleCondition`. The condition under which this rule is triggered.

`id`

`number`. An ID that uniquely identifies a rule within a ruleset. Mandatory and should be >= 1.

`priority` Optional

`number`. Rule priority. Defaults to 1. When specified, should be >= 1. See Matching precedents for details on how priority affects which rules are applied.

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

* dnr-block-only
* dnr-dynamic-with-options
* dnr-redirect-url
Browser compatibility
---------------------

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


declarativeNetRequest.updateEnabledRulesets - Mozilla

declarativeNetRequest.updateEnabledRulesets
===========================================

Updates the extension's set of static rulesets. The rulesets with IDs listed in `options.disableRulesetIds` are first deactivated, and then the rulesets listed in `options.enableRulesetIds` are activated. Note that the set of enabled static rulesets persists across sessions but not across extension updates, i.e. the `declarative_net_request.rule_resources` manifest key determines the set of enabled static rulesets on each extension update.

Syntax
------

```js
let updatedRulesets = browser.declarativeNetRequest.updateEnabledRulesets(
    options                // object
);
```

### Parameters

`options`

An object detailing the rulesets to activate or deactivate in the extension's static rulesets.

`disableRulesetIds` Optional

An array of `string`. IDs of static Rulesets to deactivated.

`enableRulesetIds` Optional

An array of `string`. IDs of static Rulesets to activated.

### Return value

A `Promise` If the request was successful, the promise is fulfilled with no arguments. If the request fails, the promise is rejected with an error message.

Examples
--------

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

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


declarativeNetRequest.MAX_NUMBER_OF_REGEX_RULES - Mozilla

declarativeNetRequest.MAX\_NUMBER\_OF\_REGEX\_RULES
===================================================

The maximum number of regular expression rules that an extension can add.

In Chrome, its value is 1000, and this limit is evaluated separately for the set of dynamic and session rules, and those specified in the rule resources file.

In Firefox, this limit is evaluated separately per ruleset.

In Safari, there is no separate limit on the number of `regexFilter` rules.

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

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


declarativeNetRequest.updateDynamicRules - Mozilla

declarativeNetRequest.updateDynamicRules
========================================

Modifies the set of dynamic rules for the extension. The rules with IDs listed in `options.removeRuleIds` are first removed, and then the rules given in `options.addRules` are added. Note that:

* This update happens as an atomic operation: either all specified rules are added and removed, or an error is returned.
* These rules are persisted across browser sessions and across extension updates.
* Static rules specified as part of the extension package can not be removed using this function.
* `declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES` is the maximum number of dynamic and session rules an extension can add.
Syntax
------

```js
let updatedRules = browser.declarativeNetRequest.updateDynamicRules(
    options                // object
);
```

### Parameters

`options`

An object containing details of the rules to add or delete from the dynamic rules.

`addRules` Optional

An array of `declarativeNetRequest.Rule`. Details of the rules to add.

`removeRuleIds` Optional

An array of `number`. IDs of the rules to remove. Any invalid IDs are ignored.

### Return value

A `Promise` If the request was successful, the promise is fulfilled with no arguments. If the request fails, the promise is rejected with an error message.

Examples
--------

### Example extensions

* dnr-dynamic-with-options
Browser compatibility
---------------------

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


declarativeNetRequest.URLTransform - Mozilla

declarativeNetRequest.URLTransform
==================================

Details describing a URL transformation to perform for a redirect rule. This object can be specified at `rule.action`.redirect.transform.

Type
----

Values of this type are objects. They contain these properties:

`fragment` Optional

A `string`. The new fragment for the request. Should be either empty, in which case the existing fragment is cleared; or should begin with '#'.

`host` Optional

A `string`. The new host name for the request.

`password` Optional

A `string`. The new password for the request.

`path` Optional

A `string`. The new path for the request. If empty, the existing path is cleared.

`port` Optional

A `string`. The new port for the request. If empty, the existing port is cleared.

`query` Optional

A `string`. The new query for the request. Should be either empty, in which case the existing query is cleared; or should begin with '?'.

`queryTransform` Optional

An object describing how to add, remove, or replace query key-value pairs. Cannot be specified if 'query' is specified.

`addOrReplaceParams` Optional

An array of objects describing the list of query key-value pairs to be added or replaced.

`key`

A `string`. The key value.

`replaceOnly` Optional

A `boolean`. If true, the query key is replaced only if it's already present. Otherwise, the key is also added if it's missing. Defaults to false.

`value`

A `string`. The value value.

`removeParams` Optional

An array of `string`. The list of query keys to be removed.

`scheme` Optional

A `string`. The new scheme for the request. Allowed values are `"http"`, `"https"`, and the scheme of the extension, for example, "moz-extension" in Firefox or "chrome-extension" in Chrome. When the extension scheme is used, the `host` must be specified to generate a meaningful redirection target.

`username` Optional

A `string`. The new username for the request.

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

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


declarativeNetRequest.RuleAction - Mozilla

declarativeNetRequest.RuleAction
================================

Details of the action to take if a rule is matched, as the `action` property of a `declarativeNetRequest.Rule`.

Type
----

Values of this type are objects. They contain these properties:

`redirect` Optional

`declarativeNetRequest.Redirect`. Describes how the redirect should be performed. Only valid for redirect rules.

`requestHeaders` Optional

`declarativeNetRequest.ModifyHeaderInfo`. The request headers to modify for the request. Only valid if `type` is `"modifyHeaders"`.

`responseHeaders` Optional

`declarativeNetRequest.ModifyHeaderInfo`. The response headers to modify for the request. Only valid if `type` is `"modifyHeaders"`.

`type`

A `string`. The type of action to perform. Possible values are `"block"`, `"redirect"`, `"allow"`, `"upgradeScheme"`, `"modifyHeaders"`, and `"allowAllRequests"`. The use of the `"redirect"` and `"modifyHeaders"` actions require host permissions for the request and request initiator. The "block" and "upgradeScheme" actions also require host permissions unless the "declarativeNetRequest" permission is specified. Without these permissions, matching rules are ignored. See Permissions at declarativeNetRequest for more information. More details about the effects of rule actions are provided in Matching precedents.

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

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

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


declarativeNetRequest.GETMATCHEDRULES_QUOTA_INTERVAL - Mozilla

declarativeNetRequest.GETMATCHEDRULES\_QUOTA\_INTERVAL
======================================================

The time interval within which `declarativeNetRequest.MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL` `declarativeNetRequest.getMatchedRules` calls can be made, specified in minutes. Additional calls fail immediately and result in a promise rejection. Calls associated with a user gesture are exempt from the quota.

Its value is `10`.

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

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


declarativeNetRequest.MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL - Mozilla

declarativeNetRequest.MAX\_GETMATCHEDRULES\_CALLS\_PER\_INTERVAL
================================================================

The number of times `declarativeNetRequest.getMatchedRules` can be called within a period of `declarativeNetRequest.GETMATCHEDRULES_QUOTA_INTERVAL`.

Its value is `20`.

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

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


declarativeNetRequest.updateSessionRules - Mozilla

declarativeNetRequest.updateSessionRules
========================================

Modifies the set of scoped rules for the extension. The rules with IDs listed in `options.removeRuleIds` are first removed, and then the rules given in `options.addRules` are added. Note that:

* This update happens as an atomic operation: either all specified rules are added and removed, or an error is returned.
* These rules are not persisted across browser sessions.
* `MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES` is the maximum number of dynamic and session rules an extension can add.
Syntax
------

```js
let updatedRuleset = browser.declarativeNetRequest.updateSessionRules(
    options                // object
);
```

### Parameters

`options`

An object containing details of the rules to add or delete from the dynamic rules.

`addRules` Optional

An array of `declarativeNetRequest.Rule`. Details of the rules to add.

`removeRuleIds` Optional

An array of `number`. IDs of the rules to remove. Any invalid IDs are ignored.

### Return value

A `Promise` If the request was successful, the promise is fulfilled with no arguments. If the request fails, the promise is rejected with an error message.

Examples
--------

### Example extensions

* dnr-dynamic-with-options
Browser compatibility
---------------------

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


declarativeNetRequest.ModifyHeaderInfo - Mozilla

declarativeNetRequest.ModifyHeaderInfo
======================================

The request or response header to modify for a request, declared in the `rule.action.requestHeaders` array or `rule.action.responseHeaders` array for rules whose `rule.action``.type` is "modifyHeaders".

Each object describes one header modification. To modify multiple headers, multiple objects can be specified in these arrays, or across multiple rules.

 Matching `modifyHeaders` rules are applied in the order described at Matching precedents.
 Within each extension, all `modifyHeaders` rules with a priority lower than or equal to matching `allow` or `allowAllRequests` rules are ignored.

If multiple `modifyHeaders` rules specify the same header, the resulting modification for the header is determined based on the priority of each rule and the operations specified:

* If a rule has been appended to a header, then lower-priority rules can only append to that header. `set` and `remove` operations are not permitted.
* If a rule has set a header, lower priority rules cannot modify the header except for `append` rules from the same extension.
* If a rule has removed a header, lower priority rules cannot modify the header.
Type
----

Values of this type are objects. They contain these properties:

`header`

A `string`. The name of the header to be modified.

`operation`

A `string`. The operation to be performed on a header. Possible values are `"append"`, `"set"`, and `"remove"`.

`value` Optional

A `string`. The new value for the header. Must be specified for append and set operations. Not allowed for the "remove" operation.

Header limits
-------------

In Chrome, `"append"` is supported for the following request headers:

* `Accept`
* `Accept-Encoding`
* `Accept-Language`
* `Access-Control-Request-Headers`
* `Cache-Control`
* `Connection`
* `Content-Language`
* `Cookie`
* `Forwarded`
* `If-Match`
* `If-None-Match`
* `Keep-Alive`
* `Range`
* `Te`
* `Trailer`
* `Transfer-Encoding`
* `Upgrade`
* `Via`
* `Want-Digest`
* `X-Forwarded-For`

In Firefox, the extension needs host permissions for the new value of the `Host` header.

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

### webextensions.api.declarativeNetRequest.RuleAction.requestHeaders

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

### webextensions.api.declarativeNetRequest.RuleAction.responseHeaders

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


management.getAll() - Mozilla

management.getAll()
===================

Retrieves an array of `ExtensionInfo` objects, one for each installed add-on.

Note that Google Chrome retrieves apps as well as add-ons. In Chrome you can distinguish apps from add-ons using the `type` property of `ExtensionInfo`.

This API requires the "management" API permission.

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

Syntax
------

```js
let gettingAll = browser.management.getAll()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an array of `ExtensionInfo` objects, one for each installed add-on.

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

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

Examples
--------

Log the name of all installed add-ons:

```js
function gotAll(infoArray) {
  for (const info of infoArray) {
    if (info.type === "extension") {
      console.log(info.name);
    }
  }
}

let gettingAll = browser.management.getAll();
gettingAll.then(gotAll);
```

### Example extensions

* theme-switcher

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


management.get() - Mozilla

management.get()
================

Retrieves an `ExtensionInfo` object containing information about the specified add-on.

This API requires the "management" API permission.

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

Syntax
------

```js
let gettingInfo = browser.management.get(
  id                  // string
)
```

### Parameters

`id`

`string`. ID of the add-on whose info you want to retrieve.

### Return value

A `Promise` that will be fulfilled with an `ExtensionInfo` object, containing information about the add-on. The promise will be rejected if no extension with the given ID is installed or the extension is not allowed to be accessed by the caller.

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

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

Examples
--------

Log the name of the add-on whose ID is "my-add-on":

```js
let id = "my-add-on";

function got(info) {
  console.log(info.name);
}

let getting = browser.management.get(id);
getting.then(got);
```

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


management.onEnabled() - Mozilla

management.onEnabled()
======================

The event listener called when the `enabled` event is fired, indicating that an add-on is now enabled.

This API requires the "management" API permission.

Syntax
------

```js
browser.management.onEnabled.addListener(listener)
browser.management.onEnabled.removeListener(listener)
browser.management.onEnabled.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)`

Checks whether a `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:

`info`

`ExtensionInfo`: info about the add-on that was enabled.

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

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

Examples
--------

Log the names of add-ons when they are enabled:

```js
browser.management.onEnabled.addListener((info) => {
  console.log(`${info.name} was enabled`);
});
```

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


management.onDisabled() - Mozilla

management.onDisabled()
=======================

Fired when an add-on is disabled.

This API requires the "management" API permission.

Syntax
------

```js
browser.management.onDisabled.addListener(listener)
browser.management.onDisabled.removeListener(listener)
browser.management.onDisabled.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)`

Checks whether a `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:

`info`

`ExtensionInfo`: info about the add-on that was disabled.

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

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

Examples
--------

Log the names of add-ons when they are disabled:

```js
browser.management.onDisabled.addListener((info) => {
  console.log(`${info.name} was disabled`);
});
```

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


management.setEnabled() - Mozilla

management.setEnabled()
=======================

Enables or disables the given add-on.

This function must usually be called in the context of a user action, such as the click handler for a button. The browser may also ask the user to confirm the change.

This API requires the "management" API permission.

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

The function allows enabling/disabling of theme addons, but will return an error if used to enable or disable other types of web extension.

Syntax
------

```js
let settingEnabled = browser.management.setEnabled(
  id,              // string
  enabled         // boolean
)
```

### Parameters

`id`

`string`. ID of the add-on to enable/disable.

`enabled`

`boolean`. Whether to enable or disable the add-on.

### Return value

A `Promise` that will be fulfilled with no arguments when the add-on has been disabled or enabled.

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

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

Examples
--------

Toggle enable/disable for the add-on whose ID is "my-add-on":

```js
let id = "my-add-on";

function toggleEnabled(id) {
  let getting = browser.management.get(id);
  getting.then((info) => {
    browser.management.setEnabled(id, !info.enabled);
  });
}

toggleEnabled(id);
```

### Example extensions

* theme-switcher

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


management.onUninstalled() - Mozilla

management.onUninstalled()
==========================

Fired when an add-on is uninstalled.

This API requires the "management" API permission.

Syntax
------

```js
browser.management.onUninstalled.addListener(listener)
browser.management.onUninstalled.removeListener(listener)
browser.management.onUninstalled.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)`

Checks whether a `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:

`info`

`ExtensionInfo`: info about the add-on that was uninstalled.

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

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

Examples
--------

Log the names of add-ons when they are uninstalled:

```js
browser.management.onUninstalled.addListener((info) => {
  console.log(`${info.name} was uninstalled`);
});
```

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


management.getPermissionWarningsById() - Mozilla

management.getPermissionWarningsById()
======================================

When the user installs or upgrades an add-on, the browser may warn the user about any particularly powerful permissions that the add-on has requested. Not all permissions result in warnings, and this behavior is not standardized across browsers.

Given the ID of an add-on, this function returns the permission warnings for it as an array of strings.

This API requires the "management" API permission.

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

Syntax
------

```js
let gettingWarnings = browser.management.getPermissionWarningsById(
  id                  // string
)
```

### Parameters

`id`

`string`. ID of the add-on whose permission warnings you want to retrieve.

### Return value

A `Promise` that will be fulfilled with an array of strings, each of which contains the text of a permission warning.

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

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

Examples
--------

Log the permission warnings for the add-on whose ID is "my-add-on":

```js
let id = "my-add-on";

function gotWarnings(warnings) {
  for (const warning of warnings) {
    console.log(warning);
  }
}

browser.management.getPermissionWarningsById(id).then(gotWarnings);
```

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


management.install() - Mozilla

management.install()
====================

Installs and enables a theme extension from the given URL.

This API requires the "management" API permission and will only work with signed themes.

This is an asynchronous function that returns a Promise.

Syntax
------

```js
browser.management.install(options)
```

### Parameters

options

An object that includes the URL of the XPI file of the theme at addons.mozilla.org and an optional a hash of the XPI file, using sha256 or stronger.

### Return value

A Promise that will be fulfilled with an object, containing the `ExtensionID` defined for the theme in manifest.json.

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

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

Examples
--------

Cycle through a list of themes:

```js
"use strict";

const themes = [
  "https://addons.mozilla.org/firefox/downloads/file/1063216/insightscare-1.0-fx.xpi",
  "https://addons.mozilla.org/firefox/downloads/file/1063419/orange\_roses-1.0-fx.xpi",
  "https://addons.mozilla.org/firefox/downloads/file/1062647/sticktoyourguns-2.0-fx.xpi",
  "https://addons.mozilla.org/firefox/downloads/file/0/bad\_url.xpi",
];

let current;

async function install(url) {
  try {
    current = url;
    const { id } = await browser.management.install({ url });
    console.log(`Theme installed: ${id}`);
  } catch (e) {
    console.error(`Installation failed: ${e}`);
  }
}

browser.browserAction.onClicked.addListener(() => {
  const id = themes.indexOf(current);
  install(themes[(id + 1) % themes.length]);
});

for (const url of themes) {
  browser.menus.create({
    title: url,
    onclick: () => install(url),
    contexts: ["browser\_action"],
  });
}
```


management.uninstall() - Mozilla

management.uninstall()
======================

Uninstalls an add-on, given its ID.

This API requires the "management" API permission.

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

Syntax
------

```js
let uninstalling = browser.management.uninstall(
  id,                  // string
  options              // object
)
```

### Parameters

`id`

`string`. ID of the add-on to uninstall.

`options` Optional

`object`. Object which may contain a single property, `showConfirmDialog`. If `showConfirmDialog` is `true`, the browser will show a dialog asking the user to confirm that the add-on should be uninstalled.

* If `id` is the calling add-on's ID, `showConfirmDialog` defaults to `false`.
* If `id` is a the ID of a different add-on, the `showConfirmDialog` option is ignored and the confirmation dialog is always shown.
### Return value

A `Promise` that will be rejected with an error message if the user canceled uninstall.

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

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

Examples
--------

Uninstall the add-on whose ID is "my-addon-id", asking the user to confirm. In the callback, check whether the user canceled uninstallation.

Note that we haven't passed a fulfillment handler because if uninstallation succeeds, the add-on is no longer around to handle it.

```js
let id = "my-addon-id";

function onCanceled(error) {
  console.log(`Uninstall canceled: ${error}`);
}

let uninstalling = browser.management.uninstall(id);
uninstalling.then(null, onCanceled);
```

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


management.getSelf() - Mozilla

management.getSelf()
====================

Retrieves an `ExtensionInfo` object containing information about the calling add-on.

This API *does not* require the "management" API permission.

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

Syntax
------

```js
let gettingSelf = browser.management.getSelf()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an `ExtensionInfo` object, containing information about the add-on.

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

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

Examples
--------

Log the add-on's name:

```js
function gotSelf(info) {
  console.log(`Add-on name: ${info.name}`);
}

const gettingSelf = browser.management.getSelf();
gettingSelf.then(gotSelf);
```

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


management.getPermissionWarningsByManifest() - Mozilla

management.getPermissionWarningsByManifest()
============================================

When the user installs or upgrades an add-on, the browser may warn the user about any particularly powerful permissions that the add-on has requested. Not all permissions result in warnings, and this behavior is not standardized across browsers.

Given the text of a manifest.json file, this function returns the permission warnings that would be given for the resulting add-on, as an array of strings.

This API *does not* require the "management" API permission.

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

Syntax
------

```js
let gettingWarnings = browser.management.getPermissionWarningsByManifest(
  manifestString      // string
)
```

### Parameters

`manifestString`

`string`. String containing the manifest file. This must be a valid manifest: for example, it must contain all the mandatory manifest keys.

### Return value

A `Promise` that will be fulfilled with an array of strings, each of which contains the text of a permission warning.

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

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

Examples
--------

Log the permission warnings for the given manifest file:

```js
let manifest = {
  manifest\_version: 2,
  name: "test",
  version: "1.0",
  permissions: ["management", "<all\_urls>"],
};

let manifestString = JSON.stringify(manifest);

function gotWarnings(warnings) {
  console.log(warnings);
}

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

let gettingWarnings =
  browser.management.getPermissionWarningsByManifest(manifestString);
gettingWarnings.then(gotWarnings, gotError);
```

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


ExtensionInfo - Mozilla

ExtensionInfo
=============

An `ExtensionInfo` object contains information about an add-on.

Type
----

It is an object with the following properties:

`description`

`string`. The add-on's description, taken from the manifest.json description key.

`disabledReason`

`string`. If the add-on is disabled, the reason it was disabled. One of "unknown" or "permissions\_increase".

`enabled`

`boolean`. Whether or not the add-on is currently enabled.

`homepageUrl`

`string`. The add-on's homepage URL, taken from the manifest.json homepage\_url key.

`hostPermissions`

`array` of `string`. The add-on's host permissions.

`icons`

`array` of `object`. Information about the add-on's icons. An array of objects, one for each icon. Each object contains two properties:

* `size`: an integer representing the icon's width and height in pixels.
* `url`: a string containing a relative URL to the icon, starting at the add-on's root.

`id`

`string`. The add-on's ID.

`installType`

`string`. String describing how the add-on was installed. One of the following:

* "admin": the add-on was installed because of an administrative policy.
* "development": the add-on was installed unpacked from disk.
* "normal": the add-on was installed normally from an install package.
* "sideload": the add-on was installed by some other software on the user's computer.
* "other": the add-on was installed in some other way.

`mayDisable`

`boolean`. Whether this add-on can be disabled or uninstalled by the user.

`name`

`string`. The add-on's name, taken from the manifest.json name key.

`offlineEnabled`

`boolean`. Whether the add-on claims to support offline.

`optionsUrl`

`string`. URL for the item's options page, if it has one. This is a relative URL, starting at the add-on's root.

`permissions`

`array` of `string`. The add-on's API permissions.

`shortName`

`string`. A short version of the add-on's name, taken from the manifest.json short\_name key.

`type`

`string`. String describing the type of add-on. This is used to distinguish extensions from apps and themes. It may take any of the following values:

* "extension": most common type of add-on.
* "hosted\_app"
* "packaged\_app"
* "legacy\_packaged\_app"
* "theme"

`updateUrl`

`string`. URL for updates to this add-on, taken from the manifest.json browser\_specific\_settings key.

`version`

`string`. Version of this add-on, taken from the manifest.json version key.

`versionName`

`string`. Descriptive name for this add-on's version, taken from the manifest.json version\_name key.

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


management.uninstallSelf() - Mozilla

management.uninstallSelf()
==========================

Uninstalls the calling add-on.

This API *does not* require the "management" API permission.

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

Syntax
------

```js
let uninstallingSelf = browser.management.uninstallSelf(
  options              // object
)
```

### Parameters

`options` Optional

`object`. Object which may two properties, both optional:

`showConfirmDialog` Optional

Boolean. If `showConfirmDialog` is `true`, the browser will show a dialog asking the user to confirm that the add-on should be uninstalled. Defaults to `false`.

`dialogMessage` Optional

String. An extra message that will be displayed in the confirmation dialog.

### Return value

A `Promise` that will be rejected with an error message if the user canceled uninstall.

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

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

Examples
--------

Uninstall the add-on, asking the user to confirm. In the callback, check whether the user canceled uninstallation.

Note that we haven't passed a fulfillment handler because if uninstallation succeeds, the add-on is no longer around to handle it.

```js
function onCanceled(error) {
  console.log(`Canceled: ${error}`);
}

let uninstalling = browser.management.uninstallSelf({
  showConfirmDialog: true,
});

uninstalling.then(null, onCanceled);
```

The same, but also adding a custom message to the dialog:

```js
function onCanceled(error) {
  console.log(`Canceled: ${error}`);
}

let uninstalling = browser.management.uninstallSelf({
  showConfirmDialog: true,
  dialogMessage: "Testing self-uninstall",
});

uninstalling.then(null, onCanceled);
```

**Note:**

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


management.onInstalled() - Mozilla

management.onInstalled()
========================

Fired when an add-on is installed.

This API requires the "management" API permission.

Syntax
------

```js
browser.management.onInstalled.addListener(listener)
browser.management.onInstalled.removeListener(listener)
browser.management.onInstalled.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)`

Checks whether a `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:

`info`

`ExtensionInfo`: info about the add-on that was installed.

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

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

Examples
--------

Log the names of add-ons when they are installed:

```js
browser.management.onInstalled.addListener((info) => {
  console.log(`${info.name} was installed`);
});
```

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


proxy.settings - Mozilla

proxy.settings
==============

A `BrowserSetting` object that can be used to change the browser's proxy settings.

**Note:** Changing proxy settings requires private browsing window access because proxy settings affect private and non-private windows. Whether an extension can access private browsing windows is under user control. For details, see Extensions in Private Browsing. Your extension can check whether it can access private browsing windows using `extension.isAllowedIncognitoAccess`. If your extension does not have private window permission, calls to `proxy.settings.set()` throw an exception.

The underlying value is an object with the properties listed below.

When setting this object, all properties are optional. Note that any properties that are omitted will be reset to their default value.

`autoConfigUrl` Optional

`string`. A URL to use to configure the proxy.

`autoLogin` Optional

`boolean`. Do not prompt for authentication if the password is saved. Defaults to `false`.

`ftp` Optional
Deprecated

`string`. The address of the FTP proxy. Can include a port.

`http` Optional

`string`. The address of the HTTP proxy. Can include a port.

`httpProxyAll` Optional

`boolean`. Use the HTTP proxy server for all protocols. Defaults to `false`.

`passthrough` Optional

`string`. A comma-separated list of hosts which should not be proxied. Defaults to "localhost, 127.0.0.1".

`proxyDNS` Optional

`boolean`. Proxy DNS when using SOCKS5. Defaults to `false`.

`proxyType` Optional

`string`. The type of proxy to use. This may take any one of the following values: "none", "autoDetect", "system", "manual", "autoConfig". Defaults to "system".

`socks` Optional

`string`. The address of the SOCKS proxy. Can include a port.

`socksVersion` Optional

`integer`. The version of the SOCKS proxy. May be 4 or 5. Defaults to 5.

`ssl` Optional

`string`. The address of the TLS/SSL proxy. Can include a port.

Examples
--------

```js
let proxySettings = {
  proxyType: "manual",
  http: "http://proxy.org:8080",
  socksVersion: 4,
  passthrough: ".example.org",
};

browser.proxy.settings.set({ value: proxySettings });
```

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

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


proxy.onError - Mozilla

proxy.onError
=============

Fired when there is an error evaluating the PAC file or the `onRequest` listener.

The error can be triggered by throwing or returning an invalid value in the proxy.onRequest event handler.

Syntax
------

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

`newState`

`Object`. An Error object representing the error.

### Example extensions

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

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