bookmarks.search() - Mozilla

bookmarks.search()
==================

The **`bookmarks.search()`** function searches for bookmark tree nodes matching the given query.

This function throws an exception if any of the input parameters are invalid or are not of an appropriate type; look in the console for the error message. The exceptions don't have error IDs, and the messages themselves may change, so don't write code that tries to interpret them.

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

Syntax
------

```js
let searching = browser.bookmarks.search(
  query                  // string or object
)
```

### Parameters

`query`

A `string` or `object` describing the query to perform.

If `query` is a **string**, it consists of zero or more space-delimited search terms. Each search term matches if it is a substring in the bookmark's URL or title. Matching is case-insensitive. For a bookmark to match the query, all the query's search terms must be matched.

If `query` is an **object**, it consists of zero or more of 3 properties: `query`, `title`, and `url`, which are described below. For a bookmark to match the query, all the properties' terms must be matched.

`query` Optional

A `string` specifying one or more terms to match against; the format is identical to the string form of the `query` parameter. If this isn't a string, an exception is thrown.

`url` Optional

A `string` that must exactly match the bookmark's URL. Matching is case-insensitive, and trailing slashes are ignored.

If you pass an invalid URL, the function will throw an exception.

`title` Optional

A `string` that must exactly match the bookmark tree node's title. Matching is case-sensitive.

### Return value

A `Promise` that will be fulfilled with an array of `bookmarks.BookmarkTreeNode` objects, each representing a single matching bookmark tree node. Results are returned in the order that the nodes were created. The array is empty if no results were found.

The `BookmarkTreeNodes`—even nodes of the `"folder"` type—returned by `bookmarks.search()` are missing the `children` property. To get a complete `BookmarkTreeNode` use `bookmarks.getSubTree()`.

Example
-------

This example logs the IDs of all bookmarks:

```js
function onFulfilled(bookmarkItems) {
  for (const item of bookmarkItems) {
    console.log(item.id);
  }
}

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

browser.bookmarks.search({}).then(onFulfilled, onRejected);
```

This example looks to see if the currently active tab is bookmarked:

```js
function onFulfilled(bookmarkItems) {
  if (bookmarkItems.length) {
    console.log("active tab is bookmarked");
  } else {
    console.log("active tab is not bookmarked");
  }
}

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

function checkActiveTab(tab) {
  browser.bookmarks.search({ url: tab.url }).then(onFulfilled, onRejected);
}

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

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

bookmarks.update()
==================

**`bookmarks.update()`** updates the title and/or URL of a bookmark, or the name of a bookmark folder.

**Warning:** If your extension attempts to update a bookmark in 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 updated.

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

Syntax
------

```js
let updating = browser.bookmarks.update(
  id,                    // string
  changes                // object
)
```

### Parameters

`id`

A `string` specifying the ID of the bookmark or bookmark folder to update.

`changes`

An `object` specifying the changes to apply, with some combination of the following fields. Any items not specified aren't changed in the referenced bookmark or folder:

`title` Optional

A `string` containing the new title of the bookmark, or the new name of the folder if `id` refers to a folder.

`url` Optional

A `string` providing a new URL for the bookmark.

### Return value

A `Promise` that will be fulfilled with a single `bookmarks.BookmarkTreeNode` object, representing the updated bookmark. If the bookmark item corresponding to the `id` parameter can't be found, the promise is rejected.

Examples
--------

This example renames all folders named "MDN" to "Mozilla Developer Network (MDN)".

```js
function onFulfilled(bookmarkItem) {
  console.log(bookmarkItem.title);
}

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

function updateFolders(items) {
  for (const item of items) {
    // only folders, so skip items with a `url`
    if (!item.url) {
      browser.bookmarks
        .update(item.id, {
          title: "Mozilla Developer Network (MDN)",
        })
        .then(onFulfilled, onRejected);
    }
  }
}

browser.bookmarks.search({ title: "MDN" }).then(updateFolders, 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.getSubTree() - Mozilla

bookmarks.getSubTree()
======================

The **`bookmarks.getSubTree()`** method asynchronously retrieves a `bookmarks.BookmarkTreeNode`, given its ID.

If the item is a folder, you can access all its descendants 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 gettingSubTree = browser.bookmarks.getSubTree(
  id                     // string
)
```

### Parameters

`id`

A `string` specifying the ID of the root of the subtree to retrieve.

### Return value

A `Promise` that is fulfilled with an array containing an object, a `bookmarks.BookmarkTreeNode` object, representing the item with the given ID.

If a node corresponding to `id` could not be found, the promise will be rejected with an error message.

Examples
--------

This example recursively prints out the subtree under a given node:

```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: ${bookmarkItem.id}`);
    indent++;
  }
  if (bookmarkItem.children) {
    for (const child of bookmarkItem.children) {
      logItems(child, indent);
    }
  }
}

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

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

let subTreeID = "root\_\_\_\_\_";

browser.bookmarks.getSubTree(subTreeID).then(logSubTree, 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.onMoved - Mozilla

bookmarks.onMoved
=================

Fired when a bookmark or folder is moved to a different parent folder or position within a folder.

**Note:** If you're moving multiple bookmarks, because this API is asynchronous, the move calls may get processed in any order. Consequently, the value of each bookmark's index 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.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`id`

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

`moveInfo`

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

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

### moveInfo

`parentId`

`string`. The new parent folder.

`index`

`integer`. The new index of this item in its parent.

`oldParentId`

`string`. The old parent folder.

`oldIndex`

`integer`. The old index of the item in its parent.

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

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

Examples
--------

```js
function handleMoved(id, moveInfo) {
  console.log(`Item: ${id} moved`);
  console.log(`Old index: ${moveInfo.oldIndex}`);
  console.log(`New index: ${moveInfo.index}`);
  console.log(`Old folder: ${moveInfo.oldParentId}`);
  console.log(`New folder: ${moveInfo.parentId}`);
}

function handleClick() {
  browser.bookmarks.onMoved.addListener(handleMoved);
}

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

bookmarks.remove()
==================

The **`bookmarks.remove()`** method removes a single bookmark or an empty bookmark folder.

**Warning:** If your extension attempts to remove a bookmark 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 removingBookmark = browser.bookmarks.remove(
  id                 // string
)
```

### Parameters

`id`

A `string` specifying the ID of the bookmark or empty folder to remove.

### Return value

A `Promise` that will be fulfilled with no arguments.

If the node corresponding to the `id` parameter can't be found or was a non-empty folder, the promise is rejected with an error message.

Examples
--------

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

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

let bookmarkId = "abcdefghijkl";

let removingBookmark = browser.bookmarks.remove(bookmarkId);
removingBookmark.then(onRemoved, onRejected);
```

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

bookmarks.getChildren()
=======================

**`bookmarks.getChildren()`** retrieves all the immediate children of a bookmark folder, identified as a `BookmarkTreeNode` ID.

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

Syntax
------

```js
let gettingChildren = browser.bookmarks.getChildren(
  id                     // string
)
```

### Parameters

`id`

A `string` that specifies the ID of the folder whose children are to be retrieved.

### Return value

A `Promise` that is fulfilled with an array of `BookmarkTreeNode` objects. Each entry represents a child node. The list is in the same order as the bookmarks appear in the user interface. Separators are included in the results. The list includes subfolders but does not include any children contained in subfolders.

If the specified node has no children, the array is empty.

If the node identified by `id` is not found, the promise is rejected with an error message.

Examples
--------

```js
function onFulfilled(children) {
  for (child of children) {
    console.log(child.id);
  }
}

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

let gettingChildren = browser.bookmarks.getChildren("unfiled\_\_\_\_\_");
gettingChildren.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.BookmarkTreeNode - Mozilla

bookmarks.BookmarkTreeNode
==========================

An object of type `bookmarks.BookmarkTreeNode` represents a node in the bookmark tree, where each node is a bookmark, a bookmark folder, or a separator. Child nodes are ordered by an `index` within their respective parent folders.

Type
----

An `object` with the following properties:

`children` Optional

An `array` of `bookmarks.BookmarkTreeNode` objects which represent the node's children. The list is ordered in the list in which the children appear in the user interface. This field is omitted if the node isn't a folder.

`dateAdded` Optional

A number representing the creation date of the node in milliseconds since the epoch.

`dateGroupModified` Optional

A number representing the date and time the contents of this folder last changed, in milliseconds since the epoch.

`id`

A `string` which uniquely identifies the node. Each ID is unique within the user's profile and remains unchanged across browser restarts.

`index` Optional

A number which represents the zero-based position of this node within its parent folder, where zero represents the first entry.

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

`parentId` Optional

A `string` which specifies the ID of the parent folder. This property is not present in the root node.

`title`

A `string` which contains the text displayed for the node in menus and lists of bookmarks.

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

`unmodifiable` Optional

A `string` as described by the type `bookmarks.BookmarkTreeNodeUnmodifiable`. Represents the reason that the node can't be changed. If the node can be changed, this is omitted.

`url` Optional

A `string` which represents the URL for the bookmark. If the node represents a folder, this property is omitted.

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

bookmarks.create()
==================

Creates a bookmark or folder as a child of the `BookmarkTreeNode` with the specified `parentId`. To create a folder, omit or leave empty the `CreateDetails.url` parameter.

**Warning:** If your extension tries to create a new bookmark in the bookmark tree's root node, it raises an error: "*The bookmark root cannot be modified*" and the bookmark won't be created.

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

Syntax
------

```js
let createBookmark = browser.bookmarks.create(
  bookmark                  // CreateDetails object
)
```

### Parameters

`bookmark`

A `bookmarks.CreateDetails` object.

### Return value

A `Promise` that will be fulfilled with a `BookmarkTreeNode` that describes the new bookmark node.

**Note:** If you create multiple bookmarks, because this API is asynchronous, the create 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 create calls are completed. If the index associated with a bookmark matters to your extension, then – when creating multiple bookmarks – the extension should wait for each `bookmarks.create` call to complete before creating the next bookmark. Waiting ensures that the index associated with each bookmark is not affected by a create call executing concurrently while the original call is in progress.

Examples
--------

This example creates a bookmark for this page, placing it in the default folder ("Other Bookmarks" in Firefox and Chrome).

```js
function onCreated(node) {
  console.log(node);
}

let createBookmark = browser.bookmarks.create({
  title: "bookmarks.create() on MDN",
  url: "https://developer.mozilla.org/Add-ons/WebExtensions/API/bookmarks/create",
});

createBookmark.then(onCreated);
```

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

bookmarks.get()
===============

Given the ID of a `bookmarks.BookmarkTreeNode` or an array of such IDs, the **`bookmarks.get()`** method retrieves the matching nodes.

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

Syntax
------

```js
let getBookmarks = browser.bookmarks.get(
  idOrIdList                // string or string array
)
```

### Parameters

`idOrIdList`

`string` A `string` or `array` of strings specifying the IDs of one or more `BookmarkTreeNode` objects to retrieve.

### Return value

A `Promise` that will be fulfilled with an array of `BookmarkTreeNode`, one for each matching node. Separators are not included in the results. If no nodes could be found, the promise will be rejected with an error message.

Examples
--------

This example tries to get the bookmark whose ID is `bookmarkAAAA`. If no bookmark with this ID exists, `onRejected` is called:

```js
function onFulfilled(bookmarks) {
  console.log(bookmarks);
}

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

let gettingBookmarks = browser.bookmarks.get("bookmarkAAAA");
gettingBookmarks.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.onChanged - Mozilla

bookmarks.onChanged
===================

Fired when there is a change to:

* the title or URL of a bookmark
* the name of a folder.
Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`id`

`string`. ID of the item that changed.

`changeInfo`

`object`. Object containing two properties: `title`, a string containing the item's title, and `url`, a string containing the item's URL. If the item is a folder, `url` is omitted.

**Note:** Multiple events may occur when a bookmark changes, and that changeInfo object may contain only the data that has changed, rather than all the data for the bookmark. In other words, if the `url` for a bookmark changes, the changeInfo may only contain the new `url` information.

Examples
--------

```js
function handleChanged(id, changeInfo) {
  console.log(`Item: ${id} changed`);
  console.log(`Title: ${changeInfo.title}`);
  console.log(`Url: ${changeInfo.url}`);
}

function handleClick() {
  browser.bookmarks.onChanged.addListener(handleChanged);
}

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

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.onChildrenReordered - Mozilla

bookmarks.onChildrenReordered
=============================

Fired when the children of a folder have changed their order due to the order being sorted in the UI. This is not called as a result of a call to `bookmarks.move()` or a drag operation in the UI.

Syntax
------

```js
browser.bookmarks.onChildrenReordered.addListener(listener)
browser.bookmarks.onChildrenReordered.removeListener(listener)
browser.bookmarks.onChildrenReordered.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 folder whose children were reordered.

`reorderInfo`

`object`. Object containing Additional objects. See the reorderInfo section for more details.

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

### reorderInfo

`childIds`

`array` of `string`. Array containing the IDs of all the bookmark items in this folder, in the order they now appear in the UI.

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

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

Examples
--------

```js
function handleChildrenReordered(id, reorderInfo) {
  console.log(`Item: ${id} children reordered`);
  console.log(`Children: ${reorderInfo.childIds}`);
}

function handleClick() {
  browser.bookmarks.onChildrenReordered.addListener(handleChildrenReordered);
}

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.


idle.IdleState - Mozilla

idle.IdleState
==============

String describing the device's idle state.

Type
----

Values of this type are strings. Possible values are: `"active"`, `"idle"`, `"locked"`.

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


idle.queryState() - Mozilla

idle.queryState()
=================

Returns `"locked"` if the system is locked, `"idle"` if the user has not generated any input for a specified number of seconds, or `"active"` otherwise.

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

Syntax
------

```js
let querying = browser.idle.queryState(
  detectionIntervalInSeconds // integer
)
```

### Parameters

`detectionIntervalInSeconds`

`integer`. The system is considered idle if `detectionIntervalInSeconds` seconds have elapsed since the last user input detected.

### Return value

A `Promise` that will be fulfilled with an `idle.IdleState` string, indicating the current state.

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

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

Examples
--------

In this simple snippet, we call `queryState()` and then check if the returned `newState` is `idle` or `active`, logging a message as appropriate. Because we have specified a `detectionIntervalInSeconds` of 15, an `idle` state will only be reported if there has been no user activity for at least 15 seconds

```js
function onGot(newState) {
  if (newState === "idle") {
    console.log("Please come back — we miss you!");
  } else if (newState === "active") {
    console.log("Glad to still have you with us!");
  }
}

let querying = browser.idle.queryState(15);
querying.then(onGot);
```

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


idle.setDetectionInterval() - Mozilla

idle.setDetectionInterval()
===========================

Sets the interval, in seconds, used to determine when the system is in an idle state for `idle.onStateChanged` events. The default interval is 60 seconds.

The detection interval is specific to the extension that calls the method. Changing the interval in one extension will not affect the detection interval in another extension.

Syntax
------

```js
browser.idle.setDetectionInterval(
  intervalInSeconds // integer
)
```

### Parameters

`intervalInSeconds`

`integer`. Threshold, in seconds, used to determine when the system is in an idle state. The minimum value you can supply here is 15.

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

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

Examples
--------

```js
browser.idle.setDetectionInterval(15);
```

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


idle.onStateChanged - Mozilla

idle.onStateChanged
===================

Fired when the system changes to an active, idle or locked state. The event listener is passed a string that has one of three values:

* "locked" if the screen is locked or the screensaver activates
* "idle" if the system is unlocked and the user has not generated any input for a specified number of seconds. This number defaults to 60, but can be set using `idle.setDetectionInterval()`.
* "active" when the user generates input on an idle system.
Syntax
------

```js
browser.idle.onStateChanged.addListener(listener)
browser.idle.onStateChanged.removeListener(listener)
browser.idle.onStateChanged.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`newState`

`idle.IdleState`. The new idle state.

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

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

Examples
--------

```js
function newState(state) {
  console.log(`New state: ${state}`);
}

browser.idle.onStateChanged.addListener(newState);
```

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


webNavigation.onTabReplaced - Mozilla

webNavigation.onTabReplaced
===========================

Fired when the contents of the tab is replaced by a different (usually previously pre-rendered) tab.

Syntax
------

```js
browser.webNavigation.onTabReplaced.addListener(
  listener,                   // function
  filter                      // optional object
);
browser.webNavigation.onTabReplaced.removeListener(listener)
browser.webNavigation.onTabReplaced.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`details`

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

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

### details

`replacedTabId`

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

`tabId`

`integer`. The ID of the tab that replaced the old tab.

`timeStamp`

`number`. The time when the replacement happened, in milliseconds since the epoch.

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

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

Examples
--------

```js
function logOnTabReplaced(details) {
  console.log(`onTabReplaced ${details}`);
}

browser.webNavigation.onTabReplaced.addListener(logOnTabReplaced);
```

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


webNavigation.onCommitted - Mozilla

webNavigation.onCommitted
=========================

Fired when a navigation is committed. At least part of the new document has been received from the server and the browser has decided to switch to the new document.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`details`

`object`. Details about the navigation event. See the details section for more information.

`filter` Optional

`object`. An object containing a single property `url`, which is an `Array` of `events.UrlFilter` objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.

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

### details

`tabId`

`integer`. The ID of the tab in which the navigation is about to occur.

`url`

`string`. The URL to which the given frame will navigate.

`processId` Optional
Deprecated

`integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.

`frameId`

`integer`. Frame in which the navigation will occur. `0` indicates that navigation happens in the tab's top-level browsing context, not in a nested `<iframe>`. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.

`parentFrameId`

`integer`. ID of this frame's parent. Set to `-1` if this is a top-level frame.

`timeStamp`

`number`. The time that the navigation was committed, in milliseconds since the epoch.

`transitionType`

`transitionType`. The reason for the navigation. (For example, `"link"` if the user clicked a link, or `"reload"` if the user reloaded the page.)

`transitionQualifiers`

`Array` of `transitionQualifier`. Extra information about the navigation: for example, whether there was a server or client redirect.

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

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

Examples
--------

Logs the target URLs and extra transition information for `onCommitted`, if the target URL's hostname contains "example.com" or starts with "developer".

```js
const filter = {
  url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};

function logOnCommitted(details) {
  console.log(`target URL: ${details.url}`);
  console.log(`transition type: ${details.transitionType}`);
  console.log(`transition qualifiers: ${details.transitionQualifiers}`);
}

browser.webNavigation.onCommitted.addListener(logOnCommitted, filter);
```

### Example extensions

* navigation-stats

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


webNavigation.onDOMContentLoaded - Mozilla

webNavigation.onDOMContentLoaded
================================

Fired when the DOMContentLoaded event is fired in the page. At this point the document is loaded and parsed, and the DOM is fully constructed, but linked resources such as images, stylesheets and subframes may not yet be loaded.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`details`

`object`. Details about the navigation event. See the details section for more information.

`filter` Optional

`object`. An object containing a single property `url`, which is an `Array` of `events.UrlFilter` objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.

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

### details

`tabId`

`integer`. The ID of the tab in which the navigation has occurred.

`url`

`string`. The URL to which the given frame has navigated.

`processId` Optional
Deprecated

`integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.

`frameId`

`integer`. Frame in which the navigation is occurring. `0` indicates that navigation happens in the tab's top-level browsing context, not in a nested `<iframe>`. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.

`timeStamp`

`number`. The time at which `DOMContentLoaded` was fired, in milliseconds since the epoch.

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

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

Examples
--------

Logs the target URLs for `onDOMContentLoaded`, if the target URL's hostname contains "example.com" or starts with "developer".

```js
const filter = {
  url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};

function logOnDOMContentLoaded(details) {
  console.log(`onDOMContentLoaded: ${details.url}`);
}

browser.webNavigation.onDOMContentLoaded.addListener(
  logOnDOMContentLoaded,
  filter,
);
```

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


webNavigation.onBeforeNavigate - Mozilla

webNavigation.onBeforeNavigate
==============================

Fired when the browser is about to start a navigation event.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`details`

`object`. Details about the navigation event. See the details section for more information.

`filter` Optional

`object`. An object containing a single property `url`, which is an `Array` of `events.UrlFilter` objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.

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

### details

`tabId`

`integer`. The ID of the tab in which the navigation is about to occur.

`url`

`string`. The URL to which the given frame will navigate.

`processId` Optional
Deprecated

`integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.

`frameId`

`integer`. Frame in which the navigation is about to occur. `0` indicates that navigation happens in the tab's top-level browsing context, not in a nested `<iframe>`. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.

`parentFrameId`

`integer`. ID of this frame's parent. Set to `-1` if this is a top-level frame.

`timeStamp`

`number`. The time when the browser is about to start the navigation, in milliseconds since the epoch.

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

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

Examples
--------

Logs the target URLs for `onBeforeNavigate`, if the target's hostname contains "example.com" or starts with "developer".

```js
const filter = {
  url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};

function logOnBefore(details) {
  console.log(`onBeforeNavigate to: ${details.url}`);
}

browser.webNavigation.onBeforeNavigate.addListener(logOnBefore, filter);
```

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


webNavigation.onCompleted - Mozilla

webNavigation.onCompleted
=========================

Fired when a document, including the resources it refers to, is completely loaded and initialized. This is equivalent to the DOM `load` event.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`details`

`object`. Details about the navigation event. See the details section for more information.

`filter` Optional

`object`. An object containing a single property `url`, which is an `Array` of `events.UrlFilter` objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.

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

### details

`tabId`

`integer`. The ID of the tab in which the navigation has occurred.

`url`

`string`. The URL to which the given frame has navigated.

`processId` Optional
Deprecated

`integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.

`frameId`

`integer`. Frame in which the navigation has occurred. `0` indicates that navigation happened in the tab's top-level browsing context, not in a nested `<iframe>`. A positive value indicates that navigation happened in a nested iframe. Frame IDs are unique for a given tab and process.

`timeStamp`

`number`. The time at which the page finished loading, in milliseconds since the epoch.

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

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

Examples
--------

Logs the target URLs for `onCompleted`, if the target URL's hostname contains "example.com" or starts with "developer".

```js
const filter = {
  url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};

function logOnCompleted(details) {
  console.log(`onCompleted: ${details.url}`);
}

browser.webNavigation.onCompleted.addListener(logOnCompleted, filter);
```

### Example extensions

* navigation-stats

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


webNavigation.onErrorOccurred - Mozilla

webNavigation.onErrorOccurred
=============================

Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, or the user aborted the navigation.

Syntax
------

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

Events have three functions:

`addListener(listener)`

`addListener(listener, filter)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

The function called when this event occurs.

The `listener` function is called with these arguments:

`details`

`object`. Details about the navigation event. **`details`** has the following properties:

`tabId`

`integer`. The ID of the tab in which the navigation was happening.

`url`

`string`. The URL to which the given frame was navigating.

`processId` Optional
Deprecated

`integer`. This value is never set in modern browsers. It used to represent the ID of the process running the renderer for this tab.

`frameId`

`integer`. Frame in which the navigation was happening.

`0` indicates that navigation happened in the tab's top-level browsing context, not in a nested `<iframe>`.

A positive value indicates that navigation happened in a nested iframe.

Frame IDs are unique for a given tab and process.

`timeStamp`

`number`. The time at which the error occurred, in milliseconds since the epoch.

`error`

`string`. The error code. This is an internal error code, and is not guaranteed to stay the same or be consistent from one browser to another.

`filter` Optional

`object`. An object containing a single property `url`, which is an `Array` of `events.UrlFilter` objects.

If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array.

If you omit this parameter, the event fires for all transitions.

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

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

Examples
--------

Logs the target URLs for `onErrorOccurred`, if the target URL's `hostname` contains `"example.com"` or starts with `"developer"`.

```js
const filter = {
  url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};

function logOnErrorOccurred(details) {
  console.log(`onErrorOccurred: ${details.url}`);
  console.log(details.error);
}

browser.webNavigation.onErrorOccurred.addListener(logOnErrorOccurred, filter);
```

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


webNavigation.onCreatedNavigationTarget - Mozilla

webNavigation.onCreatedNavigationTarget
=======================================

Fired when a new window, or a new tab in an existing window, is created to host the target of a navigation. For example, this event is sent when:

* the user opens a link in a new tab or window
* a web page loads a resource into a new tab or window using `window.open()` (but note that the event is not sent if the browser's popup blocker blocks the load).

The event is not sent if a tab or window is created without a navigation target (for example, if the user opens a new tab by pressing `Ctrl+T`).

If this event is fired, it will be fired before `webNavigation.onBeforeNavigate`.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`details`

`object`. Details about the navigation event. See the details section for more information.

`filter` Optional

`object`. An object containing a single property `url`, which is an `Array` of `events.UrlFilter` objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions. Note that `filter` is not supported in Firefox.

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

### details

`sourceFrameId`

`integer`. ID of the frame from which the navigation is initiated. `0` indicates that the frame is the tab's top-level browsing context, not a nested `<iframe>`. A positive value indicates that navigation is initiated from a nested iframe. Frame IDs are unique for a given tab and process.

`processId` Optional
Deprecated

`integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process the navigation originated from.

`sourceTabId`

`integer`. The ID of the tab from which the navigation is initiated. For example, if the user opens a link in a new tab, this will be the ID of the tab containing the link.

`tabId`

`integer`. The ID of the newly created tab.

`timeStamp`

`number`. The time when the browser created the navigation target, in milliseconds since the epoch.

`url`

`string`. The URL which will be loaded in the new tab.

`windowId`

`number`. The ID of the window in which the new tab is created.

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

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

Examples
--------

Logs the target URL, source Tab ID, and source frame ID for `onCreatedNavigationTarget`, if the target's hostname contains "example.com" or starts with "developer".

```js
const filter = {
  url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};

function logOnCreatedNavigationTarget(details) {
  console.log(`onCreatedNavigationTarget: ${details.url}`);
  console.log(details.sourceTabId);
  console.log(details.sourceFrameId);
}

browser.webNavigation.onCreatedNavigationTarget.addListener(
  logOnCreatedNavigationTarget,
  filter,
);
```

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


webNavigation.onReferenceFragmentUpdated - Mozilla

webNavigation.onReferenceFragmentUpdated
========================================

Fired if the fragment identifier for a page is changed. For example, if a page implements a table of contents using fragments, and the user clicks an entry in the table of contents, this event fires. All future events for this frame will use the updated URL.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`details`

`object`. Details about the navigation event. See the details section for more information.

`filter` Optional

`object`. An object containing a single property `url`, which is an `Array` of `events.UrlFilter` objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.

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

### details

`tabId`

`integer`. The ID of the tab in which the navigation is about to occur.

`url`

`string`. The URL to which the given frame will navigate.

`processId` Optional
Deprecated

`integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.

`frameId`

`integer`. Frame in which the navigation will occur. `0` indicates that navigation happens in the tab's top-level browsing context, not in a nested `<iframe>`. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.

`timeStamp`

`number`. The time that the fragment identifier for the page was changed, in milliseconds since the epoch.

`transitionType`

``transitionType``. The reason for the navigation: for example, `"link"` if the user clicked a link.

`transitionQualifiers`

`Array` of `transitionQualifier`. Extra information about the navigation: for example, whether there was a server or client redirect.

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

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

Examples
--------

Logs the target URLs and extra transition information for `onReferenceFragmentUpdated`, if the target URL's hostname contains "example.com" or starts with "developer".

```js
const filter = {
  url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};

function logOnReferenceFragmentUpdated(details) {
  console.log(`onReferenceFragmentUpdated: ${details.url}`);
  console.log(`Transition type: ${details.transitionType}`);
  console.log(`Transition qualifiers: ${details.transitionQualifiers}`);
}

browser.webNavigation.onReferenceFragmentUpdated.addListener(
  logOnReferenceFragmentUpdated,
  filter,
);
```

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


webNavigation.onHistoryStateUpdated - Mozilla

webNavigation.onHistoryStateUpdated
===================================

Fired when the page used the >history API to update the URL displayed in the browser's location bar. All future events for this frame will use the updated URL.

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`details`

`object`. Details about the navigation event. See the details section for more information.

`filter` Optional

`object`. An object containing a single property `url`, which is an `Array` of `events.UrlFilter` objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.

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

### details

`tabId`

`integer`. The ID of the tab in which the navigation is about to occur.

`url`

`string`. The URL to which the given frame will navigate.

`processId` Optional
Deprecated

`integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.

`frameId`

`integer`. Frame in which the navigation will occur. `0` indicates that navigation happens in the tab's top-level browsing context, not in a nested `<iframe>`. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.

`timeStamp`

`number`. The time that the URL was changed by the history API, in milliseconds since the epoch.

`transitionType`

``transitionType``. The reason for the navigation: for example, `"link"` if the user clicked a link.

`transitionQualifiers`

`Array` of `transitionQualifier`. Extra information about the navigation: for example, whether there was a server or client redirect.

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

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

Examples
--------

Logs the target URLs and extra transition information for `onHistoryStateUpdated`, if the target URL's hostname contains "example.com" or starts with "developer".

```js
const filter = {
  url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};

function logOnHistoryStateUpdated(details) {
  console.log(`onHistoryStateUpdated: ${details.url}`);
  console.log(`Transition type: ${details.transitionType}`);
  console.log(`Transition qualifiers: ${details.transitionQualifiers}`);
}

browser.webNavigation.onHistoryStateUpdated.addListener(
  logOnHistoryStateUpdated,
  filter,
);
```

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


webNavigation.getFrame() - Mozilla

webNavigation.getFrame()
========================

Retrieves information about a particular frame. A frame may be the top-level frame in a tab or a nested `<iframe>`, and is uniquely identified by a tab ID and a frame ID.

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

Syntax
------

```js
let gettingFrame = browser.webNavigation.getFrame(
  details                // object
)
```

### Parameters

`details`

`object`. Information about the frame to retrieve information about.

`tabId`

`integer`. The ID of the tab in which the frame is.

`processId` Optional
Deprecated

`integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.

`frameId`

`integer`. The ID of the frame in the given tab.

### Return value

A `Promise` that will be fulfilled with an object containing the following properties:

`errorOccurred`

`boolean`. True if the last navigation in this frame was interrupted by an error, i.e. the `onErrorOccurred` event fired.

`url`

`string`. The URL currently associated with this frame, if the frame identified by `frameId` existed at one point in the tab identified by `tabId`. The fact that a URL is associated with a given `frameId` does not imply that the corresponding frame still exists.

`parentFrameId`

`integer`. ID of this frame's parent. This is -1 if there is no parent frame: that is, if this frame is the top-level browsing context in the tab.

If the tab is discarded, the promise will instead resolve with a `null` value. If the specified tab or frame ID could not be found, or some other error occurs, the promise will be rejected with an error message.

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

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

Examples
--------

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

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

let gettingFrame = browser.webNavigation.getFrame({
  tabId: 19,
  frameId: 1537,
});

// Edge specific - processId is required not optional, must be integer not null
//let gettingFrame = browser.webNavigation.getFrame({ tabId: 19, processId: 0, frameId: 1537 });

gettingFrame.then(onGot, onError);
```

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


webNavigation.getAllFrames() - Mozilla

webNavigation.getAllFrames()
============================

Given a tab ID, retrieves information about all the frames it contains.

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

Syntax
------

```js
let gettingFrames = browser.webNavigation.getAllFrames(
  details                // object
)
```

### Parameters

`details`

`object`. Information about the tab to retrieve all frames from.

`tabId`

`integer`. The ID of the tab.

### Return value

A `Promise` that will be fulfilled with an array of objects, each of which has the following properties:

`errorOccurred`

`boolean`. True if the last navigation in this frame was interrupted by an error, i.e. the `onErrorOccurred` event fired.

`processId` Optional
Deprecated

`integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.

`frameId`

`integer`. The ID of the frame. If this is the main frame, then `frameId` is zero.

`parentFrameId`

`integer`. ID of this frame's parent. This is -1 if there is no parent frame: that is, if this frame is the top-level browsing context in the tab.

`url`

`string`. The URL currently associated with this frame.

If the tab is discarded, the promise will instead resolve with a `null` value. If the specified tab could not be found, or some other error occurs, the promise will be rejected with an error message.

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

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

Examples
--------

This code logs the URLs of all frames in the active tab, when the user clicks a browser action:

```js
function logFrameInfo(framesInfo) {
  for (const frameInfo of framesInfo) {
    console.log(frameInfo);
  }
}

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

function logAllFrames(tabs) {
  browser.webNavigation
    .getAllFrames({
      tabId: tabs[0].id,
    })
    .then(logFrameInfo, onError);
}

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

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


webNavigation.TransitionType - Mozilla

webNavigation.TransitionType
============================

Cause of the navigation: for example, the user clicked a link, or typed an address, or clicked a bookmark.

Note that many values here are not currently supported in Firefox: see the browser compatibility table for details.

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.

"start\_page"

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


webNavigation.TransitionQualifier - Mozilla

webNavigation.TransitionQualifier
=================================

Extra information about a transition. Note that many values here are not currently supported in Firefox: see the browser compatibility table for details.

Type
----

Values of this type are strings. Possible values are:

"client\_redirect"

Redirect(s) caused by JavaScript running in the page or a "refresh" pragma in the page's meta tag.

"server\_redirect"

Redirect(s) caused by a 3XX HTTP status code sent from the server.

"forward\_back"

The user used the forward or back button to trigger the navigation.

"from\_address\_bar"

The user triggered the navigation from the address bar.

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


find.removeHighlighting() - Mozilla

find.removeHighlighting()
=========================

Remove any highlighting of a previous search that was applied by a previous call to `find.highlightResults()`, or by the browser's native UI.

Syntax
------

```js
browser.find.removeHighlighting()
```

### Parameters

None.

### Return value

None.

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

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

Examples
--------

```js
browser.find.removeHighlighting();
```


find.find() - Mozilla

find.find()
===========

Searches for text in a tab.

You can use this function to search normal HTTP(S) web pages. It searches a single tab: you can specify the ID of a particular tab to search, or it will search the active tab by default. It searches all frames in the tab.

You can make the search case-sensitive and make it match whole words only.

By default, the function just returns the number of matches found. By passing in the `includeRangeData` and `includeRectData` options, you can get more information about the location of the matches in the target tab.

This function stores the results internally, so the next time any extension calls `find.highlightResults()`, then the results of this find call will be highlighted, until the next time someone calls `find()`.

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

Syntax
------

```js
browser.find.find(
  queryphrase,       // string
  options            // optional object
)
```

### Parameters

`options` Optional

`object`. An object specifying additional options. It may take any of the following properties, all optional:

`caseSensitive`

`boolean`. If `true` the, the search is case-sensitive. Defaults to `false`.

`entireWord`

`boolean`. Match only entire words: so "Tok" will not be matched inside "Tokyo". Defaults to `false`.

`includeRangeData`

`boolean`. Include range data in the response, which describe where in the page DOM the match was found. Defaults to `false`.

`includeRectData`

`boolean`. Include rectangle data in the response, which describes where in the rendered page the match was found. Defaults to `false`

`matchDiacritics`

`boolean`. If `true`, the search distinguishes between accented letters and their base letters. For example, when set to `true`, searching for "résumé" does not find a match for "resume". Defaults to `false`.

`tabId`

`integer`. ID of the tab to search. Defaults to the active tab.

`queryphrase`

`string`. The text to search for.

### Return value

A `Promise` that will be fulfilled with an object containing up to three properties:

`count`

`integer`. The number of results found.

`rangeData` Optional

`array`. If `includeRangeData` was given in the `options` parameter, then this property will be included. It is provided as an array of `RangeData` objects, one for each match. Each `RangeData` object describes where in the DOM tree the match was found. This would enable, for example, an extension to get the text surrounding each match, so as to display context for the matches.

The items correspond to the items given in `rectData`, so `rangeData[i]` describes the same match as `rectData[i]`.

Each `RangeData` contains the following properties:

`endOffset`

The ordinal position of the end of the match within its text node.

`endTextNodePos`

The ordinal position of the text node in which the match ended.

`framePos`

The index of the frame containing the match. 0 corresponds to the parent window. Note that the order of objects in the `rangeData` array will sequentially line up with the order of frame indexes: for example, `framePos` for the first sequence of `rangeData` objects will be 0, `framePos` for the next sequence will be 1, and so on.

`startOffset`

The ordinal position of the start of the match within its text node.

`startTextNodePos`

The ordinal position of the text node in which the match started.

`rectData` Optional

`array`. If `includeRectData` was given in the `options` parameter, then this property will be included. It is an array of `RectData` objects. It contains client rectangles for all the text matched in the search, relative to the top-left of the viewport. Extensions can use this to provide custom highlighting of the results.

Each `RectData` object contains rectangle data for a single match. It has two properties:

`rectsAndTexts`

An object containing two properties, both arrays:

* `rectList`: an array of objects which each have four integer properties: `top`, `left`, `bottom`, `right`. These describe a rectangle relative to the top-left of the viewport.
* `textList`: an array of strings, corresponding to the `rectList` array. The entry at `textList[i]` contains the part of the match bounded by the rectangle at `rectList[i]`.

For example, consider part of a web page that looks like this:

![Text reading "this domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission." and a "More information" link.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/find/find/rects-1.png)

If you search for "You may", the match needs to be described by two rectangles:

![This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.". The words "you may" are highlighted.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/find/find/rects-2.png)

In this case, in the `RectData` that describes this match, `rectsAndTexts.rectList` and `rectsAndTexts.textList` will each have 2 items.

* `textList[0]` will contain "You ", and `rectList[0]` will contain its bounding rectangle.
* `textList[1]` will contain "may", and `rectList[1]` will contain *its* bounding rectangle.

`text`

The complete text of the match, "You may" in the example above.

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

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

Examples
--------

### Basic examples

Search the active tab for "banana", log the number of matches, and highlight them:

```js
function found(results) {
  console.log(`There were: ${results.count} matches.`);
  if (results.count > 0) {
    browser.find.highlightResults();
  }
}

browser.find.find("banana").then(found);
```

Search for "banana" across all tabs (note that this requires the "tabs" permission or matching host permissions, because it accesses `tab.url`):

```js
async function findInAllTabs(allTabs) {
  for (const tab of allTabs) {
    const results = await browser.find.find("banana", { tabId: tab.id });
    console.log(`In page "${tab.url}": ${results.count} matches.`);
  }
}

browser.tabs.query({}).then(findInAllTabs);
```

### Using rangeData

In this example the extension uses `rangeData` to get the context in which the match was found. The context is the complete `textContent` of the node in which the match was found. If the match spanned nodes, the context is the concatenation of the `textContent` of all spanned nodes.

Note that for simplicity, this example doesn't handle pages that contain frames. To support this you'd need to split `rangeData` into groups, one per frame, and execute the script in each frame.

The background script:

```js
// background.js

async function getContexts(matches) {
  // get the active tab ID
  const activeTabArray = await browser.tabs.query({
    active: true,
    currentWindow: true,
  });
  const tabId = activeTabArray[0].id;

  // execute the content script in the active tab
  await browser.tabs.executeScript(tabId, { file: "get-context.js" });
  // ask the content script to get the contexts for us
  const contexts = await browser.tabs.sendMessage(tabId, {
    ranges: matches.rangeData,
  });
  for (const context of contexts) {
    console.log(context);
  }
}

browser.browserAction.onClicked.addListener((tab) => {
  browser.find.find("example", { includeRangeData: true }).then(getContexts);
});
```

The content script:

```js
/\*\*
 \* Get all the text nodes into a single array
 \*/
function getNodes() {
  const walker = document.createTreeWalker(
    document,
    window.NodeFilter.SHOW\_TEXT,
    null,
    false,
  );
  const nodes = [];
  while ((node = walker.nextNode())) {
    nodes.push(node);
  }

  return nodes;
}

/\*\*
 \* Gets all text nodes in the document, then for each match, return the
 \* complete text content of nodes that contained the match.
 \* If a match spanned more than one node, concatenate the textContent
 \* of each node.
 \*/
function getContexts(ranges) {
  const contexts = [];
  const nodes = getNodes();

  for (const range of ranges) {
    let context = nodes[range.startTextNodePos].textContent;
    let pos = range.startTextNodePos;
    while (pos < range.endTextNodePos) {
      pos++;
      context += nodes[pos].textContent;
    }
    contexts.push(context);
  }
  return contexts;
}

browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
  sendResponse(getContexts(message.ranges));
});
```

### Using rectData

In this example the extension uses `rectData` to "redact" the matches, by adding black DIVs over the top of their bounding rectangles:

![Three search results with some texted redacted by black rectangles.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/find/find/redacted.png)

Note that in many ways this is a poor way to redact pages.

The background script:

```js
// background.js

async function redact(matches) {
  // get the active tab ID
  const activeTabArray = await browser.tabs.query({
    active: true,
    currentWindow: true,
  });
  const tabId = activeTabArray[0].id;

  // execute the content script in the active tab
  await browser.tabs.executeScript(tabId, { file: "redact.js" });
  // ask the content script to redact matches for us
  await browser.tabs.sendMessage(tabId, { rects: matches.rectData });
}

browser.browserAction.onClicked.addListener((tab) => {
  browser.find.find("banana", { includeRectData: true }).then(redact);
});
```

The content script:

```js
// redact.js

/\*\*
 \* Add a black DIV where the rect is.
 \*/
function redactRect(rect) {
  const redaction = document.createElement("div");
  redaction.style.backgroundColor = "black";
  redaction.style.position = "absolute";
  redaction.style.top = `${rect.top}px`;
  redaction.style.left = `${rect.left}px`;
  redaction.style.width = `${rect.right - rect.left}px`;
  redaction.style.height = `${rect.bottom - rect.top}px`;
  document.body.appendChild(redaction);
}

/\*\*
 \* Go through every rect, redacting them.
 \*/
function redactAll(rectData) {
  for (const match of rectData) {
    for (const rect of match.rectsAndTexts.rectList) {
      redactRect(rect);
    }
  }
}

browser.runtime.onMessage.addListener((message) => {
  redactAll(message.rects);
});
```

### Example extensions

* find-across-tabs


find.highlightResults() - Mozilla

find.highlightResults()
=======================

Highlights the results of a previous call to `find.find()`.

When an extension calls `find()`, the matches are not highlighted automatically, but they are stored by the browser. Call `highlightResults()` to highlight them.

Note that the stored results are global across all extensions, so for example, if extension A calls `find("apple")`, then extension B calls `find("banana")`, then if extension A calls `highlightResults()`, the results for "banana" will be highlighted.

Syntax
------

```js
browser.find.highlightResults(
  options // optional object
)
```

### Parameters

`options` Optional

`object`. An object specifying additional options. It may take any of the following properties, all optional:

`tabId`

`integer`. ID of the tab to highlight. Defaults to the active tab.

`rangeIndex`

`integer`. Index of the range to highlight. Defaults to highlighting all ranges.

`noScroll`

`boolean`. Don't scroll to highlighted item. Defaults to `true`.

### Return value

None.

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

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

Examples
--------

Search the active tab for "banana", log the number of matches, and highlight them:

```js
function found(results) {
  console.log(`There were: ${results.count} matches.`);
  if (results.count > 0) {
    browser.find.highlightResults();
  }
}

browser.find.find("banana").then(found);
```


extensionTypes.ImageFormat - Mozilla

extensionTypes.ImageFormat
==========================

The format of an image.

Type
----

Values of this type are strings. Possible values are: `"jpeg"`, `"png"`.

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

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

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


extensionTypes.ImageDetails - Mozilla

extensionTypes.ImageDetails
===========================

Details about the format, quality, area and scale of a captured image.

Type
----

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

`format` Optional

`extensionTypes.ImageFormat`. The format of the resulting image. Default is `"png"`.

`quality` Optional

`integer`. When format is `"jpeg"`, this controls the quality of the resulting image. It is a number between 0 and 100, which is converted to a value between 0 and 1 and then used as the `encoderOptions` argument to `HTMLCanvasElement.toDataURL()`. If it is omitted, 92 is used. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. This value is ignored for PNG images.

`rect` Optional

An `object` specifying the area of the document to capture, in CSS pixels, relative to the page. All properties default to `0`. The properties are:

* `x`: The coordinate of the left side of the rectangle.
* `y`: The coordinate of the top side of the rectangle.
* `width`: The width of the rectangle.
* `height`: The height of the rectangle.

This option was introduced in Firefox 82. If omitted, the currently visible viewport is captured.

`scale` Optional

`number`. The scale to render at, defaults to `devicePixelRatio`. This option was introduced in Firefox 82.

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


extensionTypes.RunAt - Mozilla

extensionTypes.RunAt
====================

The soonest that the JavaScript or CSS will be injected into the tab.

Type
----

Values of this type are strings. Possible values are: `"document_start"`, `"document_end"`, `"document_idle"`.

* `"document_start"`: corresponds to `loading`. The DOM is still loading.
* `"document_end"`: corresponds to `interactive`. The DOM has finished loading, but resources such as scripts and images may still be loading.
* `"document_idle"`: corresponds to `complete`. The document and all its resources have finished loading.

The default value is `"document_idle"`.

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


extensionTypes.InjectDetails - Mozilla

extensionTypes.InjectDetails
============================

This type is given as a parameter to the `tabs.executeScript()`, `tabs.insertCSS()`, and `tabs.removeCSS()` methods. For the details of its properties and what they are used for, see the documentation pages for those methods:

* `tabs.executeScript()`
* `tabs.insertCSS()`
* `tabs.removeCSS()`


contentScripts.RegisteredContentScript - Mozilla

contentScripts.RegisteredContentScript
======================================

A `RegisteredContentScript` is returned by a call to `contentScripts.register()` and represents the content scripts registered in that call.

It defines a single function `unregister()`, which can be used to unregister the content scripts.

**Note:** If this object is destroyed (for example because it goes out of scope) then the content scripts will be unregistered automatically, so you should keep a reference to this object for as long as you want the content scripts to stay registered.

Methods
-------

`unregister()`

Unregisters the content scripts represented by this object.

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

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

Examples
--------

This code toggles a registered content script on a browser action click:

```js
let registered = null;

async function register() {
  registered = await browser.contentScripts.register({
    matches: ["\*://\*.org/\*"],
    js: [
      {
        code: "document.body.innerHTML = '<h1>This page has been eaten<h1>'",
      },
    ],
    runAt: "document\_idle",
  });
}

function toggle() {
  if (registered) {
    registered.unregister();
    registered = null;
  } else {
    register();
  }
}

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


contentScripts.register() - Mozilla

contentScripts.register()
=========================

Use this function to register one or more content scripts.

It accepts one parameter, which is an object with similar properties to the objects given in the `content_scripts` manifest key (but note that `content_scripts` is an array of objects, while the argument to `register()` is a single object).

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

Syntax
------

```js
let registering = browser.contentScripts.register(
  contentScriptOptions       // object
)
```

### Parameters

`contentScriptOptions`

`object`. A `RegisteredContentScriptOptions` object representing the content scripts to register. It has similar syntax to the objects in the `content_scripts` manifest key array. The differences are:

* property names use camel case, rather than underscores (snake case) — for example, `excludeMatches`, not `exclude_matches`.
* the `js` and `css` properties allow you to register strings as well as URLs, so their syntax has to distinguish these types.

The `RegisteredContentScriptOptions` object has the following properties:

`allFrames` Optional

Same as `all_frames` in the `content_scripts` key.

`cookieStoreId` Optional

A string or array of strings. Registers the content script in the tabs that belong to one or more cookie store IDs. This enables scripts to be registered for all default or non-contextual identity tabs, private browsing tabs (if the extension is enabled in private browsing), the tabs of a contextual identity, or a combination of these. See Work with contextual identities for more information.

`css` Optional

An array of objects. Each object has either a property named `file`, which is a URL starting at the extension's manifest.json and pointing to a CSS file to register, or a property named `code`, which is some CSS code to register.

`excludeGlobs` Optional

Same as `exclude_globs` in the `content_scripts` key.

`excludeMatches` Optional

Same as `exclude_matches` in the `content_scripts` key.

`includeGlobs` Optional

Same as `include_globs` in the `content_scripts` key.

`js` Optional

An array of objects. Each object has either a property named `file`, which is a URL starting at the extension's manifest.json and pointing to a JavaScript file to register, or a property named `code`, which is some JavaScript code to register.

`matchAboutBlank` Optional

Same as `match_about_blank` in the `content_scripts` key.

`matches`

Same as `matches` in the `content_scripts` key.

`runAt` Optional

Same as `run_at` in the `content_scripts` key.

### Return value

A `Promise` that will be fulfilled with a `contentScripts.RegisteredContentScript` object that you can use to unregister the content scripts.

Currently, content scripts are unregistered when the related extension page (from which the content scripts were registered) is unloaded, so you should register a content script from an extension page that persists at least as long as you want the content scripts to stay registered.

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

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

Examples
--------

This example registers the `defaultCode` content script for all `.org` URLs:

```js
const defaultHosts = "\*://\*.org/\*";
const defaultCode =
  "document.body.innerHTML = '<h1>This page has been eaten<h1>'";

async function register(hosts, code) {
  return await browser.contentScripts.register({
    matches: [hosts],
    js: [{ code }],
    runAt: "document\_idle",
  });
}

let registered = register(defaultHosts, defaultCode);
```

This code registers the JS file at content\_scripts/example.js:

```js
const scriptObj = await browser.contentScripts.register({
  js: [{ file: "/content\_scripts/example.js" }],
  matches: ["<all\_urls>"],
  allFrames: true,
  runAt: "document\_start",
});
```

### Example extensions

* content-script-register


contentScripts.RegisteredContentScript.unregister() - Mozilla

contentScripts.RegisteredContentScript.unregister()
===================================================

Unregisters the content scripts represented by this `RegisteredContentScript` object.

Syntax
------

```js
registered.unregister()
```

### Parameters

None.

### Return value

None.

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

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

Examples
--------

This code toggles a registered content script on a browser action click:

```js
let registered = null;

async function register() {
  registered = await browser.contentScripts.register({
    matches: ["\*://\*.org/\*"],
    js: [
      {
        code: "document.body.innerHTML = '<h1>This page has been eaten<h1>'",
      },
    ],
    runAt: "document\_idle",
  });
}

function toggle() {
  if (registered) {
    registered.unregister();
    registered = null;
  } else {
    register();
  }
}

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


notifications.clear() - Mozilla

notifications.clear()
=====================

Clears a notification, given its ID.

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

Syntax
------

```js
let clearing = browser.notifications.clear(
  id                            // string
)
```

### Parameters

`id`

`string`. The ID of the notification to clear. This is the same as the ID passed into `notifications.create()`'s callback.

### Return value

A `Promise` that will be fulfilled with a boolean: `true` if the notification was cleared, or `false` if it was not (for example, because the notification referenced by `id` did not exist).

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

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

Examples
--------

This example shows a notification when the user clicks a browser action, unless the notification was already being shown, in which case it clears the notification:

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

function toggleAlarm(all) {
  if (myNotification in all) {
    browser.notifications.clear(myNotification);
  } else {
    browser.notifications.create(myNotification, {
      type: "basic",
      iconUrl: browser.runtime.getURL("icons/cake-48.png"),
      title: "Am imposing title",
      message: "Some interesting content",
    });
  }
}

function handleClick() {
  let gettingAll = browser.notifications.getAll();
  gettingAll.then(toggleAlarm);
}

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

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


notifications.onClosed - Mozilla

notifications.onClosed
======================

Fired when a notification is closed, either by the system or by the user.

Syntax
------

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

`notificationId`

`string`. ID of the notification that closed.

`byUser`

`boolean`. `true` if the notification was closed by the user, or `false` if it was closed by the system. This argument is not supported in Firefox.

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

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

Examples
--------

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

```js
browser.notifications.onClosed.addListener((notificationId) => {
  console.log(`Notification ${notificationId} has closed.`);
});
```

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


notifications.update() - Mozilla

notifications.update()
======================

Updates a notification, given its ID.

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

Syntax
------

```js
let updating = browser.notifications.update(
  id,                            // string
  options                        // NotificationOptions
)
```

### Parameters

`id`

`string`. The ID of the notification to update. This is the same as the ID passed into `notifications.create()`'s callback.

`options`

`notifications.NotificationOptions`. Defines the notification's new content and behavior.

### Return value

A `Promise` that will be fulfilled with a boolean: `true` if the notification was updated, or `false` if it was not (for example, because the notification referenced by `id` did not exist).

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

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

Examples
--------

This example uses `update()` to update a progress notification. Clicking the browser action shows the notification and starts an `alarm`, which we use to update the notification's progress indicator.

Note that you'll need the "alarms" permission to create alarms (as well as the "notifications" permission to create notifications). Also note that Firefox does not support the `progress` attribute.

```js
let cakeNotification = "cake-notification";

/\*

CAKE\_INTERVAL is set to 0.3 seconds in this example.
Such a short period is chosen to make the extension's behavior
more obvious, but this is not recommended in real life.
Note that in Chrome, alarms cannot be set for less than
a minute.

\*/
let CAKE\_PREP\_INTERVAL = 0.005;

let progress = 0;

browser.alarms.onAlarm.addListener((alarm) => {
  progress += 10;
  if (progress > 100) {
    browser.notifications.clear(cakeNotification);
    browser.alarms.clear("cake-progress");
  } else {
    browser.notifications.update(cakeNotification, { progress });
  }
});

browser.browserAction.onClicked.addListener(() => {
  browser.notifications.getAll((all) => {
    if (all.length > 0) {
      browser.notifications.clear(cakeNotification);
      return;
    }
    progress = 0;
    browser.notifications.create(cakeNotification, {
      type: "progress",
      iconUrl: browser.extension.getURL("icons/cake-48.png"),
      title: "Your cake is being prepared…",
      message: "Something something cake",
      progress,
    });
    browser.alarms.create("cake-progress", {
      periodInMinutes: CAKE\_PREP\_INTERVAL,
    });
  });
});
```

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


notifications.onButtonClicked - Mozilla

notifications.onButtonClicked
=============================

Fired when the user clicks one of the notification's buttons.

Syntax
------

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

`notificationId`

`string`. ID of the notification whose button was clicked.

`buttonIndex`

`integer`. The zero-based index of the button that was clicked.

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

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

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


notifications.create() - Mozilla

notifications.create()
======================

Creates and displays a notification.

Pass a `notifications.NotificationOptions` to define the notification's content and behavior.

You can optionally provide an ID for the notification. If you omit the ID, an ID will be generated. You can use the ID to `update` or `clear` the notification.

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

**Warning:** If you call `notifications.create()` more than once in rapid succession, Firefox may end up not displaying any notification at all.

Syntax
------

```js
let creating = browser.notifications.create(
  id,                   // optional string
  options               // NotificationOptions
)
```

### Parameters

`id` Optional

`string`. This is used to refer to this notification in `notifications.update()`, `notifications.clear()`, and event listeners. If you omit this argument or pass an empty string, then a new ID will be generated for this notification. If the ID you provide matches the ID of an existing notification from this extension, then the other notification will be cleared.

`options`

`notifications.NotificationOptions`. Defines the notification's content and behavior.

### Return value

A `Promise` that will be fulfilled when the notification is created and the display process has been started, which is before the notification is actually displayed to the user. It is fulfilled with a string representing the notification's ID.

Examples
--------

This example displays a notification periodically, using `alarm`. Clicking the browser action dismisses the notification. You need the "alarms" permission to create alarms (as well as the "notifications" permission to create notifications).

```js
let cakeNotification = "cake-notification";

/\*

CAKE\_INTERVAL is set to 6 seconds in this example.
Such a short period is chosen to make the extension's behavior
more obvious, but this is not recommended in real life.
Note that in Chrome, alarms cannot be set for less
than a minute.

\*/
let CAKE\_INTERVAL = 0.1;

browser.alarms.create("", { periodInMinutes: CAKE\_INTERVAL });

browser.alarms.onAlarm.addListener((alarm) => {
  browser.notifications.create(cakeNotification, {
    type: "basic",
    iconUrl: browser.runtime.getURL("icons/cake-96.png"),
    title: "Time for cake!",
    message: "Something something cake",
  });
});

browser.browserAction.onClicked.addListener(() => {
  const clearing = browser.notifications.clear(cakeNotification);
  clearing.then(() => {
    console.log("cleared");
  });
});
```

### Example extensions

* export-helpers
* forget-it
* google-userinfo
* notify-link-clicks-i18n
* runtime-examples
Browser compatibility
---------------------

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

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