notifications.NotificationOptions - Mozilla

notifications.NotificationOptions
=================================

This type contains all the data needed to:

* create a notification using `notifications.create()`,
* update an existing notification using `notifications.update()`.
Type
----

Values of this type are objects. They contain the properties listed below.

The first three properties - `type`, `title`, `message` - are mandatory in `notifications.create()`, but optional in `notifications.update()`. Firefox currently: only supports the `type`, `title`, `message`, and `iconUrl` properties; and the only supported value for `type` is `'basic'`.

`type`

`notifications.TemplateType`. The type of notification you want. Depending on your choice here, certain other properties are either mandatory or are not permitted.

`message`

`string`. The notification's main content.

`title`

`string`. The notification's title.

`iconUrl` Optional

`string`. A URL pointing to an icon to display in the notification. The URL can be: a data URL, a blob URL, a http or https URL, or the relative URL of a file within the extension. When using an SVG image, ensure that the image includes height and width attributes, for example, `<svg width="96" height="96"…`. Otherwise, the image may not display.

`contextMessage` Optional

`string`. Supplementary content to display.

`priority` Optional

`number`. The notification's priority: may be 0, 1, or 2. Defaults to 0 if omitted.

`eventTime` Optional

`number`. A timestamp for the notification in milliseconds since the epoch.

`buttons` Optional

`array` of `button`. An array of up to 2 buttons to include in the notification. You can listen for button clicks using `notifications.onButtonClicked`. Each button is specified as an object with the following properties:

`title`

`string`. Title for the button.

`iconUrl` Optional

`string`. URL pointing to an icon for the button.

`imageUrl`

`string`. A URL pointing to an image to use in the notification. The URL can be: a data URL, a blob URL, or the relative URL of a file within the extension. When using an SVG image, ensure that the image includes height and width attributes, for example, `<svg width="96" height="96"…`. Otherwise, the image may not display.

*This property is only permitted if `type` is `"image"`. In this case, it is mandatory if the `NotificationOptions` is used in `notifications.create()`, and optional if it is used in `notifications.update()`.*

`items`

`array` of `item`. An array of items to include in the notification. Depending on the settings for the operating system's notification mechanism, some of the items you provide might not be displayed. Each item is specified as an object with the following properties:

`title`

`string`. Title to display in the item.

`message`

`string`. Message to display in the item.

*This property is only permitted if `type` is `"list"`. In this case, it is mandatory if the `NotificationOptions` is used in `notifications.create()`, and optional if it is used in `notifications.update()`.*

`progress`

`integer`. An integer between 0 and 100, used to represent the current progress in a progress indicator.

*This property is only permitted if `type` is `"progress"`. In this case, it is mandatory if the `NotificationOptions` is used in `notifications.create()`, and optional if it is used in `notifications.update()`.*

Note that `appIconMaskUrl` and `isClickable` are not supported.

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

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

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


notifications.onClicked - Mozilla

notifications.onClicked
=======================

Fired when the user clicks a notification, but not on any of the notification's buttons (for that, see `notifications.onButtonClicked`).

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`notificationId`

`string`. ID of the notification that the user clicked.

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

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

Examples
--------

In this simple example we add a listener to the `notifications.onClicked` event to listen for system notifications being clicked. When this occurs, we log an appropriate message to the console.

```js
browser.notifications.onClicked.addListener((notificationId) => {
  console.log(`Notification ${notificationId} was clicked by the user`);
});
```

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


notifications.TemplateType - Mozilla

notifications.TemplateType
==========================

This is a string, and represents the type of notification to create. There are four types of notification: "basic", "image", "list", "progress".

This is passed into `notifications.create()` and `notifications.update()` as the `type` property of `NotificationOptions`.

Type
----

Values of this type are strings. Possible values are:

* `"basic"`: the notification includes:
    + a title (`NotificationOptions.title`)
    + a message (`NotificationOptions.message`)
    + an icon (`NotificationOptions.iconUrl`) Optional
    + an extra message (`NotificationOptions.contextMessage`) Optional
    + up to two buttons (`NotificationOptions.buttons`) Optional
* `"image"`: everything in `"basic"` and also:
    + an image (`NotificationOptions.imageUrl`)
* `"list"`: everything in `"basic"` and also:
    + a list of items (`NotificationOptions.items`)
* `"progress"`: everything in `"basic"` and also:
    + a progress indicator (`NotificationOptions.progress`)

Currently Firefox only supports "basic" here.

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


notifications.getAll() - Mozilla

notifications.getAll()
======================

Gets all currently active notifications created by the extension.

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

Syntax
------

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

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an object. Each currently active notification is a property of this object: the name of the property is the ID of the notification, and the value of the property is a `notifications.NotificationOptions` object describing that notification.

Note that you can define an ID for a notification explicitly by passing it into `notifications.create()`. If you don't do this, the browser will generate one. Explicitly-specified IDs are strings, but generated IDs are numbers.

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

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

Examples
--------

This example shows a notification when the user clicks a browser action, unless the notification was already being shown, in which case it clears the notification. It uses getAll() to figure out whether the notification is being shown:

```js
const myNotification = "my-notification";

function toggleAlarm(all) {
  const ids = Object.keys(all);
  if (ids.includes(myNotification)) {
    browser.notifications.clear(myNotification);
  } else {
    console.log("showing");

    browser.notifications.create(myNotification, {
      type: "basic",
      title: "Am imposing title",
      message: "Some interesting content",
    });
  }
}

function handleClick() {
  console.log("clicked");
  browser.notifications.getAll().then(toggleAlarm);
}

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

This example logs the title of all active notifications:

```js
function logNotifications(all) {
  for (const id in all) {
    console.log(`Title: ${all[id].title}`);
  }
}

browser.notifications.getAll().then(logNotifications);
```

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


notifications.onShown - Mozilla

notifications.onShown
=====================

Fired immediately after a notification has been shown.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`notificationId`

`string`. ID of the notification that has been shown.

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

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

Examples
--------

Add a listener to the `notifications.onShown` event and log its details:

```js
function logShown(itemId) {
  console.log(`shown: ${itemId}`);
  browser.notifications.getAll().then((all) => {
    console.log(all[itemId]);
  });
}

browser.notifications.onShown.addListener(logShown);
```

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


devtools.panels - Mozilla

devtools.panels
===============

**Note:** Although the APIs are based on the Chrome devtools APIs, there are still many features that are not yet implemented in Firefox, and therefore are not documented here. To see which features are currently missing please see Limitations of the devtools APIs.

The `devtools.panels` API lets a devtools extension define its user interface inside the devtools window.

The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".

With the `devtools.panels` API you can create new panels in the devtools window.

Like all the `devtools` APIs, this API is only available to code running in the document defined in the devtools\_page manifest.json key, or in other devtools documents created by the extension (such as the panel's own document). See Extending the developer tools for more.

Types
-----

`devtools.panels.ElementsPanel`

Represents the HTML/CSS inspector in the browser's devtools.

`devtools.panels.ExtensionPanel`

Represents a devtools panel created by the extension.

`devtools.panels.ExtensionSidebarPane`

Represents a pane that an extension has added to the HTML/CSS inspector in the browser's devtools.

Properties
----------

`devtools.panels.elements`

A reference to an `ElementsPanel` object.

`devtools.panels.themeName`

The name of the current devtools theme.

Functions
---------

`devtools.panels.create()`

Creates a new devtools panel.

Events
------

`devtools.panels.onThemeChanged`

Fired when the devtools theme changes.

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

* devtools-panels
Browser compatibility
---------------------

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

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

* devtools-panels

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


devtools.inspectedWindow - Mozilla

devtools.inspectedWindow
========================

**Note:** This page describes the WebExtensions devtools APIs as they exist in Firefox 54. Although the APIs are based on the Chrome devtools APIs, there are still many features that are not yet implemented in Firefox, and therefore are not documented here. To see which features are currently missing please see Limitations of the devtools APIs.

The `devtools.inspectedWindow` API lets a devtools extension interact with the window that the developer tools are attached to.

Like all the `devtools` APIs, this API is only available to code running in the document defined in the devtools\_page manifest.json key, or in other devtools documents created by the extension (such as the document hosted by a panel the extension created). See Extending the developer tools for more.

Properties
----------

`devtools.inspectedWindow.tabId`

The ID of the window that the developer tools are attached to.

Functions
---------

`devtools.inspectedWindow.eval()`

Evaluate some JavaScript in the target window.

`devtools.inspectedWindow.reload()`

Reload the target window's document.

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

* devtools-panels
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.devtools.inspectedWindow` API.


devtools.network - Mozilla

devtools.network
================

The `devtools.network` API lets a devtools extension get information about network requests associated with the window that the devtools are attached to (the inspected window).

Like all the `devtools` APIs, this API is only available to code running in the document defined in the devtools\_page manifest.json key, or in other devtools documents created by the extension (such as the panel's own document). See Extending the developer tools for more.

Functions
---------

`devtools.network.getHAR()`

Get a HAR log for the page loaded in the current tab.

Events
------

`devtools.network.onNavigated`

Fired when the user navigates the inspected window to a new page.

`devtools.network.onRequestFinished`

Fired when the network request has finished and its details are available to the extension.

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.devtools.network` API.


devtools.network.onNavigated - Mozilla

devtools.network.onNavigated
============================

Fired when the user navigates the inspected window to a new page.

Syntax
------

```js
browser.devtools.network.onNavigated.addListener(listener)
browser.devtools.network.onNavigated.removeListener(listener)
browser.devtools.network.onNavigated.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:

`url`

`string`. The new URL for the window.

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

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

Examples
--------

```js
function handleNavigated(url) {
  console.log(url);
}

browser.devtools.network.onNavigated.addListener(handleNavigated);
```

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


devtools.network.getHAR() - Mozilla

devtools.network.getHAR()
=========================

Get a HAR log for the page loaded in the current tab.

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

Syntax
------

```js
let getting = browser.devtools.network.getHAR()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an object containing the HAR log for the current tab. For details of what the log object contains, refer to the HAR specification.

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

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

Examples
--------

Log the URLs of requests contained in the HAR log:

```js
async function logRequests() {
  let harLog = await browser.devtools.network.getHAR();
  console.log(`HAR version: ${harLog.version}`);
  for (const entry of harLog.entries) {
    console.log(entry.request.url);
  }
}

logRequestsButton.addEventListener("click", logRequests);
```

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


devtools.network.onRequestFinished - Mozilla

devtools.network.onRequestFinished
==================================

Fired when a network request has finished and its details are available to the extension.

The request is given as a HAR entry object, which is also given an asynchronous `getContent()` method that gets the response body content.

Note that although your extension can add a listener at any time, it will only start firing after the user has activated the browser's network panel at least once.

Syntax
------

```js
browser.devtools.network.onRequestFinished.addListener(listener)
browser.devtools.network.onRequestFinished.removeListener(listener)
browser.devtools.network.onRequestFinished.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:

`request`

`object`. An object representing the request. This object is a single HAR entry object. It also defines an asynchronous `getContent()` method, which returns a `Promise` that resolves with an array of two elements. The first element is the HTTP response body as a string, while the second element is the MIME type of the HTTP response also as a string.

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

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

Examples
--------

Add a listener that logs the server IP address and response body for every network request.

```js
function handleRequestFinished(request) {
  console.log("Server IP: ", request.serverIPAddress);
  request.getContent().then(([content, mimeType]) => {
    console.log("Content: ", content);
    console.log("MIME type: ", mimeType);
  });
}

browser.devtools.network.onRequestFinished.addListener(handleRequestFinished);
```

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


devtools.inspectedWindow.tabId - Mozilla

devtools.inspectedWindow.tabId
==============================

The ID of the `tab` that this instance of the devtools is attached to, represented as a number.

This can be sent to the extension's background page, so that background page can use the `tabs` API to interact with the tab:

```js
// devtools-panel.js

const scriptToAttach = "document.body.innerHTML = 'Hi from the devtools';";

attachContentScriptButton.addEventListener("click", () => {
  browser.runtime.sendMessage({
    tabId: browser.devtools.inspectedWindow.tabId,
    script: scriptToAttach,
  });
});
```

```js
// background.js

function handleMessage(request, sender, sendResponse) {
  browser.tabs.executeScript(request.tabId, {
    code: request.script,
  });
}

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

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


devtools.inspectedWindow.eval() - Mozilla

devtools.inspectedWindow.eval()
===============================

Executes JavaScript in the window that the devtools are attached to.

This is somewhat like using `tabs.executeScript()` to attach a content script, but with two main differences:

First, the JavaScript can use a set of special commands that browsers typically provide in their devtools console implementation: for example, using "$0" to refer to the element currently selected in the Inspector.

Second, the JavaScript you execute can see any changes made to the page by scripts that the page loaded. This is in contrast to content scripts, which see the page as it would exist if no page scripts were loaded. However, note that the isolation provided by content scripts is a deliberate security feature, intended to make it harder for malicious or uncooperative web pages to confuse or subvert WebExtensions APIs by redefining DOM functions and properties. This means you need to be very careful if you waive this protection by using `eval()`, and should use content scripts unless you need to use `eval()`.

The script is evaluated by default in the main frame of the page. The script must evaluate to a value that can be represented as JSON (meaning that, for example, it may not evaluate to a function or an object that contains any functions). By default, the script does not see any content scripts attached to the page.

You can't call `eval()` on privileged browser windows such as "about:addons".

You can optionally provide an `options` parameter, which includes options to evaluate the script in a different frame or in the context of attached content scripts. Note that Firefox does not yet support the `options` parameter.

The `eval()` function returns a `Promise` that resolves to the evaluated result of the script or to an error.

Helpers
-------

The script gets access to a number of objects that help the injected script interact with the developer tools. The following helpers are currently supported:

`$0`

Contains a reference to the element that's currently selected in the devtools Inspector.

`inspect()`

Given an object, if it is an DOM element in the page, selects it in the devtools Inspector, otherwise it creates an object preview in the webconsole.

See some examples.

Syntax
------

```js
let evaluating = browser.devtools.inspectedWindow.eval(
  expression,       // string
  options           // object
)
```

### Parameters

`expression`

`string`. The JavaScript expression to evaluate. The string must evaluate to an object that can be represented as JSON, or an exception will be thrown. For example, `expression` must not evaluate to a function.

`options` Optional

`object`. Options for the function (Note that Firefox does not yet support this options), as follows:

`frameURL` Optional

`string`. The URL of the frame in which to evaluate the expression. If this is omitted, the expression is evaluated in the main frame of the window.

`useContentScriptContext` Optional

`boolean`. If `true`, evaluate the expression in the context of any content scripts that this extension has attached to the page. If you set this option, then you must have actually attached some content scripts to the page, or a Devtools error will be thrown.

`contextSecurityOrigin` Optional

`string`. Evaluate the expression in the context of a content script attached by a different extension, whose origin matches the value given here. This overrides `useContentScriptContext`.

### Return value

A `Promise` that will be fulfilled with an `array` containing two elements.

If no error occurred, element 0 will contain the result of evaluating the expression, and element 1 will be `undefined`.

If an error occurred, element 0 will be `undefined`, and element 1 will contain an object giving details about the error. Two different sorts of errors are distinguished:

* errors encountered evaluating the JavaScript (for example, syntax errors in the expression). In this case, element 1 will contain:
    + a boolean property `isException`, set to `true`
    + a string property `value`, giving more details.
* other errors (for example, an expression that evaluates to an object that can't be represented as JSON). In this case, element 1 will contain:
    + a boolean property `isError`, set to `true`
    + a string property `code` containing an error code.
Browser compatibility
---------------------

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

Examples
--------

This tests whether jQuery is defined in the inspected window, and logs the result. Note that this wouldn't work in a content script, because even if jQuery were defined, the content script would not see it.

```js
function handleError(error) {
  if (error.isError) {
    console.log(`Devtools error: ${error.code}`);
  } else {
    console.log(`JavaScript error: ${error.value}`);
  }
}

function handleResult(result) {
  console.log(result);
  if (result[0] !== undefined) {
    console.log(`jQuery: ${result[0]}`);
  } else if (result[1]) {
    handleError(result[1]);
  }
}

const checkjQuery = "typeof jQuery !== 'undefined'";

evalButton.addEventListener("click", () => {
  browser.devtools.inspectedWindow.eval(checkjQuery).then(handleResult);
});
```

### Helper examples

This uses the `$0` helper to set the background color of the element that's currently selected in the Inspector:

```js
const evalButton = document.querySelector("#reddinate");
const evalString = "$0.style.backgroundColor = 'red'";

function handleError(error) {
  if (error.isError) {
    console.log(`Devtools error: ${error.code}`);
  } else {
    console.log(`JavaScript error: ${error.value}`);
  }
}

function handleResult(result) {
  if (result[1]) {
    handleError(result[1]);
  }
}

evalButton.addEventListener("click", () => {
  browser.devtools.inspectedWindow.eval(evalString).then(handleResult);
});
```

This uses the `inspect()` helper to select the first <h1> element in the page:

```js
const inspectButton = document.querySelector("#inspect");
const inspectString = "inspect(document.querySelector('h1'))";

function handleError(error) {
  if (error.isError) {
    console.log(`Devtools error: ${error.code}`);
  } else {
    console.log(`JavaScript error: ${error.value}`);
  }
}

function handleResult(result) {
  if (result[1]) {
    handleError(result[1]);
  }
}

inspectButton.addEventListener("click", () => {
  browser.devtools.inspectedWindow.eval(inspectString).then(handleResult);
});
```

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


devtools.inspectedWindow.reload() - Mozilla

devtools.inspectedWindow.reload()
=================================

Reloads the window that the devtools are attached to.

Syntax
------

```js
browser.devtools.inspectedWindow.reload(
  reloadOptions       // object
)
```

### Parameters

`reloadOptions` Optional

`object`. Options for the function, as follows:

`ignoreCache` Optional

`boolean`. If true, this makes the reload ignore the browser cache (as if the user had pressed Shift+Ctrl+R).

`userAgent` Optional

`string`. Set a custom user agent for the page. The string supplied here will be sent in the browser's User-Agent header, and will be returned by calls to `navigator.userAgent` made by scripts running in the page.

`injectedScript` Optional

`string`. Inject the given JavaScript expression into all frames in the page, before any other scripts.

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

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

Examples
--------

Reload the inspected window, setting the user agent and injecting a script:

```js
const reloadButton = document.querySelector("#reload-button");

reloadButton.addEventListener("click", () => {
  browser.devtools.inspectedWindow.reload({
    injectedScript: "alert(navigator.userAgent);",
    userAgent: "Not a real UA",
  });
});
```

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


devtools.panels.ElementsPanel - Mozilla

devtools.panels.ElementsPanel
=============================

An `ElementsPanel` represents the HTML/CSS inspector in the browser's devtools. This is called the Page Inspector in Firefox and the Elements panel in Chrome.

Functions
---------

`devtools.panels.ElementsPanel.createSidebarPane()`

Creates a pane in the inspector's sidebar.

Events
------

`devtools.panels.ElementsPanel.onSelectionChanged`

Fired when the user selects a different element in the page, for example using the "Inspect element" context menu item.

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


devtools.panels.elements - Mozilla

devtools.panels.elements
========================

An `ElementsPanel` object, which represents the browser's HTML/CSS inspector.

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.devtools.panels` API.


devtools.panels.onThemeChanged - Mozilla

devtools.panels.onThemeChanged
==============================

Fired when the devtools theme changes.

Syntax
------

```js
browser.devtools.panels.onThemeChanged.addListener(listener)
browser.devtools.panels.onThemeChanged.removeListener(listener)
browser.devtools.panels.onThemeChanged.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:

`themeName`

`string`. Name of the new theme: this will be one of the permitted values for `devtools.panels.themeName`.

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

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

Examples
--------

```js
browser.devtools.panels.onThemeChanged.addListener((newThemeName) => {
  console.log(`New theme: ${newThemeName}`);
});
```

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


devtools.panels.ExtensionSidebarPane - Mozilla

devtools.panels.ExtensionSidebarPane
====================================

The `ExtensionSidebarPane` object represents a pane that an extension has added to the sidebar in the browser's HTML/CSS inspector.

![new pane titled "My pane" that displays a JSON object](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/panels/ExtensionSidebarPane/inspector-sidebar.png)

To create an `ExtensionSidebarPane`, call the `browser.devtools.panels.elements.createSidebarPane()` function.

Functions
---------

`devtools.panels.ExtensionSidebarPane.setExpression()`

Evaluate a JavaScript expression in the web page that the inspector is inspecting. The result is displayed in the sidebar pane.

`devtools.panels.ExtensionSidebarPane.setObject()`

Sets a JSON object that will be displayed in the sidebar pane.

`devtools.panels.ExtensionSidebarPane.setPage()`

Loads the page pointed to by the supplied URL.

Events
------

`devtools.panels.ExtensionSidebarPane.onShown`

Fired when the sidebar pane is shown.

`devtools.panels.ExtensionSidebarPane.onHidden`

Fired when the sidebar pane is hidden.

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.devtools.panels` API.


devtools.panels.themeName - Mozilla

devtools.panels.themeName
=========================

The name of the currently selected devtools theme.

This is a string whose possible values are:

* "light"
* "dark"
* "firebug"
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.devtools.panels` API.


devtools.panels.ExtensionPanel - Mozilla

devtools.panels.ExtensionPanel
==============================

An `ExtensionPanel` represents a panel added to the devtools. It's the resolution of the `Promise` returned by `browser.devtools.panels.create()`.

Type
----

Values of this type are objects. The define two events, `onShown` and `onHidden`.

* `onShown` is emitted when the panel is shown in the devtools (for example, because the user clicked on the panel's tab in the devtools window).
* `onHidden` is emitted when the panel is hidden (for example, because the user switched to a different tab in the devtools window).
Browser compatibility
---------------------

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

Examples
--------

This code creates a new panel, then adds handlers for its `onShown` and `onHidden` events.

```js
function handleShown(e) {
  console.log(e);
  console.log("panel is being shown");
}

function handleHidden(e) {
  console.log(e);
  console.log("panel is being hidden");
}

browser.devtools.panels
  .create(
    "My Panel", // title
    "icons/star.png", // icon
    "devtools/panel/panel.html", // content
  )
  .then((newPanel) => {
    newPanel.onShown.addListener(handleShown);
    newPanel.onHidden.addListener(handleHidden);
  });
```

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


devtools.panels.create() - Mozilla

devtools.panels.create()
========================

Adds a new panel to the devtools.

This function takes: a title, a URL to an icon file, and a URL to an HTML file. It creates a new panel in the devtools, whose content is specified by the HTML file. It returns a `Promise` that resolves to an `ExtensionPanel` object representing the new panel.

Syntax
------

```js
let creating = browser.devtools.panels.create(
  title,       // string
  iconPath,    // string
  pagePath     // string
)
```

### Parameters

`title`

`string`. The panel's title. This will appear in the row of tabs along the top of the devtools window, and is the main way the user will be able to identify your panel.

`iconPath`

`string`. Specifies an icon which will be shown next to the title. It's provided as a URL to an image file that's been bundled with your extension. Chromium-based browsers and Safari resolve this URL as absolute, while Firefox resolves this URL as relative to the current extension page (unless expressed as an absolute URL, e.g. "/icons/panel.png").

`pagePath`

string. Specifies an HTML file that defines the content of the panel. It's provided as a URL to an HTML file bundled with your extension. The URL may be resolved as an absolute URL or relative to the current extension page. See the browser compatibility data for more information. The HTML file can include CSS and JavaScript files, just like a normal web page. The JavaScript running in the panel can use the devtools APIs. See Extending the developer tools.

### Return value

A `Promise` that will be fulfilled with an `ExtensionPanel` object representing the new panel.

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

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

Examples
--------

Create a new panel, and add listeners to its onShown and onHidden events:

```js
function handleShown() {
  console.log("panel is being shown");
}

function handleHidden() {
  console.log("panel is being hidden");
}

browser.devtools.panels
  .create(
    "My Panel", // title
    "/icons/star.png", // icon
    "/devtools/panel/panel.html", // content
  )
  .then((newPanel) => {
    newPanel.onShown.addListener(handleShown);
    newPanel.onHidden.addListener(handleHidden);
  });
```

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


devtools.panels.ExtensionSidebarPane.onHidden - Mozilla

devtools.panels.ExtensionSidebarPane.onHidden
=============================================

Called when the sidebar pane becomes hidden, as a result of the user switching away from it.

Syntax
------

```js
browser.devtools.panels.onHidden.addListener(listener)
browser.devtools.panels.onHidden.removeListener(listener)
browser.devtools.panels.onHidden.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

Function called when this event occurs. This function will be passed no arguments.

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

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

Examples
--------

Create a sidebar pane, and log show and hide events.

```js
function onCreated(sidebarPane) {
  sidebarPane.onShown.addListener(() => {
    console.log("Shown");
  });

  sidebarPane.onHidden.addListener(() => {
    console.log("Hidden");
  });
}

browser.devtools.panels.elements.createSidebarPane("My pane").then(onCreated);
```

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


devtools.panels.ElementsPanel.setExpression() - Mozilla

devtools.panels.ElementsPanel.setExpression()
=============================================

Evaluates an expression in the context of the inspected page, and displays the result in the extension sidebar pane.

The expression's execution context is the same as that for `inspectedWindow.eval()`.

JSON objects and DOM nodes are displayed as an expandable tree, as in the JSON viewer in Firefox. You can optionally specify a `rootTitle` string: this will be displayed as the title of the tree's root.

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

Syntax
------

```js
let evaluating = browser.devtools.panels.setExpression(
  expression,       // string
  rootTitle         // string
)
```

### Parameters

`expression`

`string`. The expression to evaluate.

`rootTitle` Optional

string. The title of the root of the tree in which results are displayed.

### Return value

A `Promise` that will be fulfilled with no arguments, once the expression has been evaluated.

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

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

Examples
--------

This code creates a sidebar pane that displays the `tagName` of the currently selected element:

```js
function onCreated(sidebarPane) {
  browser.devtools.panels.elements.onSelectionChanged.addListener(() => {
    const exp = "$0 && $0.tagName";
    const title = "Selected Element tagName";
    sidebarPane.setExpression(exp, title);
  });
}

browser.devtools.panels.elements.createSidebarPane("My pane").then(onCreated);
```

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


devtools.panels.ExtensionSidebarPane.onShown - Mozilla

devtools.panels.ExtensionSidebarPane.onShown
============================================

Fired when the sidebar pane becomes visible as a result of the user switching to it.

Syntax
------

```js
browser.devtools.panels.onShown.addListener(listener)
browser.devtools.panels.onShown.removeListener(listener)
browser.devtools.panels.onShown.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`window`

`object`. The `window` object of the sidebar page, if a page was set with `setPage()`.

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

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

Examples
--------

Create a sidebar pane, and log show and hide events.

```js
function onCreated(sidebarPane) {
  sidebarPane.onShown.addListener(() => {
    console.log("Shown");
  });

  sidebarPane.onHidden.addListener(() => {
    console.log("Hidden");
  });
}

browser.devtools.panels.elements.createSidebarPane("My pane").then(onCreated);
```

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


devtools.panels.ExtensionSidebarPane.setPage() - Mozilla

devtools.panels.ExtensionSidebarPane.setPage()
==============================================

Sets an HTML page to be displayed in the sidebar pane.

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

Syntax
------

```js
browser.devtools.panels.setPage(
  path // string containing relative path to page
)
```

### Parameters

extensionPageURL

`string`. The relative path of an HTML page to display within the sidebar.

### Return value

A `Promise` that will be fulfilled with no arguments, once the URL has been set.

The selected page will not be loaded until the user selects the devtools sidebar.

Examples
--------

Create a new pane, and populate it with an HTML page. You could run this code in a script loaded by your extension's devtools page.

```js
function onCreated(sidebarPane) {
  sidebarPane.setPage("sidebar/sidebar.html");
}
```

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.devtools.panels` API.


devtools.panels.ExtensionSidebarPane.setObject() - Mozilla

devtools.panels.ExtensionSidebarPane.setObject()
================================================

Displays a JSON object in the extension's sidebar pane.

The object is displayed as an expandable tree, as in the JSON viewer in Firefox. You can optionally specify a `rootTitle` string: this will be displayed as the title of the tree's root.

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

Syntax
------

```js
let setting = browser.devtools.panels.setObject(
  jsonObject,       // string, array, or JSON object
  rootTitle         // string
)
```

### Parameters

`jsonObject`

`String` or `Array` or `Object`. The object to display. If this is an object it is JSON-serialized, so properties like functions will be omitted.

`rootTitle` Optional

`String`. The title of the root of the tree in which the object is displayed.

### Return value

A `Promise` that will be fulfilled with no arguments, once the object has been set.

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

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

Examples
--------

Create a new pane, and populate it with a JSON object. You could run this code in a script loaded by your extension's devtools page.

```js
function onCreated(sidebarPane) {
  sidebarPane.setObject({
    someBool: true,
    someString: "hello there",
    someObject: {
      someNumber: 42,
      someOtherString: "this is my pane's content",
    },
  });
}

browser.devtools.panels.elements.createSidebarPane("My pane").then(onCreated);
```

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


onSelectionChanged - Mozilla

onSelectionChanged
==================

Fires when the user selects a different page element for inspection with the browser's developer tools, for example by selecting the "Inspect Element" context menu item in Firefox.

Syntax
------

```js
browser.devtools.panels.elements.onSelectionChanged.addListener(listener)
browser.devtools.panels.elements.onSelectionChanged.removeListener(listener)
browser.devtools.panels.elements.onSelectionChanged.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

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

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

Examples
--------

Listen for selection changed events, and log the text content of the newly selected element:

```js
function handleSelectedElement() {
  browser.devtools.inspectedWindow.eval("$0.textContent").then((result) => {
    console.log(result[0]);
  });
}

browser.devtools.panels.elements.onSelectionChanged.addListener(
  handleSelectedElement,
);
```

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


devtools.panels.ElementsPanel.createSidebarPane() - Mozilla

devtools.panels.ElementsPanel.createSidebarPane()
=================================================

Adds a new pane to the sidebar in the HTML/CSS inspector.

The HTML/CSS inspector, called the Page Inspector in Firefox and the Elements panel in Chrome, displays the page DOM in the main part of its window, and has a sidebar that displays various other aspects of the page HTML/CSS in a tabbed interface. For example, in Firefox, the sidebar can display the CSS rules for the selected element, or its fonts, or its box model.

The `createSidebarPane()` function adds a new pane to the sidebar. For example, the screenshot below shows a new pane titled "My pane", that displays a JSON object:

![Image showing a new pane titled "My pane", that displays a JSON object](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/panels/ElementsPanel/createSidebarPane/inspector-sidebar.png)

This function takes one argument, which is a string representing the pane's title. It returns a `Promise` that resolves to an `ExtensionSidebarPane` object representing the new pane. You can use that object to define the pane's content and behavior.

Syntax
------

```js
let creating = browser.devtools.panels.elements.createSidebarPane(
  title       // string
)
```

### Parameters

`title`

`string`. The pane's title. This will appear in the row of tabs along the top of the sidebar, and is the main way the user will be able to identify your pane.

### Return value

A `Promise` that will be fulfilled with an `ExtensionSidebarPane` object representing the new pane.

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

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

Examples
--------

Create a new pane, and populate it with a JSON object. You could run this code in a script loaded by your extension's devtools page.

```js
function onCreated(sidebarPane) {
  sidebarPane.setObject({
    someBool: true,
    someString: "hello there",
    someObject: {
      someNumber: 42,
      someOtherString: "this is my pane's content",
    },
  });
}

browser.devtools.panels.elements.createSidebarPane("My pane").then(onCreated);
```

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


getLastChecked - Mozilla

getLastChecked
==============

Returns the time since the last request was completed.

Syntax
------

```js
let state = browser.captivePortal.getLastChecked()
```

### Return value

A Promise that is fulfilled with an integer representing time in milliseconds.

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

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


onConnectivityAvailable - Mozilla

onConnectivityAvailable
=======================

Fires when the captive portal service determines that the user can connect to the internet.

Syntax
------

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

`status`

`string` The status of the service, being one of `captive` if there is an unlocked captive portal present or `clear` if no captive portal is detected.

Examples
--------

Handle a change user's ability to connect to the internet:

```js
function handleConnectivity(connectivityInfo) {
  console.log(`The captive portal status: ${connectivityInfo.status}`);
}

browser.captivePortal.onConnectivityAvailable.addListener(handleConnectivity);
```

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

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


captivePortal.canonicalURL - Mozilla

captivePortal.canonicalURL
==========================

Return the canonical URL of the captive-portal detection page. Read-only.

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


getState - Mozilla

getState
========

Returns the portal state as one of `unknown`, `not_captive`, `unlocked_portal`, or `locked_portal`.

Syntax
------

```js
let state = browser.captivePortal.getState()
```

### Return value

A Promise that is fulfilled with a string containing one of `unknown`, `not_captive`, `unlocked_portal`, or `locked_portal`.

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

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


onStateChanged - Mozilla

onStateChanged
==============

Fires when the captive portal state changes.

Syntax
------

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

`details`

`string` The captive portal state, being one of `unknown`, `not_captive`, `unlocked_portal`, or `locked_portal`.

Examples
--------

Handle a change in captive portal status:

```js
function handlePortalStatus(portalstatusInfo) {
  console.log(`The portal status is now: ${portalstatusInfo.details}`);
}

browser.captivePortal.onStateChanged.addListener(handlePortalStatus);
```

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

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


cookies.set() - Mozilla

cookies.set()
=============

The **`set()`** method of the `cookies` API sets a cookie containing the specified cookie data. This method is equivalent to issuing an HTTP `Set-Cookie` header during a request to a given URL.

The call succeeds only if you include the "cookies" API permission in your manifest.json file, as well as host permissions for the given URL specified in its manifest. The given URL also needs the necessary permissions to create a cookie with the given parameters.

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

Syntax
------

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

### Parameters

`details`

An `object` containing the details of the cookie you wish to set. It can have the following properties:

`domain` Optional

A `string` representing the domain of the cookie. If omitted, the cookie becomes a host-only cookie.

`expirationDate` Optional

A `number` that represents the expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie.

`firstPartyDomain` Optional

A `string` representing the first-party domain with which the cookie will be associated. This property must be supplied if the browser has first-party isolation enabled. See First-party isolation.

`httpOnly` Optional

A `boolean` that specifies whether the cookie should be marked as HttpOnly (`true`), or not (false). If omitted, it defaults to false.

`name` Optional

A `string` representing the name of the cookie. If omitted, this is empty by default.

`partitionKey` Optional

An `object` representing the storage partition to set the cookie in. Include this object to set a cookie in partitioned storage. This object contains:

`topLevelSite` Optional

A `string` representing the first-party URL of the top-level site storage partition containing the cookie.

`path` Optional

A `string` representing the path of the cookie. If omitted, this defaults to the path portion of the URL parameter.

`sameSite` Optional

A `cookies.SameSiteStatus` value that indicates the SameSite state of the cookie. If omitted, it defaults to 0, 'no\_restriction'.

`secure` Optional

A `boolean` that specifies whether the cookie should be marked as secure (`true`), or not (false). If omitted, it defaults to false.

`storeId` Optional

A `string` representing the ID of the cookie store in which to set the cookie. If omitted, the cookie is set in the current execution context's cookie store by default.

`url`

A `string` representing the request-URI to associate with the cookie. This value can affect the default domain and path values of the created cookie. If host permissions for this URL are not specified in the manifest file, the method call will fail.

`value` Optional

A `string` representing the value of the cookie. If omitted, this is empty by default.

### Return value

A `Promise` that will be fulfilled with a `cookies.Cookie` object containing details about the cookie that's been set. If the call fails for any reason, 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
--------

This example sets a cookie for the document hosted by the currently active tab:

```js
let getActive = browser.tabs.query({ active: true, currentWindow: true });
getActive.then(setCookie);

function setCookie(tabs) {
  browser.cookies.set({
    url: tabs[0].url,
    name: "favorite-color",
    value: "red",
  });
}
```

### Example extensions

* cookie-bg-picker

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


cookies.getAllCookieStores() - Mozilla

cookies.getAllCookieStores()
============================

The **`getAllCookieStores()`** method of the `cookies` API returns a list of all cookie stores.

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

Syntax
------

```js
let gettingStores = browser.cookies.getAllCookieStores()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an `array` of `cookies.CookieStore` objects representing all the existing cookie stores.

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

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

Examples
--------

In the following snippet, the `getAllCookieStores()` method is used to retrieve all the cookie stores currently available in the browser, and print out each cookie store ID, and the tabs that currently share each cookie store.

```js
function logStores(cookieStores) {
  for (const store of cookieStores) {
    console.log(`Cookie store: ${store.id}\n Tab IDs: ${store.tabIds}`);
  }
}

browser.cookies.getAllCookieStores().then(logStores);
```

Each member of the `cookieStores` array is a `cookies.CookieStore` object.

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


cookies.onChanged - Mozilla

cookies.onChanged
=================

The `onChanged` event of the `cookies` API fires when a cookie that the extension can access is set or removed.

**Note:** When storage partitioning is active, `cookies.Cookie.partitionKey` contains the description of the cookie's storage partition. When modifying cookies, it's important to pass this value to `cookies.set()` or `cookies.remove()` to ensure the extension works with the correct cookie.

Note that updating a cookie's properties is implemented as a two step process:

1. First, the cookie to be updated is first removed entirely, generating a notification with a `cookies.OnChangedCause` of `overwrite`.
2. Next, a new cookie is written with the updated values, generating a second notification with a `cookies.OnChangedCause` of `explicit`.
Syntax
------

```js
browser.cookies.onChanged.addListener(listener)
browser.cookies.onChanged.removeListener(listener)
browser.cookies.onChanged.hasListener(listener)
```

This API is also available as `browser.cookies.onChanged.*`.

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:

`changeInfo`

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

`removed`

A `boolean` that is set to `true` if a cookie was removed, and false if not.

`cookie`

A `cookies.Cookie` object containing information about the cookie that was set or removed.

`cause`

A `cookies.OnChangedCause` value representing the underlying reason behind the cookie's change.

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

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

Examples
--------

This example listens for `onChanged` events and logs details from the `changeInfo` argument:

```js
browser.cookies.onChanged.addListener((changeInfo) => {
  console.log(
    `Cookie changed: \n` +
      ` \* Cookie: ${JSON.stringify(changeInfo.cookie)}\n` +
      ` \* Cause: ${changeInfo.cause}\n` +
      ` \* Removed: ${changeInfo.removed}`,
  );
});
```

### Example extensions

* cookie-bg-picker

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


cookies.remove() - Mozilla

cookies.remove()
================

The **`remove()`** method of the `cookies` API deletes a cookie, given its name and URL.

The call succeeds only if you include the "cookies" API permission in your manifest.json file, as well as host permissions for the given URL specified in its manifest.

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

Syntax
------

```js
let removing = browser.cookies.remove(
  details               // object
)
```

### Parameters

`details`

An `object` containing information to identify the cookie to remove. It contains the following properties:

`firstPartyDomain` Optional

A `string` representing the first-party domain with which the cookie to remove is associated. This property must be supplied if the browser has first-party isolation enabled. See First-party isolation.

`name`

A `string` representing the name of the cookie to remove.

`partitionKey` Optional

An `object` representing the storage partition containing the cookie. Include this object to remove a cookie from partitioned storage. This object contains:

`topLevelSite` Optional

A `string` representing the first-party URL of the top-level site storage partition containing the cookie.

`storeId` Optional

A `string` representing the ID of the cookie store to find the cookie in. If unspecified, the cookie is looked for by default in the current execution context's cookie store.

`url`

A `string` representing the URL associated with the cookie. If the extension does not have host permissions for this URL, the API call will fail.

### Return value

A `Promise` that will be fulfilled with a `cookies.Cookie` object containing details about the cookie that's been removed. If a cookie matching the `details` parameter could not be found, the promise is fulfilled with `null`. If the call fails for any reason, 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
--------

This example tries to remove the cookie named "favorite-color", whose URL matches the URL of the document hosted by the currently active tab:

```js
function onRemoved(cookie) {
  console.log(`Removed: ${cookie}`);
}

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

function removeCookie(tabs) {
  let removing = browser.cookies.remove({
    url: tabs[0].url,
    name: "favorite-color",
  });
  removing.then(onRemoved, onError);
}

let getActive = browser.tabs.query({ active: true, currentWindow: true });
getActive.then(removeCookie);
```

### Example extensions

* cookie-bg-picker

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


cookies.OnChangedCause - Mozilla

cookies.OnChangedCause
======================

The `OnChangedCause` type of the `cookies` API represents the reason a cookie changed.

Type
----

Values of this type are strings. Possible values are:

`evicted`

A cookie has been automatically removed due to garbage collection.

`expired`

A cookie has been automatically removed due to expiry.

`explicit`

A cookie has been inserted or removed via an explicit call to `cookies.remove()`.

`expired_overwrite`

A cookie has been overwritten by a cookie with an already-expired expiration date.

`overwrite`

A call to `cookies.set()` overwrote this cookie with a different one.

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

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

Examples
--------

You can listen to the `cookies.onChanged` event to be notified when cookies change. The listener is passed a `changeInfo` object that contains a `cause` property, whose value is the `OnChangeCaused` string:

```js
browser.cookies.onChanged.addListener((changeInfo) => {
  console.log(
    `Cookie changed: \n` +
      ` \* Cookie: ${JSON.stringify(changeInfo.cookie)}\n` +
      ` \* Cause: ${changeInfo.cause}\n` +
      ` \* Removed: ${changeInfo.removed}`,
  );
});
```

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


cookies.CookieStore - Mozilla

cookies.CookieStore
===================

The `CookieStore` type of the `cookies` API represents a cookie store in the browser.

Windows in different browsing modes may use different cookie stores. For example, a private browsing/incognito mode window uses a separate cookie store from a non-incognito/private window. Also, a window may have several cookie stores when using container tabs in Firefox.

See Work with the Cookies API for more information about cookie stores.

Type
----

Values of this type are objects, which can contain the following properties:

`id`

A `string` representing the unique identifier for the cookie store.

`incognito` Optional

 A boolean value that indicates whether this is an incognito cookie store.
 This property is not supported in Chrome or Safari. However, you can identify incognito cookie stores in Chrome because their `id` is always "1".

`tabIds`

An `array` of `integers`, which identifies all of the browser tabs that share this cookie store.

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

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

Examples
--------

In the following snippet, the `cookies.getAllCookieStores()` method is used to retrieve all the cookie stores currently available in the browser, and print out each cookie store ID, and the tabs that currently share each cookie store.

```js
function logStores(cookieStores) {
  for (const store of cookieStores) {
    console.log(`Cookie store: ${store.id}\n Tab IDs: ${store.tabIds}`);
  }
}

browser.cookies.getAllCookieStores().then(logStores);
```

The following code snippet gets all cookie stores and then logs the total number of stores and how many of those stores are incognito.

```js
browser.cookies.getAllCookieStores().then((stores) => {
  const incognitoStores = stores.map((store) => store.incognito);
  console.log(
    `Of ${stores.length} cookie stores, ${incognitoStores.length} are incognito.`,
  );
});
```

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


cookies.Cookie - Mozilla

cookies.Cookie
==============

The `Cookie` type of the `cookies` API represents information about an HTTP cookie.

Type
----

Values of this type are objects, which can contain the following properties:

`domain`

A `string` representing the domain the cookie belongs to (e.g. "www.google.com", "example.com").

`expirationDate` Optional

A `number` representing the expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies.

`firstPartyDomain`

A `string` representing the first-party domain associated with the cookie. This will be an empty string if the cookie was set while first-party isolation was off. See First-party isolation.

`hostOnly`

A `boolean`, `true` if the cookie is a host-only cookie (i.e. the request's host must exactly match the domain of the cookie), or `false` otherwise.

`httpOnly`

A `boolean`, `true` if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts), or `false` otherwise.

`name`

A `string` representing the name of the cookie.

`partitionKey` Optional

An `object` representing the description of the storage partition containing the cookie. This object is omitted (null) if the cookie is not in partitioned storage. This object contains the following properties:

`topLevelSite`

A `string` representing the first-party URL of the cookie's storage partition, if the cookie is in storage that is partitioned by top-level site.

`path`

A `string` representing the path of the cookie.

`secure`

A `boolean`, `true` if the cookie is marked as secure (i.e. its scope is limited to secure channels, typically HTTPS), or `false` otherwise.

`session`

A `boolean`, `true` if the cookie is a session cookie, or `false` if it is a persistent cookie with an expiration date.

`sameSite`

A `cookies.SameSiteStatus` value that indicates the SameSite state of the cookie.

`storeId`

A `string` representing the ID of the cookie store containing this cookie, as provided by `cookies.getAllCookieStores()`.

`value`

A `string` representing the value of the cookie.

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

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

Examples
--------

Most methods in the cookies API involve a `Cookie` object being used either as an input parameter or as part of the return value. For example, a call to `cookies.getAll()` returns an array of `Cookie` objects.

In the example below we've asked for all cookies, then logged some of the values of each of the resulting `Cookie` objects:

```js
function logCookies(cookies) {
  for (cookie of cookies) {
    console.log(`Domain: ${cookie.domain}`);
    console.log(`Name: ${cookie.name}`);
    console.log(`Value: ${cookie.value}`);
    console.log(`Persistent: ${!cookie.session}`);
  }
}

let gettingAll = browser.cookies.getAll({});
gettingAll.then(logCookies);
```

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


cookies.getAll() - Mozilla

cookies.getAll()
================

The **`getAll()`** method of the `cookies` API retrieves all cookies from a single cookie store that match the given information.

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

Syntax
------

```js
let getting = browser.cookies.getAll(
  details                // object
)
```

### Parameters

`details`

An `object` containing details that can be used to match cookies to be retrieved. Included properties are as follows (see Cookie type for more information on these):

`domain` Optional

A `string` representing a domain that cookies must be associated with (they can be associated either with this exact domain or one of its subdomains).

`firstPartyDomain` Optional

A `string` representing the first-party domain with which the cookie to retrieve is associated.

This property must be supplied if the browser has first-party isolation enabled. You can however pass `null` in this situation. If you do this, then cookies with any value for `firstPartyDomain`, as well as cookies which do not have `firstPartyDomain` set at all, will be included in the results. See First-party isolation.

`name` Optional

A `string` representing a name that the cookies should have.

`partitionKey` Optional

An `object` defining which storage partitions to return cookies from:

* if omitted, returns only cookies from unpartitioned storage.
* if included without `topLevelSite`, returns all cookies from partitioned and unpartitioned storage.
* if included with `topLevelSite` specified, returns cookies from the specified partition storage.

This object contains:

`topLevelSite` Optional

A `string` representing the first-party URL of the top-level site storage partition containing the cookies.

`path` Optional

A `string` representing a path — the cookies' path must be identical to this one.

`secure` Optional

A `boolean` — filters cookies by their `secure` property, allowing you to filter secure cookies vs. non-secure cookies.

`session` Optional

A `boolean` — filters the cookies by their `session` property, allowing you to filter session cookies vs. persistent cookies.

`storeId` Optional

A `string` representing the cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used.

`url` Optional

A `string` representing a URL that the retrieved cookies must be associated with.

### Return value

A `Promise` that will be fulfilled with an array of ``cookies.Cookie`` objects that match the properties given in the `details` parameter. Only unexpired cookies are returned. The cookies returned will be sorted by path length, longest to shortest. If multiple cookies have the same path length, those with the earliest creation time will be first.

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

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

Examples
--------

In the following snippet, we are making a call to get all of the cookies the browser currently has stored that have a name of "favorite-color". When the result is returned, we are printing the value of each result to the console.

```js
function logCookies(cookies) {
  for (const cookie of cookies) {
    console.log(cookie.value);
  }
}

browser.cookies
  .getAll({
    name: "favorite-color",
  })
  .then(logCookies);
```

### Example extensions

* list-cookies

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


cookies.SameSiteStatus - Mozilla

cookies.SameSiteStatus
======================

The `SameSiteStatus` type of the `cookies` API represents information about the `SameSite` state of a cookie.

Type
----

Values of this type are strings. Possible values are:

`no_restriction`

Corresponds to a cookie set with `SameSite=None`.

`lax`

Corresponds to a cookie set with `SameSite=Lax`.

`strict`

Corresponds to a cookie set with `SameSite=Strict`.

`unspecified`

Corresponds to a cookie set without the `SameSite` attribute. This state is not part of any SameSite standard, and is only supported by browsers that store this state internally. Other browsers map the absence of the SameSite flag to the default state (e.g. Lax). See the browser compatibility table for more details.

See SameSite cookies for more information.

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

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


cookies.get() - Mozilla

cookies.get()
=============

The **`get()`** method of the `cookies` API retrieves information about a single cookie, given its name and URL.

If more than one cookie with the same name exists for a given URL, the one with the longest path will be returned. For cookies with the same path length, the cookie with the earliest creation time will be returned. If no matching cookie could be found, `null` is returned.

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

Syntax
------

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

### Parameters

`details`

An `object` containing details that can be used to match a cookie to be retrieved. It can include the following properties:

`firstPartyDomain` Optional

A `string` representing the first-party domain with which the cookie to retrieve is associated. This property must be supplied if the browser has first-party isolation enabled. See First-party isolation.

`name`

A `string` representing the name of the cookie to retrieve.

`partitionKey` Optional

An `object` representing the storage partition containing the cookie. Include this object with `topLevelSite` to obtain a cookie from partitioned storage. Otherwise, returns the cookie from unpartitioned storage. This object contains:

`topLevelSite` Optional

A `string` representing the first-party URL of the top-level site storage partition containing the cookie.

`storeId` Optional

A `string` representing the ID of the `cookie store` in which to look for the cookie (as returned by `cookies.getAllCookieStores()`). By default, the current execution context's cookie store will be used.

`url`

A `string` representing the URL with which the cookie to retrieve is associated. This argument may be a full URL, in which case any data following the URL path (e.g. the query string) is ignored. If host permissions for this URL are not specified in the extension's manifest file, the API call will fail.

### Return value

A `Promise` that will be fulfilled with a `Cookie` object containing details about the cookie, or `null` if the cookie was not found.

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

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

Examples
--------

This example tries to get the cookie named "favorite-color", associated with the URL for the currently active tab:

```js
function logCookie(cookie) {
  if (cookie) {
    console.log(cookie.value);
  }
}

function getCookie(tabs) {
  let getting = browser.cookies.get({
    url: tabs[0].url,
    name: "favorite-color",
  });
  getting.then(logCookie);
}

let getActive = browser.tabs.query({
  active: true,
  currentWindow: true,
});
getActive.then(getCookie);
```

### Example extensions

* cookie-bg-picker

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


downloads.download() - Mozilla

downloads.download()
====================

The **`download()`** function of the `downloads` API downloads a file, given its URL and other optional preferences.

If the URL uses the HTTP or HTTPS protocol, the request includes all the relevant cookies, that is, those cookies set for the URL's hostname, secure flag, path, and so on. The default cookies, the cookies from the normal browsing session, are used unless:

* the `incognito` option is used, then the private browsing cookies are used.
* the `cookieStoreId` option is used, then the cookies from the specified store are used.

If both `filename` and `saveAs` are specified, the Save As dialog is displayed, populated with the `filename`.

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

Syntax
------

```js
let downloading = browser.downloads.download(
  options                   // object
)
```

### Parameters

`options`

An `object` specifying what file you wish to download, and any other preferences you wish to set concerning the download. It can contain the following properties:

`allowHttpErrors` Optional

A `boolean` flag that enables downloads to continue even if they encounter HTTP errors. Using this flag, for example, enables the download of server error pages. Default value `false`. When set to:

* `false`, the download is canceled when it encounters an HTTP error.
* `true`, the download continues when an HTTP error is encountered and the HTTP server error is not reported. However, if the download fails due to file-related, network-related, user-related, or other error, that error is reported.

`body` Optional

A `string` representing the post body of the request.

`conflictAction` Optional

A string representing the action you want taken if there is a filename conflict, as defined in the `downloads.FilenameConflictAction` type (defaults to "uniquify" when it is not specified).

`cookieStoreId` Optional

The cookie store ID of the contextual identity the download is associated with. If omitted, the default cookie store is used. Use requires the "cookies" API permission. See Work with contextual identities for more information.

`filename` Optional

A `string` representing a file path relative to the default downloads directory — this provides the location where you want the file to be saved, and what filename you want to use. Absolute paths, empty paths, path components that start and/or end with a dot (.), and paths containing back-references (`../`) will cause an error. If omitted, this value will default to the filename already given to the download file, and a location immediately inside the downloads directory.

`headers` Optional

If the URL uses the HTTP or HTTPS protocols, an `array` of `objects` representing additional HTTP headers to send with the request. Each header is represented as a dictionary object containing the keys `name` and either `value` or `binaryValue`. The headers that are forbidden by `XMLHttpRequest` and `fetch` cannot be specified, however, Firefox 70 and later enables the use of the `Referer` header. Attempting to use a forbidden header throws an error.

`incognito` Optional

A `boolean`: if present and set to true, then associate this download with a private browsing session. This means that it will only appear in the download manager for any private windows that are currently open.

`method` Optional

A `string` representing the HTTP method to use if the `url` uses the HTTP[S] protocol. This may be either "GET" or "POST".

`saveAs` Optional

A `boolean` that specifies whether to provide a file chooser dialog to allow the user to select a filename (`true`), or not (`false`).

If this option is omitted, the browser will show the file chooser or not based on the general user preference for this behavior (in Firefox this preference is labeled "Always ask you where to save files" in about:preferences, or `browser.download.useDownloadDir` in about:config).

**Note:** Firefox for Android raises an error if `saveAs` is set to `true`. The parameter is ignored when `saveAs` is `false` or not included.

`url`

A `string` representing the URL to download.

### Return value

A `Promise`. If the download started successfully, the promise will be fulfilled with the `id` of the new `downloads.DownloadItem`. Otherwise, the promise will be rejected with an error message taken from `downloads.InterruptReason`.

If you use URL.createObjectURL() to download data created in JavaScript and you want to revoke the object URL (with revokeObjectURL) later (as it is strongly recommended), you need to do that after the download has been completed. To do so, listen to the downloads.onChanged event.

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

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

Examples
--------

The following snippet attempts to download an example file, also specifying a filename and location to save it in, and `uniquify` as the value of the `conflictAction` option.

```js
function onStartedDownload(id) {
  console.log(`Started downloading: ${id}`);
}

function onFailed(error) {
  console.log(`Download failed: ${error}`);
}

let downloadUrl = "https://example.org/image.png";

let downloading = browser.downloads.download({
  url: downloadUrl,
  filename: "my-image-again.png",
  conflictAction: "uniquify",
});

downloading.then(onStartedDownload, onFailed);
```

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


downloads.DownloadQuery - Mozilla

downloads.DownloadQuery
=======================

The `DownloadQuery` type of the `downloads` API defines a set of parameters that can be used to search the downloads manager for a specific set of downloads.

This type is used for example in `downloads.search()` and `downloads.erase()`, as a query object to filter the set of `DownloadItems` to return or erase.

Type
----

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

`cookieStoreId` Optional

The cookie store ID of the contextual identity in which the download took place. See Work with contextual identities for more information.

`query` Optional

An `array` of `string`s. Include only `DownloadItems` whose `filename` or `url` contains all of the given strings. You can also include terms beginning with a dash (-) — these terms **must not** be contained in the item's `filename` or `url` for it to be included.

`startedBefore` Optional

A `DownloadTime`. Include only `DownloadItems` that started before the given time.

`startedAfter` Optional

A `DownloadTime`. Include only `DownloadItems` that started after the given time.

`endedBefore` Optional

A `DownloadTime`. Include only `DownloadItems` that ended before the given time.

`endedAfter` Optional

A `DownloadTime`. Include only `DownloadItems` that ended after the given time.

`totalBytesGreater` Optional

A `number` representing a number of bytes. Include only `DownloadItems` whose `totalBytes` is greater than the given number.

`totalBytesLess` Optional

A `number` representing a number of bytes. Include only `DownloadItems` whose `totalBytes` is less than the given number.

`filenameRegex` Optional

A `string` representing a regular expression. Include only `DownloadItems` whose `filename` value matches the given regular expression.

`urlRegex` Optional

A `string` representing a regular expression. Include only `DownloadItems` whose `url` value matches the given regular expression.

`limit` Optional

An `integer` representing a number of results. Include only the specified number of `DownloadItems`.

`orderBy` Optional

An `array` of `string`s representing `DownloadItem` properties the search results should be sorted by. For example, including `startTime` then `totalBytes` in the array would sort the `DownloadItems` by their start time, then total bytes — in ascending order. To specify sorting by a property in descending order, prefix it with a hyphen, for example `-startTime`.

`id` Optional

An `integer` representing the ID of the `downloads.DownloadItem` you want to query.

`url` Optional

A `string` representing the absolute URL that the download was initiated from, before any redirects.

`filename` Optional

A string representing the absolute local path of the download file you want to query.

`danger` Optional

A string representing a `downloads.DangerType` — include only `DownloadItems` with this `danger` value.

`mime` Optional

A `string` representing a MIME type. Include only `DownloadItems` with this `mime` value.

`startTime` Optional

A `string` representing an ISO 8601 format time. Include only `DownloadItems` with this `startTime` value.

`endTime` Optional

A `string` representing an ISO 8601 format time. Include only will limited to `DownloadItems` with this `endTime` value.

`state` Optional

A `string` representing a download `downloads.State` (`in_progress`, `interrupted`, or `complete`). Include only `DownloadItems` with this `state` value.

`paused` Optional

A `boolean` that indicates whether a download is paused — i.e. has stopped reading data from the host, but kept the connection open (`true`), or not (`false`). Include only `DownloadItems` with this `paused` value.

`error` Optional

A string representing an `downloads.InterruptReason` — a reason why a download was interrupted. Include only `DownloadItems` with this `error` value.

`bytesReceived` Optional

A `number` representing the number of bytes received so far from the host, without considering file compression. Include only `DownloadItems` with this `bytesReceived` value.

`totalBytes` Optional

A `number` representing the total number of bytes in the downloaded file, without considering file compression. Include only `DownloadItems` with this `totalBytes` value.

`fileSize` Optional

`number`. Number of bytes in the whole file post-decompression, or -1 if unknown. A `number` representing the total number of bytes in the file after decompression. Include only `DownloadItems` with this `fileSize` value.

`exists` Optional

A `boolean` indicating whether a downloaded file still exists (`true`) or not (`false`). Include only `DownloadItems` with this `exists` value.

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


downloads.State - Mozilla

downloads.State
===============

The `State` type of the `downloads` API defines different states that a current download can be in.

A `downloads.DownloadItem`'s `state` property will contain a string taken from the values defined in this type.

Type
----

Values of this type are strings. Possible values are:

`in_progress`

The browser is currently receiving download data from the server.

`interrupted`

An error broke the connection with the server.

`complete`

The download completed successfully.

**Note:** These string constants will never change, but new constants may be added.

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


downloads.show() - Mozilla

downloads.show()
================

The **`show()`** function of the `downloads` API shows the downloaded file in its containing folder in the underlying platform's file manager.

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

Syntax
------

```js
let showing = browser.downloads.show(
  downloadId             // integer
)
```

### Parameters

`downloadId`

An `integer` representing the ID of the `DownloadItem` to show.

### Return value

A `Promise`. If the request succeeds, the promise will be fulfilled with a boolean about whether the request was successful. If the request fails, 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
--------

This example shows the most recently downloaded item:

```js
function onShowing(success) {
  console.log(`Showing download item: ${success}`);
}

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

function openDownload(downloadItems) {
  if (downloadItems.length > 0) {
    latestDownloadId = downloadItems[0].id;
    let showing = browser.downloads.show(latestDownloadId);
    showing.then(onShowing, onError);
  }
}

let searching = browser.downloads.search({
  limit: 1,
  orderBy: ["-startTime"],
});

searching.then(openDownload, onError);
```

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


downloads.DoubleDelta - Mozilla

downloads.DoubleDelta
=====================

The `DoubleDelta` type of the `downloads` API represents the difference between two doubles.

Type
----

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

`current` Optional

A `number` representing the current double value.

`previous` Optional

A `number` representing the previous double value.

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


downloads.pause() - Mozilla

downloads.pause()
=================

The **`pause()`** function of the `downloads` API pauses a download.

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

Syntax
------

```js
let pausing = browser.downloads.pause(
  downloadId      // integer
)
```

### Parameters

`downloadId`

An `integer` representing the `id` of the download to pause.

### Return value

A `Promise`. If the call was successful, the download will be put in a paused state, and the promise will be fulfilled with no arguments. If the call fails, the promise will be rejected with an error message. The call will fail if the download is not active: for example, because it has finished downloading.

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

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

Examples
--------

```js
function onPaused() {
  console.log(`Paused download`);
}

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

let pausing = browser.downloads.pause(downloadId);
pausing.then(onPaused, onError);
```

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


downloads.acceptDanger() - Mozilla

downloads.acceptDanger()
========================

The **`acceptDanger()`** function of the `downloads` API prompts the user to either accept or cancel a potentially dangerous download.

This function can't be called from background scripts, only in scripts that are running in a visible window (such as a browser or page action's popup).

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

Syntax
------

```js
let prompting = browser.downloads.acceptDanger(
  downloadId      // integer
)
```

### Parameters

`downloadId`

An `integer` representing the `id` of the `DownloadItem` in question.

### Return value

A `Promise`. When the dialog closes, the promise will be fulfilled with no arguments.

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


downloads.showDefaultFolder() - Mozilla

downloads.showDefaultFolder()
=============================

The **`showDefaultFolder()`** function of the `downloads` API opens the default downloads folder in the platform's file manager.

Syntax
------

```js
browser.downloads.showDefaultFolder();
```

### Parameters

None.

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

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

Examples
--------

The following snippet contains a show button, which when clicked invokes `showDefaultFolder()` to open the default downloads folder in the platform's file manager:

```js
let showBtn = document.querySelector(".show");

showBtn.onclick = () => {
  browser.downloads.showDefaultFolder();
};
```

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


downloads.removeFile() - Mozilla

downloads.removeFile()
======================

The **`removeFile()`** function of the `downloads` API removes a downloaded file from disk.

This API removes the file from disk, but does not remove it from the browser's downloads history, therefore a call to `downloads.search()` will still return the item as a `DownloadItem`, but its `exists` attribute will be `false`.

To remove a file from the downloads history, you need to use `downloads.erase()`.

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

**Note:** If you want to remove a downloaded file from disk *and* erase it from history, you have to call `removeFile()` before you call `downloads.erase()`. If you try it the other way around you'll get an error when calling `removeFile()`, because the browser will no longer have a record of the download.

Syntax
------

```js
let removing = browser.downloads.removeFile(
  downloadId      // integer
)
```

### Parameters

`downloadId`

An `integer` representing the id of the `DownloadItem` you want to delete from disk.

### Return value

A `Promise`. If the request was successful, the promise will be fulfilled with no arguments. If the request failed, the promise will be rejected with an error message.

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

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

Examples
--------

Remove the most recently downloaded file:

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

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

function remove(downloadItems) {
  if (downloadItems.length > 0) {
    let removing = browser.downloads.removeFile(downloadItems[0].id);
    removing.then(onRemoved, onError);
  }
}

let searching = browser.downloads.search({
  limit: 1,
  orderBy: ["-startTime"],
});

searching.then(remove, onError);
```

### Example extensions

* latest-download

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


downloads.StringDelta - Mozilla

downloads.StringDelta
=====================

The `StringDelta` type of the `downloads` API represents the difference between two strings.

Type
----

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

`current` Optional

A `string` representing the current string value.

`previous` Optional

A `string` representing the previous string value.

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


downloads.onCreated - Mozilla

downloads.onCreated
===================

The **`onCreated()`** event of the `downloads` API fires when a download begins, i.e. when `downloads.download()` is successfully invoked.

The listener is passed the `downloads.DownloadItem` object in question as a parameter.

Syntax
------

```js
browser.downloads.onCreated.addListener(listener)
browser.downloads.onCreated.removeListener(listener)
browser.downloads.onCreated.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

Check whether a given `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. This function is passed this argument:

`downloadItem`

The `downloads.DownloadItem` object in question.

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

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

Examples
--------

Log the URL of items as they are downloaded:

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

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

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


downloads.cancel() - Mozilla

downloads.cancel()
==================

The **`cancel()`** function of the `downloads` API cancels a download. The call will fail if the download is not active: for example, because it has completed downloading.

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

Syntax
------

```js
let canceling = browser.downloads.cancel(
  downloadId      // integer
)
```

### Parameters

`downloadId`

`integer`. The id of the download to cancel.

### Return value

A `Promise`. If the request was successful, the promise will be fulfilled with no arguments. If the request failed, the promise will be rejected with an error message.

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

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

Examples
--------

```js
let downloadId = 13;

function onCanceled() {
  console.log(`Canceled download`);
}

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

let canceling = browser.downloads.cancel(downloadId);
canceling.then(onCanceled, onError);
```

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


downloads.setShelfEnabled() - Mozilla

downloads.setShelfEnabled()
===========================

The **`setShelfEnabled()`** function of the `downloads` API enables or disables the gray shelf at the bottom of every window associated with the current browser profile. The shelf will be disabled as long as at least one extension has disabled it.

If you try to enable the shelf when at least one other extension has already disabled it, the call will fail and `runtime.lastError` will be set with an appropriate error message.

**Note:** To use this function in your extension you must ask for the `"downloads.shelf"` manifest permission, as well as the `"downloads"` permission.

Syntax
------

```js
chrome.downloads.setShelfEnabled(enabled);
```

This API is also available as `browser.downloads.setShelfEnabled()`.

### Parameters

`enabled`

A `boolean` representing the state that you want to set `setShelfEnabled()` to — `true` for enable, and `false` for disable.

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