downloads.onChanged - Mozilla

downloads.onChanged
===================

The **`onChanged()`** event of the `downloads` API is fired when any of a `downloads.DownloadItem`'s properties changes (except for `bytesReceived`).

The listener is passed a `downloadDelta` as a parameter — an object containing the `downloadId` of the `downloads.DownloadItem` object in question, plus the status of all the properties that changed.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

`downloadDelta`

An `object` representing the `downloads.DownloadItem` object that changed, and the status of all the properties that changed in it. See the downloadDelta section for more details.

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

### downloadDelta

The `downloadDelta` object has the following properties available:

`id`

An `integer` representing the `id` of the `downloads.DownloadItem` that changed.

`url` Optional

A `downloads.StringDelta` object describing a change in a `downloads.DownloadItem`'s `url`.

`filename` Optional

A `downloads.StringDelta` object describing a change in a `downloads.DownloadItem`'s `filename`.

`danger` Optional

A `downloads.StringDelta` object describing a change in a `downloads.DownloadItem`'s `danger`.

`mime` Optional

A `downloads.StringDelta` object describing a change in a `downloads.DownloadItem`'s `mime`.

`startTime` Optional

A `downloads.StringDelta` object describing a change in a `downloads.DownloadItem`'s `startTime`.

`endTime` Optional

A `downloads.StringDelta` object describing a change in a `downloads.DownloadItem`'s `endTime`.

`state` Optional

A `downloads.StringDelta` object describing a change in a `downloads.DownloadItem`'s `state`.

`canResume` Optional

A `downloads.BooleanDelta` object describing a change in a `downloads.DownloadItem`'s `canResume` status.

`paused` Optional

A `downloads.BooleanDelta` object describing a change in a `downloads.DownloadItem`'s `paused` status.

`error` Optional

A `downloads.StringDelta` object describing a change in a `downloads.DownloadItem`'s `error` status.

`totalBytes` Optional

A `downloads.DoubleDelta` object describing a change in a `downloads.DownloadItem`'s `totalBytes`.

`fileSize` Optional

A `downloads.DoubleDelta` object describing a change in a `downloads.DownloadItem`'s `fileSize`.

`exists` Optional

A `downloads.BooleanDelta` object describing a change in a `downloads.DownloadItem`'s `exists` status.

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

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

Examples
--------

Log a message when downloads complete:

```js
function handleChanged(delta) {
  if (delta.state && delta.state.current === "complete") {
    console.log(`Download ${delta.id} has completed.`);
  }
}

browser.downloads.onChanged.addListener(handleChanged);
```

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


downloads.erase() - Mozilla

downloads.erase()
=================

The **`erase()`** function of the `downloads` API erases matching `DownloadItems` from the browser's download history, without deleting the downloaded files from disk.

To remove the files from disk, you need to use `downloads.removeFile()`.

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 `downloads.removeFile()` before you call `erase()`. If you try it the other way around you'll get an error when calling `downloads.removeFile()`, because it no longer exists according to the browser.

Syntax
------

```js
let erasing = browser.downloads.erase(
  query                    // DownloadQuery
)
```

### Parameters

`query`

A `downloads.DownloadQuery` object.

### Return value

A `Promise`. If the call was successful, the promise will be fulfilled with an array of integers representing the ids of the erased `DownloadItems`. If no items matching the query parameter could be found, the array will be empty. If the call 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
--------

Erase the most recent download:

```js
function onErased(ids) {
  console.log(`Erased: ${ids}`);
}

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

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

erasing.then(onErased, onError);
```

Erase everything:

```js
function onErased(ids) {
  console.log(`Erased: ${ids}`);
}

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

let erasing = browser.downloads.erase({});
erasing.then(onErased, onError);
```

### Example extensions

* latest-download

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


downloads.DownloadItem - Mozilla

downloads.DownloadItem
======================

The `DownloadItem` type of the `downloads` API represents a downloaded file.

Type
----

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

`byExtensionId` Optional

A `string` representing the ID of the extension that triggered the download (if it was triggered by an extension). This does not change once set. If the download was not triggered by an extension this is undefined.

`byExtensionName` Optional

A `string` representing the name of the extension that triggered the download (if it was triggered by an extension). This may change if the extension changes its name or the user changes their locale. If the download was not triggered by an extension this is undefined.

`bytesReceived`

A `number` representing the number of bytes received so far from the host during the download; this does not take file compression into consideration.

`canResume`

A `boolean` indicating whether a currently-interrupted (e.g. paused) download can be resumed from the point where it was interrupted (`true`), or not (`false`).

`cookieStoreId` Optional

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

`danger`

A string indicating whether this download is thought to be safe or known to be suspicious. Its possible values are defined in the `downloads.DangerType` type.

`endTime` Optional

A `string` (in ISO 8601 format) representing the number of milliseconds between the UNIX epoch and when this download ended. This is undefined if the download has not yet finished.

`error` Optional

A string indicating why a download was interrupted. Possible values are defined in the `downloads.InterruptReason` type. This is undefined if an error has not occurred.

`estimatedEndTime` Optional

A `string` (in ISO 8601 format) representing the estimated number of milliseconds between the UNIX epoch and when this download is estimated to be completed. This is undefined if it is not known (in particular, it is undefined in the `DownloadItem` that's passed into `downloads.onCreated`).

`exists`

A `boolean` indicating whether a downloaded file still exists (`true`) or not (`false`). This information might be out-of-date, as browsers do not automatically watch for file removal — to check whether a file exists, call the `downloads.search()` method, filtering for the file in question.

`filename`

A `string` representing the file's absolute local path.

`fileSize`

A `number` indicating the total number of bytes in the whole file, after decompression. A value of -1 here means that the total file size is unknown.

`id`

An `integer` representing a unique identifier for the downloaded file that is persistent across browser sessions.

`incognito`

A `boolean` that indicates whether the download is recorded in the browser's history (`false`), or not (`true`).

`mime`

A `string` representing the downloaded file's MIME type.

`paused`

A `boolean` indicating whether the download is paused, i.e. if the download has stopped reading data from the host but has kept the connection open. If so, the value is `true`, `false` if not.

`referrer`

A `string` representing the downloaded file's referrer.

`startTime`

A `string` (in ISO 8601 format) representing the number of milliseconds between the UNIX epoch and when this download began.

`state`

A `string` Indicating whether the download is progressing, interrupted, or complete. Possible values are defined in the `downloads.State` type.

`totalBytes`

A `number` indicating the total number of bytes in the file being downloaded. This does not take file compression into consideration. A value of -1 here means that the total number of bytes is unknown.

`url`

A `string` representing the absolute URL from which the file was downloaded.

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.getFileIcon() - Mozilla

downloads.getFileIcon()
=======================

The **`getFileIcon()`** function of the `downloads` API retrieves an icon for the specified download.

For new downloads, file icons are available after the `downloads.onCreated` event has been received. The image returned by this function while a download is in progress may be different from the image returned after the download is complete.

Icon retrieval is done by querying the underlying platform. The icon that is returned will therefore depend on a number of factors including state of the download, platform, registered file types and visual theme.

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

Syntax
------

```js
let gettingIcon = browser.downloads.getFileIcon(
  downloadId,           // integer
  options               // optional object
)
```

### Parameters

`downloadId`

An `integer` representing the ID of the download.

`options` Optional

An options `object` representing preferences for the icon to be retrieved. It can take the following properties:

`size` Optional

An `integer` representing the size of the icon. The returned icon's size will be the provided size squared (in pixels). If omitted, the default size for the icon is 32x32 pixels.

### Return value

A `Promise`. If the request succeeds, the promise will be fulfilled with a string representing the absolute URL of the icon. 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 logs the icon URL for the most recent download:

```js
function gotIcon(iconUrl) {
  console.log(iconUrl);
}

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

function getIcon(downloadItems) {
  if (downloadItems.length > 0) {
    latestDownloadId = downloadItems[0].id;
    let gettingIcon = browser.downloads.getFileIcon(latestDownloadId);
    gettingIcon.then(gotIcon, onError);
  }
}

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

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

### Example extensions

* latest-download

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


downloads.onErased - Mozilla

downloads.onErased
==================

The **`onErased()`** event of the `downloads` API fires when a download is erased from the browser history.

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

Syntax
------

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

`listener`

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

`downloadId`

An `integer` representing the `id` of the `downloads.DownloadItem` that was erased.

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

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

Examples
--------

Add a listener for `onErased` events, then erase the most recent download:

```js
function handleErased(item) {
  console.log(`Erased: ${item}`);
}

browser.downloads.onErased.addListener(handleErased);

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

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


downloads.resume() - Mozilla

downloads.resume()
==================

The **`resume()`** function of the `downloads` API resumes a paused download. If the request was successful, the download will be unpaused and progress will resume. The `resume()` call will fail if the download is not active: for example, because it has finished downloading.

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

Syntax
------

```js
let resuming = browser.downloads.resume(
  downloadId      // integer
)
```

### Parameters

`downloadId`

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

### 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 = 2;

function onResumed() {
  console.log(`Resumed download`);
}

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

let resuming = browser.downloads.resume(downloadId);
resuming.then(onResumed, onError);
```

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


downloads.InterruptReason - Mozilla

downloads.InterruptReason
=========================

The `InterruptReason` type of the `downloads` API defines a set of possible reasons why a download was interrupted.

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

Type
----

Values of this type are strings. Possible values are split into categories, with each set having the same substring at the beginning:

File-related errors:

* `"FILE_FAILED"`
* `"FILE_ACCESS_DENIED"`
* `"FILE_NO_SPACE"`
* `"FILE_NAME_TOO_LONG"`
* `"FILE_TOO_LARGE"`
* `"FILE_VIRUS_INFECTED"`
* `"FILE_TRANSIENT_ERROR"`
* `"FILE_BLOCKED"`
* `"FILE_SECURITY_CHECK_FAILED"`
* `"FILE_TOO_SHORT"`

Network-related errors:

* `"NETWORK_FAILED"`
* `"NETWORK_TIMEOUT"`
* `"NETWORK_DISCONNECTED"`
* `"NETWORK_SERVER_DOWN"`
* `"NETWORK_INVALID_REQUEST"`

Server-related errors:

* `"SERVER_FAILED"`
* `"SERVER_NO_RANGE"`
* `"SERVER_BAD_CONTENT"`
* `"SERVER_UNAUTHORIZED"`
* `"SERVER_CERT_PROBLEM"`
* `"SERVER_FORBIDDEN"`

User-related errors:

* `"USER_CANCELED"`
* `"USER_SHUTDOWN"`

Miscellaneous:

* `"CRASH"`
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.DownloadTime - Mozilla

downloads.DownloadTime
======================

The `DownloadTime` type of the `downloads` API represents the time a download took to complete.

Type
----

A `DownloadTime` can be one of three different types:

* a JavaScript `Date` object.
* a string:
    + if this contains only digits, it's interpreted as the number of milliseconds since the UNIX epoch.
    + otherwise, it's interpreted as an ISO 8601 string.
* a number: this is interpreted as the number of milliseconds since the UNIX epoch.
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.FilenameConflictAction - Mozilla

downloads.FilenameConflictAction
================================

The `FilenameConflictAction` type of the `downloads` API specifies what to do if the name of a downloaded file conflicts with an existing file.

This type defines the values that can be used for the `conflictAction` property of the `downloads.download` function's `options` parameter.

Type
----

Values of this type are strings. Possible values are:

`"uniquify"`

The browser will modify the filename to make it unique.

`"overwrite"`

The browser will overwrite the old file with the newly-downloaded file.

`"prompt"`

The browser will prompt the user, asking them to choose whether to uniquify or overwrite.

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.search() - Mozilla

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

The **`search()`** function of the `downloads` API queries the `DownloadItems` available in the browser's downloads manager, and returns those that match the specified search criteria.

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

Syntax
------

```js
let searching = browser.downloads.search(query);
```

### Parameters

`query`

A `downloads.DownloadQuery` object.

### Return value

A `Promise`. The promise is fulfilled with an `array` of ``downloads.DownloadItem`` objects that match the given criteria.

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

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

Examples
--------

In general, you restrict the items retrieved using the `query` parameter.

### Get downloads matching "query"

```js
function logDownloads(downloads) {
  for (const download of downloads) {
    console.log(download.id);
    console.log(download.url);
  }
}

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

browser.downloads
  .search({
    query: ["imgur"],
  })
  .then(logDownloads, onError);
```

### Get a specific item

To get a specific `DownloadItem`, the easiest way is to set only the `id` field, as seen in the snippet below:

```js
function logDownloads(downloads) {
  for (const download of downloads) {
    console.log(download.id);
    console.log(download.url);
  }
}

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

const id = 13;

browser.downloads.search({ id }).then(logDownloads, onError);
```

### Get all downloads

If you want to return all `DownloadItems`, set `query` to an empty object.

```js
function logDownloads(downloads) {
  for (const download of downloads) {
    console.log(download.id);
    console.log(download.url);
  }
}

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

browser.downloads.search({}).then(logDownloads, onError);
```

### Get the most recent download

You can get the most recent download by specifying the following search parameters:

```js
function logDownloads(downloads) {
  for (const download of downloads) {
    console.log(download.id);
    console.log(download.url);
  }
}

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

browser.downloads
  .search({
    limit: 1,
    orderBy: ["-startTime"],
  })
  .then(logDownloads, onError);
```

You can see this code in action in our latest-download example.

### Example extensions

* latest-download

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


downloads.BooleanDelta - Mozilla

downloads.BooleanDelta
======================

The `BooleanDelta` type of the `downloads` API represents the difference between two booleans.

Type
----

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

`current` Optional

A `boolean` representing the current boolean value.

`previous` Optional

A `boolean` representing the previous boolean 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.DangerType - Mozilla

downloads.DangerType
====================

The `DangerType` type of the `downloads` API defines a set of possible reasons that a downloadable file might be considered dangerous.

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

**Note:** These string constants will never change, however the set of DangerTypes may change.

Type
----

Values of this type are strings. Possible values are:

`file`

The download's filename is suspicious.

`url`

The download's URL is known to be malicious.

`content`

The downloaded file is known to be malicious.

`uncommon`

The download's URL is not commonly downloaded.

`host`

The download came from a host known to distribute malicious binaries.

`unwanted`

The download is potentially unwanted or unsafe.

`safe`

The download presents no known danger to the user's computer.

`accepted`

The user has accepted the dangerous download.

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.open() - Mozilla

downloads.open()
================

The **`open()`** function of the `downloads` API opens the downloaded file with its associated application. A `downloads.onChanged` event fires when the item is opened for the first time.

To use this function in your extension you must ask for the "downloads.open" manifest permission, as well as the "downloads" permission. Also, you can only call this function from inside the handler for a user action.

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

Syntax
------

```js
let opening = browser.downloads.open(
  downloadId      // integer
)
```

### Parameters

`downloadId`

An `integer` representing the `id` of the `downloads.DownloadItem` you want to open.

### Return value

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

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

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

Examples
--------

This example opens the most recently downloaded item:

```js
function onOpened() {
  console.log(`Opened download item`);
}

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

function openDownload(downloadItems) {
  if (downloadItems.length > 0) {
    let opening = browser.downloads.open(downloadItems[0].id);
    opening.then(onOpened, onError);
  }
}

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

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

### Example extensions

* latest-download

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


browserSettings.ftpProtocolEnabled - Mozilla

browserSettings.ftpProtocolEnabled
==================================

A `BrowserSetting` object that determines whether the FTP protocol is enabled in the browser.

The underlying value is a boolean.

**Note:** From Firefox version 88 this setting is read-only.

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

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

Examples
--------

Toggle the setting:

```js
function toggleAllowFtp() {
  function toggle(current) {
    console.log(`Current value: ${current.value}`);
    browser.browserSettings.ftpProtocolEnabled.set({ value: !current.value });
  }

  browser.browserSettings.ftpProtocolEnabled.get({}).then(toggle);
}

browser.browserAction.onClicked.addListener(() => {
  toggleAllowFtp();
});
```


browserSettings.overrideContentColorScheme - Mozilla

browserSettings.overrideContentColorScheme
==========================================

A `BrowserSetting` object whose underlying value is a string.

Firefox enables users to choose a theme for the browser UI. These themes apply either a light or dark theme to webpages. Using the `layout.css.prefers-color-scheme.content-override` preference, users can override the theme and choose to render webpages in a light or dark theme or follow the device's theme. This browser setting exposes that preference.

This object takes these values:

* "light": Applies a light theme to webpages.
* "dark": Applies a dark theme to webpages.
* "system": Applies a light or dark theme to webpages based on the device's theme.
* "browser": Applies a light or dark theme to webpages based on the browser's theme.
Browser compatibility
---------------------

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

Examples
--------

This example overrides the setting to use the dark theme for webpages:

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.overrideContentColorScheme
  .set({ value: "dark" })
  .then(logResult);
```


browserSettings.allowPopupsForUserEvents - Mozilla

browserSettings.allowPopupsForUserEvents
========================================

A `BrowserSetting` object that can be used to enable or disable the ability of web pages to open popups in response to user actions.

The underlying value is a boolean.

By default, browsers allow web pages to open popups in response to a particular set of events: for example, click, mouseup, submit. If `allowPopupsForUserEvents` is set to `false`, no user events will be able to open popups. If it is set to `true`, the default set of events will be allowed to open popups.

For example, suppose a web page has code like this:

```js
window.addEventListener("click", (e) => {
  window.open("https://example.com", "myPopup", "height=400,width=400");
});
```

By default, this will open a popup window. If your extension sets `allowPopupsForUserEvents` to `false`, then it will not open a popup, and the user will be informed that the popup was blocked.

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

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

Examples
--------

Toggle the setting:

```js
function toggleAllowPopup() {
  function toggle(current) {
    console.log(`Current value: ${current.value}`);
    browser.browserSettings.allowPopupsForUserEvents.set({
      value: !current.value,
    });
  }

  browser.browserSettings.allowPopupsForUserEvents.get({}).then(toggle);
}

browser.browserAction.onClicked.addListener(() => {
  toggleAllowPopup();
});
```


browserSettings.contextMenuShowEvent - Mozilla

browserSettings.contextMenuShowEvent
====================================

A `BrowserSetting` object which determines whether the browser's context menu is shown on the mouseup event or on the mousedown event.

Its underlying value is a string that may be either "mouseup" or "mousedown".

The default value is "mouseup" on Windows, and "mousedown" on macOS and Linux. Assigning to it on Windows has no effect - the setting is only designed to allow the context menu to be opened on mouseup instead of mousedown, not the inverse.

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

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

Examples
--------

Set the setting to "mouseup":

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.contextMenuShowEvent
  .set({ value: "mouseup" })
  .then(logResult);
```


browserSettings.newTabPageOverride - Mozilla

browserSettings.newTabPageOverride
==================================

A `BrowserSetting` object that can be used to get a string representing the URL for the "new tab" page: that is, the page that's loaded when the user opens a new empty tab.

Note that this is a read-only setting.

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

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

Examples
--------

Get the current value of the new tab URL:

```js
browser.browserSettings.newTabPageOverride.get({}).then((result) => {
  console.log(result.value);
});
```


browserSettings.closeTabsByDoubleClick - Mozilla

browserSettings.closeTabsByDoubleClick
======================================

A `BrowserSetting` object that can be used to enable or disable the user's ability to close a tab using double-click.

The underlying value is a boolean.

By default, closeTabsByDoubleClick is false. The setting can be changed by the user in about:config.

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

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


browserSettings.homepageOverride - Mozilla

browserSettings.homepageOverride
================================

A `BrowserSetting` object that can be used to get a string representing the URL currently set as the browser's homepage.

Note that this is a read-only setting. To change the homepage, see chrome\_settings\_overrides.

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

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

Examples
--------

Get the current value of the homepage URL:

```js
browser.browserSettings.homepageOverride.get({}).then((result) => {
  console.log(result.value);
});
```


browserSettings.newTabPosition - Mozilla

browserSettings.newTabPosition
==============================

A `BrowserSetting` object that can be used to control the position of newly opened tabs relative to already open tabs.

The underlying value is a string that can take one of three values:

* "afterCurrent": Open all new tabs next to the current tab.
* "relatedAfterCurrent": The default. Open new tabs next to the current tab if they are related to the current tab (for example, if they were opened via a link in the current tab). Otherwise, open new tabs at the end of the tabstrip.
* "atEnd": Open all tabs at the end of the tabstrip.
Browser compatibility
---------------------

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

Examples
--------

This code sets the value to "afterCurrent" and then logs the new value:

```js
async function setAfterCurrent() {
  let result = await browser.browserSettings.newTabPosition.set({
    value: "afterCurrent",
  });
  console.log(`Result: ${result}`);
  let newValue = await browser.browserSettings.newTabPosition.get({});
  console.log(`New value: ${newValue.value}`);
}
```


browserSettings.zoomSiteSpecific - Mozilla

browserSettings.zoomSiteSpecific
================================

A `BrowserSetting` object whose underlying value is a boolean.

This property sets the configuration setting `browser.zoom.siteSpecific`, which controls how zoom settings are applied to sites and tabs.

If `browser.zoom.siteSpecific` is true, zoom operations apply to all pages from the same site so that:

* when a page loads, if there is a zoom level for that site it is applied to the page otherwise the global default zoom level is applied.
* when the zoom level for a page changes, the zoom levels of other pages from the site in other tabs are also changed.

If `browser.zoom.siteSpecific` is set false, zoom operations apply to the active tab only so that:

* when a new tab opens, the global default zoom level is applied.
* when the zoom level in a tab changes, it persists across page loads and does not affect the zoom level in any other tab.

When Firefox is installed, `browser.zoom.siteSpecific` is true.

If `privacy.websites``.resistFingerprinting` is true, this setting has no effect and zoom is set on a per-tab basis.

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

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

Examples
--------

Set the setting to `false`:

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.zoomSiteSpecific.set({ value: false }).then(logResult);
```


browserSettings.colorManagement - Mozilla

browserSettings.colorManagement
===============================

A `BrowserSetting` object used to query and set the browser's color management features.

By default, Firefox applies color management to tagged media and defaults to sRGB for untagged media. This behavior means that some untagged media, such as that used in animation and movie production, may have undesired color corrections made to it. Use these settings to prevent that.

The object has these properties:

`mode`

A string that represents the mode used for color management. Valid values are `off`, `full`, and `tagged_only`.

`useNativeSRGB`

A boolean representing whether or not built-in sRGB color management is used.

`useWebRenderCompositor`

A boolean representing whether or not the WebRender compositor is used.

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

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

Examples
--------

Set color mode to "full":

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.colorManagement.mode
  .set({ value: "full" })
  .then(logResult);
```

Get the native sRGB color management color mode:

```js
function logResult(result) {
  console.log(`Current useNativeSRGB value: ${result.value}`);
}

browser.browserSettings.colorManagement.useNativeSRGB.get({}).then(logResult);
```


browserSettings.useDocumentFonts - Mozilla

browserSettings.useDocumentFonts
================================

A `BrowserSetting` object whose underlying value is a boolean.

By default, of course, web pages can specify the fonts they want using CSS properties like `font-family`. This setting enables an extension to instruct Firefox to ignore the fonts specified by the page, and only use system fonts.

Its underlying value is a boolean:

* `true`: use the fonts specified by the web page. This is the default.
* `false`: use the system fonts.
Browser compatibility
---------------------

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

Examples
--------

Set the setting to `false`:

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.useDocumentFonts.set({ value: false }).then(logResult);
```


browserSettings.tlsVersionRestrictionConfig - Mozilla

browserSettings.tlsVersionRestrictionConfig
===========================================

A `BrowserSetting` object used to read the highest and lowest versions of TLS supported by the browser.

The object has these properties:

`minimum`

The lowest TLS version supported by the browser. Valid values are `TLSv1`, `TLSv1.1`, `TLSv1.2`, `TLSv1.3`, and `unknown`.

`maximum`

The highest TLS version supported by the browser. Valid values are `TLSv1`, `TLSv1.1`, `TLSv1.2`, `TLSv1.3`, and `unknown`.

This is a read-only setting.

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

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

Examples
--------

Get the highest TLS version supported by the browser:

```js
browser.browserSettings.tlsVersionRestrictionConfig.maximum
  .get({})
  .then((result) => {
    console.log(`Highest TLS version supported: ${result}`);
  });
```


browserSettings.openBookmarksInNewTabs - Mozilla

browserSettings.openBookmarksInNewTabs
======================================

A `BrowserSetting` object whose underlying value is a boolean.

If set to `true`, then when the user selects a bookmark, it will be opened in a new tab. If set to `false` (the default) bookmarks are opened in the current tab.

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

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

Examples
--------

Set the setting to `true`:

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.openBookmarksInNewTabs
  .set({ value: true })
  .then(logResult);
```


browserSettings.imageAnimationBehavior - Mozilla

browserSettings.imageAnimationBehavior
======================================

A `BrowserSetting` object that can be used to change the way the browser handles animated images, such as GIFs.

The underlying value is a string that can take one of three values:

* "normal": the default. Play animated images as normal.
* "none": don't animate images at all.
* "once": play the animation once.
Browser compatibility
---------------------

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

Examples
--------

Disable animated images:

```js
browser.browserSettings.imageAnimationBehavior.set({ value: "none" });
```


browserSettings.cacheEnabled - Mozilla

browserSettings.cacheEnabled
============================

A `BrowserSetting` object that can be used to globally enable or disable the browser cache.

The underlying value is a boolean.

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

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

Examples
--------

Getting the current value of this setting:

```js
function logResult(result) {
  console.log(`Current value: ${result.value}`);
  console.log(`Current level of control: ${result.levelOfControl}`);
}

browser.browserSettings.cacheEnabled.get({}).then(logResult);
```

Disabling the browser cache:

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.cacheEnabled.set({ value: false }).then(logResult);
```


browserSettings.overrideDocumentColors - Mozilla

browserSettings.overrideDocumentColors
======================================

A `BrowserSetting` object whose underlying value is a string.

Firefox enables the user to set their own colors for document backgrounds and text. By default these values are only applied when a high-contrast theme is selected (a high-contrast theme is a feature of some operating system UIs that increases the contrast for improved accessibility). However, users can also choose to apply these colors always or never. This browser setting exposes that preference.

Its underlying value is a string that may take any one of the following values:

* "high-contrast-only": Apply the user's choices only when a high-contrast theme is selected. This is the default.
* "never": Never apply the user's choices.
* "always": Always apply the user's choices.
Browser compatibility
---------------------

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

Examples
--------

Set the setting to "always":

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.overrideDocumentColors
  .set({ value: "always" })
  .then(logResult);
```


browserSettings.openSearchResultsInNewTabs - Mozilla

browserSettings.openSearchResultsInNewTabs
==========================================

A `BrowserSetting` object whose underlying value is a boolean.

If set to `true`, then when the user selects a term in the browser's search box, the search results are displayed in a new tab. If set to `false` (the default) the search results are shown in the current tab.

Note that this does not affect the behavior when selecting items from the omnibox/awesomebar,only the dedicated search box.

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

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

Examples
--------

Set the setting to `true`:

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.openSearchResultsInNewTabs
  .set({ value: true })
  .then(logResult);
```


browserSettings.openUrlbarResultsInNewTabs - Mozilla

browserSettings.openUrlbarResultsInNewTabs
==========================================

A `BrowserSetting` object whose underlying value is a boolean.

When the user focuses the address bar and starts typing, the browser offers autocomplete suggestions: a dropdown list of web pages based on the user's incomplete input and their browsing history.

If set to `true`, then when the user selects one of these items, the item is opened in a new tab. If set to `false` (the default) the item is opened in the current tab.

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

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

Examples
--------

Set the setting to `true`:

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.openUrlbarResultsInNewTabs
  .set({ value: true })
  .then(logResult);
```


browserSettings.webNotificationsDisabled - Mozilla

browserSettings.webNotificationsDisabled
========================================

A `BrowserSetting` object that can be used to prevent websites from showing notifications using the `Notifications` Web API.

The `Notifications` API is used to display desktop notifications to the user. There are three levels of permission for notifications: *allow*, *deny*, and *prompt*. Users can set this permission for every site. If the user has not set a permission for a particular site, then the browser will fall back to a global permission, which defaults to *prompt*.

Setting `browserSettings.webNotificationsDisabled` to `true` switches the global permission to *deny*.

Note that this won't affect sites for which the user has set a per-site preference. For example, if the user sets https://example.org to *allow*, and an extension then sets `browserSettings.webNotificationsDisabled` to `true`, then pages under https://example.org will still be allowed to show notifications.

Setting `browserSettings.webNotificationsDisabled` to `false` switches the global default back to its default value.

Note that this setting has no effect on notifications created by extensions using the `notifications` API.

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

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

Examples
--------

Toggle the setting:

```js
async function toggleWebNotifications() {
  let current = await browser.browserSettings.webNotificationsDisabled.get({});
  console.log(`Current value: ${current.value}`);
  browser.browserSettings.webNotificationsDisabled.set({
    value: !current.value,
  });
}

browser.browserAction.onClicked.addListener(() => {
  toggleWebNotifications();
});
```


browserSettings.zoomFullPage - Mozilla

browserSettings.zoomFullPage
============================

A `BrowserSetting` object whose underlying value is a boolean.

By default zoom applies to all the content of a web page. Using the Zoom Text Only setting users can choose to zoom only the text on a page. This settings enables web extensions to control this setting and determine whether zoom is applied to the entire page or to text only.

The settings are:

* `true`: zoom applies to all the content of a web page (default).
* `false`: zoom applies to web page text only.
Browser compatibility
---------------------

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

Examples
--------

Set the setting to `false`:

```js
function logResult(result) {
  console.log(`Setting was modified: ${result}`);
}

browser.browserSettings.zoomFullPage.set({ value: false }).then(logResult);
```


action.ColorArray - Mozilla

action.ColorArray
=================

Type
----

An `array` of four integers in the range 0-255, defining an RGBA color. The four values specify the following channels:

1. Red
2. Green
3. Blue
4. Alpha (opacity).

For example, opaque red is `[255, 0, 0, 255]`.

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


action.disable() - Mozilla

action.disable()
================

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

**Note:** This API is available in Manifest V3 or higher.

Syntax
------

```js
browser.action.disable(
  tabId // optional integer
)
```

### Parameters

`tabId` Optional

`integer`. The id of the tab for which you want to disable the browser action.

Examples
--------

Disable the browser action when clicked, and re-enable it every time a new tab is opened:

```js
browser.tabs.onCreated.addListener(() => {
  browser.action.enable();
});

browser.action.onClicked.addListener(() => {
  browser.action.disable();
});
```

Disable the browser action only for the active tab:

```js
browser.action.onClicked.addListener((tab) => {
  browser.action.disable(tab.id);
});
```

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


action.getTitle() - Mozilla

action.getTitle()
=================

Gets the browser action's title.

**Note:** This API is available in Manifest V3 or higher.

Just as you can set the title on a per-tab basis using `action.setTitle()`, so you can retrieve a tab-specific title by passing the tab's ID into this function.

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

Syntax
------

```js
let gettingTitle = browser.action.getTitle(
  details               // object
)
```

### Parameters

`details`

An object with the following properties:

`tabId` Optional

`integer`. Specify the tab to get the title from.

`windowId` Optional

`integer`. Specify the window to get the title from.

* If `windowId` and `tabId` are both supplied, the function fails and the promise it returns is rejected.
* If `windowId` and `tabId` are both omitted, the global title is returned.
### Return value

A `Promise` that will be fulfilled with a string containing the browser action's title.

Examples
--------

This code switches the title between "this" and "that" each time the user clicks the browser action:

```js
function toggleTitle(title) {
  if (title === "this") {
    browser.action.setTitle({ title: "that" });
  } else {
    browser.action.setTitle({ title: "this" });
  }
}

browser.action.onClicked.addListener(() => {
  let gettingTitle = browser.action.getTitle({});
  gettingTitle.then(toggleTitle);
});
```

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


action.getBadgeTextColor() - Mozilla

action.getBadgeTextColor()
==========================

Gets the text color for the browser action's badge.

**Note:** This API is available in Manifest V3 or higher.

In Firefox, unless the badge text color is explicitly set using `action.setBadgeTextColor()`, the badge text color is automatically set to black or white so as to maximize contrast with the specified badge background color. For example, if you set the badge background color to white, the default badge text color is set to black, and vice versa.

Other browsers always use a white text color.

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

Syntax
------

```js
browser.action.getBadgeTextColor(
  details // object
)
```

### Parameters

`details`

`object`.

`tabId` Optional

`integer`. Specifies the tab to get the badge text color from.

`windowId` Optional

`integer`. Specifies the window from which to get the badge text color.

* If `windowId` and `tabId` are both supplied, the function fails.
* If `windowId` and `tabId` are both omitted, the global badge text color is returned.
### Return value

A `Promise` that will be fulfilled with the retrieved color as a `action.ColorArray`.

Examples
--------

Log the badge's text color:

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

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

browser.action.getBadgeTextColor({}).then(onGot, onFailure);
```

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


action.isEnabled() - Mozilla

action.isEnabled()
==================

Returns `true` if the browser action is enabled.

**Note:** This API is available in Manifest V3 or higher.

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

Syntax
------

```js
let gettingIsEnabled = browser.action.isEnabled(
  details // object
)
```

### Parameters

`details`

`object`. An object optionally containing the `tabId` or `windowId` to check.

`tabId` Optional

`integer`. ID of a tab to check.

`windowId` Optional

`integer`. ID of a window to check.

* If windowId and tabId are both supplied, the function fails.
* If windowId and tabId are both omitted, the global enabled/disabled status is returned.
### Return value

A `Promise` that will be fulfilled with `true` if the extension's browser action is enabled, and `false` otherwise.

Examples
--------

Check the global state:

```js
browser.action.isEnabled({}).then((result) => {
  console.log(result);
});
```

Check the state of the currently active tab:

```js
async function enabledInActiveTab() {
  let tabs = await browser.tabs.query({
    currentWindow: true,
    active: true,
  });
  let enabled = await browser.action.isEnabled({
    tabId: tabs[0].id,
  });
  console.log(enabled);
}
```

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

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


action.getBadgeText() - Mozilla

action.getBadgeText()
=====================

Gets the browser action's badge text.

**Note:** This API is available in Manifest V3 or higher.

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

Syntax
------

```js
let gettingText = browser.action.getBadgeText(
  details               // object
)
```

### Parameters

`details`

An object with the following properties:

`tabId` Optional

`integer`. Specifies the tab from which to get the badge text.

`windowId` Optional

`integer`. Specifies the window from which to get the badge text.

* If windowId and tabId are both supplied, the function fails.
* If windowId and tabId are both omitted, the global badge text is returned.
### Return value

A `Promise` that will be fulfilled with a string containing the badge text.

Examples
--------

Log the badge text:

```js
function gotBadgeText(text) {
  console.log(text);
}

let gettingBadgeText = browser.action.getBadgeText({});
gettingBadgeText.then(gotBadgeText);
```

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


action.getPopup() - Mozilla

action.getPopup()
=================

Gets the HTML document set as the popup for this browser action.

**Note:** This API is available in Manifest V3 or higher.

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

Syntax
------

```js
let gettingPopup = browser.action.getPopup(
  details               // object
)
```

### Parameters

`details`

An object with the following properties:

`tabId` Optional

`integer`. The tab whose popup to get.

`windowId` Optional

`integer`. The windows whose popup to get.

* If `windowId` and `tabId` are both supplied, the function fails.
* If `windowId` and `tabId` are both omitted, the global popup is returned.
### Return value

A `Promise` that will be fulfilled with a string containing the URL for the popup's document. This will be a fully qualified URL, such as `moz-extension://d1d8a2eb-fe60-f646-af30-a866c5b39942/popups/popup2.html`.

Examples
--------

Get the popup's URL:

```js
function gotPopup(popupURL) {
  console.log(popupURL);
}

let gettingPopup = browser.action.getPopup({});
gettingPopup.then(gotPopup);
```

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


action.setBadgeBackgroundColor() - Mozilla

action.setBadgeBackgroundColor()
================================

Sets the background color for the badge. Tabs without a specific badge background color will inherit the global badge background color, which defaults to `[217, 0, 0, 255]` in Firefox.

**Note:** This API is available in Manifest V3 or higher.

In Firefox, unless the badge text color is explicitly set using `action.setBadgeTextColor()`, then the badge text color iw automatically set to black or white to maximize contrast with the specified badge background color. For example, if you set the badge background color to white, the default badge text color is set to black, and vice versa.

Other browsers always use a white text color, so setting a dark background may be preferable to ensure the text is readable.

Syntax
------

```js
browser.action.setBadgeBackgroundColor(
  details // object
)
```

### Parameters

`details`

An object with the following properties:

`color`

The color, specified as one of:

* a string: any CSS <color> value, for example `"red"`, `"#FF0000"`, or `"rgb(255 0 0)"`. If the string is not a valid color, the returned promise will be rejected and the background color won't be altered.
* a ``action.ColorArray`` object.
* `null`. If a `tabId` is specified, it removes the tab-specific badge background color so that the tab inherits the global badge background color. Otherwise it reverts the global badge background color to the default value.

`tabId` Optional

`integer`. Sets the badge background color only for the given tab. The color is reset when the user navigates this tab to a new page.

`windowId` Optional

`integer`. Sets the badge background color only for the given tab.

* If `windowId` and `tabId` are both supplied, the function fails and the color is not set.
* If `windowId` and `tabId` are both omitted, the global badge background color is set instead.
Examples
--------

A background color that starts off as red, and turns green when the browser action is clicked:

```js
browser.action.setBadgeText({ text: "1234" });
browser.action.setBadgeBackgroundColor({ color: "red" });

browser.action.onClicked.addListener(() => {
  browser.action.setBadgeBackgroundColor({ color: "green" });
});
```

Set the badge background color only for the active tab:

```js
browser.action.setBadgeText({ text: "1234" });
browser.action.setBadgeBackgroundColor({ color: "red" });

browser.action.onClicked.addListener((tab) => {
  browser.action.setBadgeBackgroundColor({
    color: "green",
    tabId: tab.id,
  });
});
```

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

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

The default color in Firefox is: `[217, 0, 0, 255]`.

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


action.setTitle() - Mozilla

action.setTitle()
=================

Sets the browser action's title. The title is displayed in a tooltip over the browser action's icon. You can pass a `tabId` in or a `windowId` as an optional parameter — if you do this then the title is changed only for the specified tab or window. Tabs or windows without a specific title inherit the global title text, which defaults to the `default_title` or `name` specified in the manifest.

**Note:** This API is available in Manifest V3 or higher.

Syntax
------

```js
browser.action.setTitle(
  details // object
)
```

### Parameters

`details`

`object`. The new title and optionally the ID of the tab or window to target.

`title`

`string` or `null`. The string the browser action should display when moused over.

If `title` is an empty string, the used title will be the extension name, but `action.getTitle` will still provide the empty string.

If `title` is `null`:

* If `tabId` is specified, and the tab has a tab-specific title set, then the tab will inherit the title from the window to which it belongs.
* if `windowId` is specified, and the window has a window-specific title set, then the window will inherit the global title.
* Otherwise, the global title will be reset to the manifest title.

`tabId` Optional

`integer`. Sets the title only for the given tab.

`windowId` Optional

`integer`. Sets the title for the given window.

* If `windowId` and `tabId` are both supplied, the function fails and the title is not set.
* If `windowId` and `tabId` are both omitted, the global title is set.
Examples
--------

This code switches the title between "this" and "that" each time the user clicks the browser action:

```js
function toggleTitle(title) {
  if (title === "this") {
    browser.action.setTitle({ title: "that" });
  } else {
    browser.action.setTitle({ title: "this" });
  }
}

browser.action.onClicked.addListener(() => {
  let gettingTitle = browser.action.getTitle({});
  gettingTitle.then(toggleTitle);
});
```

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


action.setBadgeText() - Mozilla

action.setBadgeText()
=====================

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

**Note:** This API is available in Manifest V3 or higher.

Tabs without a specific badge text will inherit the global badge text, which is `""` by default.

Syntax
------

```js
browser.action.setBadgeText(
  details // object
)
```

This API is also available as `chrome.action.setBadgeText()`.

### Parameters

`details`

An object with the following properties:

`text`

`string` or `null`. Any number of characters can be passed, but only about four can fit in the space.

Use an empty string - `""` - if you don't want any badge.

If a `tabId` is specified, `null` removes the tab-specific badge text so that the tab inherits the global badge text. Otherwise it reverts the global badge text to `""`.

If a `windowId` is specified, `null` removes the window-specific badge text so that the tab inherits the global badge text. Otherwise it reverts the global badge text to `""`.

`tabId` Optional

`integer`. Set the badge text only for the given tab. The text is reset when the user navigates this tab to a new page.

`windowId` Optional

`integer`. Set the badge text for the given window.

* If `windowId` and `tabId` are both supplied, the function fails.
* If `windowId` and `tabId` are both omitted, the global badge is set.
Examples
--------

Add a badge indicating how many times the user clicked the button:

```js
let clicks = 0;

function increment() {
  browser.action.setBadgeText({ text: (++clicks).toString() });
}

browser.action.onClicked.addListener(increment);
```

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


action.getBadgeBackgroundColor() - Mozilla

action.getBadgeBackgroundColor()
================================

Gets the background color of the browser action's badge.

**Note:** This API is available in Manifest V3 or higher.

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

Syntax
------

```js
browser.action.getBadgeBackgroundColor(
  details // object
)
```

### Parameters

`details`

An object with the following properties:

`tabId` Optional

`integer`. Specifies the tab to get the badge background color from.

`windowId` Optional

`integer`. Specifies the window from which to get the badge background color.

* If `windowId` and `tabId` are both supplied, the function fails.
* If `windowId` and `tabId` are both omitted, the global badge background color is returned.
### Return value

A `Promise` that will be fulfilled with the retrieved color as a `action.ColorArray`.

Examples
--------

Log the badge's background color:

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

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

browser.action.getBadgeBackgroundColor({}).then(onGot, onFailure);
```

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


action.setBadgeTextColor() - Mozilla

action.setBadgeTextColor()
==========================

Sets the text color for the browser action's badge. Tabs without a specific badge text color will inherit the global badge text color.

**Note:** This API is available in Manifest V3 or higher.

Syntax
------

```js
browser.action.setBadgeTextColor(
  details // object
)
```

### Parameters

`details`

An object with the following properties:

`color`

The color, specified as one of:

* a string: any CSS <color> value, for example `"red"`, `"#FF0000"`, or `"rgb(255 0 0)"`. If the string is not a valid color, the returned promise will be rejected and the text color won't be altered.
* a ``action.ColorArray`` object.
* `null`. If a `tabId` is specified, it removes the tab-specific badge text color so that the tab inherits the global badge text color. Otherwise it reverts the global badge text color to the default value.

`tabId` Optional

`integer`. Sets the badge text color only for the given tab. The color is reset when the user navigates this tab to a new page.

`windowId` Optional

`integer`. Sets the badge text color only for the given tab.

* If `windowId` and `tabId` are both supplied, the function fails and the color is not set.
* If `windowId` and `tabId` are both omitted, the global badge text color is set instead.
Examples
--------

A badge text color that starts off as red, and turns green when the browser action is clicked:

```js
browser.action.setBadgeText({ text: "1234" });
browser.action.setBadgeTextColor({ color: "red" });

browser.action.onClicked.addListener(() => {
  browser.action.setBadgeTextColor({ color: "green" });
});
```

Set the badge text color only for the active tab:

```js
browser.action.setBadgeText({ text: "1234" });
browser.action.setBadgeTextColor({ color: "red" });

browser.action.onClicked.addListener((tab) => {
  browser.action.setBadgeTextColor({
    color: "green",
    tabId: tab.id,
  });
});
```

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


action.setIcon() - Mozilla

action.setIcon()
================

Sets the icon for the browser action.

**Note:** This API is available in Manifest V3 or higher.

You can specify a single icon as either the path to an image file or a `action.ImageDataType` object.

You can specify multiple icons in different sizes by supplying a dictionary containing multiple paths or `ImageData` objects. This means the icon doesn't have to be scaled for a device with a different pixel density.

Tabs without a specific icon will inherit the global icon, which defaults to the `default_icon` specified in the manifest.

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

Syntax
------

```js
let settingIcon = browser.action.setIcon(
  details         // object
)
```

### Parameters

`details`

`object`. An object containing either `imageData` or `path` properties, and optionally a `tabId` property.

`imageData` Optional

``action.ImageDataType`` or `object`. This is either a single `ImageData` object or a dictionary object.

Use a dictionary object to specify multiple `ImageData` objects in different sizes, so the icon does not have to be scaled for a device with a different pixel density. If `imageData` is a dictionary, the value of each property is an `ImageData` object, and its name is its size, like this:

```js
let settingIcon = browser.action.setIcon({
  imageData: {
    16: image16,
    32: image32,
  },
});
```

The browser will choose the image to use depending on the screen's pixel density. See Choosing icon sizes for more information on this.

`path` Optional

`string` or `object`. This is either a relative path to an icon file or it is a dictionary object.

Use a dictionary object to specify multiple icon files in different sizes, so the icon does not have to be scaled for a device with a different pixel density. If `path` is a dictionary, the value of each property is a relative path, and its name is its size, like this:

```js
let settingIcon = browser.action.setIcon({
  path: {
    16: "path/to/image16.jpg",
    32: "path/to/image32.jpg",
  },
});
```

The browser will choose the image to use depending on the screen's pixel density. See Choosing icon sizes for more information on this.

`tabId` Optional

`integer`. Sets the icon only for the given tab. The icon is reset when the user navigates this tab to a new page.

`windowId` Optional

`integer`. Sets the icon for the given window.

* If `windowId` and `tabId` are both supplied, the function fails and the icon is not set.
* If `windowId` and `tabId` are both omitted, the global icon is set.

If each one of `imageData` and `path` is one of `undefined`, `null` or empty object:

* If `tabId` is specified, and the tab has a tab-specific icon set, then the tab will inherit the icon from the window to which it belongs.
* If `windowId` is specified, and the window has a window-specific icon set, then the window will inherit the global icon.
* Otherwise, the global icon will be reset to the manifest icon.
### Return value

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

Examples
--------

The code below uses a browser action to toggle a listener for `webRequest.onHeadersReceived`, and uses `setIcon()` to indicate whether listening is on or off:

```js
function logResponseHeaders(requestDetails) {
  console.log(requestDetails);
}

function startListening() {
  browser.webRequest.onHeadersReceived.addListener(
    logResponseHeaders,
    { urls: ["<all\_urls>"] },
    ["responseHeaders"],
  );
  browser.action.setIcon({ path: "icons/listening-on.svg" });
}

function stopListening() {
  browser.webRequest.onHeadersReceived.removeListener(logResponseHeaders);
  browser.action.setIcon({ path: "icons/listening-off.svg" });
}

function toggleListener() {
  if (browser.webRequest.onHeadersReceived.hasListener(logResponseHeaders)) {
    stopListening();
  } else {
    startListening();
  }
}

browser.action.onClicked.addListener(toggleListener);
```

The code below sets the icon using an `ImageData` object:

```js
function getImageData() {
  let canvas = document.createElement("canvas");
  let ctx = canvas.getContext("2d");

  ctx.fillStyle = "green";
  ctx.fillRect(10, 10, 100, 100);

  return ctx.getImageData(50, 50, 100, 100);
}

browser.action.onClicked.addListener(() => {
  browser.action.setIcon({ imageData: getImageData() });
});
```

The following snippet updates the icon when the user clicks it, but only for the active tab:

```js
browser.action.onClicked.addListener((tab) => {
  browser.action.setIcon({
    tabId: tab.id,
    path: "icons/updated-48.png",
  });
});
```

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


action.ImageDataType - Mozilla

action.ImageDataType
====================

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

Type
----

An `ImageData` object.

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


action.getUserSettings() - Mozilla

action.getUserSettings()
========================

Gets the user-specified settings for the browser action.

**Note:** This API is available in Manifest V3 or higher.

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

Syntax
------

```js
let userSettings = await browser.action.getUserSettings();
```

### Parameters

This function takes no parameters.

### Return value

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

`userSettings`

An object containing the user-specified settings for the browser action with these properties:

`isOnToolbar` Optional

`boolean`. Whether the user has pinned the action's icon to the browser UI. This setting does not indicate whether the action icon is visible. The icon's visibility depends on the size of the browser window and the layout of the browser UI.

Examples
--------

This code logs a message indicating whether the action is pinned or not:

```js
function gotSettings(userSettings) {
  if (userSettings.isOnToolbar) {
    console.log("Action is pinned to toolbar.");
  } else {
    console.log("Action is not pinned to toolbar.");
  }
}

let gettingUserSettings = browser.action.getUserSettings();
gettingUserSettings.then(gotSettings);
```

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


action.openPopup() - Mozilla

action.openPopup()
==================

Open the browser action's popup.

**Note:** This API is available in Manifest V3 or higher.

In stable versions of Firefox, you can only call this function from inside the handler for a user action. See Browser compatibility for details.

Syntax
------

```js
browser.action.openPopup(
  options // optional object
)
```

### Parameters

`details` Optional

An object with the following properties:

`windowId` Optional

`integer`. Window to open the popup for. Defaults to the current window.

### Return value

A `Promise` that is resolved with no arguments.

Examples
--------

Open the popup when the user selects a context menu item:

```js
browser.menus.create({
  id: "open-popup",
  title: "open popup",
  contexts: ["all"],
});

browser.menus.onClicked.addListener(() => {
  browser.action.openPopup();
});
```

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

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


action.enable() - Mozilla

action.enable()
===============

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

**Note:** This API is available in Manifest V3 or higher.

Syntax
------

```js
browser.action.enable(
  tabId // optional integer
)
```

### Parameters

`tabId` Optional

`integer`. The id of the tab for which you want to enable the browser action.

Examples
--------

Disable the browser action when clicked, and re-enable it every time a new tab is opened:

```js
browser.tabs.onCreated.addListener(() => {
  browser.action.enable();
});

browser.action.onClicked.addListener(() => {
  browser.action.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.action` API. This documentation is derived from `browser_action.json` in the Chromium code.


action.onClicked - Mozilla

action.onClicked
================

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

**Note:** This API is available in Manifest V3 or higher.

To define a right-click action, use the `contextMenus` API with the "browser\_action" context type.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`tab`

`tabs.Tab`. The tab that was active when the icon was clicked.

`OnClickData`

An object containing information about the click.

`modifiers`

An `array`. The keyboard modifiers active at the time of the click, being one or more of `Shift`, `Alt`, `Command`, `Ctrl`, or `MacCtrl`.

`button`

An `integer`. Indicates the button used to click the page action icon: `0` for a left-click or a click not associated with a mouse, such as one from the keyboard and `1` for a middle button or wheel click. Note that the right-click is not supported because Firefox consumes that click to display the context menu before this event is triggered.

Examples
--------

When the user clicks the icon, disable it for the active tab, and log the tab's URL:

```js
browser.action.onClicked.addListener((tab) => {
  // disable the active tab
  browser.action.disable(tab.id);
  // requires the "tabs" or "activeTab" permission, or host permissions for the URL
  console.log(tab.url);
});
```

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


action.setPopup() - Mozilla

action.setPopup()
=================

Sets the HTML document that is opened as a popup when the user clicks on the browser action's icon. Tabs without a specific popup will inherit the global popup, which defaults to the `default_popup` specified in the manifest.

**Note:** This API is available in Manifest V3 or higher.

Syntax
------

```js
browser.action.setPopup(
  details // object
)
```

### Parameters

`details`

An object with the following properties:

`tabId` Optional

`integer`. Sets the popup only for a specific tab. The popup is reset when the user navigates this tab to a new page.

`windowId` Optional

`integer`. Sets the popup only for the specified window.

`popup`

`string` or `null`. The HTML file to show in a popup, specified as a URL.

This can point to a file packaged within the extension (for example, created using `extension.getURL`), or a remote document (e.g. `https://example.org/`).

If an empty string (`""`) is passed here, the popup is disabled, and the extension will receive `action.onClicked` events.

If `popup` is `null`:

* If `tabId` is specified, removes the tab-specific popup so that the tab inherits the global popup.
* If `windowId` is specified, removes the window-specific popup so that the window inherits the global popup.
* If `tabId` and `windowId` are both omitted, reverts the global popup to the default value.

* If `windowId` and `tabId` are both supplied, the function fails and the popup is not set.
* If `windowId` and `tabId` are both omitted, the global popup is set.
Examples
--------

This code adds a pair of context menu items that you can use to switch between two popups. Note that you'll need the "contextMenus" permission set in the extension's manifest to create context menu items.

```js
function onCreated() {
  if (browser.runtime.lastError) {
    console.log("error creating item:", browser.runtime.lastError);
  } else {
    console.log("item created successfully");
  }
}

browser.contextMenus.create(
  {
    id: "popup-1",
    type: "radio",
    title: "Popup 1",
    contexts: ["all"],
    checked: true,
  },
  onCreated,
);

browser.contextMenus.create(
  {
    id: "popup-2",
    type: "radio",
    title: "Popup 2",
    contexts: ["all"],
    checked: false,
  },
  onCreated,
);

browser.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "popup-1") {
    browser.action.setPopup({ popup: "/popup/popup1.html" });
  } else if (info.menuItemId === "popup-2") {
    browser.action.setPopup({ popup: "/popup/popup2.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.action` API. This documentation is derived from `browser_action.json` in the Chromium code.


dom.openOrClosedShadowRoot() - Mozilla

dom.openOrClosedShadowRoot()
============================

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

**Note:** In Firefox, the equivalent property is `element.openOrClosedShadowRoot`. This read-only property represents the shadow root hosted by the element, regardless of whether its `mode` is `open` or `closed`.

Use `Element.attachShadow()` to add a shadow root to an element.

Syntax
------

```js
let shadowRoot = browser.dom.openOrClosedShadowRoot(
  element,    // HTMLElement
)
```

### Parameters

`element`

`HTMLElement`. The host element.

### Return value

 A `ShadowRoot` object instance, regardless of whether its
 `mode` is set to `open` or
 `closed`, or `null` if no shadow root is present.

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

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

See also
--------

* `Element.shadowRoot`
* `chrome.dom.openOrClosedShadowRoot`


scripting.executeScript() - Mozilla

scripting.executeScript()
=========================

Injects a script into a target context. The script is run at `document_idle` by default.

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

To use this API you must have the `"scripting"` permission and permission for the target's URL, either explicitly as a host permission or using the activeTab permission. Note that some special pages do not allow this permission, including reader view, view-source, and PDF viewer pages.

In Firefox and Safari, partial lack of host permissions can result in a successful execution (with the partial results in the resolved promise). In Chrome, any missing permission prevents any execution from happening (see Issue 1325114).

The scripts you inject are called content scripts.

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

Syntax
------

```js
let results = await browser.scripting.executeScript(
  details             // object
)
```

### Parameters

`details`

An object describing the script to inject. It contains these properties:

`args` Optional

An array of arguments to carry into the function. This is only valid if the `func` parameter is specified. The arguments must be JSON-serializable.

`files` Optional

`array` of `string`. An array of path of the JS files to inject, relative to the extension's root directory. Exactly one of `files` and `func` must be specified.

`func` Optional

`function`. A JavaScript function to inject. This function is serialized and then deserialized for injection. This means that any bound parameters and execution context are lost. Exactly one of `files` and `func` must be specified.

`injectImmediately` Optional

`boolean`. Whether the injection into the target is triggered as soon as possible, but not necessarily prior to page load.

`target`

`scripting.InjectionTarget`. Details specifying the target to inject the script into.

`world` Optional

`scripting.ExecutionWorld`. The execution environment for a script to execute in.

### Return value

A `Promise` that fulfills with an array of `InjectionResult` objects, which represent the result of the injected script in every injected frame.

The promise is rejected if the injection fails, such as when the injection target is invalid. When script execution has started, its result is included in the result, whether successful (as `result`) or unsuccessfully (as `error`).

Each `InjectionResult` object has these properties:

`frameId`

`number`. The frame ID associated with the injection.

`result` Optional

`any`. The result of the script execution.

`error` Optional

`any`. If an error occurs, contains the value the script threw or rejected with. Typically this is an error object with a message property but it could be any value (including primitives and undefined).

Chrome does not support the `error` property yet (see Issue 1271527: Propagate errors from scripting.executeScript to InjectionResult). As an alternative, runtime errors can be caught by wrapping the code to execute in a try-catch statement. Uncaught errors are also reported to the console of the target tab.

The result of the script is the last evaluated statement, which is similar to the results seen if you executed the script in the Web Console (not any `console.log()` output). For example, consider a script like this:

```js
let foo = "my result";
foo;
```

Here the results array contains the string "`my result`" as an element.

The script result must be a structured cloneable value in Firefox or a JSON-serializable value in Chrome. The Chrome incompatibilities article discusses this difference in more detail in the Data cloning algorithm section.

Examples
--------

This example executes a one-line code snippet in the active tab:

```js
browser.action.onClicked.addListener(async (tab) => {
  try {
    await browser.scripting.executeScript({
      target: {
        tabId: tab.id,
      },
      func: () => {
        document.body.style.border = "5px solid green";
      },
    });
  } catch (err) {
    console.error(`failed to execute script: ${err}`);
  }
});
```

This example executes a script from a file (packaged with the extension) called `"content-script.js"`. The script is executed in the active tab. The script is executed in subframes and the main document:

```js
browser.action.onClicked.addListener(async (tab) => {
  try {
    await browser.scripting.executeScript({
      target: {
        tabId: tab.id,
        allFrames: true,
      },
      files: ["content-script.js"],
    });
  } catch (err) {
    console.error(`failed to execute script: ${err}`);
  }
});
```

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

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

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


scripting.ExecutionWorld - Mozilla

scripting.ExecutionWorld
========================

 Specifies the execution environment of a script injected with `scripting.executeScript()`
 or registered with `scripting.registerContentScripts()`.

Type
----

Values of this type are strings. Possible values are:

* `ISOLATED`
 The default execution environment of content scripts.
 This environment is isolated from the page's context: while they share the same document, the global scopes and available APIs differ.
* `MAIN`
 The execution environment of the web page. This environment is shared with the web page, without isolation.
 Scripts in this environment do not have any access to APIs that are only available to content scripts.

**Warning:** Due to the lack of isolation, the web page can detect the executed code and interfere with it.
 Do not use the `MAIN` world unless it is acceptable for web pages to read, access, or modify the logic or data that flows through the executed code.
 `MAIN` is not supported in Firefox (although it is planned and the work to introduce it is tracked by Bug 1736575). In the meantime, JavaScript code running in the isolated content script sandbox can use the Firefox "Xray vision" feature, as described in Share objects with page scripts.
Browser compatibility
---------------------

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

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


scripting.removeCSS() - Mozilla

scripting.removeCSS()
=====================

Removes a CSS stylesheet injected by a call to `scripting.insertCSS()`.

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

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

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

Syntax
------

```js
await browser.scripting.removeCSS(
  details       // object
)
```

### Parameters

`details`

An object describing the CSS to remove and where to remove it from. It contains the following properties:

`css` Optional

`string`. A string containing the CSS to inject. Either `css` or `files` must be specified and must match the stylesheet inserted through `scripting.insertCSS()`.

`files` Optional

`array` of `string`. The path of a CSS files to inject, relative to the extension's root directory. Either `files` or `css` must be specified and must match the stylesheet inserted through `scripting.insertCSS()`.

`origin` Optional

`string`. The style origin for the injection, either `USER` or `AUTHOR`. Defaults to `AUTHOR`. Must match the origin of the stylesheet inserted through `scripting.insertCSS()`.

`target`

`scripting.InjectionTarget`. Details specifying the target to remove the CSS from.

### Return value

A `Promise` that fulfills with no arguments when all the CSS is removed. If any error occurs, the promise is rejected. Attempts to remove non-existent stylesheets are ignored.

Examples
--------

This example adds some CSS using `scripting.insertCSS`, then removes it again when the user clicks a browser action:

```js
// Assuming some style has been injected previously with the following code:
//
// await browser.scripting.insertCSS({
// target: {
// tabId: tab.id,
// },
// css: "\* { background: #c0ffee }",
// });
//
// We can remove it when a user clicked an extension button like this:
browser.action.onClicked.addListener(async (tab) => {
  try {
    await browser.scripting.removeCSS({
      target: {
        tabId: tab.id,
      },
      css: "\* { background: #c0ffee }",
    });
  } catch (err) {
    console.error(`failed to remove CSS: ${err}`);
  }
});
```

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

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

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


scripting.updateContentScripts() - Mozilla

scripting.updateContentScripts()
================================

Updates registered content scripts. If there are errors during script parsing and file validation, or if the IDs specified do not exist, no scripts are updated.

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

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

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

### Syntax

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

### Parameters

`scripts`

`array` of `scripting.RegisteredContentScript`. Details of a script to update. All the properties are optional except for `id`.

### Return value

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

Examples
--------

This example updates a content script registered with ID `a-script` by setting `allFrames` to `true`:

```js
try {
  await browser.scripting.registerContentScripts([
    {
      id: "a-script",
      js: ["script.js"],
      matches: ["\*://example.org/\*"],
    },
  ]);

  // Update content script registered before to allow execution
  // in all frames:
  await browser.scripting.updateContentScripts([
    {
      id: "a-script",
      allFrames: true,
    },
  ]);
} catch (err) {
  console.error(`failed to register or update content scripts: ${err}`);
}
```

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

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

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


scripting.registerContentScripts() - Mozilla

scripting.registerContentScripts()
==================================

Registers one or more content scripts.

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

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

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

Syntax
------

```js
await browser.scripting.registerContentScripts(
  scripts         // array
)
```

### Parameters

`scripts`

`array` of `scripting.RegisteredContentScript`. A list of scripts to register.

### Return value

A `Promise` that fulfills with an array of `scripting.RegisteredContentScript`. If there are errors during script parsing and file validation, or if the IDs specified do not exist, no scripts are registered and the promise is rejected.

Examples
--------

This example registers a content script that injects the file `"script.js"`:

```js
const aScript = {
  id: "a-script",
  js: ["script.js"],
  matches: ["https://example.com/\*"],
};

try {
  await browser.scripting.registerContentScripts([aScript]);
} catch (err) {
  console.error(`failed to register content scripts: ${err}`);
}
```

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

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

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


scripting.ContentScriptFilter - Mozilla

scripting.ContentScriptFilter
=============================

This object contains a list of IDs of scripts to retrieve with `scripting.getRegisteredContentScripts()` or to unregister with `scripting.unregisterContentScripts()`.

Type
----

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

`ids`

`array` of `string`. Array of scripts IDs.

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

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

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


scripting.RegisteredContentScript - Mozilla

scripting.RegisteredContentScript
=================================

This object contains details of a script to be registered or that is registered.

Type
----

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

`allFrames` Optional

`boolean`. If specified `true`, the script is inject into all frames, even if the frame is not the top-most frame in the tab. Each frame is checked independently for URL requirements; it does not inject into child frames if the URL requirements are not met. Defaults to `false`, meaning that only the top frame is matched.

`css` Optional

`array` of `string`. The list of CSS files to be injected into matching pages. These are injected in the order they appear in this array.

`excludeMatches` Optional

`array` of `string`. Array of pages that this content script is excluded from but would otherwise be injected into.

`id`

`string`. The ID of the content script, specified in the API call.

`js` Optional

`array` of `string`. Array of path to JavaScript files in the extension package to inject into matching pages. Scripts are injected in the order they appear in this array.

`matches` Optional

`array` of `string`. Array of the pages this content script is injected into. Must be specified for `scripting.registerContentScripts()`.

`persistAcrossSessions` Optional

`boolean`. Specifies if this content script persists across browser restarts and updates and extension restarts. Defaults to `true`.

`runAt` Optional

`extensionTypes.RunAt`. Specifies when JavaScript files are injected into the web page. The default value is `document_idle`. In Firefox, `runAt` also affects the point where the CSS is inserted. In Chrome, `runAt` does not affect the CSS insertion point.

`world` Optional

`scripting.ExecutionWorld`. The execution environment for a script to execute in. The default value is `ISOLATED`.

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

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

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


scripting.insertCSS() - Mozilla

scripting.insertCSS()
=====================

Injects CSS into a page.

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

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

You can only inject CSS into pages whose URL can be expressed using a match pattern: meaning its scheme must be one of "http", "https", or "file". This means you can't inject CSS into any of the browser's built-in pages, such as about:debugging, about:addons, or the page that opens when you open a new empty tab.

**Note:** Firefox resolves URLs in injected CSS files relative to the CSS file rather than the page it's injected into.

The inserted CSS can be removed by calling `scripting.removeCSS()`.

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

Syntax
------

```js
await browser.scripting.insertCSS(
  details     // object
)
```

### Parameters

`details`

An object describing the CSS to insert and where to insert it. It contains the following properties:

`css` Optional

`string`. A string containing the CSS to inject. Either `css` or `files` must be specified.

`files` Optional

`array` of `string`. The path of CSS files to inject relative to the extension's root directory. Either `files` or `css` must be specified.

`origin` Optional

`string`. The style origin for the injection, either `USER`, to add the CSS as a user stylesheet, or `AUTHOR`, to add it as an author stylesheet. Defaults to `AUTHOR`.

* `USER` enables you to prevent websites from overriding the CSS you insert: see Cascading order.
* `AUTHOR` stylesheets behave as if they appear after all author rules specified by the web page. This behavior includes any author stylesheets added dynamically by the page's scripts, even if that addition happens after the `insertCSS` call completes.

`target`

`scripting.InjectionTarget`. Details specifying the target to inject the CSS into.

### Return value

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

Examples
--------

This example inserts CSS taken from a string into the active tab.

```js
browser.action.onClicked.addListener(async (tab) => {
  try {
    await browser.scripting.insertCSS({
      target: {
        tabId: tab.id,
      },
      css: `body { border: 20px dotted pink; }`,
    });
  } catch (err) {
    console.error(`failed to insert CSS: ${err}`);
  }
});
```

This example inserts CSS loaded from a file (packaged with the extension) called `"content-style.css"`:

```js
browser.action.onClicked.addListener(async (tab) => {
  try {
    await browser.scripting.insertCSS({
      target: {
        tabId: tab.id,
      },
      files: ["content-style.css"],
    });
  } catch (err) {
    console.error(`failed to insert CSS: ${err}`);
  }
});
```

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

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

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


scripting.InjectionTarget - Mozilla

scripting.InjectionTarget
=========================

This object contains details specifying the injection target for CSS and JavaScript. Its used in `scripting.executeScript()`, `scripting.insertCSS()`, and `scripting.removeCSS()`.

Type
----

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

`allFrames` Optional

`boolean`. Whether the script or CSS is injected into all frames within the tab. Defaults to `false`. Cannot be `true` if `frameIds` is specified.

`frameIds` Optional

`array` of `number`. Array of the IDs of the frames to inject into.

`tabId`

`number`. The ID of the tab to inject into.

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

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

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