webRequest.StreamFilter.status - Mozilla

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

A string that describes the current status of the request. It will be one of the following values:

`"uninitialized"`

The filter is not fully initialized. No filter functions may be called.

`"transferringdata"`

The underlying channel is currently transferring data, which will be routed to the extension in one or more `ondata` events. The extension can call filter functions such as `write()`, `close()`, or `disconnect()`.

`"finishedtransferringdata"`

The underlying channel has finished transferring data. In this state the extension can still write response data using the filter's `write()` function.

`"suspended"`

Data transfer is currently suspended. In this state the extension can resume the request by calling the filter's `resume()` function, and can write response data using the filter's `write()` function.

`"closed"`

The extension has closed the request by calling the filter's `close()` function. The filter will not fire any more events, and the extension may not call any filter functions.

`"disconnected"`

The extension has disconnected the filter from the request by calling the filter's `disconnect()` function. All further data will be delivered directly, without passing through the filter. The filter will not fire any more events, and the extension may not call any filter functions.

`"failed"`

An error has occurred and the filter has been disconnected from the request. The extension can find an error message in `error`, and may not call any filter functions.

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

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

Examples
--------

```js
function listener(details) {
  let filter = browser.webRequest.filterResponseData(details.requestId);
  console.log(filter.status); // uninitialized

  filter.onstart = (event) => {
    console.log(filter.status); // transferringdata
  };

  filter.ondata = (event) => {
    console.log(filter.status); // transferringdata
    // pass through the response data
    filter.write(event.data);
  };

  filter.onstop = (event) => {
    console.log(filter.status); // finishedtransferringdata
    filter.disconnect();
    console.log(filter.status); // disconnected
  };
}

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


webRequest.StreamFilter.onstop - Mozilla

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

An event handler that will be called when the stream has no more data to deliver. In the event handler you can still call filter functions such as `write()`, `disconnect()`, or `close()`.

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

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

Examples
--------

This example will append "extra stuff" to the response:

```js
function listener(details) {
  const filter = browser.webRequest.filterResponseData(details.requestId);
  const encoder = new TextEncoder();

  filter.ondata = (event) => {
    // pass through all the response data
    filter.write(event.data);
  };

  filter.onstop = (event) => {
    filter.write(encoder.encode("extra stuff"));
    filter.disconnect();
  };
}

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

Here's another version of the example above:

```js
function listener(details) {
  const filter = browser.webRequest.filterResponseData(details.requestId);
  const encoder = new TextEncoder();

  const data = [];
  filter.ondata = (event) => {
    data.push(event.data);
  };

  filter.onstop = (event) => {
    for (const buffer of data) {
      filter.write(buffer);
    }
    filter.write(encoder.encode("extra stuff"));
    filter.close();
  };
}

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


webRequest.StreamFilter.suspend() - Mozilla

webRequest.StreamFilter.suspend()
=================================

Suspends a request. After this is called, no more data will be delivered until the request is resumed with a call to `resume()`.

You can't call this function until after the `onstart` event has fired.

Syntax
------

```js
filter.suspend()
```

### Parameters

None.

### Return value

None.

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

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

Examples
--------

This example uses suspend/resume to delay a web request.

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

  filter.onstart = (event) => {
    filter.suspend();

    setTimeout(() => {
      filter.resume();
      filter.disconnect();
    }, 1000);
  };
}

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


tabs.reload() - Mozilla

tabs.reload()
=============

Reload a tab, optionally bypassing the local web cache.

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

Syntax
------

```js
let reloading = browser.tabs.reload(
  tabId,            // optional integer
  reloadProperties  // optional object
)
```

### Parameters

`tabId` Optional

`integer`. The ID of the tab to reload. Defaults to the selected tab of the current window.

`reloadProperties` Optional

An object with the following properties:

`bypassCache` Optional

`boolean`. Bypass the local web cache. Default is `false`.

### Return value

A `Promise` that will be fulfilled with no arguments when the tab has been reloaded. If any error occurs, the promise will be rejected with an error message.

Examples
--------

Reload the active tab of the current window:

```js
browser.tabs.reload();
```

Reload the active tab of the current window, bypassing the cache:

```js
browser.tabs.reload({ bypassCache: true });
```

Reload the tab whose ID is 2, bypassing the cache and calling a callback when done:

```js
function onReloaded() {
  console.log(`Reloaded`);
}

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

let reloading = browser.tabs.reload(2, { bypassCache: true });
reloading.then(onReloaded, onError);
```

### Example extensions

* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.onHighlightChanged - Mozilla

tabs.onHighlightChanged
=======================

**Warning:** This event is deprecated. Use `tabs.onHighlighted` instead.

Fired when the highlighted or selected tabs in a window changes.

Syntax
------

```js
browser.tabs.onHighlightChanged.addListener(listener)
browser.tabs.onHighlightChanged.removeListener(listener)
browser.tabs.onHighlightChanged.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`selectInfo`

`object`. See the selectInfo section for more details.

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

### selectInfo

`windowId`

`integer`. The window whose tabs changed.

`tabIds`

`array` of `integer`. All highlighted tabs in the window.

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

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

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


tabs.onZoomChange - Mozilla

tabs.onZoomChange
=================

Fired when a tab is zoomed.

Syntax
------

```js
browser.tabs.onZoomChange.addListener(listener)
browser.tabs.onZoomChange.removeListener(listener)
browser.tabs.onZoomChange.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`ZoomChangeInfo`

`object`. Information about the zoom event. See the ZoomChangeInfo section for more details.

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

### ZoomChangeInfo

`tabId`

`integer`. ID of the tab that was zoomed.

`oldZoomFactor`

`number`. The previous zoom factor.

`newZoomFactor`

`number`. The new zoom factor.

`zoomSettings`

`tabs.ZoomSettings`. Zoom settings for the tab.

Examples
--------

Listen for zoom events and log the info:

```js
function handleZoomed(zoomChangeInfo) {
  console.log(`Tab: ${zoomChangeInfo.tabId} zoomed`);
  console.log(`Old zoom: ${zoomChangeInfo.oldZoomFactor}`);
  console.log(`New zoom: ${zoomChangeInfo.newZoomFactor}`);
}

browser.tabs.onZoomChange.addListener(handleZoomed);
```

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

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

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


tabs.setZoomSettings() - Mozilla

tabs.setZoomSettings()
======================

Sets zoom settings for the specified tab. These settings are reset to the default settings upon navigating the tab.

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

Syntax
------

```js
let settingZoomSettings = browser.tabs.setZoomSettings(
  tabId,           // optional integer
  zoomSettings     // ZoomSettings
)
```

### Parameters

`tabId` Optional

`integer`. The ID of the tab to change the zoom settings for. Defaults to the active tab of the current window.

`zoomSettings`

`tabs.ZoomSettings`. Defines how zoom changes are handled and at what scope.

### Return value

A `Promise` that will be fulfilled with no arguments after the zoom settings have been changed. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.getZoom

Examples
--------

Disable zooming for the current tab:

```js
function onSet() {
  console.log(`Set zoom factor`);
}

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

let setting = browser.tabs.setZoomSettings({ mode: "disabled" });
setting.then(onSet, onError);
```

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

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

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


tabs.WindowType - Mozilla

tabs.WindowType
===============

The type of window that hosts this tab.

Type
----

Values of this type are strings. Possible values are:

* **"normal"**
* **"popup"**
* **"panel"**
* **"devtools"**
Browser compatibility
---------------------

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

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


tabs.onDetached - Mozilla

tabs.onDetached
===============

Fired when a tab is detached from a window, for example because it is being moved between windows.

Syntax
------

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

`tabId`

`integer`. ID of the tab that was detached.

`detachInfo`

`object`. ID of the previous window, and index of the tab within it. See the detachInfo section for more details.

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

### detachInfo

`oldWindowId`

`integer`. ID of the previous window.

`oldPosition`

`integer`. Index position that the tab had in the old window.

Examples
--------

Listen for detach events, and log the info:

```js
function handleDetached(tabId, detachInfo) {
  console.log(`Tab: ${tabId} moved`);
  console.log(`Old window: ${detachInfo.oldWindowId}`);
  console.log(`Old index: ${detachInfo.oldPosition}`);
}

browser.tabs.onDetached.addListener(handleDetached);
```

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

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

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


tabs.sendRequest() - Mozilla

tabs.sendRequest()
==================

**Warning:** This method has been deprecated. Use `tabs.sendMessage()` instead.

Sends a single request to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The `extension.onRequest` event is fired in each content script running in the specified tab for the current extension.

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

Syntax
------

```js
let sending = browser.tabs.sendRequest(
  tabId,                   // integer
  request                  // any
)
```

### Parameters

`tabId`

`integer`.

`request`

`any`.

### Return value

A `Promise` that will be fulfilled with the JSON response object sent by the handler of the message in the content script, or with no arguments if the content script did not send a response. If an error occurs while connecting to the specified tab or any other error occurs, the promise will be rejected with an error message.

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

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

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


tabs.ZoomSettings - Mozilla

tabs.ZoomSettings
=================

Defines zoom settings for a tab: `mode`, `scope`, and default zoom factor.

Type
----

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

`defaultZoomFactor` Optional

`number`. The default zoom level for the current tab. Note that this is only used in `tabs.getZoomSettings`.

`mode` Optional

`tabs.ZoomSettingsMode`. Defines whether zoom changes are handled by the browser, by the extension, or are disabled.

`scope` Optional

`tabs.ZoomSettingsScope`. Defines whether zoom changes will persist for the page's origin, or only take effect in this tab.

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

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

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


tabs.create() - Mozilla

tabs.create()
=============

Creates a new tab.

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

Syntax
------

```js
let creating = browser.tabs.create(
  createProperties   // object
)
```

### Parameters

`createProperties`

`object`. Properties to give the new tab. To learn more about these properties, see the `tabs.Tab` documentation.

`active` Optional

`boolean`. Whether the tab should become the active tab in the window. If `false`, it has no effect. Does not affect whether the window is focused (see `windows.update`). Defaults to `true`.

`cookieStoreId` Optional

`string`. Use this to create a tab whose cookie store ID is `cookieStoreId`. This option is only available if the extension has the `"cookies"` permission. See Work with contextual identities for more information.

`discarded` Optional

`boolean`. Whether the tab is created and made visible in the tab bar without any content loaded into memory, a state known as discarded. The tab's content is loaded when the tab is activated.

`index` Optional

`integer`. The position the tab should take in the window. The provided value will be clamped to between zero and the number of tabs in the window.

`muted` Optional

`boolean`. Whether the tab should be muted. Defaults to `false`.

`openerTabId` Optional

`integer`. The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as the newly created tab.

`openInReaderMode` Optional

`boolean`. If `true`, open this tab in Reader Mode. Defaults to `false`.

`pinned` Optional

`boolean`. Whether the tab should be pinned. Defaults to `false`.

`selected` Optional

`boolean`. Whether the tab should become the selected tab in the window. Defaults to `true`.

**Warning:** This property is deprecated, and is not supported in Firefox. Use `active` instead.

`title` Optional

`string`. The title of the tab. Allowed only if the tab is created with `discarded` set to `true`.

`url` Optional

`string`. The URL to navigate the tab to initially. Defaults to the New Tab Page.

Fully-qualified URLs must include a scheme (for example, 'http://www.google.com' not 'www.google.com').

For security reasons, in Firefox, this may not be a privileged URL. So passing any of the following URLs will fail:

* chrome: URLs
* javascript: URLs
* data: URLs
* file: URLs (i.e., files on the filesystem. However, to use a file packaged inside the extension, see below)
* privileged about: URLs (for example, `about:config`, `about:addons`, `about:debugging`). Non-privileged URLs (e.g., `about:blank`) are allowed.
* The New Tab page (`about:newtab`) can be opened if no value for URL is provided.

To load a page that's packaged with your extension, specify an absolute URL starting at the extension's manifest.json file. For example: '/path/to/my-page.html'. If you omit the leading '/', the URL is treated as a relative URL, and different browsers may construct different absolute URLs.

`windowId` Optional

`integer`. The window to create the new tab in. Defaults to the current window.

### Return value

A `Promise` that will be fulfilled with a `tabs.Tab` object containing details about the created tab. If the tab could not be created (for example, because `url` used a privileged scheme) the promise will be rejected with an error message.

The promise returned by `browser.tabs.create()` resolves as soon as the tab has been created. The tab may still be loading. To detect when the tab has finished loading, listen to the `tabs.onUpdated` or the `webNavigation.onCompleted` event before calling `tabs.create`.

Examples
--------

Open "https://example.org" in a new tab:

```js
function onCreated(tab) {
  console.log(`Created new tab: ${tab.id}`);
}

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

browser.browserAction.onClicked.addListener(() => {
  let creating = browser.tabs.create({
    url: "https://example.org",
  });
  creating.then(onCreated, onError);
});
```

### Example extensions

* commands
* contextual-identities
* find-across-tabs
* firefox-code-search
* open-my-page-button
* permissions
* store-collected-images
* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.onMoved - Mozilla

tabs.onMoved
============

Fired when a tab is moved within a window.

Only one move event is fired, representing the tab the user directly moved. Move events are not fired for the other tabs that must move in response. This event is not fired when a tab is moved between windows. For that, see `tabs.onDetached`.

Syntax
------

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

`tabId`

`integer`. ID of the tab the user moved.

`moveInfo`

`object`. Information about the move. See the moveInfo section for more details.

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

### moveInfo

`windowId`

`integer`. ID of this tab's window.

`fromIndex`

`integer`. Initial index of this tab in the window.

`toIndex`

`integer`. Final index of this tab in the window.

Examples
--------

Listen for and log move events:

```js
function handleMoved(tabId, moveInfo) {
  console.log(
    `Tab ${tabId} moved from ${moveInfo.fromIndex} to ${moveInfo.toIndex}`,
  );
}

browser.tabs.onMoved.addListener(handleMoved);
```

### Example extensions

* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.setZoom() - Mozilla

tabs.setZoom()
==============

Zooms the specified tab.

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

Syntax
------

```js
let zooming = browser.tabs.setZoom(
  tabId,           // optional integer
  zoomFactor       // number
)
```

### Parameters

`tabId` Optional

`integer`. The ID of the tab to zoom. Defaults to the active tab of the current window.

`zoomFactor`

`number`. The new zoom factor. Use a value of 0 here to set the tab to its current default zoom factor. Otherwise, this must be a number between 0.3 and 5, specifying a zoom factor.

### Return value

A `Promise` that will be fulfilled with no arguments after the zoom factor has been changed. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.

Examples
--------

Set the zoom factor for the current tab to 2:

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

let setting = browser.tabs.setZoom(2);
setting.then(null, onError);
```

Set the zoom factor for the tab whose ID is 16 tab to 0.5:

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

let setting = browser.tabs.setZoom(16, 0.5);
setting.then(null, onError);
```

### Example extensions

* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.getCurrent() - Mozilla

tabs.getCurrent()
=================

Get a `tabs.Tab` containing information about the tab that this script is running in.

**Note:** This function is only useful in contexts where there is a browser tab, such as an options page.

If you call it from a background script or a popup, it will return `undefined`.

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

Syntax
------

```js
const gettingCurrent = browser.tabs.getCurrent()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with a `tabs.Tab` object containing information about the current tab. If any error occurs the promise will be rejected with an error message.

Examples
--------

Get information about the current tab:

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

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

const gettingCurrent = browser.tabs.getCurrent();
gettingCurrent.then(onGot, onError);
```

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

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

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


tabs.getZoomSettings() - Mozilla

tabs.getZoomSettings()
======================

Gets the current zoom settings for a specified tab.

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

Syntax
------

```js
let gettingZoomSettings = browser.tabs.getZoomSettings(
  tabId                       // optional integer
)
```

### Parameters

`tabId` Optional

`integer`. The ID of the tab to get the current zoom settings from. Defaults to the active tab of the current window.

### Return value

A `Promise` that will be fulfilled with a `tabs.ZoomSettings` object representing the tab's current zoom settings. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.

Examples
--------

Get the zoom settings for the current tab:

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

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

let gettingZoomSettings = browser.tabs.getZoomSettings();
gettingZoomSettings.then(onGot, onError);
```

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

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

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


tabs.warmup() - Mozilla

tabs.warmup()
=============

To optimize system resource usage, browsers may drop GPU resources associated with tabs that the user has not accessed for a certain amount of time. If a browser has done this for a tab, then reactivating the tab (for example, when the user switches to it) may take longer than it normally would.

The `tabs.warmup()` API enables an extension to start the process of rendering the resources for an inactive tab, if the extension expects that the user might switch to the tab soon. This then makes the actual tab switch faster than it would be otherwise.

Note this API does not work on discarded tabs and does not need to be called immediately prior to switching tabs. It is merely a performance improvement when the tab switch can be anticipated, such as when hovering over a button that when clicked would switch to the tab.

It is expected that this API would mostly be useful to tab management extensions.

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

Syntax
------

```js
let warming = browser.tabs.warmup(
  tabId               // integer
)
```

### Parameters

`tabId`

`integer`. ID of the tab to warm up. If the argument passed here is not an integer (in particular, if it is `null` or `undefined`) then `warmup()` will throw an exception synchronously.

### Return value

A `Promise` that will be fulfilled with no arguments if the tab identified by `tabId` is successfully warmed up. If `tabId` does not identify an open tab, or if warming up fails for some other reason, then the promise will be rejected with an error message.

Examples
--------

This code adds a listener to the `browserAction.onClicked` event. The listener retrieves all tabs in the current window that contain pages under "https://developer.mozilla.org/" and warms up the first one that it finds.

```js
function onSuccess() {
  console.log("success!");
}

function onFailure(error) {
  // e.g. ID of a nonexistent tab
  console.error(error);
}

async function warmupMDN() {
  const mdnTabs = await browser.tabs.query({
    currentWindow: true,
    url: "https://developer.mozilla.org/\*",
  });

  if (mdnTabs.length > 0) {
    const warming = browser.tabs.warmup(mdnTabs[0].id);
    warming.then(onSuccess, onFailure);
  }
}

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

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

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


tabs.update() - Mozilla

tabs.update()
=============

Navigate the tab to a new URL, or modify other properties of the tab.

To use this function, pass the ID of the tab to update, and an `updateProperties` object containing the properties you want to update. Properties that are not specified in `updateProperties` are not modified.

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

Syntax
------

```js
let updating = browser.tabs.update(
  tabId,              // optional integer
  updateProperties    // object
)
```

### Parameters

`tabId` Optional

`integer`. Defaults to the selected tab of the current window.

`updateProperties`

`object`. The set of properties to update for this tab. To learn more about these properties, see the `tabs.Tab` documentation.

`active` Optional

`boolean`. Whether the tab should become active. Does not affect whether the window is focused (see `windows.update`). If `true`, non-active highlighted tabs will stop being highlighted. If `false`, does nothing.

`autoDiscardable` Optional

`boolean`. Whether the tab can be discarded by the browser. The default value is `true`. When set to `false`, the browser cannot automatically discard the tab. However, the tab can be discarded by `tabs.discard`.

`highlighted` Optional

`boolean`. Adds or removes the tab from the current selection. If `true` and the tab is not highlighted, it will become active by default.

If you only want to highlight the tab without activating it, Firefox accepts setting `highlighted` to `true` and `active` to `false`. Other browsers may activate the tab even in this case.

`loadReplace` Optional

`boolean`. Whether the new URL should replace the old URL in the tab's navigation history, as accessed via the "Back" button.

For example, suppose the user creates a new tab using Ctrl+T. By default, in Firefox, this would load "about:newtab". If your extension then updates this page using `tabs.update`, without `loadReplace`, the "Back" button will be enabled and will take the user back to "about:newtab". If the extension sets `loadReplace`, then the "Back" button will be disabled and it will be just as if the URL supplied by the extension was the first page visited in that tab.

Note though that the original URL will still appear in the browser's global history.

`muted` Optional

`boolean`. Whether the tab should be muted.

`openerTabId` Optional

`integer`. The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as this tab.

`pinned` Optional

`boolean`. Whether the tab should be pinned.

`selected`
Deprecated
 Optional

`boolean`. Whether the tab should be selected. This property has been replaced by `active` and `highlighted`.

`successorTabId` Optional

`integer`. The id of the tab's successor.

`url` Optional

`string`. A URL to navigate the tab to.

For security reasons, in Firefox, this may not be a privileged URL. So passing any of the following URLs will fail, with `runtime.lastError` being set to an error message:

* chrome: URLs
* javascript: URLs
* data: URLs
* file: URLs (i.e., files on the filesystem. However, to use a file packaged inside the extension, see below)
* privileged about: URLs (for example, `about:config`, `about:addons`, `about:debugging`, `about:newtab`). Non-privileged URLs (e.g., `about:blank`) are allowed.

To load a page that's packaged with your extension, specify an absolute URL starting at the extension's manifest.json file. For example: '/path/to/my-page.html'. If you omit the leading '/', the URL is treated as a relative URL, and different browsers may construct different absolute URLs.

### Return value

A `Promise` that will be fulfilled with a `tabs.Tab` object containing details about the updated tab. The `tabs.Tab` object doesn't contain `url`, `title` and `favIconUrl` unless matching host permissions or the `"tabs"` permission has been requested. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.

Examples
--------

Navigate the active tab in the current window to `https://developer.mozilla.org`:

```js
function onUpdated(tab) {
  console.log(`Updated tab: ${tab.id}`);
}

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

let updating = browser.tabs.update({ url: "https://developer.mozilla.org" });
updating.then(onUpdated, onError);
```

Activate the first tab in the current window, and navigate it to `https://developer.mozilla.org`:

```js
function onUpdated(tab) {
  console.log(`Updated tab: ${tab.id}`);
}

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

function updateFirstTab(tabs) {
  let updating = browser.tabs.update(tabs[0].id, {
    active: true,
    url: "https://developer.mozilla.org",
  });
  updating.then(onUpdated, onError);
}

let querying = browser.tabs.query({ currentWindow: true });
querying.then(updateFirstTab, onError);
```

### Example extensions

* chill-out
* firefox-code-search
* menu-labelled-open
* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.Tab - Mozilla

tabs.Tab
========

The type **`tabs.Tab`** contains information about a tab. This provides access to information about what content is in the tab, how large the content is, what special states or restrictions are in effect, and so forth.

Type
----

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

`active`

`boolean`. Whether the tab is active in its window. This may be true even if the tab's window is not currently focused.

The active tab is usually the selected one. However, on Firefox for Android, extension popups open in a new tab. When this popup tab is selected, the active tab will instead be the one in which the popup opened.

`attention` Optional

`boolean`. Indicates whether the tab is drawing attention. For example, when the tab displays a modal dialog, `attention` will be `true`.

`audible` Optional

`boolean`. Indicates whether the tab is producing sound. However, the user will not hear the sound if the tab is muted (see the `mutedInfo` property).

`autoDiscardable` Optional

`boolean`. Whether the tab can be discarded by the browser. The default value is `true`. When set to `false`, the browser cannot automatically discard the tab. However, the tab can be discarded by `tabs.discard`.

`cookieStoreId` Optional

`string`. The cookie store of the tab. See Work with contextual identities for more information.

`discarded` Optional

`boolean`. Whether the tab is discarded. A discarded tab is one whose content has been unloaded from memory, but is still visible in the tab strip. Its content gets reloaded the next time it's activated.

`favIconUrl` Optional

`string`. The URL of the tab's favicon. Only present if the extension has the `"tabs"` permission or host permissions. It may also be `undefined` if the page has no favicon, or an empty string if the tab is loading.

`height` Optional

`integer`. The height of the tab in pixels.

`hidden`

`boolean`. Whether the tab is hidden.

`highlighted`

`boolean`. Whether the tab is highlighted, i.e. part of the current tab selection. An active tab is always highlighted, but some browsers may allow additional tabs to be highlighted, for example by clicking them while holding `Ctrl`, `Shift` or `⌘ Command` keys.

Firefox for Android doesn't support highlighting multiple tabs.

`id` Optional

`integer`. The tab's ID. Tab IDs are unique within a browser session. The tab ID may also be set to `tabs.TAB_ID_NONE` for browser windows that don't host content tabs (for example, devtools windows).

`incognito`

`boolean`. Whether the tab is in a private browsing window.

`index`

`integer`. The zero-based index of the tab within its window.

`isArticle`

`boolean`. True if the tab can be rendered in Reader Mode, false otherwise.

`isInReaderMode`

`boolean`. True if the tab is currently being rendered in Reader Mode, false otherwise.

`lastAccessed` Optional

`double`. Time at which the tab was last accessed, in milliseconds since the epoch.

`mutedInfo` Optional

`tabs.MutedInfo`. The current muted state for the tab and the reason for the last state change.

`openerTabId` Optional

`integer`. The ID of the tab that opened this tab, if any. This property is only present if the opener tab still exists and is in the same window.

`pinned`

`boolean`. Whether the tab is pinned.

`selected`
Deprecated

`boolean`. Whether the tab is selected. This property has been replaced by `active` and `highlighted`.

`sessionId` Optional

`string`. The session ID used to uniquely identify a `Tab` obtained from the `sessions` API.

`status` Optional

`string`. Either *loading* or *complete*.

`successorTabId` Optional

`integer` The ID of the tab's successor.

`title` Optional

`string`. The title of the tab. Only present if the extension has the `"tabs"` permission or host permissions that matches the tab's URL.

`url` Optional

`string`. The URL of the document that the tab is displaying. Only present if the extension has the `"tabs"` permission or a matching host permissions.

`width` Optional

`integer`. The width of the tab in pixels.

`windowId`

`integer`. The ID of the window that hosts this tab.

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

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

### Example extensions

* annotate-page
* apply-css
* beastify
* bookmark-it
* cookie-bg-picker
* find-across-tabs
* tabs-tabs-tabs

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


tabs.highlight() - Mozilla

tabs.highlight()
================

Highlights (selects) one or more tabs. Tabs are specified using a window ID and a range of tab indices.

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

Syntax
------

```js
let highlighting = browser.tabs.highlight(
  highlightInfo         // object
)
```

### Parameters

`highlightInfo`

`object`.

`windowId` Optional

`integer`. ID of the window that contains the tabs.

`populate` Optional

`boolean`. Defaults to `true`. If set to `false`, the `windows.Window` object won't have a `tabs` property containing a list of `tabs.Tab` objects representing the tabs open in the window.

**Note:** Populating the window (the default behavior) can be an expensive operation if there are lots of tabs. For better performance it's recommended to manually set `populate` to `false` if you don't need tab details.

`tabs`

`array` of integer values specifying one or more tab indices to highlight. Previously highlighted tabs not included in `tabs` will stop being highlighted. The first tab in `tabs` will become active.

### Return value

A `Promise` that will be fulfilled with a `windows.Window` object containing details about the window whose tabs were highlighted. If the window could not be found or some other error occurs, the promise will be rejected with an error message.

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

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

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


tabs.getZoom() - Mozilla

tabs.getZoom()
==============

Gets the current zoom factor for the specified tab.

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

Syntax
------

```js
let gettingZoom = browser.tabs.getZoom(
  tabId                     // optional integer
)
```

### Parameters

`tabId` Optional

`integer`. The ID of the tab to get the current zoom factor from. Defaults to the active tab of the current window.

### Return value

A `Promise` that will be fulfilled with the tab's current zoom factor, as a number between 0.3 and 5. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.

Examples
--------

Get the zoom factor for the current tab:

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

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

let gettingZoom = browser.tabs.getZoom();
gettingZoom.then(onGot, onError);
```

Get the zoom factor for the tab whose ID is 2:

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

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

let gettingZoom = browser.tabs.getZoom(2);
gettingZoom.then(onGot, onError);
```

### Example extensions

* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.removeCSS() - Mozilla

tabs.removeCSS()
================

Removes from a page CSS which was previously injected by a call to `tabs.insertCSS()`.

**Note:** When using Manifest V3 or higher, use `scripting.insertCSS()` and `scripting.removeCSS()` to insert and remove CSS.

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

Syntax
------

```js
let removing = browser.tabs.removeCSS(
  tabId,           // optional integer
  details          // object
)
```

### Parameters

`tabId` Optional

`integer`. The ID of the tab from which to remove the CSS. Defaults to the active tab of the current window.

`details`

An object describing the CSS to remove from the page. It contains the following properties:

`allFrames` Optional

`boolean`. If `true`, the code will be removed from all frames of the current page. If it is `false`, code is only removed from the top frame. Defaults to `false`.

`code` Optional

`string`. CSS to remove, as a text string. This must exactly match a CSS string previously inserted into the page using `tabs.insertCSS()`.

`cssOrigin` Optional

`string`. This can take one of two values: "user", for CSS added as a user stylesheet, or "author" for CSS added as an author stylesheet. If this option was set previously by `tabs.insertCSS()`, then it must exactly match.

`file` Optional

`string`. Path to a file containing the CSS to remove. This must exactly match a CSS file previously inserted into the page using `tabs.insertCSS()`.

`frameId` Optional

`integer`. The frame from which to remove the CSS. Defaults to `0` (the top-level frame).

`matchAboutBlank` Optional

`boolean`. If `true`, the CSS will be removed from embedded "about:blank" and "about:srcdoc" frames if your extension has access to their parent document. Defaults to `false`.

### Return value

A `Promise` that will be fulfilled with no arguments when all the CSS has been removed. If any error occurs, the promise will be rejected with an error message.

Examples
--------

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

```js
let css = "body { border: 20px dotted pink; }";

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

let insertingCSS = browser.tabs.insertCSS(2, { code: css });
insertingCSS.then(null, onError);

browser.browserAction.onClicked.addListener(() => {
  let removing = browser.tabs.removeCSS(2, { code: css });
  removing.then(null, onError);
});
```

### Example extensions

* apply-css
* beastify
Browser compatibility
---------------------

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

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


tabs.duplicate() - Mozilla

tabs.duplicate()
================

Duplicates a tab, given its ID.

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

Syntax
------

```js
let duplicating = browser.tabs.duplicate(
  tabId,              // integer
  duplicateProperties // optional object
)
```

### Parameters

`tabId`

`integer`. The ID of the tab to be duplicated.

`duplicateProperties` Optional

`object`. An object describing how the tab is duplicated. It contains the following properties:

`index` Optional

`integer`. The position of the new tab in the window. The value is constrained to the range zero to the number of tabs in the window.

`active` Optional

`boolean`. Whether the tab becomes the active tab in the window. Does not affect whether the window is focused. Defaults to `true`.

### Return value

A `Promise` that will be fulfilled with a `tabs.Tab` object containing details about the duplicated tab. The `Tab` object only contains `url`, `title` and `favIconUrl` if the extension has the `"tabs"` permission or matching host permissions. If any error occurs the promise will be rejected with an error message.

**Note:** Beginning with Firefox 68, the promise returned by browser.tabs.duplicate() resolves as soon as the tab has been duplicated. Previously, the promise only resolved once the tab had fully been loaded.

Examples
--------

Duplicate the first tab, and then log the ID of the newly created tab:

```js
function onDuplicated(tabInfo) {
  console.log(tabInfo.id);
}

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

// Duplicate the first tab in the array
function duplicateFirstTab(tabs) {
  console.log(tabs);
  if (tabs.length > 0) {
    let duplicating = browser.tabs.duplicate(tabs[0].id);
    duplicating.then(onDuplicated, onError);
  }
}

// Query for all open tabs
let querying = browser.tabs.query({});
querying.then(duplicateFirstTab, onError);
```

### Example extensions

* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.onActiveChanged - Mozilla

tabs.onActiveChanged
====================

**Warning:** This event is deprecated. Use `tabs.onActivated` instead.

Fires when the selected tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to `tabs.onUpdated` events to be notified when a URL is set.

Syntax
------

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

`tabId`

`integer`. The ID of the tab that has become active.

`selectInfo`

`object`. See the selectInfo section for more details.

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

### selectInfo

`windowId`

`integer`. The ID of the window containing the selected tab.

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

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

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


tabs.captureVisibleTab() - Mozilla

tabs.captureVisibleTab()
========================

Creates a data URL encoding the image of an area of the currently active tab in the specified window. You must have the `<all_urls>` permission to use this method. (Alternately, Chrome allows use of this method with the `activeTab` permission and a qualifying user gesture).

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

Syntax
------

```js
let capturing = browser.tabs.captureVisibleTab(
  windowId,               // optional integer
  options                 // optional extensionTypes.ImageDetails
)
```

### Parameters

`windowId` Optional

`integer`. The target window. Defaults to the current window.

`options` Optional

`extensionTypes.ImageDetails`.

### Return value

A `Promise` that will be fulfilled with a data URL which encodes the captured image. May be assigned to the 'src' property of an HTML Image element for display. If any error occurs the promise will be rejected with an error message.

Examples
--------

Capture an image of the active tab in the current window, with default settings:

```js
function onCaptured(imageUri) {
  console.log(imageUri);
}

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

browser.browserAction.onClicked.addListener(() => {
  let capturing = browser.tabs.captureVisibleTab();
  capturing.then(onCaptured, onError);
});
```

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

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

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


tabs.goForward() - Mozilla

tabs.goForward()
================

Navigate to the next page in tab's history, if available.

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

Syntax
------

```js
let goingForward = browser.tabs.goForward(
  tabId,                       // optional integer
  callback                       // optional function
)
```

### Parameters

`tabId` Optional

`integer`. The ID of the tab to navigate. Defaults to the active tab of the current window.

`callback` Optional

`function`. When the page navigation finishes, this function is called without parameters.

### Return value

A `Promise` that is fulfilled when the page navigation finishes.

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

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

Examples
--------

Go forward to the next page in the current tab:

```js
function onGoForward() {
  console.log("Gone forward");
}

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

let goingForward = browser.tabs.goForward();
goingForward.then(onGoForward, onError);
```

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


tabs.executeScript() - Mozilla

tabs.executeScript()
====================

Injects JavaScript code into a page.

**Note:** When using Manifest V3 or higher, use `scripting.executeScript()` to execute scripts.

You can inject code into pages whose URL can be expressed using a match pattern. To do so, its scheme must be one of: `http`, `https`, or `file`.

You must have the permission for the page's URL—either explicitly, as a host permission—or, via the activeTab permission. Note that some special pages do not allow this permission, including reader view, view-source, and PDF viewer pages.

You can also inject code into pages packaged with your own extension:

```js
browser.tabs.create({ url: "/my-page.html" }).then(() => {
  browser.tabs.executeScript({
    code: `console.log('location:', window.location.href);`,
  });
});
```

You don't need any special permissions to do this.

You *cannot* inject code 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.

The scripts you inject are called content scripts.

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

Syntax
------

```js
let executing = browser.tabs.executeScript(
  tabId,                 // optional integer
  details                // object
)
```

### Parameters

`tabId` Optional

`integer`. The ID of the tab in which to run the script.

Defaults to the active tab of the current window.

`details`

An object describing the script to run.

It contains the following properties:

`allFrames` Optional

`boolean`. If `true`, the code will be injected into all frames of the current page.

If `true` and `frameId` is set, then it will raise an error. (`frameId` and `allFrames` are mutually exclusive.)

If it is `false`, code is only injected into the top frame.

Defaults to `false`.

`code` Optional

`string`. Code to inject, as a text string.

**Warning:** Don't use this property to interpolate untrusted data into JavaScript, as this could lead to a security issue.

`file` Optional

`string`. Path to a file containing the code to inject.

* In Firefox, relative URLs not starting at the extension root are resolved relative to the current page URL.
* In Chrome, these URLs are resolved relative to the extension's base URL.

To work cross-browser, you can specify the path as a relative URL, starting at the extension's root, like this: `"/path/to/script.js"`.

`frameId` Optional

`integer`. The frame where the code should be injected.

Defaults to `0` (the top-level frame).

`matchAboutBlank` Optional

`boolean`. If `true`, the code will be injected into embedded `about:blank` and `about:srcdoc` frames if your extension has access to their parent document. The code cannot be inserted in top-level `about:` frames.

Defaults to `false`.

`runAt` Optional

`extensionTypes.RunAt`. The soonest that the code will be injected into the tab.

Defaults to `"document_idle"`.

### Return value

A `Promise` that will resolve to an array of objects. The array's values represent the result of the script in every injected frame.

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

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

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

The result values must be structured cloneable (see Data cloning algorithm).

**Note:** The last statement may be also a `Promise`, but this feature is unsupported by webextension-polyfill library.

If any error occurs, the promise will be rejected with an error message.

Examples
--------

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

```js
function onExecuted(result) {
  console.log(`We made it green`);
}

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

const makeItGreen = 'document.body.style.border = "5px solid green"';

const executing = browser.tabs.executeScript({
  code: makeItGreen,
});
executing.then(onExecuted, onError);
```

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

```js
function onExecuted(result) {
  console.log(`We executed in all subframes`);
}

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

const executing = browser.tabs.executeScript({
  file: "/content-script.js",
  allFrames: true,
});
executing.then(onExecuted, onError);
```

This example executes a script from a file (packaged with the extension) called `"content-script.js"`. The script is executed in the tab with an ID of `2`:

```js
function onExecuted(result) {
  console.log(`We executed in tab 2`);
}

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

const executing = browser.tabs.executeScript(2, {
  file: "/content-script.js",
});
executing.then(onExecuted, onError);
```

### Example extensions

* beastify
* context-menu-copy-link-with-types
* devtools-panels
* imagify
* menu-demo
* menu-remove-element
Browser compatibility
---------------------

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

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


tabs.printPreview() - Mozilla

tabs.printPreview()
===================

Opens print preview for the active tab.

This is an asynchronous function that returns a `Promise`. An extension can detect when print preview has been closed by listening to the afterprint event:

```js
window.addEventListener("afterprint", resumeFunction, false);
```

Syntax
------

```js
let openingPreview = browser.tabs.printPreview()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with no arguments when the preview page has opened.

Examples
--------

In this example a background script listens for a click on a browser action, then opens print preview for the currently active tab:

```js
browser.browserAction.onClicked.addListener(() => {
  browser.tabs.printPreview().then(() => {
    console.log("Entered print preview");
  });
});
```

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

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


tabs.query() - Mozilla

tabs.query()
============

Gets all tabs that have the specified properties, or all tabs if no properties are specified.

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

Syntax
------

```js
let querying = browser.tabs.query(queryObj)
```

### Parameters

`queryObj`

`object`. The `query()` function will only get tabs whose properties match the properties included here.

See the `tabs.Tab` documentation to learn more about these properties.

`active` Optional

`boolean`. Whether the tabs are active in their windows.

`audible` Optional

`boolean`. Whether the tabs are audible.

`autoDiscardable` Optional

`boolean`. Whether the tab can be discarded by the browser. The default value is `true`. When set to `false`, the browser cannot automatically discard the tab. However, the tab can be discarded by `tabs.discard`.

`cookieStoreId` Optional

`string` or `array` of `string`. Use this to return tabs whose `tab.cookieStoreId` matches any of the `cookieStoreId` strings. This option is only available if the add-on has the `"cookies"` permission. See Work with contextual identities for more information.

`currentWindow` Optional

`boolean`. Whether the tabs are in the current window.

`discarded` Optional

`boolean`. Whether the tabs are discarded. A discarded tab is one whose content has been unloaded from memory, but is still visible in the tab strip. Its content gets reloaded the next time it's activated.

`hidden` Optional

`boolean`. Whether the tabs are hidden.

`highlighted` Optional

`boolean`. Whether the tabs are highlighted.

`index` Optional

`integer`. The position of the tabs within their windows.

`muted` Optional

`boolean`. Whether the tabs are muted.

`lastFocusedWindow` Optional

`boolean`. Whether the tabs are in the last focused window.

`pinned` Optional

`boolean`. Whether the tabs are pinned.

`status` Optional

`tabs.TabStatus`. Whether the tabs have completed loading.

`title` Optional

`string`. Match page titles against a pattern. Requires the "tabs" permission or host permissions for the tab to match.

`url` Optional

`string` or `array` of `string`. Match tabs against one or more match patterns. Note that fragment identifiers are not matched. Requires the "tabs" permission or host permissions for the tab to match.

`windowId` Optional

`integer`. The `id` of the parent window, or `windows.WINDOW_ID_CURRENT` for the current window.

`windowType` Optional

`tabs.WindowType`. The type of window the tabs are in.

### Return value

A `Promise` that will be fulfilled with an `array` of ``tabs.Tab`` objects, containing information about each matching tab.

If any error occurs, the promise will be rejected with an error message.

Examples
--------

Get all tabs:

```js
function logTabs(tabs) {
  for (const tab of tabs) {
    // tab.url requires the `tabs` permission or a matching host permission.
    console.log(tab.url);
  }
}

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

browser.tabs.query({}).then(logTabs, onError);
```

Get all tabs in the current window:

```js
function logTabs(tabs) {
  for (const tab of tabs) {
    // tab.url requires the `tabs` permission or a matching host permission.
    console.log(tab.url);
  }
}

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

browser.tabs.query({ currentWindow: true }).then(logTabs, onError);
```

Get the active tab in the current window:

```js
function logTabs(tabs) {
  // tabs[0].url requires the `tabs` permission or a matching host permission.
  console.log(tabs[0].url);
}

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

browser.tabs
  .query({ currentWindow: true, active: true })
  .then(logTabs, onError);
```

Get tabs for all HTTP and HTTPS URLs under `"mozilla.org"` or any of its subdomains:

```js
function logTabs(tabs) {
  for (const tab of tabs) {
    // tab.url requires the `tabs` permission or a matching host permission.
    console.log(tab.url);
  }
}

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

browser.tabs.query({ url: "\*://\*.mozilla.org/\*" }).then(logTabs, onError);
```

### Example extensions

* annotate-page
* apply-css
* beastify
* bookmark-it
* chill-out
* contextual-identities
* cookie-bg-picker
* find-across-tabs
* history-deleter
* imagify
* list-cookies
* session-state
* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.TAB_ID_NONE - Mozilla

tabs.TAB\_ID\_NONE
==================

A special ID value given to tabs that are not browser tabs (for example, tabs in devtools windows).

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

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

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


tabs.remove() - Mozilla

tabs.remove()
=============

Closes one or more tabs.

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

Syntax
------

```js
let removing = browser.tabs.remove(
  tabIds          // integer or integer array
)
```

### Parameters

`tabIds`

`integer` or `array` of `integer` The ids of the tab or tabs to close.

### Return value

A `Promise` that will be fulfilled with no arguments when all the specified tabs have been removed or their `beforeunload` prompts have been handled. If any error occurs, the promise will be rejected with an error message.

Examples
--------

Close a single tab:

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

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

let removing = browser.tabs.remove(2);
removing.then(onRemoved, onError);
```

Close multiple tabs:

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

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

let removing = browser.tabs.remove([15, 14, 1]);
removing.then(onRemoved, onError);
```

### Example extensions

* contextual-identities
* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.TabStatus - Mozilla

tabs.TabStatus
==============

Indicates whether the tab has finished loading.

Type
----

Values of this type are strings. Possible values are: `"loading"` and `"complete"`.

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

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

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


tabs.detectLanguage() - Mozilla

tabs.detectLanguage()
=====================

Detects the primary language of the content in a tab, using the Compact Language Detector (CLD).

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

Syntax
------

```js
let detecting = browser.tabs.detectLanguage(
  tabId,                  // optional integer
  callback                // optional function
)
```

### Parameters

`tabId` Optional

`integer`. Defaults to the active tab of the current window.

`callback` Optional

`function`. Currently, if a `tabId` is specified, this method uses this callback to return the results instead of returning a promise. The callback receives as its only input parameter a string containing the detected language code such as `en` or `fr`.

### Return value

A `Promise` that will be fulfilled with a string representing an ISO language code such as `en` or `fr`. For a complete list of languages supported by this method, see kLanguageInfoTable. For an unknown language, `"und"` will be returned (but see bug 1288263). If any error occurs the promise will be rejected with an error message.

Examples
--------

Detect and log the language of the active tab when the user clicks a browser action:

```js
function onLanguageDetected(lang) {
  console.log(`Language is: ${lang}`);
}

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

browser.browserAction.onClicked.addListener(() => {
  browser.tabs.detectLanguage().then(onLanguageDetected, onError);
});
```

Detect and log the language of every open tab when the user clicks a browser action (note that this example requires the "tabs" permission):

```js
function onLanguageDetected(url, lang) {
  console.log(`Language in ${url} is: ${lang}`);
}

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

function detectLanguages(tabs) {
  for (const tab of tabs) {
    browser.tabs
      .detectLanguage(tab.id)
      .then((lang) => onLanguageDetected(tab.url, lang), onError);
  }
}

browser.browserAction.onClicked.addListener(() => {
  browser.tabs.query({}).then(detectLanguages, onError);
});
```

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

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

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


tabs.move() - Mozilla

tabs.move()
===========

Moves one or more tabs to a new position in the same window or to a different window.

You can only move tabs to and from windows whose `WindowType` is `"normal"`.

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

Syntax
------

```js
let moving = browser.tabs.move(
  tabIds,              // integer or integer array
  moveProperties       // object
)
```

### Parameters

`tabIds`

`integer` or `array` of `integer`. ID of the `tab` to move, or an array of tab IDs.

`moveProperties`

`object`. An object that specifies where to move the tab(s).

`windowId` Optional

`integer`. The ID of the window to which you want to move the tab(s). If you omit this, then each tab in `tabIds` will be moved to `index` in its current window. If you include this, and `tabIds` contains more than one tab, then the first tab in `tabIds` will be moved to `index`, and the other tabs will follow it in the order given in `tabIds`.

`index`

`integer`. The index position to move the tab to, starting at 0. A value of -1 will place the tab at the end of the window.

If you pass a value less than -1, the function will throw an error.

Note that you can't move pinned tabs to a position after any unpinned tabs in a window, or move any unpinned tabs to a position before any pinned tabs. For example, if you have one or more pinned tabs in the target window and `tabIds` refers to an unpinned tab, then you can't pass 0 here. If you try to do this, the function will silently fail (it will not throw an error).

### Return value

A `Promise` that will be fulfilled with a ``tabs.Tab`` object or an `array` of ``tabs.Tab`` objects, containing details about the moved tabs. If no tabs were moved (for example, because you tried to move an unpinned tab before a pinned tab) this will be an empty array. If any error occurs, the promise will be rejected with an error message.

Examples
--------

Move the first tab in the current window to the last position in the current window:

```js
function onMoved(tab) {
  console.log(`Moved: ${tab}`);
}

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

function firstToLast(windowInfo) {
  if (windowInfo.tabs.length === 0) {
    return;
  }
  let moving = browser.tabs.move(windowInfo.tabs[0].id, { index: -1 });
  moving.then(onMoved, onError);
}

browser.browserAction.onClicked.addListener(() => {
  let gettingCurrent = browser.windows.getCurrent({ populate: true });
  gettingCurrent.then(firstToLast, onError);
});
```

Move all tabs served over HTTP or HTTPS from \*.mozilla.org to the end of their window:

```js
function onMoved(tab) {
  console.log(`Moved: ${tab}`);
}

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

function moveMoz(tabs) {
  let mozTabIds = tabs.map((tabInfo) => tabInfo.id);
  let moving = browser.tabs.move(mozTabIds, { index: -1 });
  moving.then(onMoved, onError);
}

browser.browserAction.onClicked.addListener(() => {
  let gettingMozTabs = browser.tabs.query({ url: "\*://\*.mozilla.org/\*" });
  gettingMozTabs.then(moveMoz, onError);
});
```

Move all tabs served over HTTP or HTTPS from \*.mozilla.org to the window that hosts the first such tab, starting at position 0:

```js
function onMoved(tab) {
  console.log(`Moved: ${tab}`);
}

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

function moveMoz(tabs) {
  let mozTabIds = tabs.map((tabInfo) => tabInfo.id);
  let targetWindow = tabs[0].windowId;
  let moving = browser.tabs.move(mozTabIds, {
    windowId: targetWindow,
    index: 0,
  });
  moving.then(onMoved, onError);
}

browser.browserAction.onClicked.addListener(() => {
  let gettingMozTabs = browser.tabs.query({ url: "\*://\*.mozilla.org/\*" });
  gettingMozTabs.then(moveMoz, onError);
});
```

### Example extensions

* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.sendMessage() - Mozilla

tabs.sendMessage()
==================

Sends a single message from the extension's background scripts (or other privileged scripts, such as popup scripts or options page scripts) to any content scripts or extension pages/iframes that belong to the extension and are running in the specified tab.

The message will be received in the extension context by any listeners to the `runtime.onMessage` event. Listeners may then optionally return something as a response back to the sender.

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

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

Syntax
------

```js
const sending = browser.tabs.sendMessage(
  tabId,     // integer
  message,   // any
  options    // optional object
)
```

### Parameters

`tabId`

`integer`. ID of the tab whose content scripts we want to send a message to.

`message`

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

`options` Optional

`object`.

`frameId` Optional

`integer`. Sends the message to a specific frame identified by `frameId` instead of all frames in the tab. Whether the content script is executed in all frames depends on the `all_frames` setting in the `content_scripts` section of `manifest.json`.

### Return value

A `Promise` that will be fulfilled with the response object sent by the handler of the message in the content script, or with no arguments if the content script did not send a response.

If an error occurs while connecting to the specified tab or any other error occurs, the promise will be rejected with an error message.

If several frames respond to the message, the promise is resolved to one of answers.

Examples
--------

Here's an example of a background script that sends a message to the content scripts running in the active tab when the user clicks the browser action. The background script also expects the content script to send a response:

```js
// background-script.js
"use strict";

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

function sendMessageToTabs(tabs) {
  for (const tab of tabs) {
    browser.tabs
      .sendMessage(tab.id, { greeting: "Hi from background script" })
      .then((response) => {
        console.log("Message from the content script:");
        console.log(response.response);
      })
      .catch(onError);
  }
}

browser.browserAction.onClicked.addListener(() => {
  browser.tabs
    .query({
      currentWindow: true,
      active: true,
    })
    .then(sendMessageToTabs)
    .catch(onError);
});
```

Here's the corresponding content script:

```js
// content-script.js
"use strict";

browser.runtime.onMessage.addListener((request) => {
  console.log("Message from the background script:");
  console.log(request.greeting);
  return Promise.resolve({ response: "Hi from content script" });
});
```

### Example extensions

* beastify
* cookie-bg-picker
* imagify
Browser compatibility
---------------------

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

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


tabs.print() - Mozilla

tabs.print()
============

Call this function to print the contents of the active tab. If this function is called, the user will be presented with the print dialog from the underlying platform, and will have the chance to change the print settings and then print the currently active tab.

Syntax
------

```js
browser.tabs.print()
```

### Parameters

None.

### Return value

None.

Examples
--------

In this example a background script listens for a click on a browser action, then tries to print the currently active tab:

```js
browser.browserAction.onClicked.addListener(() => {
  browser.tabs.print();
});
```

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

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


tabs.onAttached - Mozilla

tabs.onAttached
===============

Fired when a tab is attached to a window, for example because it was moved between windows.

Syntax
------

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

`tabId`

`integer`. ID of the tab that was attached to a new window.

`attachInfo`

`object`. ID of the new window, and index of the tab within it. See the attachInfo section for more details.

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

### attachInfo

`newWindowId`

`integer`. ID of the new window.

`newPosition`

`integer`. Index position that the tab has in the new window.

Examples
--------

Listen for attach events, and log the info:

```js
function handleAttached(tabId, attachInfo) {
  console.log(`Tab: ${tabId} attached`);
  console.log(`New window: ${attachInfo.newWindowId}`);
  console.log(`New index: ${attachInfo.newPosition}`);
}

browser.tabs.onAttached.addListener(handleAttached);
```

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

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

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


tabs.getSelected() - Mozilla

tabs.getSelected()
==================

**Warning:** This method has been deprecated. Use `tabs.query({active: true})` instead.

Gets the tab that is selected in the specified window.

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

Syntax
------

```js
let gettingSelected = browser.tabs.getSelected(
  windowId           // optional integer
)
```

### Parameters

`windowId` Optional

`integer`. Defaults to the current window.

### Return value

A `Promise` that will be fulfilled with a `tabs.Tab` object containing information about the selected tab. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.

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

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

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


tabs.onCreated - Mozilla

tabs.onCreated
==============

Fired when a tab is created.

Note that the tab's URL may not be given its final value at the time this event fired. In particular, Firefox opens a new tab with the URL "about:blank" before loading the new page into it. You can listen to `tabs.onUpdated` events to be notified when a URL is set.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`tab`

`tabs.Tab`. Details of the tab that was created.

Examples
--------

Log the IDs of newly created tabs:

```js
function handleCreated(tab) {
  console.log(tab.id);
}

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

### Example extensions

* session-state
* tabs-tabs-tabs
Browser compatibility
---------------------

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

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


tabs.onHighlighted - Mozilla

tabs.onHighlighted
==================

Fired when the set of highlighted tabs in a window changes.

Note that before version 63, Firefox didn't have the concept of highlighting multiple tabs, so this event was just an alias for `tabs.onActivated`.

Syntax
------

```js
browser.tabs.onHighlighted.addListener(listener)
browser.tabs.onHighlighted.removeListener(listener)
browser.tabs.onHighlighted.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`highlightInfo`

`object`. ID(s) of the highlighted tabs, and ID of their window. See the highlightInfo section for more details.

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

### highlightInfo

`windowId`

`integer`. ID of the window whose tabs changed.

`tabIds`

`array` of `integer`. IDs of the highlighted tabs in the window.

Examples
--------

Listen for highlighting events, and log the IDs of highlighted tabs:

```js
function handleHighlighted(highlightInfo) {
  console.log(`Highlighted tabs: ${highlightInfo.tabIds}`);
}

browser.tabs.onHighlighted.addListener(handleHighlighted);
```

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

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

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


tabs.onReplaced - Mozilla

tabs.onReplaced
===============

Fired when a tab is replaced with another tab due to prerendering or instant.

This event may not be relevant for or supported by browsers other than Chrome.

Syntax
------

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

`addedTabId`

`integer`. ID of the replacement tab.

`removedTabId`

`integer`. ID of the tab that was replaced.

Examples
--------

Listen for replacement events, and log the associated info:

```js
function handleReplaced(addedTabId, removedTabId) {
  console.log(`New tab: ${addedTabId}`);
  console.log(`Old tab: ${removedTabId}`);
}

browser.tabs.onReplaced.addListener(handleReplaced);
```

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

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

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


tabs.show() - Mozilla

tabs.show()
===========

Shows one or more tabs that were previously hidden by a call to `tabs.hide`.

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

Syntax
------

```js
let showing = browser.tabs.show(
  tabIds          // integer or integer array
)
```

### Parameters

`tabIds`

`integer` or `array` of `integer`. The IDs of the tab or tabs to show.

### Return value

A `Promise` that will be fulfilled with no arguments. If any error occurs, the promise will be rejected with an error message.

Examples
--------

Show a single tab:

```js
function onShown() {
  console.log(`Shown`);
}

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

browser.tabs.show(2).then(onShown, onError);
```

Show multiple tabs:

```js
function onShown() {
  console.log(`Shown`);
}

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

browser.tabs.show([15, 14, 1]).then(onShown, onError);
```

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

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


tabs.saveAsPDF() - Mozilla

tabs.saveAsPDF()
================

Saves the current page as a PDF file. This will open a dialog, supplied by the underlying operating system, asking the user where they want to save the PDF file.

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

Syntax
------

```js
let saving = browser.tabs.saveAsPDF(
  pageSettings   // object
)
```

### Parameters

`pageSettings`

`object`. Settings for the saved page, as a `tabs.PageSettings` object. This object must be given, but all its properties are optional. Any properties not specified here will get the default values listed in the `PageSettings` documentation.

### Return value

A `Promise` that will be fulfilled with a status string when the dialog has closed. The string may be any of:

* "saved"
* "replaced"
* "canceled"
* "not\_saved"
* "not\_replaced"
Examples
--------

In this example a background script listens for a click on a browser action, then tries to save the currently active tab as a PDF file, then logs the result:

```js
browser.browserAction.onClicked.addListener(() => {
  browser.tabs.saveAsPDF({}).then((status) => {
    console.log(status);
  });
});
```

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

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


tabs.PageSettings - Mozilla

tabs.PageSettings
=================

The type **`tabs.PageSettings`** is used to control how a tab is rendered as a PDF by the `tabs.saveAsPDF()` method.

All its properties are optional.

For setting headers and footers, you can include certain special characters in the strings you supply. These will be replaced in the rendered output as follows:

* "&P": the page number, like "2"
* "&PT": the page number and the total number of pages, like "2 of 3"
* "&D": the current date/time
* "&T": the page title
* "&U": the page URL
Type
----

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

`edgeBottom` Optional

`number`. The spacing between the bottom of the footers and the bottom edge of the paper (inches). Default: 0.

`edgeLeft` Optional

`number`. The spacing between the left header/footer and the left edge of the paper (inches). Default: 0.

`edgeRight` Optional

`number`. The spacing between the right header/footer and the left edge of the paper (inches). Default: 0.

`edgeTop` Optional

`number`. The spacing between the top of the headers and the top edge of the paper (inches). Default: 0

`footerCenter` Optional

`string`. The text for the page's center footer. Default: ''.

`footerLeft` Optional

`string`. The text for the page's left footer. Default: '&PT'.

`footerRight` Optional

`string`. The text for the page's right footer. Default: '&D'.

`headerCenter` Optional

`string`. The text for the page's center header. Default: ''.

`headerLeft` Optional

`string`. The text for the page's left header. Default: '&T'.

`headerRight` Optional

`string`. The text for the page's right header. Default: '&U'.

`marginBottom` Optional

`number`. The margin between the page content and the bottom edge of the paper (inches). Default: 0.5.

`marginLeft` Optional

`number`. The margin between the page content and the left edge of the paper (inches). Default: 0.5.

`marginRight` Optional

`number`. The margin between the page content and the right edge of the paper (inches). Default: 0.5.

`marginTop` Optional

`number`. The margin between the page content and the top edge of the paper (inches). Default: 0.5.

`orientation` Optional

`integer`. Page orientation: 0 means "portrait", 1 means "landscape". Default: 0.

`paperHeight` Optional

`number`. The paper height in paper size units. Default: 11.0.

`paperSizeUnit` Optional

`integer`. The paper size unit: 0 = inches, 1 = millimeters. Default: 0.

`paperWidth` Optional

`number`. The paper width in paper size units. Default: 8.5.

`scaling` Optional

`number`. Page content scaling factor. 1 means 100% or normal size. Default: 1.

`showBackgroundColors` Optional

`boolean`. Whether the page background colors should be shown. Default: false.

`showBackgroundImages` Optional

`boolean`. Whether the page background images should be shown. Default: false.

`shrinkToFit` Optional

`boolean`. Whether the page content should shrink to fit the page width (overrides scaling). Default: true.

`toFileName` Optional

`string`. The name of the file the PDF is saved in, with or without the `.pdf` extension.

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

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


tabs.moveInSuccession() - Mozilla

tabs.moveInSuccession()
=======================

Modifies the succession relationship for a group of tabs.

Using the `tabs` API, a tab can be assigned a *successor* tab in the same window. If tab B is the successor of tab A, and tab A is closed while it is the active tab, tab B will be activated next. If tab A doesn't have a successor, then the browser is free to determine which tab to activate next. If tab B is the successor of tab A, then tab A is called a *predecessor* of tab B. A tab can have at most one successor, but it can have any number of predecessors. A tab cannot take itself or a tab in a different window as a successor.

All tabs start out with no successor; tabs only get a successor if assigned one by a WebExtension. However, the browser must not orphan a tab in a succession relationship with other tabs, if possible: if tab B is the successor of tab A, and tab C is the successor of tab B, and B is closed (or moved to another window), then tab A will take tab C as its successor. Preventing C from being orphaned in this way is called *moving a tab* (B) *from its line of succession*.

`tabs.moveInSuccession()` takes an array of tab IDs, and moves all of those tabs from their lines of succession. It then makes each tab the successor of the previous tab in the array, forming a chain. It can optionally set the successor of the last tab in the chain to an anchor tab, which is *not* moved from its line of succession. Additional options can control whether the tab chain is "prepended" or "appended" to the anchor tab, and whether the operation acts like a linked-list insert.

While the successor tab can be assigned with `tabs.update()`, it is often desirable to use `tabs.moveInSuccession()` to change successors, even if only a single tab is having its successor assigned. The difference is that `browser.tabs.moveInSuccession([a], b)` moves tab `a` from its line of succession, so any predecessors of `a` will adopt `a`'s previous successor; whereas if `browser.tabs.update(a, {successorTabId: b})` is used instead, tab `a` may continue to be the successor of other tabs, which could be unexpected. Another advantage of `tabs.moveInSuccession()` is that all of the succession changes happen atomically, without having to worry about races between calls to `tabs.update()` and `tabs.get()` and other operations like the user closing a tab.

Syntax
------

```js
browser.tabs.moveInSuccession([1, 3, 5, 7, 2, 9], 4, {insert:true})
```

### Parameters

`tabIds`

`array` of `integer`. An array of tab `ID`s. The order of the elements in the array defines the relationship of the tabs. Any invalid tab `ID`s, or tab `ID`s corresponding to tabs not in the same window as `tabId` (or the first tab in the array, if `tabId` is omitted), will be ignored—they will keep their current successors and predecessors.

`tabId` Optional

`integer`. The `ID` of the tab that will be the successor of the last tab in the `tabIds` array. If this `ID` is invalid or `tabs.TAB_ID_NONE`, the last tab will not have a successor. Defaults to `tabs.TAB_ID_NONE`.

`options` Optional

`object`.

`append` Optional

`boolean`. Determines whether to move the tabs in `tabIds` before or after `tabId` in the succession. If `false`, the tabs are moved before `tabId`, if `true`, the tabs are moved after `tabId`. Defaults to `false`.

`insert` Optional

`boolean`. Determines whether to link up the current predecessors or successor (depending on `options.append`) of `tabId` to the other side of the chain after it is prepended or appended. If true, one of the following happens: if `options.append` is `false`, the first tab in the array is set as the successor of any current predecessors of `tabId`; if `options.append` is `true`, the current successor of tabId is set as the successor of the last tab in the array. Defaults to `false`.

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

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


tabs.hide() - Mozilla

tabs.hide()
===========

Hides one or more tabs.

Hidden tabs are no longer visible in the browser's tabstrip. Hidden tabs are not automatically discarded: the code running in them continues to run. You can explicitly discard tabs whenever you hide them: although this is not appropriate in all situations, it will help to reduce the resources used by the browser.

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

Not all tabs are eligible for being hidden:

* Tabs that are pinned cannot be hidden.
* Tabs that are sharing the screen, microphone or camera cannot be hidden.
* The current active tab cannot be hidden.
* Tabs that are in the process of being closed cannot be hidden.

The first time an extension hides a tab, the browser will tell the user that the tab is being hidden, show them how they can access the hidden tab, and give them the option of disabling the extension instead.

To use this API you must have the "tabHide" permission.

Syntax
------

```js
let hiding = browser.tabs.hide(
  tabIds          // integer or integer array
)
```

### Parameters

`tabIds`

`integer` or `array` of `integer`. The IDs of the tab or tabs to hide.

If any of these tabs are not eligible for being hidden, they will not be hidden, but the call will still succeed and eligible tabs will still be hidden. For example, if you pass `[1, 3]`, and `1` identifies the active tab, then only `3` will be hidden.

However, if any of the tab IDs are invalid, the call will fail and no tabs will be hidden.

### Return value

A `Promise` that will be fulfilled with an array containing the IDs of the tabs that were hidden. If any error occurs, the promise will be rejected with an error message.

Examples
--------

Hide a single tab:

```js
function onHidden() {
  console.log(`Hidden`);
}

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

browser.tabs.hide(2).then(onHidden, onError);
```

Hide multiple tabs:

```js
function onHidden() {
  console.log(`Hidden`);
}

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

browser.tabs.hide([15, 14, 1]).then(onHidden, onError);
```

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

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


tabs.MutedInfoReason - Mozilla

tabs.MutedInfoReason
====================

Specifies the reason a tab was muted or unmuted.

Type
----

Values of this type are strings. Possible values are:

"capture"

Tab capture started, forcing a muted state change.

"extension"

An extension set the muted state. If this is the reason, `extensionId` in `tabs.mutedInfo` will contain the ID of the extension responsible.

"user"

The user set the muted state.

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

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

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


tabs.toggleReaderMode() - Mozilla

tabs.toggleReaderMode()
=======================

Toggles Reader Mode for the given tab.

This function toggles Reader Mode for the given tab. It takes a tab ID as a parameter: if this is omitted, the currently active tab is toggled.

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

Reader Mode, also known as Reader View, is a browser feature that makes it easier for the user to focus on an article by:

* hiding non-essential page elements like sidebars, footers, and ads
* changing the page's text size, contrast and layout for better readability.

Reader Mode is useful specifically for articles: meaning, pages that have a body of text content as their main feature. Pages that don't have an identifiable article are not eligible for display in Reader Mode. To find out whether a page is an article, check the `isArticle` property of `tabs.Tab`.

To find out whether a tab is already in Reader Mode, check the `isInReaderMode` property of `tabs.Tab`. To track tabs changing into or out of Reader Mode, you'll need to keep track of the current state of all tabs, and check when `isInReaderMode` changes:

```js
function handleUpdated(tabId, changeInfo, tabInfo) {
  if (changeInfo.status === "complete") {
    console.log(`Tab ${tabId} reader mode: ${tabInfo.isInReaderMode}`);
  }
}

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

Syntax
------

```js
let toggling = browser.tabs.toggleReaderMode(
  tabId            // optional integer
)
```

### Parameters

`tabId` Optional

`integer`. The ID of the tab to display in Reader Mode. Defaults to the selected tab of the current window.

### Return value

A `Promise` that will be fulfilled with no arguments when the tab has been updated. If any error occurs (for example, because the page was not an article), the promise will be rejected with an error message.

Examples
--------

This code switches every new page into Reader Mode, if that page is eligible for it:

```js
function switchToReaderMode(tabId, changeInfo, tabInfo) {
  if (changeInfo.isArticle) {
    browser.tabs.toggleReaderMode(tabId);
  }
}

browser.tabs.onUpdated.addListener(switchToReaderMode);
```

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

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


tabs.ZoomSettingsScope - Mozilla

tabs.ZoomSettingsScope
======================

Defines whether zoom changes will persist for the page's origin, or only take effect in this tab. This defaults to `per-origin` when `tabs.zoomSettingsMode` is "automatic", and is always `per-tab` otherwise.

Type
----

Values of this type are strings. Possible values are:

"per-origin"

All other tabs with the same origin as this tab will have the zoom changes applied to them. This scope is only available if `tabs.zoomSettingsMode` is "automatic".

"per-tab"

Zoom changes only take effect in this tab, and zoom changes in other tabs will not affect the zooming of this tab. Also:

* in Firefox the zoom level persists across page loads and navigation within the tab.
* in Chrome-based browsers zoom changes are reset on navigation; navigating a tab will always load pages with their per-origin zoom factors.

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

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

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


tabs.MutedInfo - Mozilla

tabs.MutedInfo
==============

This object contains a boolean indicating whether the tab is muted, and the reason for the last state change.

Type
----

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

`extensionId` Optional

`string`. The ID of the extension that last changed the muted state. Not set if an extension was not the reason the muted state last changed.

`muted`

`boolean`. Whether the tab is currently muted. Equivalent to whether the muted audio indicator is showing.

`reason` Optional

`tabs.MutedInfoReason`. The reason the tab was muted or unmuted. Not set if the tab's muted state has never been changed.

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

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

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