proxy.ProxyInfo - Mozilla

proxy.ProxyInfo
===============

Contains information about a proxy. This object, or an array of these objects, is returned from the listener to `proxy.onRequest`. It instructs the browser whether to proxy the request, and if so, which proxy to use.

Type
----

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

`type`

`string`. This describes whether to proxy at all, and if so, what kind of proxy to use. It may take one of the following values:

* `"direct"`: don't proxy the request. If this value is given, all other properties of this object are ignored. However, this setting doesn't override any proxy set by the user. Use `proxy.settings` to check whether a manual proxy is being used and, if necessary, monitor those settings for changes using `BrowserSetting.onChange`.
* `"http"`: HTTP proxy (or SSL CONNECT for HTTPS)
* `"https"`: HTTP proxying over TLS connection to proxy
* `"socks"`: SOCKS v5 proxy
* `"socks4"`: SOCKS v4 proxy

`host`

`string`. The hostname of the proxy server. Mandatory unless `type` is `"direct"`.

`port`

`number`. The port number of the proxy server. Mandatory unless `type` is `"direct"`.

`username`

`string`. Username for the proxy service. This is usable with "socks". For HTTP proxy authorizations, use `webRequest.onAuthRequired`.

`password`

`string`. Password for the proxy service. This is usable with "socks". For HTTP proxy authorizations, use `webRequest.onAuthRequired`.

`proxyDNS`

`boolean`. If true, the proxy server is used to resolve certain DNS queries (only usable with `"socks4"` and `"socks"`). Defaults to `false`.

`failoverTimeout`

`number`. Failover timeout in seconds. If the connection fails to connect the proxy server after this number of seconds, the next proxy server in the array returned from the `proxy.onRequest` listener will be used.

`proxyAuthorizationHeader`

`string`. This string, if set to non-empty, is passed directly as a value to the `Proxy-Authorization` request header sent to HTTPS proxies as part of HTTPS and CONNECT requests. In other words, this can be used to directly authenticate to HTTPS proxies that allow (non-challenging) authentication.

For instance, if you want to send "username" and "password" for "basic" authentication, you can set the `proxyAuthorizationHeader` property to `Basic dXNlcm5hbWU6cGFzc3dvcmQ=`

`connectionIsolationKey` Optional

`string`. An optional key used for additional isolation of this proxy connection. Applies to HTTPS proxies only.

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

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


proxy.RequestDetails - Mozilla

proxy.RequestDetails
====================

Contains information about a web request. An instance of this object is passed into the `proxy.onRequest` listener.

Type
----

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

`cookieStoreId`

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

`documentUrl`

`string`. URL of the page into which the requested resource will be loaded.

`frameId`

`integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.

`fromCache`

`boolean`. Indicates if this response will be fetched from disk cache.

`incognito`

`boolean`. `true` for private browsing requests.

`method`

`string`. Standard HTTP method: for example, "GET" or "POST".

`originUrl`

`string`. URL of the resource that triggered the request. Note that this may not be the same as the URL of the page into which the requested resource will be loaded. For example, if a document triggers a load in a different window through the target attribute of a link, or a CSS document includes an image using the `url()` functional notation, then this is the URL of the original document or of the CSS document, respectively.

`parentFrameId`

`integer`. ID of the frame that contains the frame that sent the request. Set to -1 if no parent frame exists.

`requestId`

`string`. The ID of the request. Request IDs are unique within a browser session, so you can use an ID to identify different events associated with the same request.

`requestHeaders` Optional

`webRequest.HttpHeaders`. The HTTP request headers that will be sent with this request. Note that this is only included if the `"requestHeaders"` option was passed into `addListener()`.

`tabId`

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

`thirdParty`

`boolean`. Indicates whether the request and its content window hierarchy is third party.

`timeStamp`

`number`. The time when this event fired, in milliseconds since the epoch.

`type`

`webRequest.ResourceType`. The type of resource being requested: for example, "image", "script", or "stylesheet".

`url`

`string`. Target of the request.

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

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


proxy.onRequest - Mozilla

proxy.onRequest
===============

Fired when a web request is about to be made, to give the extension an opportunity to proxy it.

This event is closely modeled on the events defined in the `webRequest` API. Like those events, its `addListener()` function takes three arguments:

* the listener that is called when the event is fired.
* a `RequestFilter` object controlling which requests cause the event to fire.
* an array of strings to control other aspects of the event's behavior.

The event is fired before any of the `webRequest` events for the same request.

When the event is fired, the listener is called with an object containing information about the request. The listener returns a `proxy.ProxyInfo` object representing a proxy to use (or an array of `proxy.ProxyInfo` objects, enabling the browser to fail over if a proxy is unreachable).

To use `proxy.onRequest`, an extension must have the "proxy" API permission and the host permission for the URLs of the requests that it intercepts, which means that the match patterns in the `filter` argument must be a subset of the extension's host permissions.

Syntax
------

```js
browser.proxy.onRequest.addListener(
  listener,             // function
  filter,               // object
  extraInfoSpec         // optional array of strings
)
browser.proxy.onRequest.removeListener(listener)
browser.proxy.onRequest.hasListener(listener)
```

Events have three functions:

`addListener(listener, filter, extraInfoSpec)`

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 that is called when this event occurs. The function is passed a single argument, which is a `proxy.RequestDetails` object containing details of the request.

The listener can return any of:

* a `proxy.ProxyInfo` object.
* an array of `proxy.ProxyInfo` objects.
* a `Promise` that resolves to a `ProxyInfo` object.
* a `Promise` that resolves to an array of `ProxyInfo` objects.

If the listener returns an array, or a Promise that resolves to an array, then all `ProxyInfo` objects after the first one represent failovers: if the proxy at position N in the array is not reachable when its `ProxyInfo.failoverTimeout` expires the browser will try the proxy at position N+1.

If there is an error specifying the `proxy.ProxyInfo` objects, then `proxy.onError` is called.

`filter`

`webRequest.RequestFilter`. A set of filters that restricts the events that are sent to the listener.

`extraInfoSpec` Optional

`array` of `string`. Extra options for the event. Pass `"requestHeaders"` to include the request headers in the `details` object passed to the listener.

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

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

Examples
--------

This code intercepts requests to `<all_urls>`, and proxies them if they are not for a top-level frame.

```js
function shouldProxyRequest(requestInfo) {
  return requestInfo.parentFrameId !== -1;
}

function handleProxyRequest(requestInfo) {
  if (shouldProxyRequest(requestInfo)) {
    console.log(`Proxying: ${requestInfo.url}`);
    return { type: "http", host: "127.0.0.1", port: 65535 };
  }
  return { type: "direct" };
}

browser.proxy.onRequest.addListener(handleProxyRequest, {
  urls: ["<all\_urls>"],
});
```

### Example extensions

* proxy-blocker


history.deleteAll() - Mozilla

history.deleteAll()
===================

Deletes all visits from the browser's history.

This function triggers `history.onVisitRemoved` just once, with `allHistory` set to `true` and an empty `urls` argument.

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

Syntax
------

```js
let deletingAll = browser.history.deleteAll()
```

### Parameters

None.

### Return value

A `Promise` will be fulfilled with no parameters when all history has been deleted.

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

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

Examples
--------

Delete all history when the user clicks a browser action:

```js
function onDeleteAll() {
  console.log("Deleted all history");
}

function deleteAllHistory() {
  let deletingAll = browser.history.deleteAll();
  deletingAll.then(onDeleteAll);
}

deleteAllHistory();
```

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


history.TransitionType - Mozilla

history.TransitionType
======================

This describes how the browser navigated to a particular page. For example, "link" means that the browser navigated to the page because the user clicked a link.

Type
----

Values of this type are strings. Possible values are:

"link"

The user clicked a link in another page.

"typed"

The user typed the URL into the address bar. This is also used if the user started typing into the address bar, then selected a URL from the suggestions it offered. See also "generated".

"auto\_bookmark"

The user clicked a bookmark or an item in the browser history.

"auto\_subframe"

Any nested iframes that are automatically loaded by their parent.

"manual\_subframe"

Any nested iframes that are loaded as an explicit user action. Loading such an iframe will generate an entry in the back/forward navigation list.

"generated"

The user started typing in the address bar, then clicked on a suggested entry that didn't contain a URL.

"auto\_toplevel"

The page was passed to the command line or is the start page.

"form\_submit"

The user submitted a form. Note that in some situations, such as when a form uses a script to submit its contents, submitting a form does not result in this transition type.

"reload"

The user reloaded the page, using the Reload button or by pressing Enter in the address bar. This is also used for session restore and reopening closed tabs.

"keyword"

The URL was generated using a keyword search configured by the user.

"keyword\_generated"

Corresponds to a visit generated for a keyword.

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


history.search() - Mozilla

history.search()
================

Searches the browser's history for `history.HistoryItem` objects matching the given criteria.

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

Syntax
------

```js
let searching = browser.history.search(
  query                  // object
)
```

### Parameters

`query`

An object which indicates what to look for in the browser's history. This object has the following fields:

`text`

`string`. Search history items by URL and title. The string is split up into separate search terms at space boundaries. Each search term is matched case-insensitively against the history item's URL and title. The history item will be returned if all search terms match.

For example, consider this item:

URL: `"http://example.org"`

Title: `"Example Domain"`
```

"http"              -> matches
"domain"            -> matches
"MAIN ample"        -> matches
"main tt"           -> matches
"main https"        -> does not match
```

Specify an empty string (`""`) to retrieve all `history.HistoryItem` objects that meet all the other criteria.

`startTime` Optional

`number` or `string` or `object`. A value indicating a date and time. This can be represented as: a `Date` object, an ISO 8601 date string, or the number of milliseconds since the epoch. If it is supplied, this option excludes results whose `lastVisitTime` is earlier than this time. If it is omitted, the search is limited to the last 24 hours.

`endTime` Optional

`number` or `string` or `object`. A value indicating a date and time. This can be represented as: a `Date` object, an ISO 8601 date string, or the number of milliseconds since the epoch. If it is supplied, this option limits results to those visited before this date. If it is omitted, then all entries are considered from the start time onwards.

`maxResults` Optional

`number`. The maximum number of results to retrieve. Defaults to 100, with a minimum value of 1. The function will throw an error if you pass it a `maxResults` value less than 1.

### Return value

A `Promise` will be fulfilled with an array of objects of type `history.HistoryItem`, each describing a single matching history item. Items are sorted in reverse chronological order.

Examples
--------

Logs the URL and last visit time for all history items visited in the last 24 hours:

```js
function onGot(historyItems) {
  for (const item of historyItems) {
    console.log(item.url);
    console.log(new Date(item.lastVisitTime));
  }
}

browser.history.search({ text: "" }).then(onGot);
```

Logs the URL and last visit time for all history items ever visited:

```js
function onGot(historyItems) {
  for (const item of historyItems) {
    console.log(item.url);
    console.log(new Date(item.lastVisitTime));
  }
}

browser.history
  .search({
    text: "",
    startTime: 0,
  })
  .then(onGot);
```

Logs the URL and last visit time of the most recent visit to a page that contain the string "mozilla":

```js
function onGot(historyItems) {
  for (const item of historyItems) {
    console.log(item.url);
    console.log(new Date(item.lastVisitTime));
  }
}

browser.history
  .search({
    text: "mozilla",
    startTime: 0,
    maxResults: 1,
  })
  .then(onGot);
```

### Example extensions

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


history.deleteUrl() - Mozilla

history.deleteUrl()
===================

Removes all visits to the given URL from the browser history.

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

Syntax
------

```js
let deletingUrl = browser.history.deleteUrl(
  details         // object
)
```

### Parameters

`details`

`object`. Object containing the URL whose visits to remove.

`url`

`string`. The URL whose visits should be removed.

### Return value

A `Promise` will be fulfilled with no parameters when the visits have been removed.

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

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

Examples
--------

Remove all visits to "https://example.org/" from history, then check that this URL no longer returned from `history.search()`:

```js
let urlToRemove = "https://example.org/";

function onGot(results) {
  if (!results.length) {
    console.log(`${urlToRemove} was removed`);
  } else {
    console.log(`${urlToRemove} was not removed`);
  }
}

function onRemoved() {
  let searching = browser.history.search({
    text: urlToRemove,
    startTime: 0,
  });

  searching.then(onGot);
}

let deletingUrl = browser.history.deleteUrl({ url: urlToRemove });

deletingUrl.then(onRemoved);
```

Remove the last-visited page from history, with a listener to `history.onVisitRemoved` to log the URL of the removed page:

```js
function onRemoved(removeInfo) {
  if (removeInfo.urls.length) {
    console.log(`Removed: ${removeInfo.urls[0]}`);
  }
}

browser.history.onVisitRemoved.addListener(onRemoved);

function onGot(results) {
  if (results.length) {
    console.log(`Removing: ${results[0].url}`);
    browser.history.deleteUrl({ url: results[0].url });
  }
}

let searching = browser.history.search({
  text: "",
  startTime: 0,
  maxResults: 1,
});

searching.then(onGot);
```

### Example extensions

* history-deleter

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


history.VisitItem - Mozilla

history.VisitItem
=================

An object describing a single visit to a page.

Type
----

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

`id`

`string`. The unique identifier for the `history.HistoryItem` associated with this visit.

`visitId`

`string`. The unique identifier for this visit.

`visitTime` Optional

`number`. When this visit occurred, represented in milliseconds since the epoch.

`referringVisitId`

`string`. The visit ID of the referrer.

`transition`

`history.TransitionType`. Describes how the browser navigated to the page on this occasion.

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


history.addUrl() - Mozilla

history.addUrl()
================

Adds a record to the browser's history of a visit to the given URL. The visit's time is recorded as the time of the call, and the `TransitionType` is recorded as "link".

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

Syntax
------

```js
let addingUrl = browser.history.addUrl(
  details         // object
)
```

### Parameters

`details`

`object`. Object containing the URL to add.

`url`

`string`. The URL to add.

`title` Optional

string: The title of the page. If this is not supplied, the title will be recorded as `null`.

`transition` Optional

`history.TransitionType`. Describes how the browser navigated to the page on this occasion. If this is not supplied, a transition type of "link" will be recorded.

`visitTime` Optional

`number` or `string` or `object`. A value indicating a date and time. This can be represented as: a `Date` object, an ISO 8601 date string, or the number of milliseconds since the epoch. Sets the visit time to this value. If this is not supplied, the current time will be recorded.

### Return value

A `Promise` will be fulfilled with no parameters when the item has been added.

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

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

Examples
--------

Add a record of a visit to "https://example.org/", then check that the new visit was recorded by searching history for the most recent item and logging it:

```js
function onGot(results) {
  if (results.length) {
    console.log(results[0].url);
    console.log(new Date(results[0].lastVisitTime));
  }
}

browser.history
  .addUrl({ url: "https://example.org/" })
  .then(() =>
    browser.history.search({
      text: "https://example.org/",
      startTime: 0,
      maxResults: 1,
    }),
  )
  .then(onGot);
```

Add a record of a visit to "https://example.org", but give it a `visitTime` 24 hours in the past, and a `transition` of "typed":

```js
const DAY = 24 \* 60 \* 60 \* 1000;

function oneDayAgo() {
  return Date.now() - DAY;
}

function onGot(visits) {
  for (const visit of visits) {
    console.log(new Date(visit.visitTime));
    console.log(visit.transition);
  }
}

browser.history
  .addUrl({
    url: "https://example.org/",
    visitTime: oneDayAgo(),
    transition: "typed",
  })
  .then(() =>
    browser.history.getVisits({
      url: "https://example.org/",
    }),
  )
  .then(onGot);
```

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


history.onVisited - Mozilla

history.onVisited
=================

Fired each time the user visits a page. A `history.HistoryItem` object is passed to the listener. This event fires before the page has loaded.

Syntax
------

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

`result`

`history.HistoryItem`. An object representing the item in the browser's history.

At the time that this event is sent, the browser doesn't yet know the title of the page. If the browser has visited this page before and has remembered its old title, then the `HistoryItem.title` object will contain the old title of the page. If the browser doesn't have a record of the page's old title, then `HistoryItem.title` will be empty. To get the titles of pages as soon as they are known, listen for `history.onTitleChanged`.

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

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

Examples
--------

Listen for visits, and log the URL and visit time.

```js
function onVisited(historyItem) {
  console.log(historyItem.url);
  console.log(new Date(historyItem.lastVisitTime));
}

browser.history.onVisited.addListener(onVisited);
```

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


history.onTitleChanged - Mozilla

history.onTitleChanged
======================

Fired when the title of a page visited by the user is recorded. To listen for visits to a page you use `history.onVisited`. However, the `history.HistoryItem` that this event passes to its listener does not include the page title, because the page title is typically not known at the time `history.onVisited` is sent. Instead, the stored `history.HistoryItem` is updated with the page title after the page has loaded, once the title is known. The `history.onTitleChanged` event is fired at that time. So if you need to know the titles of pages as they are visited, listen for `history.onTitleChanged`.

Syntax
------

```js
browser.history.onTitleChanged.addListener(listener)
browser.history.onTitleChanged.removeListener(listener)
browser.history.onTitleChanged.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 an object with these properties:

`id`

`String`. The unique identifier for the `history.HistoryItem` associated with this visit.

`url`

`String`. URL of the page visited.

`title`

`String`. Title of the page visited.

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

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

Examples
--------

Listen for title change events, and log the ID, URL, and title of the visited pages.

```js
function handleTitleChanged(item) {
  console.log(item.id);
  console.log(item.title);
  console.log(item.url);
}

browser.history.onTitleChanged.addListener(handleTitleChanged);
```

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


history.deleteRange() - Mozilla

history.deleteRange()
=====================

Removes all visits to pages that the user made during the given time range. If this removes all visits made to a given page, then the page will be no longer appear in the browser history and `history.onVisitRemoved` will fire for it.

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

Syntax
------

```js
let deletingRange = browser.history.deleteRange(
  range           // object
)
```

### Parameters

`range`

`object`. Specification of the time range for which to delete visits.

`startTime`

`number` or `string` or `object`. A value indicating a date and time. This can be represented as: a `Date` object, an ISO 8601 date string, or the number of milliseconds since the epoch. Specifies the start time for the range.

`endTime`

`number` or `string` or `object`. A value indicating a date and time. This can be represented as: a `Date` object, an ISO 8601 date string, or the number of milliseconds since the epoch. Specifies the end time for the range.

### Return value

A `Promise` will be fulfilled with no parameters when the range has been deleted.

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

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

Examples
--------

Delete all visits made in the last minute:

```js
const MINUTE = 60 \* 1000;

function oneMinuteAgo() {
  return Date.now() - MINUTE;
}

browser.history.deleteRange({
  startTime: oneMinuteAgo(),
  endTime: Date.now(),
});
```

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


history.getVisits() - Mozilla

history.getVisits()
===================

Retrieves information about all visits to the given URL.

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

Syntax
------

```js
let getting = browser.history.getVisits(
  details                // object
)
```

### Parameters

`details`

An object with the following properties:

`url`

`string`. The URL for which to retrieve visit information.

### Return value

A `Promise` will be fulfilled with an array of ``history.VisitItem`` objects each representing a visit to the given URL. Visits are sorted in reverse chronological order.

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

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

Examples
--------

List all visits to the most recently-visited page:

```js
function gotVisits(visits) {
  console.log(`Visit count: ${visits.length}`);
  for (const visit of visits) {
    console.log(visit.visitTime);
  }
}

function listVisits(historyItems) {
  if (historyItems.length) {
    console.log(`URL ${historyItems[0].url}`);
    const gettingVisits = browser.history.getVisits({
      url: historyItems[0].url,
    });
    gettingVisits.then(gotVisits);
  }
}

let searching = browser.history.search({
  text: "",
  startTime: 0,
  maxResults: 1,
});

searching.then(listVisits);
```

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


history.HistoryItem - Mozilla

history.HistoryItem
===================

A `HistoryItem` object provides information about a page in the browser history.

Type
----

This is an object with the following properties:

`id`

`string`. Unique identifier for the item.

`url` Optional

`string`. The URL of the page.

`title` Optional

`string`. The title of the page.

`lastVisitTime` Optional

`number`. The date and time the page was last loaded, represented in milliseconds since the epoch.

`visitCount` Optional

`number`. The number of times the user has visited the page.

`typedCount` Optional

`number`. The number of times the user has navigated to this page by typing in the address.

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


history.onVisitRemoved - Mozilla

history.onVisitRemoved
======================

Fired when a page is removed completely from the browser history.

* If all visits to a single page are removed (for example, using `history.deleteUrl`), then this event is fired once.
* If a range of visits is removed (for example, using `history.deleteRange` or a browser feature like "Clear Recent History"), then it is fired once for each page *whose visits all fall within the cleared range*.
* If the browser's entire history is cleared (for example, using `history.deleteAll`), then it is fired only once.
Syntax
------

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

`removed`

`object`. Details of the removal. This is an object containing two properties: a boolean `allHistory` and an array `urls`.

* If this event is firing because all history was cleared, `allHistory` will be `true` and `urls` will be an empty array.
* Otherwise, `allHistory` will be `false` and `urls` will contain one item, which is the URL of the removed page.

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

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

Examples
--------

```js
function onRemoved(removed) {
  if (removed.allHistory) {
    console.log("All history removed");
  } else if (removed.urls.length) {
    console.log(`URL removed: ${removed.urls[0]}`);
  }
}

browser.history.onVisitRemoved.addListener(onRemoved);
```

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


windows.getAll() - Mozilla

windows.getAll()
================

Gets information about all open windows, passing them into a callback.

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

Syntax
------

```js
let gettingAll = browser.windows.getAll(
  getInfo                // optional object
)
```

### Parameters

`getInfo` Optional

`object`. This controls what `windows.Window` objects are retrieved.

`populate` Optional

`boolean`. Defaults to `false`. If set to `true`, each `windows.Window` object will have a `tabs` property that contains a list of `tabs.Tab` objects representing the tabs in that window. The `Tab` objects will contain the `url`, `title` and `favIconUrl` properties only if the extension's manifest file includes the `"tabs"` permission or host permissions that match the tab's URL.

`windowTypes` Optional

An `array` of `windows.WindowType` objects. If set, the `windows.Window` objects returned will be filtered based on their type. If unset the default filter is set to `['normal', 'panel', 'popup']`, with `'panel'` window types limited to the extension's own windows.

### Return value

A `Promise` that will be fulfilled with an array of `windows.Window` objects, representing all windows that match the given criteria. If any 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
--------

Log the URLs for the tabs across all "normal" browser windows. Note that you'll need the "tabs" permission or matching host permissions to access tab URLs.

```js
function logTabsForWindows(windowInfoArray) {
  for (const windowInfo of windowInfoArray) {
    console.log(`Window: ${windowInfo.id}`);
    console.log(windowInfo.tabs.map((tab) => tab.url));
  }
}

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

browser.browserAction.onClicked.addListener((tab) => {
  browser.windows
    .getAll({
      populate: true,
      windowTypes: ["normal"],
    })
    .then(logTabsForWindows, onError);
});
```

### Example extensions

* private-browsing-theme
* window-manipulator

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


windows.onCreated - Mozilla

windows.onCreated
=================

Fired when a window is created.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`window`

A `windows.Window` object containing details of the window that was created.

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

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

Examples
--------

Log the IDs of new windows as they are created:

```js
browser.windows.onCreated.addListener((window) => {
  console.log(`New window: ${window.id}`);
});
```

### Example extensions

* private-browsing-theme

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


windows.WINDOW_ID_NONE - Mozilla

windows.WINDOW\_ID\_NONE
========================

The `windowId` value that represents the absence of a browser window.

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

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

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


windows.WindowState - Mozilla

windows.WindowState
===================

The state of this browser window.

Type
----

Values of this type are `strings`. Possible values are:

`"normal"`

The window is at the default size or user-selected size.

`"minimized"`

The window is only visible as an icon in the taskbar or .

`"maximized"`

The window fills the screen on which it is displayed not including any screen areas reserved by the operating system.

`"fullscreen"`

The window is running as a full screen application or content in a tab is using the Fullscreen API

`"docked"`

A docked window occupies a fixed position relative to other windows owned by the same application.

macOS compatibility: Beginning in macOS 10.10, the default maximizing behavior for windows changed to run applications as full screen applications instead of "zoomed" windows. `fullscreen` refers to both the browser running as a full screen application and when content in a tab uses the Fullscreen API.

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


windows.CreateType - Mozilla

windows.CreateType
==================

Specifies the type of browser window to create.

Type
----

Values of this type are `strings`. Possible values are:

* `"normal"`
* `"popup"`
* `"panel"`
* `"detached_panel"`
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.windows` API. This documentation is derived from `windows.json` in the Chromium code.


windows.onRemoved - Mozilla

windows.onRemoved
=================

Fired when a window is closed.

Syntax
------

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

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

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

### Parameters

`listener`

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

`windowId`

`integer`. ID of the window that was closed.

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

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

Examples
--------

Log the IDs of windows as they are removed.

```js
browser.windows.onRemoved.addListener((windowId) => {
  console.log(`Closed window: ${windowId}`);
});
```

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


windows.WindowType - Mozilla

windows.WindowType
==================

The type of browser window this is.

Type
----

Values of this type are `strings`. Possible values are:

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

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

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


windows.getCurrent() - Mozilla

windows.getCurrent()
====================

Gets the current browser window, passing its details into a callback.

The "current" window is not necessarily the same as the currently focused window. If this function is called from a background script, then it returns the currently focused window. But if it is called from a script whose document is associated with a particular browser window, then it returns that browser window. For example, if the browser is displaying a sidebar, then every browser window has its own instance of the sidebar document. If a script running in the sidebar document calls `getCurrent()`, then it will return that sidebar document's window.

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

Syntax
------

```js
let gettingCurrent = browser.windows.getCurrent(
  getInfo               // optional object
)
```

### Parameters

`getInfo` Optional

`object`.

`populate` Optional

`boolean`. If true, the `windows.Window` object will have a `tabs` property that contains a list of `tabs.Tab` objects representing the tabs in the window. The `Tab` objects only contain the `url`, `title` and `favIconUrl` properties if the extension's manifest file includes the `"tabs"` permission or host permissions that match the tab's URL.

`windowTypes`
Deprecated
 Optional

An `array` of ``windows.WindowType`` objects. If set, the `windows.Window` returned will be filtered based on its type. If unset the default filter is set to `['normal', 'panel', 'popup']`, with `'panel'` window types limited to the extension's own windows.

**Note:** If supplied, the `windowTypes` component of `getInfo` is ignored. The use of `windowTypes` has been deprecated as of Firefox 62.

### Return value

A `Promise` that will be fulfilled with a `windows.Window` object containing the details of the window. If any 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
--------

When the user clicks a browser action's icon, this example gets the current window and logs the URLs of the tabs it contains. Note that you'll need the "tabs" permission or matching host permissions to access tab URLs.

```js
function logTabs(windowInfo) {
  for (const tabInfo of windowInfo.tabs) {
    console.log(tabInfo.url);
  }
}

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

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

### Example extensions

* annotate-page
* theme-integrated-sidebar
* window-manipulator

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


windows.get() - Mozilla

windows.get()
=============

Gets details about a window, given its ID. The details are passed into a callback.

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

Syntax
------

```js
let getting = browser.windows.get(
  windowId,              // integer
  getInfo                // optional object
)
```

### Parameters

`windowId`

`integer`. The ID of the window object you want returned.

`getInfo` Optional

`object`. Contains options to filter the type of window.

`populate` Optional

`boolean`. If `true`, the `windows.Window` object will have a `tabs` property that contains a list of `tabs.Tab` objects representing the tabs open in the window. The `Tab` objects only contain the `url`, `title` and `favIconUrl` properties if the extension's manifest file includes the `"tabs"` permission or a matching host permission.

`windowTypes` Optional

`array` of `windows.WindowType` objects. If set, the `windows.Window` returned will be filtered based on its type. If unset the default filter is set to `['normal', 'panel', 'popup']`, with `'panel'` window types limited to the extension's own windows.

**Note:** If supplied, the `windowTypes` component of `getInfo` is ignored. The use of `windowTypes` has been deprecated as of Firefox 62.

### Return value

A `Promise` that will be fulfilled with a `windows.Window` object containing the details of the window. If any 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 example gets the current window and logs the URLs of the tabs it contains. Note that you'll need the "tabs" permission or matching host permissions to access tab URLs.

**Note:** This example is a bit unrealistic: in this situation you would more probably use `windows.getCurrent()`.

```js
function logTabs(windowInfo) {
  for (const tabInfo of windowInfo.tabs) {
    console.log(tabInfo.url);
  }
}

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

browser.browserAction.onClicked.addListener((tab) => {
  browser.windows.get(tab.windowId, { populate: true }).then(logTabs, onError);
});
```

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


windows.create() - Mozilla

windows.create()
================

Creates a new window.

When you create the window, you can:

* Load one or more new tabs into the window.
* Move a tab from an existing window into the new window.
* Set the size and position of the window.
* Create a "panel" style window, which in this context means a window without any of the normal browser UI (address bar, toolbar, etc.).
* Set various properties of the window, such as whether it is focused or private.

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

Syntax
------

```js
let creating = browser.windows.create(
  createData            // optional object
)
```

### Parameters

`createData` Optional

`object`.

`allowScriptsToClose` Optional

`boolean`. When the window is opened, it will contain a single tab, or more than one tab if `url` is given and includes an array containing more than one URL. By default scripts running in these pages are not allowed to close their tab using `window.close()`. If you include `allowScriptsToClose` and set it to `true`, then this default behavior is changed, so scripts can close their tabs. Note that:

* this only applies to the tabs that were opened when the window was created. If the user opens more tabs in this window, then scripts will not be able to close those new tabs.
* if the URL(s) given in `url` point to extension pages (that is, they are pages included with this extension and loaded with the "moz-extension:" protocol) then scripts *are* by default allowed to close those tabs.

`cookieStoreId` Optional

`integer`. If present, specifies the `CookieStoreId` for all the tabs created when the window is opened. See Work with contextual identities for more information on using `cookieStoreId`.

`focused` Optional

`boolean`. If `true`, the new window will be focused. If `false`, the new window will be opened in the background and the currently focused window will stay focused. Defaults to `true`.

`height` Optional

`integer`. The height in pixels of the new window, including the frame. If not specified defaults to a natural height.

`incognito` Optional

`boolean`. Whether the new window should be an incognito (private) window. Note that if you specify `incognito` and `tabId`, the ID must refer to a private tab — that is, you can't move a non-private tab to a private window.

`left` Optional

`integer`. The number of pixels to position the new window from the left edge of the screen. If not specified, the new window is offset naturally from the last focused window. This value is ignored for panels. (In Firefox, this value currently is ignored for popups (bug 1271047) but can be set using browser.windows.update().)

`state` Optional

A `windows.WindowState` value. The initial state of the window. The `minimized`, `maximized` and, `fullscreen` states cannot be combined with `left`, `top`, `width`, or `height`.

`tabId` Optional

`integer`. If included, moves a tab of the specified ID from an existing window into the new window.

`titlePreface` Optional

`string`. Use this to add a string to the beginning of the browser window's title. Depending on the underlying operating system, this might not work on browser windows that don't have a title (such as about:blank in Firefox).

`top` Optional

`integer`. The number of pixels to position the new window from the top edge of the screen. If not specified, the new window is offset naturally from the last focused window. This value is ignored for panels. (In Firefox, this value currently is ignored for popups (bug 1271047) but can be set using browser.windows.update().)

`type` Optional

A `windows.CreateType` value. Specifies what type of browser window to create. Specify `panel` or `popup` here to open a window without any of the normal browser UI (address bar, toolbar, etc.).

`url` Optional

`string` or `array` of `string`s. A URL or array of URLs to open as tabs in the window. Fully-qualified URLs must include a scheme (i.e. `http://www.google.com`, not `www.google.com`). Relative URLs will be relative to the current page within the extension. Defaults to the New Tab Page.

`width` Optional

`integer`. The width in pixels of the new window, including the frame. If not specified defaults to a natural width.

### Return value

A `Promise` that will be fulfilled with a `windows.Window` object containing the details of the new window. This `Window` object will always have its `tabs` property set, unlike the `Window` objects returned from `windows.get()` and similar APIs, which only contain `tabs` if the `populate` option is passed. If any error occurs, the promise will be rejected with an error message.

Examples
--------

Open a window containing two tabs:

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

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

browser.browserAction.onClicked.addListener((tab) => {
  let creating = browser.windows.create({
    url: ["https://developer.mozilla.org", "https://addons.mozilla.org"],
  });
  creating.then(onCreated, onError);
});
```

Open a window when the user clicks a browser action, and move the currently active tab into it:

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

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

browser.browserAction.onClicked.addListener((tab) => {
  let creating = browser.windows.create({
    tabId: tab.id,
  });
  creating.then(onCreated, onError);
});
```

Open a small panel-style window, and load a locally-packaged file into it:

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

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

browser.browserAction.onClicked.addListener((tab) => {
  let popupURL = browser.extension.getURL("popup/popup.html");

  let creating = browser.windows.create({
    url: popupURL,
    type: "popup",
    height: 200,
    width: 200,
  });
  creating.then(onCreated, onError);
});
```

### Example extensions

* store-collected-images
* window-manipulator
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.windows` API. This documentation is derived from `windows.json` in the Chromium code.

See also
--------

* `window.open`


windows.getLastFocused() - Mozilla

windows.getLastFocused()
========================

Gets the window that was most recently focused — typically the window 'on top'.

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

Syntax
------

```js
let gettingWindow = browser.windows.getLastFocused(
  getInfo               // optional object
)
```

### Parameters

`getInfo` Optional

`object`.

`populate` Optional

`boolean`. If `true`, the `windows.Window` object will have a `tabs` property that contains a list of `tabs.Tab` objects representing the tabs in the window. The `Tab` objects only contain the `url`, `title` and `favIconUrl` properties if the extension's manifest file includes the `"tabs"` permission or host permissions matching the tab's URL.

`windowTypes` Optional

An `array` of `windows.WindowType` objects. If set, the `windows.Window` returned will be filtered based on its type. If unset the default filter is set to `['normal', 'panel', 'popup']`, with `'panel'` window types limited to the extension's own windows.

**Note:** If supplied, the `windowTypes` component of `getInfo` is ignored. The use of `windowTypes` has been deprecated as of Firefox 62.

### Return value

A `Promise` that will be fulfilled with a `windows.Window` object containing the details of the last focused window. If any 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
--------

Get the last focused window, and log the tabs it contains. Note that you'll need the "tabs" permission or matching host permissions to access tab URLs.

```js
function logTabs(windowInfo) {
  for (const tabInfo of windowInfo.tabs) {
    console.log(tabInfo.url);
  }
}

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

browser.browserAction.onClicked.addListener((tab) => {
  browser.windows.getLastFocused({ populate: true }).then(logTabs, onError);
});
```

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


windows.onFocusChanged - Mozilla

windows.onFocusChanged
======================

Fired when the currently focused window changes. Will be `windows.WINDOW_ID_NONE` if all browser windows have lost focus.

**Note:** In Windows and some Linux window managers, WINDOW\_ID\_NONE will always be sent immediately preceding a switch from one browser window to another.

Syntax
------

```js
browser.windows.onFocusChanged.addListener(listener)
browser.windows.onFocusChanged.removeListener(listener)
browser.windows.onFocusChanged.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

`windowId`

`integer`. ID of the newly focused window.

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

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

Examples
--------

Log focus changes:

```js
browser.windows.onFocusChanged.addListener((windowId) => {
  console.log(`Newly focused window: ${windowId}`);
});
```

### Example extensions

* bookmark-it

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


windows.WINDOW_ID_CURRENT - Mozilla

windows.WINDOW\_ID\_CURRENT
===========================

`browser.windows.WINDOW_ID_CURRENT` is a value that can be used as a `windowId` parameter in some APIs to represent the current window.

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

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

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


windows.update() - Mozilla

windows.update()
================

Updates the properties of a window. Use this to move, resize, and (un)focus a window, etc.

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

Syntax
------

```js
let updating = browser.windows.update(
  windowId,              // integer
  updateInfo             // object
)
```

### Parameters

`windowId`

`integer`. ID of the window to update.

`updateInfo`

`object`. Object containing the properties to update.

`drawAttention` Optional

`boolean`. If `true`, causes the window to be displayed in a manner that draws the user's attention to the window, without changing the focused window. The effect lasts until the user changes focus to the window. This option has no effect if the window already has focus. Set to `false` to cancel a previous `drawAttention` request.

`focused` Optional

`boolean`. If `true`, brings the window to the front. If false, brings the next window in the z-order to the front.

`height` Optional

`integer`. The height to resize the window to in pixels. This value is ignored for panels.

`left` Optional

`integer`. The offset from the left edge of the screen to move the window to in pixels. This value is ignored for panels.

`state` Optional

`windows.WindowState`. The new state of the window. The `minimized`, `maximized` and `fullscreen` states cannot be combined with `left`, `top`, `width` or `height`.

`titlePreface` Optional

`string`. Use this to add a string to the beginning of the browser window's title. Depending on the underlying operating system, this might not work on browser windows that don't have a title (such as about:blank in Firefox).

`top` Optional

`integer`. The offset from the top edge of the screen to move the window to in pixels. This value is ignored for panels.

`width` Optional

`integer`. The width to resize the window to in pixels. This value is ignored for panels.

### Return value

A `Promise` that will be fulfilled with a `windows.Window` object containing the details of the updated window. If any 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
--------

When the user clicks a browser action's icon, move the window to the top left corner:

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

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

browser.browserAction.onClicked.addListener((tab) => {
  let updating = browser.windows.update(tab.windowId, {
    left: 0,
    top: 0,
  });
  updating.then(onUpdated, onError);
});
```

### Example extensions

* window-manipulator

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


windows.remove() - Mozilla

windows.remove()
================

Closes a window and all the tabs inside it, given the window's ID.

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

Syntax
------

```js
let removing = browser.windows.remove(
  windowId        // integer
)
```

### Parameters

`windowId`

`integer`. ID of the window to close.

### Return value

A `Promise` that will be fulfilled with no arguments when the window has been closed. If any 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
--------

When the user clicks a browser action's icon, close the window in which the icon was clicked:

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

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

browser.browserAction.onClicked.addListener((tab) => {
  let removing = browser.windows.remove(tab.windowId);
  removing.then(onRemoved, onError);
});
```

Close the current, e.g. popup, window when the user clicks a button on the page:

```js
// in a script loaded by the page in the window
document.querySelector("#close").addEventListener(async ({ button }) => {
  try {
    if (button) return; // not a left click
    const windowId = (await browser.windows.getCurrent()).id;
    await browser.windows.remove(windowId);
    // this point will never be reached, since the window is gone
  } catch (error) {
    console.error("Closing failed:", error);
  }
});
```

In Firefox, the same could be achieved with the `.allowScriptsToClose` window creation property and `window.close()`.

### Example extensions

* window-manipulator

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


windows.Window - Mozilla

windows.Window
==============

Information about a browser window.

Type
----

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

`alwaysOnTop`

`boolean`. Whether the window is set to be always on top.

`focused`

`boolean`. Whether the window is currently the focused window.

`height` Optional

`integer`. The height of the window, including the frame, in pixels.

`id` Optional

`integer`. The ID of the window. Window IDs are unique within a browser session.

`incognito`

`boolean`. Whether the window is incognito (private).

`left` Optional

`integer`. The offset of the window from the left edge of the screen in pixels.

`sessionId` Optional

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

`state` Optional

A `windows.WindowState` value representing the state of this browser window — maximized, minimized, etc.

`tabs` Optional

Array of `tabs.Tab` objects representing the current tabs in the window.

`title` Optional

The title of the browser window. Requires "tabs" permission or host permissions for the active tab's URL. Read only.

`top` Optional

`integer`. The offset of the window from the top edge of the screen in pixels.

`type` Optional

A `windows.WindowType` value representing the type of browser window this is — normal browser window, popup, etc.

`width` Optional

`integer`. The width of the window, including the frame, in pixels.

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


sidebarAction.getTitle() - Mozilla

sidebarAction.getTitle()
========================

Gets the sidebar's title.

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

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

Syntax
------

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

### Parameters

`details`

`object`. An object with the following properties:

`tabId` Optional

`integer`. Get the title for the sidebar specific to the given tab.

`windowId` Optional

`integer`. Get the title for the sidebar specific to the given window.

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

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

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

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

Examples
--------

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

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

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

**Note:** This API is based on Opera's `chrome.sidebarAction` API.


sidebarAction.toggle() - Mozilla

sidebarAction.toggle()
======================

Toggles the visibility of the sidebar in the active window, if the sidebar belongs to the extension.

You can only call this function from inside the handler for a user action.

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

Syntax
------

```js
browser.sidebarAction.toggle()
```

### Parameters

None.

### Return value

A `Promise` that is resolved with no arguments.

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

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

Examples
--------

Toggles the sidebar when the user selects an item from the context menu:

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

browser.menus.onClicked.addListener(() => {
  browser.sidebarAction.toggle();
});
```


sidebarAction.close() - Mozilla

sidebarAction.close()
=====================

Closes the sidebar in the active window, if it is the extension's own sidebar.

You can only call this function from inside the handler for a user action.

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

Syntax
------

```js
browser.sidebarAction.close()
```

### Parameters

None.

### Return value

A `Promise` that is resolved with no arguments.

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

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

Examples
--------

Close the sidebar when the user selects a context menu item:

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

browser.menus.onClicked.addListener(() => {
  browser.sidebarAction.close();
});
```


sidebarAction.getPanel() - Mozilla

sidebarAction.getPanel()
========================

Gets a URL to the HTML document that defines the sidebar's contents.

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

Syntax
------

```js
let gettingPanel = browser.sidebarAction.getPanel(
  details               // object
)
```

### Parameters

`details`

`object`. An object with the following properties:

`tabId` Optional

`integer`. Get the panel for the sidebar specific to the given tab.

`windowId` Optional

`integer`. Get the panel for the sidebar specific to the given window.

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

A `Promise` that will be fulfilled with a string containing the URL for the panel's document. This will be a fully qualified URL, such as:

```url
moz-extension://d1d8a2eb-fe60-f646-af30-a866c5b39942/sidebar.html
```

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

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

Examples
--------

Get the panel's URL:

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

let gettingPanel = browser.sidebarAction.getPanel({});
gettingPanel.then(onGot);
```

**Note:** This API is based on Opera's `chrome.sidebarAction` API.


sidebarAction.isOpen() - Mozilla

sidebarAction.isOpen()
======================

Returns `true` if the extension's sidebar is open in a given window.

This function accepts a `windowId` as a parameter:

* If you supply `windowId`, the function will check the given browser window.
* If you omit `windowId`, the function will check the topmost browser window.

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

Syntax
------

```js
let gettingIsOpen = browser.sidebarAction.isOpen(
  details // object
)
```

### Parameters

`details`

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

`windowId` Optional

`integer`. ID of a browser window to check. If omitted defaults to `windows.WINDOW_ID_CURRENT`, which refers to the topmost browser window.

### Return value

A `Promise` that will be fulfilled with `true` if the extension's sidebar is open in the given window, or `false` otherwise.

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

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

Examples
--------

Check the topmost window:

```js
browser.sidebarAction.isOpen({}).then((result) => {
  console.log(result);
});
```

Check all open windows:

```js
async function checkWindow(windowId) {
  const result = await browser.sidebarAction.isOpen({ windowId });
  console.log(`window: ${windowId} status: ${result}`);
}

browser.windows.getAll().then((all) => {
  for (const { id } of all) {
    checkWindow(id);
  }
});
```


sidebarAction.setTitle() - Mozilla

sidebarAction.setTitle()
========================

Sets the sidebar's title. The title is displayed anywhere the browser lists available sidebars. For example, Firefox will show it in the "View > Sidebar" menu. It's also shown at the top o the sidebar when the sidebar is open.

Types of title
--------------

Your extension should specify an title for the sidebar in the sidebar\_action manifest key. This is called the *"manifest title"*. If you don't specify the manifest title, it will default to the extension name.

If you set a new title using `setTitle()`, and include the `tabId` option, then the title is set only for the given tab. This title is called the *"tab-specific title"*.

If you set a new title using `setTitle()`, and include the `windowId` option, then the title is set only for the given window. This title is called the *"window-specific title"*, and will appear in all tabs of that window that do not have a tab-specific title set.

If you set a new title using `setTitle()`, and omit both the `tabId` and `windowId` options, then this sets the *"global title"*. The global title will then appear in all tabs that do not have a tab-specific title set and whose window does not have a window-specific title.

Syntax
------

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

### Parameters

`details`

`object`. An object with the following properties:

`title`

`string` or `null`. The sidebar's new title.

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

If `title` is `null`, then a previously set title will be removed, so that:

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

`tabId` Optional

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

`windowId` Optional

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

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

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

Examples
--------

This code changes the title for the sidebar when the user clicks a browser action, but only for the current tab:

```js
let title = "A different title";

function setTitleForTab(tab) {
  browser.sidebarAction.setTitle({ title, tabId: tab.id });
}

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

**Note:** This API is based on Opera's `chrome.sidebarAction` API.


sidebarAction.setIcon() - Mozilla

sidebarAction.setIcon()
=======================

Sets the icon for the sidebar.

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

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

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

Types of icon
-------------

Your extension should specify an icon for the sidebar in the `sidebar_action` manifest key. This is called the *"manifest icon"*.

If you don't specify an icon in the `sidebar_action` key, you get the browser's default icon. This is called the *"default icon"*.

If you set a new icon using `setIcon()`, and include the `tabId` option, then the icon is set only for the given tab. This icon is called the *"tab-specific icon"*.

If you set a new icon using `setIcon()`, and include the `windowId` option, then the icon is set only for the given window. This icon is called the *"window-specific icon"*, and will appear in all tabs of that window that do not have a tab-specific icon set.

If you set a new icon using `setIcon()`, and omit both the `tabId` and `windowId` options, then this sets the *"global icon"*. The global icon will then appear in all tabs that do not have a tab-specific icon set and whose window does not have a window-specific icon.

Syntax
------

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

### Parameters

`details`

`object`. An object with the following properties:

`imageData` Optional

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

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

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

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

`path` Optional

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

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

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

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

If `path` is an empty string, the browser will use the default icon.

If `path` is not empty but does not point to an icon file, then the icon is hidden.

If `path` is `null`, and `tabId` was specified, and the specified tab had a tab-specific icon set: then the tab-specific icon is reset to the global icon (if a global icon is set) or the manifest icon.

if `path` is `null`, and `tabId` was omitted, and there was a global icon set, it will be reset to the manifest icon.

`tabId` Optional

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

`windowId` Optional

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

* If `windowId` and `tabId` are both specified, the function fails and the icon is not set.
* If `windowId` and `tabId` are both omitted, the icon is set globally.
### Return value

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

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

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

Examples
--------

The code below toggles the sidebar icon for the active tab when the user clicks a browser action:

```js
let on = false;

function toggle(tab) {
  if (on) {
    browser.sidebarAction.setIcon({
      path: "off.svg",
      tabId: tab.id,
    });
    on = false;
  } else {
    browser.sidebarAction.setIcon({
      path: "on.svg",
      tabId: tab.id,
    });
    on = true;
  }
}

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

**Note:** This API is based on Opera's `chrome.sidebarAction` API.


sidebarAction.setPanel() - Mozilla

sidebarAction.setPanel()
========================

Sets the sidebar's panel: that is, the HTML document that defines the content of this sidebar.

Types of panel
--------------

Sidebars always have a *"manifest panel"*, which is the panel defined in the `sidebar_action` manifest key.

If you set a new panel using `setPanel()`, and include the `tabId` option, then the panel is set only for the given tab. This panel is referred to as the *"tab-specific panel"*.

If you set a new panel using `setPanel()`, and include the `windowId` option, then the panel is set only for the given window. This panel is referred to as the *"window-specific panel"*, and will appear in all tabs of that window that do not have a tab-specific panel set.

If you set a new panel using `setPanel()`, and omit both the `tabId` and `windowId` options, then this sets the *"global panel"*. The global panel will then appear in all tabs that do not have a tab-specific panel set and whose window does not have a window-specific panel.

Syntax
------

```js
browser.sidebarAction.setPanel(
  details // object
)
```

### Parameters

`details`

`object`. An object with the following properties:

`panel`

`string` or `null`. The panel to load into the sidebar, specified as a URL pointing to an HTML document, or `null`, or an empty string.

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

If `panel` is `null` or `""`, then a previously set panel will be removed, so that:

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

`tabId` Optional

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

`windowId` Optional

`integer`. Sets the panel only for the given window.

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

This code toggles the sidebar document when the user clicks a browser action:

```js
let thisPanel = browser.runtime.getURL("/this.html");
let thatPanel = browser.runtime.getURL("/that.html");

function toggle(panel) {
  if (panel === thisPanel) {
    browser.sidebarAction.setPanel({ panel: thatPanel });
  } else {
    browser.sidebarAction.setPanel({ panel: thisPanel });
  }
}

browser.browserAction.onClicked.addListener(() => {
  browser.sidebarAction.getPanel({}).then(toggle);
});
```

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

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

**Note:** This API is based on Opera's `chrome.sidebarAction` API.


sidebarAction.open() - Mozilla

sidebarAction.open()
====================

Open the sidebar in the active window.

You can only call this function from inside the handler for a user action.

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

Syntax
------

```js
browser.sidebarAction.open()
```

### Parameters

None.

### Return value

A `Promise` that is resolved with no arguments.

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

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

Examples
--------

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

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

browser.menus.onClicked.addListener(() => {
  browser.sidebarAction.open();
});
```


sidebarAction.ImageDataType - Mozilla

sidebarAction.ImageDataType
===========================

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

Type
----

An `ImageData` object.

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

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

**Note:** This API is based on Opera's `chrome.sidebarAction` API.


bookmarks.removeTree() - Mozilla

bookmarks.removeTree()
======================

The **`bookmarks.removeTree()`** method recursively removes a bookmark folder and all of its contents.

**Warning:** If your extension attempts to remove a bookmark tree from the bookmarks tree root node, the call will raise an error with the message: "The bookmark root cannot be modified" and the bookmark won't be removed.

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

Syntax
------

```js
let removingTree = browser.bookmarks.removeTree(
  id                // string
)
```

### Parameters

`id`

A `string` specifying the ID of the folder node to be deleted along with its descendants.

### Return value

A `Promise` that will be fulfilled with no arguments when the tree has been removed.

If the node corresponding to the `id` parameter can't be found, the promise is rejected with an error message.

Examples
--------

This example locates a bookmark folder named "MDN" and deletes it along with all of its contents.

```js
function onRemoved() {
  console.log("bookmark item removed!");
}

function onRejected(error) {
  console.log(`An error: ${error}`);
}

function removeMDN(searchResults) {
  if (searchResults.length) {
    let removing = browser.bookmarks.removeTree(searchResults[0].id);
    removing.then(onRemoved, onRejected);
  }
}

let searchingBookmarks = browser.bookmarks.search({ title: "MDN" });
searchingBookmarks.then(removeMDN, onRejected);
```

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


bookmarks.onImportBegan - Mozilla

bookmarks.onImportBegan
=======================

Fired when the browser has started importing a set of bookmarks.

While a set of bookmarks is being imported, `onCreated` may fire a lot of times. If your extension is listening to `onCreated`, and the listener is expensive, you should also listen for `onImportBegan` and `onImportEnded`. When you receive `onImportBegan`, ignore `onCreated` until you receive `onImportEnded`. You can handle all other notifications as usual.

Syntax
------

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

```js
function handleImportBegan() {
  console.log("Importing…");
}

function handleImportEnded() {
  console.log("Import finished.");
}

function handleClick() {
  browser.bookmarks.onImportBegan.addListener(handleImportBegan);
  browser.bookmarks.onImportEnded.addListener(handleImportEnded);
}

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

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


bookmarks.getRecent() - Mozilla

bookmarks.getRecent()
=====================

The `bookmarks.getRecent()` method retrieves a specified number of the most recently added bookmarks as an array of `BookmarkTreeNode` objects.

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

Syntax
------

```js
let gettingRecent = browser.bookmarks.getRecent(
  numberOfItems          // integer
)
```

### Parameters

`numberOfItems`

A number representing the maximum number of items to return. The returned list will contain up to this many of the most recently added items. The minimum allowed value here is 1. If you pass 0 or less, the function will throw an error.

### Return value

A `Promise` that will be fulfilled with an array of `BookmarkTreeNode` objects.

Examples
--------

This example logs the URL for the most recently added bookmark:

```js
function onFulfilled(bookmarks) {
  for (const bookmark of bookmarks) {
    console.log(bookmark.url);
  }
}

function onRejected(error) {
  console.log(`An error: ${error}`);
}

browser.bookmarks.getRecent(1).then(onFulfilled, onRejected);
```

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


bookmarks.onCreated - Mozilla

bookmarks.onCreated
===================

Fired when a bookmark item (a bookmark or a folder) is created.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`id`

`string`. The new bookmark item's ID.

`bookmark`

`bookmarks.BookmarkTreeNode`. Information about the new bookmark item.

Examples
--------

```js
function handleCreated(id, bookmarkInfo) {
  console.log(`New bookmark ID: ${id}`);
  console.log(`New bookmark URL: ${bookmarkInfo.url}`);
}

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

### Example extensions

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


bookmarks.onImportEnded - Mozilla

bookmarks.onImportEnded
=======================

Fired when the browser has finished importing a set of bookmarks.

See `bookmarks.onImportBegan`.

Syntax
------

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

```js
function handleImportBegan() {
  console.log("Importing…");
}

function handleImportEnded() {
  console.log("Import finished.");
}

function handleClick() {
  browser.bookmarks.onImportBegan.addListener(handleImportBegan);
  browser.bookmarks.onImportEnded.addListener(handleImportEnded);
}

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

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


bookmarks.CreateDetails - Mozilla

bookmarks.CreateDetails
=======================

The `CreateDetails` type is used to describe the properties of a new, bookmark, bookmark folder, or separator when calling the `bookmarks.create()` method.

Type
----

An `object` containing some combination of the following fields:

`index` Optional

An integer `Number` which specifies the position at which to place the new bookmark under its parent. A value of 0 will put it at the top of the list.

`parentId` Optional

A `string` which indicates the ID of the parent folder into which to place the new bookmark or bookmark folder. On Chrome and Firefox, the default is the "Other Bookmarks" folder on the Bookmarks menu.

`title` Optional

A `string` which specifies the title for the bookmark or the name of the folder to be created. If this isn't specified, the title is `""`.

`type` Optional

A `bookmarks.BookmarkTreeNodeType` object indicating whether this is a bookmark, a folder, or a separator. Defaults to `"bookmark"` unless `url` is omitted, in which case it defaults to `"folder"`.

`url` Optional

`string`. A `string` which specifies the URL of the page to bookmark. If this is omitted or is `null`, a folder is created instead of a bookmark.

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


bookmarks.BookmarkTreeNodeUnmodifiable - Mozilla

bookmarks.BookmarkTreeNodeUnmodifiable
======================================

The **`bookmarks.BookmarkTreeNodeUnmodifiable`** type is used to indicate the reason that a node in the bookmark tree (where each node is either a bookmark or a bookmark folder) cannot be changed. This is used as the value of the `bookmarks.BookmarkTreeNode.unmodifiable.unmodifiable` field on bookmark nodes.

Type
----

`bookmarks.BookmarkTreeNodeUnmodifiable` is a `string` which can currently have only one value: `"managed"`. This indicates that the bookmark node was configured by an administrator or by the custodian of a supervised user (such as a parent, in the case of parental controls).

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


bookmarks.move() - Mozilla

bookmarks.move()
================

The **`bookmarks.move()`** method moves the specified `BookmarkTreeNode` to the specified destination within the tree of bookmarks. This lets you move a bookmark to a new folder and/or position within the folder.

**Warning:** If your extension attempts to move a bookmark into the bookmarks tree root node, the call will raise an error with the message: "*The bookmark root cannot be modified*" and the move won't be completed.

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

Syntax
------

```js
let movingBookmark = browser.bookmarks.move(
  id,                    // string
  destination           // object
)
```

### Parameters

`id`

A `string` containing the ID of the bookmark or folder to move.

`destination`

An `object` which specifies the destination for the bookmark. This object must contain one or both of the following fields:

`parentId` Optional

A `string` which specifies the ID of the destination folder. If this value is left out, the bookmark is moved to a new location within its current folder.

`index` Optional

A 0-based index specifying the position within the folder to which to move the bookmark. A value of 0 moves the bookmark to the top of the folder. If this value is omitted, the bookmark is placed at the end of the new parent folder.

### Return value

A `Promise` that will be fulfilled with a single `bookmarks.BookmarkTreeNode` object, describing the moved node.

If the node corresponding to the `id` parameter can't be found, the promise is rejected with an error message.

**Note:** If you move multiple bookmarks, because this API is asynchronous, the move calls may get processed in any order. Consequently, the value of each bookmark's index returned in `BookmarkTreeNode` may change or be unknown until all the move calls are completed. If the index associated with a bookmark matters to your extension, then – when moving multiple bookmarks – the extension should wait for each `bookmarks.move` call to complete before moving the next bookmark. Waiting ensures that the index associated with each bookmark is not affected by a move call executing concurrently while the original call is in progress.

Examples
--------

This example moves a bookmark so that it's the first bookmark in its current folder.

```js
function onMoved(bookmarkItem) {
  console.log(bookmarkItem.index);
}

function onRejected(error) {
  console.log(`An error: ${error}`);
}

let bookmarkId = "abcdefghijkl";

let movingBookmark = browser.bookmarks.move(bookmarkId, { index: 0 });
movingBookmark.then(onMoved, onRejected);
```

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


bookmarks.BookmarkTreeNodeType - Mozilla

bookmarks.BookmarkTreeNodeType
==============================

The **`bookmarks.BookmarkTreeNodeType`** type is used to describe whether a node in the bookmark tree is a bookmark, a folder, or a separator.

Type
----

`bookmarks.BookmarkTreeNodeType` is a `string` which can have one of the following three values:

* `"bookmark"`: the node is a bookmark.
* `"folder"`: the node is a folder.
* `"separator"`: the node is a separator.
Browser compatibility
---------------------

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


bookmarks.getTree() - Mozilla

bookmarks.getTree()
===================

**`bookmarks.getTree()`** returns an array containing the root of the bookmarks tree as a `bookmarks.BookmarkTreeNode` object.

You can access the entire tree recursively using its `children` property and the `children` property of its descendants, if they are themselves folders.

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

Syntax
------

```js
let gettingTree = browser.bookmarks.getTree()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an array containing one object, a `bookmarks.BookmarkTreeNode` object representing the root node.

Examples
--------

This example prints out the entire bookmarks tree:

```js
function makeIndent(indentLength) {
  return ".".repeat(indentLength);
}

function logItems(bookmarkItem, indent) {
  if (bookmarkItem.url) {
    console.log(makeIndent(indent) + bookmarkItem.url);
  } else {
    console.log(`${makeIndent(indent)}Folder`);
    indent++;
  }
  if (bookmarkItem.children) {
    for (const child of bookmarkItem.children) {
      logItems(child, indent);
    }
  }
  indent--;
}

function logTree(bookmarkItems) {
  logItems(bookmarkItems[0], 0);
}

function onRejected(error) {
  console.log(`An error: ${error}`);
}

let gettingTree = browser.bookmarks.getTree();
gettingTree.then(logTree, onRejected);
```

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


bookmarks.onRemoved - Mozilla

bookmarks.onRemoved
===================

Fired when a bookmark or folder is removed. When a folder is removed recursively, a single notification is fired for the folder, and none for its contents.

Syntax
------

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

`id`

`string`. ID of the item that was removed.

`removeInfo`

`object`. More details about the removed item. See the removeInfo section for more details.

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

### removeInfo

`parentId`

`string`. ID of the item's parent in the tree.

`index`

`integer`. Zero-based index position of this item in its parent.

`node`

`bookmarks.BookmarkTreeNode`. Detailed information about the item that was removed.

Examples
--------

```js
function handleRemoved(id, removeInfo) {
  console.log(`Item: ${id} removed`);
  console.log(`Title: ${removeInfo.node.title}`);
  console.log(`Url: ${removeInfo.node.url}`);
}

function handleClick() {
  browser.bookmarks.onRemoved.addListener(handleRemoved);
}

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

### Example extensions

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