tabs.goBack() - Mozilla

tabs.goBack()
=============

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

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

Syntax
------

```js
let withGoingBack = browser.tabs.goBack(
  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 back to the previous page in the current tab:

```js
function onGoBack() {
  console.log("Gone back");
}

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

let goingBack = browser.tabs.goBack();
goingBack.then(onGoBack, onError);
```

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


tabs.captureTab() - Mozilla

tabs.captureTab()
=================

Creates a data URL encoding the image of an area of the given tab. You must have the `<all_urls>` permission to use this method.

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

Syntax
------

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

### Parameters

`tabId` Optional

`integer`. ID of the tab to capture. Defaults to the active tab in 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.captureTab();
  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.getAllInWindow() - Mozilla

tabs.getAllInWindow()
=====================

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

Gets details about all tabs in the specified window.

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

Syntax
------

```js
let getting = browser.tabs.getAllInWindow(
  windowId            // optional integer
)
```

### Parameters

`windowId` Optional

`integer`. Defaults to the current window.

### Return value

A `Promise` that will be fulfilled with an `array` of ``tabs.Tab`` objects, containing information about all the tabs in the window. 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.get() - Mozilla

tabs.get()
==========

Given a tab ID, get the tab's details as a `tabs.Tab` object.

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

Syntax
------

```js
let getting = browser.tabs.get(
  tabId              // integer
)
```

### Parameters

`tabId`

`integer`. ID of the tab to get.

### Return value

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

Examples
--------

Get information about a tab when it is activated:

```js
async function logListener(info) {
  try {
    let tabInfo = await browser.tabs.get(info.tabId);
    console.log(tabInfo);
  } catch (error) {
    console.error(error);
  }
}

browser.tabs.onActivated.addListener(logListener);
```

### Example extensions

* chill-out
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.insertCSS() - Mozilla

tabs.insertCSS()
================

Injects CSS into a page.

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

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

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

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

The inserted CSS may be removed again by calling `tabs.removeCSS()`.

This is an asynchronous function that returns a `Promise` (on Firefox only).

Syntax
------

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

### Parameters

`tabId` Optional

`integer`. The ID of the tab in which to insert the CSS. Defaults to the active tab of the current window.

`details`

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

`allFrames` Optional

`boolean`. If `true`, the CSS will be injected into all frames of the current page. If it is `false`, CSS is only injected into the top frame. Defaults to `false`.

`code` Optional

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

`cssOrigin` Optional

`string`. This can take one of two values: "user", to add the CSS as a user stylesheet or "author" to add it as an author stylesheet. If this option is omitted, the CSS is added as an author stylesheet.

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

`file` Optional

`string`. Path to a file containing the code to inject. In Firefox, relative URLs 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 an absolute URL, starting at the extension's root, like this: `"/path/to/stylesheet.css"`.

`frameId` Optional

`integer`. The frame where the CSS 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 be fulfilled with no arguments when all the CSS has been inserted. If any error occurs, the promise will be rejected with an error message.

Examples
--------

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

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

browser.browserAction.onClicked.addListener(() => {
  function onError(error) {
    console.log(`Error: ${error}`);
  }

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

This example inserts CSS which is loaded from a file packaged with the extension. The CSS is inserted into the tab whose ID is 2:

```js
browser.browserAction.onClicked.addListener(() => {
  function onError(error) {
    console.log(`Error: ${error}`);
  }

  let insertingCSS = browser.tabs.insertCSS(2, { file: "content-style.css" });
  insertingCSS.then(null, onError);
});
```

### Example extensions

* apply-css
* beastify
* session-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.discard() - Mozilla

tabs.discard()
==============

Discards one or more tabs.

Some browsers automatically "discard" unused tabs to free memory. Discarded tabs stay visible in the tabstrip. The browser remembers the tab's state and restores it when the user selects the tab. The details of when tabs are and what is discarded are browser-specific.

You can control whether the browser or this API discards a tab by setting its `autoDiscardable` property to `false` in `tabs.update`. This setting prevents the browser from discarding the tab. The tab can then only be discarded with this API.

It's not possible to discard the active tab or a tab whose document contains a `beforeunload` listener that would display a prompt.

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

Syntax
------

```js
let discarding = browser.tabs.discard(
  tabIds          // integer or integer array
)
```

### Parameters

`tabIds`

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

### Return value

A `Promise` that will be fulfilled with no arguments when all the specified tabs have been discarded. If any error occurs (for example, invalid tab IDs), the promise will be rejected with an error message.

If the ID of the active tab is passed in, it will not be discarded, but the promise will be fulfilled and any other tabs passed in will be discarded.

Examples
--------

Discard a single tab:

```js
function onDiscarded() {
  console.log(`Discarded`);
}

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

let discarding = browser.tabs.discard(2);
discarding.then(onDiscarded, onError);
```

Discard multiple tabs:

```js
function onDiscarded() {
  console.log(`Discarded`);
}

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

let discarding = browser.tabs.discard([15, 14, 1]);
discarding.then(onDiscarded, 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.


tabs.onActivated - Mozilla

tabs.onActivated
================

Fires when the active 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.onActivated.addListener(listener)
browser.tabs.onActivated.removeListener(listener)
browser.tabs.onActivated.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:

`activeInfo`

`object`. ID of the tab that was made active, and ID of its window. See the activeInfo section for more details.

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

### activeInfo

`previousTabId`

`integer`. The ID of the previous activated tab, if that tab is still open.

`tabId`

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

`windowId`

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

Examples
--------

Listen for and log tab activation events:

```js
function handleActivated(activeInfo) {
  console.log(`Tab ${activeInfo.tabId} was activated`);
}

browser.tabs.onActivated.addListener(handleActivated);
```

### Example extensions

* annotate-page
* bookmark-it
* chill-out
* cookie-bg-picker
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.onSelectionChanged - Mozilla

tabs.onSelectionChanged
=======================

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

Fires when the selected tab in a window changes.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

The function called when this event occurs. The function is passed 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 the selected tab changed in.

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

tabs.connect()
==============

Call this function to set up a connection between the extension's background scripts (or other privileged scripts, such as popup scripts or options page scripts) and any content scripts that belong to this extension and are running in the specified tab. This function returns a `runtime.Port` object.

When this is called, the `runtime.onConnect` event will be fired in any content script belonging to this extension that are running in the specified tab. The event listener will be passed another `runtime.Port` object. The two sides can then use the `Port` objects to exchange messages.

For more details, see connection-based messaging. You can message without creating a connection, for advice on choosing between the options, see Choosing between one-off messages and connection-based messaging.

Syntax
------

```js
browser.tabs.connect(
  tabId,      // integer
  connectInfo // optional object
)
```

### Parameters

`tabId`

`integer`. ID of the tab whose content scripts we want to connect to.

`connectInfo` Optional

An object with the following properties:

`name` Optional

`string`. Will be passed into `runtime.onConnect` event listeners in content scripts belonging to this extension and running in the specified tab.

`frameId` Optional

`integer`. Open a port to a specific frame identified by `frameId` instead of all frames in the tab.

### Return value

`runtime.Port`. A port that can be used to communicate with the content scripts running in the specified tab.

Examples
--------

In this example a background script listens for a click on a browser action, then connects to the currently active tab, then sends a message using the `Port` that's returned from `connect()`:

```js
function connectToTab(tabs) {
  if (tabs.length > 0) {
    let examplePort = browser.tabs.connect(tabs[0].id, {
      name: "tabs-connect-example",
    });
    examplePort.postMessage({ greeting: "Hi from background script" });
  }
}

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

browser.browserAction.onClicked.addListener(() => {
  let gettingActive = browser.tabs.query({
    currentWindow: true,
    active: true,
  });
  gettingActive.then(connectToTab, 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.onUpdated - Mozilla

tabs.onUpdated
==============

Fired when a tab is updated.

When the user navigates to a new URL in a tab, this typically generates several `onUpdated` events as various properties of the `tabs.Tab` object are updated. This includes the `url`, but also potentially the `title` and `favIconUrl` properties. The `status` property will cycle through `"loading"` and `"complete"`.

This event also fires for changes to a tab's properties that don't involve navigation, such as pinning and unpinning (which updates the `pinned` property) and muting or unmuting (which updates the `audible` and `mutedInfo` properties).

You can filter this event, making it only fire for tabs whose URLs match specific patterns, changes to particular properties, changes to a tab or window, or any combinations of these restrictions.

Syntax
------

```js
browser.tabs.onUpdated.addListener(
  listener, // function
  filter     // optional object
)
browser.tabs.onUpdated.removeListener(listener)
browser.tabs.onUpdated.hasListener(listener)
```

Events have three functions:

`addListener(callback, filter)`

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 updated tab.

`changeInfo`

`object`. Properties of the tab that changed. See the changeInfo section for more details.

`tab`

`tabs.Tab`. The new state of the tab.

`filter` Optional

`object`. A set of filters that restrict the events sent to this listener. This object can have one or more of these properties. Events are only sent if they satisfy all the filters provided.

`urls`

`Array`. An array of match patterns. Fires the event only for tabs whose current `url` property matches any one of the patterns.

`properties`

`Array`. An array of strings consisting of supported `tabs.Tab` object property names. Fires the event only for changes to one of the properties named in the array. These properties can be used:

* "attention"
* "autoDiscardable"
* "audible"
* "discarded"
* "favIconUrl"
* "hidden"
* "isArticle"
* "mutedInfo"
* "pinned"
* "status"
* "title"
* "url"

**Note:** The "url" value has been supported since Firefox 88. In Firefox 87 and earlier, "url" changes can be observed by filtering by "status".

`tabId`

`Integer`. Fires this event only for the tab identified by this ID.

`windowId`

`Integer`. Fires this event only for tabs in the window identified by this ID.

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

### changeInfo

Lists the changes to the state of the tab that is updated. To learn more about these properties, see the `tabs.Tab` documentation. Note that not all `tabs.Tab` properties are supported.

`attention` Optional

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

`audible` Optional

`boolean`. The tab's new audible state.

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

`discarded` Optional

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

`favIconUrl` Optional

`string`. The tab's new favicon URL. Not included when a tab loses its favicon (navigating from a page with a favicon to a page without one). Check `favIconUrl` in tab instead.

`hidden` Optional

`boolean`. True if the tab is `hidden`.

`isArticle` Optional

`boolean`. True if the tab is an article and is therefore eligible for display in `Reader Mode`.

`mutedInfo` Optional

`tabs.MutedInfo`. The tab's new muted state and the reason for the change.

`pinned` Optional

`boolean`. The tab's new pinned state.

`status` Optional

`string`. The status of the tab. Can be either *loading* or *complete*.

`title` Optional

`string`. The tab's new title.

`url` Optional

`string`. The tab's URL, if it has changed.

Examples
--------

Listen for and log all the change info and new state:

```js
function handleUpdated(tabId, changeInfo, tabInfo) {
  console.log(`Updated tab: ${tabId}`);
  console.log("Changed attributes: ", changeInfo);
  console.log("New tab Info: ", tabInfo);
}

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

Log changes to URLs:

```js
function handleUpdated(tabId, changeInfo, tabInfo) {
  if (changeInfo.url) {
    console.log(`Tab: ${tabId} URL changed to ${changeInfo.url}`);
  }
}

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

### Filtering examples

Log changes only to tabs whose `url` property is matched by `https://developer.mozilla.org/*` or `https://twitter.com/mozdevnet`:

```js
const pattern1 = "https://developer.mozilla.org/\*";
const pattern2 = "https://twitter.com/mozdevnet";

const filter = {
  urls: [pattern1, pattern2],
};

function handleUpdated(tabId, changeInfo, tabInfo) {
  console.log(`Updated tab: ${tabId}`);
  console.log("Changed attributes: ", changeInfo);
  console.log("New tab Info: ", tabInfo);
}

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

Log changes only to the `pinned` property of tabs (that is, pin and unpin actions):

```js
const filter = {
  properties: ["pinned"],
};

function handleUpdated(tabId, changeInfo, tabInfo) {
  console.log(`Updated tab: ${tabId}`);
  console.log("Changed attributes: ", changeInfo);
  console.log("New tab Info: ", tabInfo);
}

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

Combine both the previous filters, log only when the `pinned` property of tabs changes for tabs whose `url` property is matched by `https://developer.mozilla.org/*` or `https://twitter.com/mozdevnet`:

```js
const pattern1 = "https://developer.mozilla.org/\*";
const pattern2 = "https://twitter.com/mozdevnet";

const filter = {
  urls: [pattern1, pattern2],
  properties: ["pinned"],
};

function handleUpdated(tabId, changeInfo, tabInfo) {
  console.log(`Updated tab: ${tabId}`);
  console.log("Changed attributes: ", changeInfo);
  console.log("New tab Info: ", tabInfo);
}

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

Log changes only when the `pinned` property of tabs changes for tabs whose `url` property is matched by `https://developer.mozilla.org/*` or `https://twitter.com/mozdevnet` where the tab was part of the current browser window when the update event fired:

```js
const pattern1 = "https://developer.mozilla.org/\*";
const pattern2 = "https://twitter.com/mozdevnet";

const filter = {
  urls: [pattern1, pattern2],
  properties: ["pinned"],
  windowId: browser.windows.WINDOW\_ID\_CURRENT,
};

function handleUpdated(tabId, changeInfo, tabInfo) {
  console.log(`Updated tab: ${tabId}`);
  console.log("Changed attributes: ", changeInfo);
  console.log("New tab Info: ", tabInfo);
}

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

### Example extensions

* annotate-page
* apply-css
* bookmark-it
* chill-out
* cookie-bg-picker
* history-deleter
* session-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.ZoomSettingsMode - Mozilla

tabs.ZoomSettingsMode
=====================

Defines how zoom changes are handled. Extensions can pass this value into `tabs.setZoomSettings()` to control how the browser handles attempts to change zoom settings for a tab. Defaults to "automatic".

Type
----

Values of this type are strings. Possible values are:

"automatic"

Zoom changes are handled normally by the browser.

"disabled"

Disables all zooming in the tab. The tab will revert to the default zoom level, and all attempted zoom changes will be ignored.

"manual"

The extension will handle zoom changes itself, by listening for the `tabs.onZoomChange` event and scaling the page accordingly. This mode does not support `per-origin` zooming: it will ignore the `scope` `zoom setting` and always use `per-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.onRemoved - Mozilla

tabs.onRemoved
==============

Fired when a tab is closed.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`tabId`

`integer`. ID of the tab that closed.

`removeInfo`

`object`. The tab's window ID, and a boolean indicating whether the window is also being closed. See the removeInfo section for more details.

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

### removeInfo

`windowId`

`integer`. The window whose tab is closed.

`isWindowClosing`

`boolean`. `true` if the tab is being closed because its window is being closed.

Examples
--------

Listen for close events, and log the info:

```js
function handleRemoved(tabId, removeInfo) {
  console.log(`Tab: ${tabId} is closing`);
  console.log(`Window ID: ${removeInfo.windowId}`);
  console.log(`Window is closing: ${removeInfo.isWindowClosing}`);
}

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

### 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.


permissions.onAdded - Mozilla

permissions.onAdded
===================

Fired when the extension granted new permissions.

Syntax
------

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

`permissions`

`permissions.Permissions` object containing the permissions that were granted.

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

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

Examples
--------

```js
function handleAdded(permissions) {
  console.log(`New API permissions: ${permissions.permissions}`);
  console.log(`New host permissions: ${permissions.origins}`);
}

browser.permissions.onAdded.addListener(handleAdded);
```

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


permissions.request() - Mozilla

permissions.request()
=====================

Ask for the set of permissions listed in the given `permissions.Permissions` object.

The `Permissions` argument may contain either an `origins` property, which is an array of host permissions, or a `permissions` property, which is an array of API permissions, or both. Permissions must come from the set of permissions defined in the `optional_permissions` manifest.json key. The `origins` property may include permissions that match a subset of the hosts matched by an optional permission: for example, if optional\_permissions include "\*://mozilla.org/", then `permissions.origins` may include "https://developer.mozilla.org/".

The request can only be made inside the handler for a user action.

Depending on a circumstances, the browser will probably handle the request by asking the user whether to grant the requested permissions. Only a single request is made for all requested permissions: thus either all permissions are granted or none of them are.

Any permissions granted are retained by the extension, even over upgrade and disable/enable cycling.

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

Syntax
------

```js
let requesting = browser.permissions.request(
  permissions                // Permissions object
)
```

### Parameters

`permissions`

A `permissions.Permissions` object.

### Return value

A `Promise` that is fulfilled with `true` if the extension is now granted all the permissions listed in the `permissions` argument, or `false` otherwise.

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

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

Examples
--------

This code adds a click handler that asks for various permissions, then logs the result of the request and the extension's permissions after the request completed.

```js
const permissionsToRequest = {
  permissions: ["bookmarks", "history"],
  origins: ["https://developer.mozilla.org/"],
};

async function requestPermissions() {
  function onResponse(response) {
    if (response) {
      console.log("Permission was granted");
    } else {
      console.log("Permission was refused");
    }
    return browser.permissions.getAll();
  }

  const response = await browser.permissions.request(permissionsToRequest);
  const currentPermissions = await onResponse(response);

  console.log(`Current permissions:`, currentPermissions);
}

document
  .querySelector("#request")
  .addEventListener("click", requestPermissions);
```

### Example extensions

* dnr-dynamic-with-options
* dnr-redirect-url
* permissions

**Note:** Currently has a bug with requesting origins and requesting permissions on the about:addons page.

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


permissions.contains() - Mozilla

permissions.contains()
======================

Check whether the extension has the permissions listed in the given `permissions.Permissions` object.

The `Permissions` argument may contain either an origins property, which is an array of host permissions, or a `permissions` property, which is an array of API permissions, or both.

This is an asynchronous function that returns a `Promise`. The promise is fulfilled with true only if all the extension currently has all the given permissions. For host permissions, if the extension's permissions pattern-match the permissions listed in `origins`, then they are considered to match.

Syntax
------

```js
let getContains = browser.permissions.contains(
  permissions                // Permissions object
)
```

### Parameters

`permissions`

A `permissions.Permissions` object.

### Return value

A `Promise` that will be fulfilled with `true` if the extension already has all the permissions listed in the `permissions` argument, or `false` otherwise.

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

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

Examples
--------

```js
// Extension permissions are:
// "webRequest", "tabs", "\*://\*.mozilla.org/\*"

let testPermissions1 = {
  origins: ["\*://mozilla.org/"],
  permissions: ["tabs"],
};

const testResult1 = await browser.permissions.contains(testPermissions1);
console.log(testResult1); // true

let testPermissions2 = {
  origins: ["\*://mozilla.org/"],
  permissions: ["tabs", "alarms"],
};

const testResult2 = await browser.permissions.contains(testPermissions2);
console.log(testResult2); // false, "alarms" doesn't match

let testPermissions3 = {
  origins: ["https://developer.mozilla.org/"],
  permissions: ["tabs", "webRequest"],
};

const testResult3 = await browser.permissions.contains(testPermissions3);
console.log(testResult3); // true: "https://developer.mozilla.org/", matches: "\*://\*.mozilla.org/\*"

let testPermissions4 = {
  origins: ["https://example.org/"],
};

const testResult4 = await browser.permissions.contains(testPermissions4);
console.log(testResult4); // false: "https://example.org/", `origins` doesn't match
```

### Example extensions

* dnr-redirect-url

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


permissions.remove() - Mozilla

permissions.remove()
====================

Ask to give up the permissions listed in the given `permissions.Permissions` object.

The `Permissions` argument may contain either an `origins` property, which is an array of host permissions, or a `permissions` property, which is an array of API permissions, or both. Permissions must come from the set of permissions defined in the `optional_permissions` manifest.json key.

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

Syntax
------

```js
let removing = browser.permissions.remove(
  permissions                // Permissions object
)
```

### Parameters

`permissions`

A `permissions.Permissions` object.

### Return value

A `Promise` that is fulfilled with `true` if the permissions listed in the `permissions` argument are now not granted to the extension, or `false` otherwise.

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

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

Examples
--------

This code adds a click handler that removes a given permission.

```js
const permissionToRemove = {
  permissions: ["history"],
};

async function remove() {
  console.log("removing");
  const removed = await browser.permissions.remove(permissionToRemove);
  console.log(removed);
}

document.querySelector("#remove").addEventListener("click", remove);
```

### Example extensions

* dnr-dynamic-with-options
* dnr-redirect-url
* permissions

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


Permissions - Mozilla

Permissions
===========

A `Permissions` object represents a collection of permissions.

Type
----

An `object` with the following properties:

`origins` Optional

An array of match patterns, representing host permissions.

`permissions` Optional

An array of named permissions, including API permissions and clipboard permissions.

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


permissions.getAll() - Mozilla

permissions.getAll()
====================

Retrieve a `permissions.Permissions` object containing all the permissions currently granted to the extension.

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

Syntax
------

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

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with a `permissions.Permissions` object containing all the permissions currently granted to the extension. This includes all permissions the extension has listed in the `permissions` key, and any permissions listed in `optional_permissions` that the extension has been granted by calling `permissions.request()`.

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

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

Examples
--------

```js
// Extension permissions are:
// "webRequest", "tabs", "\*://\*.mozilla.org/\*"

const currentPermissions = await browser.permissions.getAll();

console.log(currentPermissions.permissions); // [ "webRequest", "tabs" ]
console.log(currentPermissions.origins); // [ "\*://\*.mozilla.org/\*" ]
```

### Example extensions

* dnr-dynamic-with-options
* permissions

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


permissions.onRemoved - Mozilla

permissions.onRemoved
=====================

Fired when some permissions are removed from the extension.

Syntax
------

```js
browser.permissions.onRemoved.addListener(listener)
browser.permissions.onRemoved.removeListener(listener)
browser.permissions.onRemoved.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`permissions`

`permissions.Permissions` object containing the permissions that were removed.

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

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

Examples
--------

```js
function handleRemoved(permissions) {
  console.log(`Removed API permissions: ${permissions.permissions}`);
  console.log(`Removed host permissions: ${permissions.origins}`);
}

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

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


topSites.get() - Mozilla

topSites.get()
==============

Gets an array containing information about pages that the user has visited often and recently.

Browsers keep a list of pages that the user visits often and recently. They use this list to help the user get back to these places easily. For example, Firefox by default provides a list of the most-visited pages in the "New Tab" page.

To determine which pages appear in the list, and the order in which they appear, the browser combines "frequency" - how often the user has visited the page - and "recency" - how recently the user visited the page.

The browser may then apply further filtering to this list before presenting it to the user. For example, in Firefox the "New Tab" page only lists one page per domain, and the user is able to block pages from appearing in the list.

The `topSites.get()` API enables an extension to get access to this list. Called without any options, it will provide the filtered list of pages - that is, the one that appears in the "New Tab" page. However, by providing various options it's possible for an extension to get the unfiltered list of pages.

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

To use the topSites API you must have the "topSites" API permission.

Syntax
------

```js
let gettingTopSites = browser.topSites.get(
    options  // object
)
```

### Parameters

`options`

`object`. Options to modify the list of pages returned. This may include any of the following properties:

`includeBlocked` Optional

`Boolean`. Include pages that the user has removed from the "New Tab" page. Defaults to `false`.

`includeFavicon` Optional

`Boolean`. Include favicons in the results, for pages where they are available. Defaults to `false`.

`includePinned` Optional

`Boolean`. Includes sites that the user has pinned to the Firefox new tab.
 Defaults to `false`.

`includeSearchShortcuts` Optional

`Boolean`. Includes search shortcuts that appear on the Firefox new tab.
 Defaults to `false`.

`limit` Optional

`Integer`. The number of pages to return. This must be a number between 1 and 100, inclusive. Defaults to 12.

`newtab` Optional

`Boolean`. If included, the method returns the list of pages returned when the user opens a new tab. If included, and set to `true`, the method ignores all other parameters except `limit` and `includeFavicon`. Defaults to `false`.

`onePerDomain` Optional

`Boolean`. Only include one page per domain. Defaults to `true`.

### Return value

A `Promise`. This will be fulfilled with an array of `MostVisitedURL` objects, one for each page listed in the browser's "New Tab" page. If an 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.

Examples
--------

This code logs the title and URL for all pages in the "New Tab" page:

```js
function logTopSites(topSitesArray) {
  for (const topSite of topSitesArray) {
    console.log(`Title: ${topSite.title}, URL: ${topSite.url}`);
  }
}

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

browser.topSites.get().then(logTopSites, onError);
```

This code logs the title and URL for all top pages, including ones the user has blocked, and potentially including multiple pages in the same domain:

```js
function logTopSites(topSitesArray) {
  for (const topSite of topSitesArray) {
    console.log(`Title: ${topSite.title}, URL: ${topSite.url}`);
  }
}

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

browser.topSites
  .get({
    includeBlocked: true,
    onePerDomain: false,
  })
  .then(logTopSites, onError);
```

### Example extensions

* top-sites

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


topSites.MostVisitedURL - Mozilla

topSites.MostVisitedURL
=======================

The `MostVisitedURL` type contains two properties: the title of a page and its URL.

Type
----

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

`favicon` Optional

`String`. A data: URL containing the favicon for the page, if `includeFavicon` was given in `topSites.get()` and the favicon was available.

`title`

`String`. The page's title.

`url`

`String`. The page's URL.

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

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

Examples
--------

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


commands.update() - Mozilla

commands.update()
=================

Change the description or keyboard shortcut for the given command.

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

Syntax
------

```js
browser.commands.update(
  details // object
);
```

### Parameters

`details`

`object`. An object with the following properties:

`name`

`string`. The name of the command to update. This must match the name of an existing command, as given for example in the `name` property of the `commands.Command` object.

`description` Optional

`string`. A new description to set for the command.

`shortcut` Optional

`string`. A new shortcut to set for the command. This can be:

* an empty string to clear the shortcut.
* a string matching the format of the `commands` manifest.json key to set a new shortcut key. If the string does not match this format, the function throws an error.

### Return value

A `Promise` that will be fulfilled with no arguments when the shortcut has been updated. The promise will be rejected with an error if the command could not be found.

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

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

Examples
--------

Updates the command named "my-command" with the given shortcut value, when the user clicks "update":

```js
const commandName = "my-command";

function updateShortcut() {
  browser.commands.update({
    name: commandName,
    shortcut: document.querySelector("#shortcut").value,
  });
}

document.querySelector("#update").addEventListener("click", updateShortcut);
```

### Example extensions

* commands


onChanged - Mozilla

onChanged
=========

Fired when the keyboard shortcut for a command is changed.

The listener is passed an object containing the name of the command, its new active shortcut, and its old shortcut.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

The function called when a command's shortcut changes. The function is passed these arguments:

`changeInfo`

`object`. An object containing the name of the command, its new active shortcut, and its old shortcut.

`name`

`string`. Name of the command. This matches the name given to the command in its manifest.json entry.

`newShortcut`

`string`. The new active shortcut for this command, or blank if no shortcut is active.

`oldShortcut`

`string`. The shortcut that was active for this command, or blank if no shortcut was active.

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

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

Examples
--------

You could log changes to command shortcuts like this:

```js
function handleChanged(changeInfo) {
  console.log(`Shortcut for: ${changeInfo.name} changed`);
  console.log(`From: ${changeInfo.oldShortcut}`);
  console.log(`To: ${changeInfo.newShortcut}`);
}

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


commands.reset() - Mozilla

commands.reset()
================

Resets the given command's description and keyboard shortcut to the values given in the extension's `commands` manifest.json key.

This effectively undoes any changes made to the command using the `commands.update()` function.

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

Syntax
------

```js
browser.commands.reset(
  name // string
);
```

### Parameters

`name`

`string`. Name of the command to reset, as given by the `name` property of the `commands.Command` object.

### Return value

A `Promise` that will be fulfilled with no arguments when the shortcut has been reset.

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

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

Examples
--------

Resets the command named "my-command" when the user clicks the "reset" button:

```js
const commandName = "my-command";

function resetShortcut() {
  browser.commands.reset(commandName);
}

document.querySelector("#reset").addEventListener("click", resetShortcut);
```

### Example extensions

* commands


getAll() - Mozilla

getAll()
========

Gets all commands for the extension that you have registered using the `commands` manifest.json key.

The commands are returned as an array of `commands.Command` objects. Alternately, if you are using the promise-based version of the API, `browser.commands.getAll()`, the commands are passed into the `onFulfilled` argument to `Promise.then()`.

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

Syntax
------

```js
let getCommands = browser.commands.getAll();
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an array of ``commands.Command`` objects, one for each command registered for the extension. If no commands were registered, the array will be empty.

Examples
--------

```js
function logCommands(commands) {
  commands.forEach((command) => {
    console.log(command);
  });
}

let getCommands = browser.commands.getAll();
getCommands.then(logCommands);
```

### Example extensions

* commands

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

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

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


Command - Mozilla

Command
=======

Information about a command. This contains the information specified for the command in the `commands` manifest.json key.

An array of these objects is returned from `commands.getAll()`.

Type
----

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

`name` Optional

`string`. Name of this command. This will be passed into the `commands.onCommand` event listener.

`description` Optional

`string`. Description of this command. This is primarily used to explain to the user what this command does.

`shortcut` Optional

`string`. Key(s) used to execute this command, specified as a string like "Ctrl+Shift+Y".

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


onCommand - Mozilla

onCommand
=========

Fired when a command is executed using its associated keyboard shortcut.

The listener is passed the command's name. This matches the name given to the command in its manifest.json entry.

Syntax
------

```js
browser.commands.onCommand.addListener(listener)
browser.commands.onCommand.removeListener(listener)
browser.commands.onCommand.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 a user enters the command's shortcut. The function is passed this argument:

`name`

`string`. Name of the command. This matches the name given to the command in its manifest.json entry.

`tab`

`tabs.Tab`. The tab that was active when the command shortcut was entered.

Examples
--------

Given a manifest.json entry like this:

```json
"commands": {
  "toggle-feature": {
    "suggested\_key": {
      "default": "Ctrl+Shift+Y"
    },
    "description": "Send a 'toggle-feature' event"
  }
}
```

You could listen for this particular command like this:

```js
browser.commands.onCommand.addListener((command) => {
  if (command === "toggle-feature") {
    console.log("toggling the feature!");
  }
});
```

### Example extensions

* commands
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.commands` API.


omnibox.onDeleteSuggestion - Mozilla

omnibox.onDeleteSuggestion
==========================

 Fired whenever the user deletes a suggestion.
 A suggestion can be deleted when `SuggestResult``.deletable` is set to true.

Syntax
------

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

`text`

`string`. The description of the deleted suggestion.

Examples
--------

This example prints the deleted suggestion to the console:

```js
function logDeletedSuggestion(text) {
  console.log(`The user deleted: ${text}`);
}

browser.omnibox.onDeleteSuggestion.addListener(logDeletedSuggestion);
```

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

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.


omnibox.onInputEntered - Mozilla

omnibox.onInputEntered
======================

Fired when the user has selected one of the suggestions your extension has added to the address bar's drop-down list.

Use this event to handle the user's selection, generally by opening the corresponding page. The event listener is passed:

* the user's selection
* a `omnibox.OnInputEnteredDisposition`: use this to determine whether to open the new page in the current tab, in a new foreground tab, or in a new background tab.
Syntax
------

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

The listener function will be passed two parameters: a string `text`, and an `omnibox.OnInputEnteredDisposition`.

### Parameters

`text`

`String`. This is the value of the `content` property of the `omnibox.SuggestResult` object that the user selected.

`disposition`

`OnInputEnteredDisposition`. A `omnibox.OnInputEnteredDisposition` enumeration, indicating whether the extension should open the page in the current tab, in a new foreground tab, or in a new background tab.

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

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

Examples
--------

This example interprets the user's input as a CSS property name and populates the drop-down list with one `omnibox.SuggestResult` object for each CSS property matching the input. The `description` property of `SuggestResult` is the full name of the property, and the `content` is the MDN page for that property.

The example also listens to `omnibox.onInputEntered`, and opens the MDN page corresponding to the selection, according to the `omnibox.OnInputEnteredDisposition` argument.

```js
browser.omnibox.setDefaultSuggestion({
  description: "Type the name of a CSS property",
});

/\*
Very short list of a few CSS properties.
\*/
const props = [
  "animation",
  "background",
  "border",
  "box-shadow",
  "color",
  "display",
  "flex",
  "flex",
  "float",
  "font",
  "grid",
  "margin",
  "opacity",
  "overflow",
  "padding",
  "position",
  "transform",
  "transition",
];

const baseURL = "https://developer.mozilla.org/en-US/docs/Web/CSS/";

/\*
Return an array of SuggestResult objects,
one for each CSS property that matches the user's input.
\*/
function getMatchingProperties(input) {
  const result = [];
  for (const prop of props) {
    if (prop.startsWith(input)) {
      console.log(prop);
      const suggestion = {
        content: `${baseURL}${prop}`,
        description: prop,
      };
      result.push(suggestion);
    } else if (result.length !== 0) {
      return result;
    }
  }
  return result;
}

browser.omnibox.onInputChanged.addListener((input, suggest) => {
  suggest(getMatchingProperties(input));
});

browser.omnibox.onInputEntered.addListener((url, disposition) => {
  switch (disposition) {
    case "currentTab":
      browser.tabs.update({ url });
      break;
    case "newForegroundTab":
      browser.tabs.create({ url });
      break;
    case "newBackgroundTab":
      browser.tabs.create({ url, active: false });
      break;
  }
});
```

### Example extensions

* firefox-code-search

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


omnibox.OnInputEnteredDisposition - Mozilla

omnibox.OnInputEnteredDisposition
=================================

The **`omnibox.OnInputEnteredDisposition`** type describes how the extension should handle a user selection from the suggestions in the address bar's drop-down list.

It's passed into the `omnibox.onInputEntered` event listener, along with the selection itself.

Type
----

Values of this type are strings. They may take any one of the following values:

"currentTab"

Open the selection in the current tab.

"newForegroundTab"

Open the selection in a new tab, and bring this new tab into the foreground.

"newBackgroundTab"

Open the selection in a new background tab, keeping the current tab in the foreground.

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


omnibox.setDefaultSuggestion() - Mozilla

omnibox.setDefaultSuggestion()
==============================

Set the default suggestion to appear in the address bar drop-down list when the user starts interacting with your extension.

Once the user has entered your keyword and started interacting with your extension, the default suggestion will always appear first in the drop-down list. Unlike the suggestions you supply in `omnibox.onInputChanged`, this item can't be selected. Use it to provide the user with some guidance about what to type and what they can expect to see when they do.

Syntax
------

```js
browser.omnibox.setDefaultSuggestion(
  suggestion            // object
)
```

### Parameters

`suggestion`

`object`. An object containing a single string property `description`, which will be displayed as the first item in the drop-down when the user starts interacting with your extension.

### Return value

None.

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

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

Examples
--------

```js
browser.omnibox.setDefaultSuggestion({
  description: "Type the name of a CSS property",
});
```

### Example extensions

* firefox-code-search

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


omnibox.onInputStarted - Mozilla

omnibox.onInputStarted
======================

Fired when the user starts interacting with your extension by entering its keyword in the address bar and then pressing the space key.

This will be sent before any `omnibox.onInputChanged` events.

Syntax
------

```js
browser.omnibox.onInputStarted.addListener(listener)
browser.omnibox.onInputStarted.removeListener(listener)
browser.omnibox.onInputStarted.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

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

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

Examples
--------

```js
browser.omnibox.onInputStarted.addListener(() => {
  console.log("User has started interacting with me.");
});
```

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


omnibox.onInputCancelled - Mozilla

omnibox.onInputCancelled
========================

Fired when the user has cancelled their interaction with your extension (for example, by clicking outside the address bar).

Syntax
------

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

The listener function is passed no parameters.

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

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

Examples
--------

```js
browser.omnibox.onInputCancelled.addListener(() => {
  console.log("The user cancelled the session.");
});
```

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


omnibox.SuggestResult - Mozilla

omnibox.SuggestResult
=====================

The **`omnibox.SuggestResult`** type defines a suggestion that the extension can add to the address bar's drop-down list.

The extension's `omnibox.onInputChanged` event listener is passed a callback. To populate the address bar's drop-down list in response to the user's input, the extension can pass an array of `omnibox.SuggestResult` objects into this callback.

Type
----

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

`content`

This is the value that will appear in the address bar itself when the user highlights this suggestion in the drop-down list. This is also the string sent to the `omnibox.onInputEntered` event listener if the user selects this suggestion. If the string is the same as what the user has already typed, this entry will not appear in the drop-down list.

`deletable`

Whether the suggest result can be deleted by the user.

`description`

This is the string that's displayed in the address bar's drop-down list.

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


omnibox.onInputChanged - Mozilla

omnibox.onInputChanged
======================

Fired whenever the user changes their input, after they have started interacting with your extension by entering its keyword in the address bar and then pressing the space key.

This is the event you'll use to populate the address bar's drop-down list with suggestions. The event listener is passed:

* the current user input (not including the keyword itself or the space after it)
* a function which the listener can call with an array of `omnibox.SuggestResult` objects, one for each suggestion. Only the first six suggestions will be displayed.
Syntax
------

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

The listener function is passed two parameters: a string `text`, and the function `suggest`.

### Parameters

`text`

`String`. The current user input in the address bar, not including the extension's keyword itself or the space after the keyword. Use this to decide which suggestions to display in the drop-down list.

`suggest`

`Function`. A function that the event listener can call to supply suggestions for the address bar's drop-down list. The function expects to receive an array of `omnibox.SuggestResult` objects, one for each suggestion. Only the first six suggestions will be displayed.

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

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

Examples
--------

This example interprets the user's input as a CSS property name and populates the drop-down list with one `omnibox.SuggestResult` object for each CSS property matching the input. The `description` property of `SuggestResult` is the full name of the property, and the `content` is the MDN page for that property.

The example also listens to `omnibox.onInputEntered`, and opens the MDN page corresponding to the selection, according to the `omnibox.OnInputEnteredDisposition` argument.

```js
browser.omnibox.setDefaultSuggestion({
  description: "Type the name of a CSS property",
});

/\*
Very short list of a few CSS properties.
\*/
const props = [
  "animation",
  "background",
  "border",
  "box-shadow",
  "color",
  "display",
  "flex",
  "flex",
  "float",
  "font",
  "grid",
  "margin",
  "opacity",
  "overflow",
  "padding",
  "position",
  "transform",
  "transition",
];

const baseURL = "https://developer.mozilla.org/en-US/docs/Web/CSS/";

/\*
Return an array of SuggestResult objects,
one for each CSS property that matches the user's input.
\*/
function getMatchingProperties(input) {
  const result = [];
  for (const prop of props) {
    if (prop.startsWith(input)) {
      console.log(prop);
      const suggestion = {
        content: `${baseURL}${prop}`,
        description: prop,
      };
      result.push(suggestion);
    } else if (result.length !== 0) {
      return result;
    }
  }
  return result;
}

browser.omnibox.onInputChanged.addListener((input, suggest) => {
  suggest(getMatchingProperties(input));
});

browser.omnibox.onInputEntered.addListener((url, disposition) => {
  switch (disposition) {
    case "currentTab":
      browser.tabs.update({ url });
      break;
    case "newForegroundTab":
      browser.tabs.create({ url });
      break;
    case "newBackgroundTab":
      browser.tabs.create({ url, active: false });
      break;
  }
});
```

### Example extensions

* firefox-code-search

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


sessions.Filter - Mozilla

sessions.Filter
===============

The `Filter` object enables you to restrict the number of `Session` objects returned by a call to `sessions.getRecentlyClosed()`.

Type
----

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

`maxResults` Optional

`number`. The maximum number of results to return.

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

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

Examples
--------

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


sessions.removeTabValue() - Mozilla

sessions.removeTabValue()
=========================

Removes a value previously stored by a call to `sessions.setTabValue`.

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

Syntax
------

```js
let removing = browser.sessions.removeTabValue(
  tabId,    // integer
  key       // string
)
```

### Parameters

`tabId`

`integer`. ID of the tab whose data you are trying to remove. Error is thrown if ID is invalid.

`key`

`string`. Key identifying the particular value to remove. This needs to match the key previously given in `sessions.setTabValue`.

### Return value

A `Promise` that will be resolved no arguments if the item was successfully removed. If the call failed (for example, because the tab ID could not be found) then the promise will be rejected with an error message.

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

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

Examples
--------

This code adds two context menu items: one stores a value associated with the current tab, the other one removes it:

```js
async function setOnActiveTab() {
  let tabArray = await browser.tabs.query({
    currentWindow: true,
    active: true,
  });
  let tabId = tabArray[0].id;
  await browser.sessions.setTabValue(tabId, "my-key", "my-value");
}

async function removeFromActiveTab() {
  let tabArray = await browser.tabs.query({
    currentWindow: true,
    active: true,
  });
  let tabId = tabArray[0].id;
  await browser.sessions.removeTabValue(tabId, "my-key");
}

browser.menus.create({
  id: "add-my-item",
  title: "add item",
  contexts: ["all"],
});

browser.menus.create({
  id: "remove-my-item",
  title: "remove item",
  contexts: ["all"],
});

browser.menus.onClicked.addListener((info) => {
  if (info.menuItemId === "add-my-item") {
    setOnActiveTab();
  } else {
    removeFromActiveTab();
  }
});
```


sessions.MAX_SESSION_RESULTS - Mozilla

sessions.MAX\_SESSION\_RESULTS
==============================

This value represents the maximum number of sessions that will be returned by a call to `sessions.getRecentlyClosed()`. It is read-only for WebExtension code, and is set to 25.

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


sessions.Session - Mozilla

sessions.Session
================

The `Session` object represents a tab or window that the user has closed in the current browsing session.

Sessions are represented as `Tab` objects if the tab was closed but its window was not closed: for example, because the user clicked the "Close tab" button, and this tab was not the only tab in its window.

Sessions are represented as `Window` objects if the window was closed: for example, because the user clicked the "Close window" button, or closed the only tab open in a window.

Note that different browsers might have a different idea of when a session is a Tab and when it is a Window. For example:

* In Chrome a session is recorded as a Window if the user closes a window that contained more than one tab. If the user closed a window that contained only one tab, this is recorded as a Tab.
* In Firefox, a session is recorded as a Window if the user closes a window (or a tab that was the last tab in the window), and a Tab if the user closes a tab that wasn't the last tab in its window.

The Tab object for a tab that is open will not have a `sessionId`. When the tab is closed, it will have a `sessionId` but will not have a tab `id`. If the tab is restored, it will get a new tab `id` and will lose the `sessionId`.

Type
----

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

`lastModified`

`number`. The time the tab or window was closed, in milliseconds since the epoch.

`tab` Optional

`object`. If the object represents a closed tab, then this property is present and will be a `tabs.Tab` object. This will contain `url`, `title`, and `favIconUrl` only if the extension has the "tabs" permission or host permissions to access the tab's URL.

`window` Optional

`object`. If the object represents a closed window, then this property is present and will be a `windows.Window` object.

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

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

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


sessions.getWindowValue() - Mozilla

sessions.getWindowValue()
=========================

Retrieves a value previously stored by a call to `sessions.setWindowValue`.

You can retrieve a value from a window even over a close/restore cycle: meaning that if you set a value, then the user closes the window, then restores the window using the browser's "restore window" feature (for example, by pressing Control+Shift+N), then you will be able to retrieve the value from the restored window. Note, though, that a restored window does not get the same ID as the original, so the ID you pass into `getWindowValue()` will be different from the ID you passed into `setWindowValue()`, even though they both refer to the same window.

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

Syntax
------

```js
let retrieving = browser.sessions.getWindowValue(
  windowId,    // integer
  key          // string
)
```

### Parameters

`windowId`

`integer`. ID of the window whose data you are trying to retrieve. Error is thrown if ID is invalid.

`key`

`string`. Key identifying the particular value to retrieve. This needs to match the key previously given in `sessions.setWindowValue`.

### Return value

A `Promise` that will be resolved with the value if it exists, or `undefined` if it does not exist. If the call failed (for example, because the window ID could not be found) then the promise will be rejected with an error message.

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

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

Examples
--------

Log the value of "my-key" for all newly created windows (this will include any windows that have been restored):

```js
function onGetResolved(r) {
  console.log(`success: ${r}`);
}

function onGetRejected(e) {
  console.log(`error: ${e}`);
}

browser.windows.onCreated.addListener((window) => {
  browser.sessions
    .getWindowValue(window.id, "my-key")
    .then(onGetResolved, onGetRejected);
});
```


sessions.getRecentlyClosed() - Mozilla

sessions.getRecentlyClosed()
============================

Returns an array of `Session` objects, representing windows and tabs that were closed in the current browsing session (that is: the time since the browser was started).

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

Syntax
------

```js
let gettingSessions = browser.sessions.getRecentlyClosed(
  filter             // optional object
)
```

### Parameters

`filter` Optional

`object`. A `sessions.Filter` object that limits the set of sessions returned.

### Return value

A `Promise`. This will be fulfilled with an array of `Session` objects, one for each of the most recently closed tabs or windows in the current browsing session, up to `sessions.MAX_SESSION_RESULTS` or the number included in the `filter` argument, whichever is smaller. The array is given in the reverse of the order in which tabs or windows were closed, so the most recently closed will be at index 0.

If an 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.

Examples
--------

This code restores the single most recently-closed session, whether it's a tab or a window:

```js
function restoreMostRecent(sessionInfos) {
  if (!sessionInfos.length) {
    console.log("No sessions found");
    return;
  }
  let sessionInfo = sessionInfos[0];
  if (sessionInfo.tab) {
    browser.sessions.restore(sessionInfo.tab.sessionId);
  } else {
    browser.sessions.restore(sessionInfo.window.sessionId);
  }
}

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

browser.browserAction.onClicked.addListener(() => {
  let gettingSessions = browser.sessions.getRecentlyClosed({
    maxResults: 1,
  });
  gettingSessions.then(restoreMostRecent, onError);
});
```

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


sessions.restore() - Mozilla

sessions.restore()
==================

Restores a closed tab or window. Restoring doesn't just reopen the tab or window: it also restores the tab's navigation history so the back/forward buttons will work. Restoring a window will restore all the tabs that the window contained when it was closed.

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

Syntax
------

```js
let restoringSession = browser.sessions.restore(
  sessionId             // string
)
```

### Parameters

`sessionId`

`string`. A string containing the session ID for the window or tab to restore. This can be found in the `sessionId` property of the `Tab` or `Window` object in the `Session` returned from `sessions.getRecentlyClosed()`.

### Return value

A `Promise`. This will be fulfilled with a `Session` object representing the session that was restored.

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

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

Examples
--------

This restores the single most recently-closed session, whether it's a window or tab:

```js
function restoreMostRecent(sessionInfos) {
  if (!sessionInfos.length) {
    console.log("No sessions found");
    return;
  }
  let sessionInfo = sessionInfos[0];
  if (sessionInfo.tab) {
    browser.sessions.restore(sessionInfo.tab.sessionId);
  } else {
    browser.sessions.restore(sessionInfo.window.sessionId);
  }
}

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

browser.browserAction.onClicked.addListener(() => {
  let gettingSessions = browser.sessions.getRecentlyClosed({
    maxResults: 1,
  });
  gettingSessions.then(restoreMostRecent, onError);
});
```

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

Known issues
------------

Bug 1538119 - Duplicate sessionId in browser.sessions.getRecentlyClosed() after "Restore previous session"


sessions.setTabValue() - Mozilla

sessions.setTabValue()
======================

Stores a key/value pair to associate with a given tab. You can subsequently retrieve this value using `sessions.getTabValue`.

Note that this data will only be visible to the extension that set it, and not to any other extensions.

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

Syntax
------

```js
let storing = browser.sessions.setTabValue(
  tabId,    // integer
  key,      // string
  value     // string or object
)
```

### Parameters

`tabId`

`integer`. ID of the tab with which you want to associate the data. Error is thrown if ID is invalid.

`key`

`string`. Key that you can later use to retrieve this particular data value.

`value`

`string` or `object`. If this is an object it is stringified, so object methods, for example, will be omitted. If a function is given here it will be stored as the value `null`.

### Return value

A `Promise` that will be resolved with no arguments if the call succeeded. If the call failed (for example, because the tab ID could not be found) then the promise will be rejected with an error message.

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

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

Examples
--------

Set a value on the active tab when the user selects a menu item. Note that you'll need the "menus" permission to run this example:

```js
async function setOnActiveTab() {
  let tabArray = await browser.tabs.query({
    currentWindow: true,
    active: true,
  });
  let tabId = tabArray[0].id;
  await browser.sessions.setTabValue(tabId, "my-key", "my-value");
}

browser.menus.create({
  id: "my-item",
  title: "my item",
  contexts: ["all"],
});

browser.menus.onClicked.addListener(setOnActiveTab);
```

### Example extensions

* session-state


sessions.forgetClosedWindow() - Mozilla

sessions.forgetClosedWindow()
=============================

Removes a closed window from the browser's list of recently closed windows. Note that the sites visited by that window are not removed from the browser's history. Use the `browsingData` or `history` APIs to remove history.

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

Syntax
------

```js
let forgettingWindow = browser.sessions.forgetClosedWindow(
  sessionId            // string
)
```

### Parameters

`sessionId`

`String`. The ID of the session you want to forget.

### Return value

A `Promise`. This will be fulfilled with no arguments when the session has been removed.

If an 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.

Examples
--------

This code forgets the single most recently-closed session, whether it's a tab or a window:

```js
function forgetMostRecent(sessionInfos) {
  if (!sessionInfos.length) {
    console.log("No sessions found");
    return;
  }
  let sessionInfo = sessionInfos[0];
  if (sessionInfo.tab) {
    browser.sessions.forgetClosedTab(
      sessionInfo.tab.windowId,
      sessionInfo.tab.sessionId,
    );
  } else {
    browser.sessions.forgetClosedWindow(sessionInfo.window.sessionId);
  }
}

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

browser.sessions
  .getRecentlyClosed({ maxResults: 1 })
  .then(forgetMostRecent, onError);
```


sessions.forgetClosedTab() - Mozilla

sessions.forgetClosedTab()
==========================

Removes a closed tab from the browser's list of recently closed tabs. Note that the sites visited by that tab are not removed from the browser's history. Use the `browsingData` or `history` APIs to remove history.

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

Syntax
------

```js
let forgettingTab = browser.sessions.forgetClosedTab(
  windowId,            // integer
  sessionId            // string
)
```

### Parameters

`windowId`

`Integer`. The ID of the window that hosted the tab you want to forget.

`sessionId`

`String`. The ID of the session you want to forget.

### Return value

A `Promise`. This will be fulfilled with no arguments when the session has been removed.

If an 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.

Examples
--------

This code forgets the single most recently-closed session, whether it's a tab or a window:

```js
function forgetMostRecent(sessionInfos) {
  if (!sessionInfos.length) {
    console.log("No sessions found");
    return;
  }
  let sessionInfo = sessionInfos[0];
  if (sessionInfo.tab) {
    browser.sessions.forgetClosedTab(
      sessionInfo.tab.windowId,
      sessionInfo.tab.sessionId,
    );
  } else {
    browser.sessions.forgetClosedWindow(sessionInfo.window.sessionId);
  }
}

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

browser.sessions
  .getRecentlyClosed({ maxResults: 1 })
  .then(forgetMostRecent, onError);
```


sessions.setWindowValue() - Mozilla

sessions.setWindowValue()
=========================

Stores a key/value pair to associate with a given window. You can subsequently retrieve this value using `sessions.getWindowValue`.

Note that this data will only be visible to the extension that set it, and not to any other extensions.

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

Syntax
------

```js
let storing = browser.sessions.setWindowValue(
  windowId,    // integer
  key,         // string
  value        // string or object
)
```

### Parameters

`windowId`

`integer`. ID of the window with which you want to associate the data. Error is thrown if ID is invalid.

`key`

`string`. Key that you can later use to retrieve this particular data value.

`value`

`string` or `object`. If this is an object it is stringified, so object methods, for example, will be omitted. If a function is given here it will be stored as the value `null`.

### Return value

A `Promise` that will be resolved with no arguments if the call succeeded. If the call failed (for example, because the window ID could not be found) then the promise will be rejected with an error message.

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

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

Examples
--------

Set a value on the active window when the user selects a menu item. Note that you'll need the "menus" permission to run this example:

```js
async function setOnActiveWindow() {
  let currentWindow = await browser.windows.getLastFocused();
  await browser.sessions.setWindowValue(currentWindow.id, "my-key", "my-value");
}

browser.menus.create({
  id: "my-item",
  title: "my item",
  contexts: ["all"],
});

browser.menus.onClicked.addListener(setOnActiveWindow);
```


sessions.onChanged - Mozilla

sessions.onChanged
==================

Fired whenever the list of closed tabs or windows changes.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

The function called when this event occurs. It's passed no parameters.

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

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

Examples
--------

This very annoying extension listens for `onChanged`, then immediately restores the most recently closed session, thus making it impossible to close windows or tabs:

```js
function restoreSession(sessionInfos) {
  if (!sessionInfos.length) {
    console.log("No sessions found");
    return;
  }
  let sessionInfo = sessionInfos[0];
  if (sessionInfo.tab) {
    browser.sessions.restore(sessionInfo.tab.sessionId);
  } else {
    browser.sessions.restore(sessionInfo.window.sessionId);
  }
}

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

function restoreMostRecent() {
  let gettingSessions = browser.sessions.getRecentlyClosed({
    maxResults: 1,
  });
  gettingSessions.then(restoreSession, onError);
}

browser.sessions.onChanged.addListener(restoreMostRecent);
```

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


sessions.removeWindowValue() - Mozilla

sessions.removeWindowValue()
============================

Removes a value previously stored by a call to `sessions.setWindowValue`.

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

Syntax
------

```js
let removing = browser.sessions.removeWindowValue(
  windowId,    // integer
  key          // string
)
```

### Parameters

`windowId`

`integer`. ID of the window whose data you are trying to remove. Error is thrown if ID is invalid.

`key`

`string`. Key identifying the particular value to remove. This needs to match the key previously given in `sessions.setWindowValue`.

### Return value

A `Promise` that will be resolved no arguments if the item was successfully removed. If the call failed (for example, because the window ID could not be found) then the promise will be rejected with an error message.

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

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

Examples
--------

This code adds two context menu items: one stores a value associated with the current window, the other one removes it:

```js
async function setOnActiveWindow() {
  let currentWindow = await browser.windows.getLastFocused();
  await browser.sessions.setWindowValue(currentWindow.id, "my-key", "my-value");
}

async function removeFromActiveWindow() {
  let currentWindow = await browser.windows.getLastFocused();
  await browser.sessions.removeWindowValue(currentWindow.id, "my-key");
}

browser.menus.create({
  id: "add-my-item",
  title: "add item",
  contexts: ["all"],
});

browser.menus.create({
  id: "remove-my-item",
  title: "remove item",
  contexts: ["all"],
});

browser.menus.onClicked.addListener((info) => {
  if (info.menuItemId === "add-my-item") {
    setOnActiveWindow();
  } else {
    removeFromActiveWindow();
  }
});
```


sessions.getTabValue() - Mozilla

sessions.getTabValue()
======================

Retrieves a value previously stored by a call to `sessions.setTabValue`.

You can retrieve a value from a tab even over a close/restore cycle: meaning that if you set a value, then the user closes the tab, then restores the tab using the browser's "restore tab" feature (for example, by pressing Control+Shift+T), then you will be able to retrieve the value from the restored tab. Note, though, that a restored tab does not get the same ID as the original, so the ID you pass into `getTabValue()` will be different from the ID you passed into `setTabValue()`, even though they both refer to the same tab.

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

Syntax
------

```js
let retrieving = browser.sessions.getTabValue(
  tabId,    // integer
  key       // string
)
```

### Parameters

`tabId`

`integer`. ID of the tab whose data you are trying to retrieve. Error is thrown if ID is invalid.

`key`

`string`. Key identifying the particular value to retrieve. This needs to match the key previously given in `sessions.setTabValue`.

### Return value

A `Promise` that will be resolved with the value if it exists, or `undefined` if it does not exist. If the call failed (for example, because the tab ID could not be found) then the promise will be rejected with an error message.

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

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

Examples
--------

Log the value of "my-key" for all newly created tabs (this will include any tabs that have been restored):

```js
function onGetResolved(r) {
  console.log(`success: ${r}`);
}

function onGetRejected(e) {
  console.log(`error: ${e}`);
}

browser.tabs.onCreated.addListener((tab) => {
  browser.sessions
    .getTabValue(tab.id, "my-key")
    .then(onGetResolved, onGetRejected);
});
```

### Example extensions

* session-state


alarms.get() - Mozilla

alarms.get()
============

Gets an alarm, given its name.

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

Syntax
------

```js
let getAlarm = browser.alarms.get(
  name                   // optional string
)
```

### Parameters

`name` Optional

`string`. The name of the alarm to get. If you don't supply this, the empty string "" will be used.

### Return value

A `Promise` that will be fulfilled with an ``Alarm`` object. This represents the alarm whose name matches `name`. If no alarms match, this will be `undefined`.

Examples
--------

```js
function gotAlarm(alarm) {
  if (alarm) {
    console.log(alarm.name);
  }
}

let getAlarm = browser.alarms.get("my-periodic-alarm");
getAlarm.then(gotAlarm);
```

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


alarms.clearAll() - Mozilla

alarms.clearAll()
=================

Cancels all active alarms.

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

Syntax
------

```js
let clearAlarms = browser.alarms.clearAll()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with a boolean. This will be `true` if any alarms were cleared, `false` otherwise. Note that Chrome always passes `true` here.

Examples
--------

```js
function onClearedAll(wasCleared) {
  console.log(wasCleared); // true/false
}

let clearAlarms = browser.alarms.clearAll();
clearAlarms.then(onClearedAll);
```

### Example extensions

* chill-out
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.alarms` API.


alarms.create() - Mozilla

alarms.create()
===============

Creates a new alarm for the current browser session. An alarm may fire once or multiple times. An alarm is cleared after it fires for the last time.

Syntax
------

```js
browser.alarms.create(
  name,              // optional string
  alarmInfo          // optional object
)
```

### Parameters

`name` Optional

`string`. A name for the alarm. Defaults to the empty string.

This can be used to refer to a particular alarm in `alarms.get()` and `alarms.clear()`. It will also be available in `alarms.onAlarm` as the `name` property of the `alarms.Alarm` object passed into the listener function.

Alarm names are unique within the scope of a single extension. If an alarm with an identical name exists, the existing alarm will be cleared and the alarm being created will replace it.

`alarmInfo` Optional

`object`. You can use this to specify when the alarm will initially fire, either as an absolute value (`when`), or as a delay from the time the alarm is set (`delayInMinutes`). To make the alarm recur, specify `periodInMinutes`.

On Chrome, unless the extension is loaded unpackaged, alarms it creates are not allowed to fire more than once per minute. If an extension tries to set `delayInMinutes` to a value < 1, or `when` to a value < 1 minute in the future, then the alarm will fire after 1 minute. If an extension tries to set `periodInMinutes` to a value < 1, then the alarm will fire every minute.

The `alarmInfo` object may contain the following properties:

`when` Optional

`double`. The time the alarm will fire first, given as milliseconds since the epoch. To get the number of milliseconds between the epoch and the current time, use `Date.now()`. If you specify `when`, don't specify `delayInMinutes`.

`delayInMinutes` Optional

`double`. The time the alarm will fire first, given as minutes from the time the alarm is set. If you specify `delayInMinutes`, don't specify `when`.

`periodInMinutes` Optional

`double`. If this is specified, the alarm will fire again every `periodInMinutes` after its initial firing. If you specify this value you may omit both `when` and `delayInMinutes`, and the alarm will then fire initially after `periodInMinutes`. If `periodInMinutes` is not specified, the alarm will only fire once.

Examples
--------

Create a one-time delay-based alarm with "" for the name:

```js
const delayInMinutes = 5;

browser.alarms.create({
  delayInMinutes,
});
```

Create a periodic delay-based alarm named "my-periodic-alarm":

```js
const delayInMinutes = 5;
const periodInMinutes = 2;

browser.alarms.create("my-periodic-alarm", {
  delayInMinutes,
  periodInMinutes,
});
```

Create a periodic absolute alarm named "my-periodic-alarm":

```js
const when = 1545696000;
const periodInMinutes = 2;

browser.alarms.create("my-periodic-alarm", {
  when,
  periodInMinutes,
});
```

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


alarms.clear() - Mozilla

alarms.clear()
==============

Cancels an alarm, given its name.

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

Syntax
------

```js
let clearAlarm = browser.alarms.clear(
  name                       // string
)
```

### Parameters

`name` Optional

`string`. The name of the alarm to clear. If you don't supply this, the empty string "" will be used.

### Return value

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

Examples
--------

```js
function onCleared(wasCleared) {
  console.log(wasCleared); // true/false
}

let clearAlarm = browser.alarms.clear("my-periodic-alarm");
clearAlarm.then(onCleared);
```

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


alarms.getAll() - Mozilla

alarms.getAll()
===============

Gets all active alarms for the extension.

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

Syntax
------

```js
let getAlarms = browser.alarms.getAll()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an array of `Alarm` objects. Each of these represents an active alarm that belongs to the extension. If no alarms are active, the array will be empty.

Examples
--------

```js
function gotAll(alarms) {
  for (const alarm of alarms) {
    console.log(alarm.name);
  }
}

browser.alarms.getAll().then(gotAll);
```

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


alarms.onAlarm - Mozilla

alarms.onAlarm
==============

Fired when any alarm set by the extension goes off.

Syntax
------

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

`alarm`

`alarms.Alarm`. The alarm that fired. Use `Alarm.name` to figure out which alarm fired.

Examples
--------

Handle an alarm going off:

```js
function handleAlarm(alarmInfo) {
  console.log(`on alarm: ${alarmInfo.name}`);
}

browser.alarms.onAlarm.addListener(handleAlarm);
```

### Example extensions

* chill-out
* dynamic-theme
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.alarms` API.


alarms.Alarm - Mozilla

alarms.Alarm
============

Information about a single alarm. This object is returned from `alarms.get()` and `alarms.getAll()`, and is passed into the `alarms.onAlarm` listener.

Type
----

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

`name`

`string`. Name of this alarm. This is the name that was passed into the `alarms.create()` call that created this alarm.

`scheduledTime`

`double`. Time at which the alarm is scheduled to fire next, in milliseconds since the epoch.

`periodInMinutes` Optional

`double`. If this is not `null`, then the alarm is periodic, and this represents its period in minutes.

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