browserAction.setIcon() - Mozilla

browserAction.setIcon()
=======================

Sets the icon for the browser action.

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

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

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

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

Syntax
------

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

### Parameters

`details`

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

`imageData` Optional

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

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

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

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

`path` Optional

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

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

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

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

`tabId` Optional

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

`windowId` Optional

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

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

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

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

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

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

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

Examples
--------

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

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

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

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

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

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

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

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

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

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

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

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

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

### Example extensions

* bookmark-it

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


browserAction.setPopup() - Mozilla

browserAction.setPopup()
========================

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

Syntax
------

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

### Parameters

`details`

An object with the following properties:

`tabId` Optional

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

`windowId` Optional

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

`popup`

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

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

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

If `popup` is `null`:

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

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

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

Examples
--------

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

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

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

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

browser.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "popup-1") {
    browser.browserAction.setPopup({ popup: "/popup/popup1.html" });
  } else if (info.menuItemId === "popup-2") {
    browser.browserAction.setPopup({ popup: "/popup/popup2.html" });
  }
});
```

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


browserAction.onClicked - Mozilla

browserAction.onClicked
=======================

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

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

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`tab`

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

`OnClickData`

An object containing information about the click.

`modifiers`

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

`button`

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

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

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

Examples
--------

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

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

### Example extensions

* bookmark-it
* favourite-colour
* find-across-tabs
* forget-it
* google-userinfo
* native-messaging
* open-my-page-button
* permissions
* runtime-examples
* store-collected-images

**Note:**

This API is based on Chromium's `chrome.browserAction` API. This documentation is derived from `browser_action.json` in the Chromium code.


browserAction.openPopup() - Mozilla

browserAction.openPopup()
=========================

Open the browser action's popup.

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

Syntax
------

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

### Parameters

`details` Optional

An object with the following properties:

`windowId` Optional

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

### Return value

A `Promise` that is resolved with no arguments.

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

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

Examples
--------

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

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

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


browserAction.ColorArray - Mozilla

browserAction.ColorArray
========================

Type
----

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

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

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

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

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

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


browserAction.setTitle() - Mozilla

browserAction.setTitle()
========================

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

Syntax
------

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

### Parameters

`details`

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

`title`

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

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

If `title` is `null`:

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

`tabId` Optional

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

`windowId` Optional

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

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

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

Examples
--------

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

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

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

### Example extensions

* bookmark-it

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


browserAction.getBadgeTextColor() - Mozilla

browserAction.getBadgeTextColor()
=================================

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

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

Other browsers always use a white text color.

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

Syntax
------

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

### Parameters

`details`

`object`.

`tabId` Optional

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

`windowId` Optional

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

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

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

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

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

Examples
--------

Log the badge's text color:

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

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

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

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


browserAction.getBadgeText() - Mozilla

browserAction.getBadgeText()
============================

Gets the browser action's badge text.

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

Syntax
------

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

### Parameters

`details`

An object with the following properties:

`tabId` Optional

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

`windowId` Optional

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

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

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

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

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

Examples
--------

Log the badge text:

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

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

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


browserAction.setBadgeBackgroundColor() - Mozilla

browserAction.setBadgeBackgroundColor()
=======================================

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

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

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

Syntax
------

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

### Parameters

`details`

An object with the following properties:

`color`

The color, specified as one of:

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

`tabId` Optional

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

`windowId` Optional

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

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

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

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

Examples
--------

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

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

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

Set the badge background color only for the active tab:

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

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

### Example extensions

* tabs-tabs-tabs

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


browserAction.setBadgeText() - Mozilla

browserAction.setBadgeText()
============================

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

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

Syntax
------

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

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

### Parameters

`details`

An object with the following properties:

`text`

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

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

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

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

`tabId` Optional

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

`windowId` Optional

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

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

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

Examples
--------

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

```js
let clicks = 0;

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

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

### Example extensions

* tabs-tabs-tabs

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


browserAction.getBadgeBackgroundColor() - Mozilla

browserAction.getBadgeBackgroundColor()
=======================================

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

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

Syntax
------

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

### Parameters

`details`

An object with the following properties:

`tabId` Optional

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

`windowId` Optional

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

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

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

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

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

Examples
--------

Log the badge's background color:

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

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

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

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


browserAction.enable() - Mozilla

browserAction.enable()
======================

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

Syntax
------

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

### Parameters

`tabId` Optional

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

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

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

Examples
--------

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

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

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

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


browserAction.getPopup() - Mozilla

browserAction.getPopup()
========================

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

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

Syntax
------

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

### Parameters

`details`

An object with the following properties:

`tabId` Optional

`integer`. The tab whose popup to get.

`windowId` Optional

`integer`. The windows whose popup to get.

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

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

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

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

Examples
--------

Get the popup's URL:

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

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

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


browserAction.isEnabled() - Mozilla

browserAction.isEnabled()
=========================

Returns `true` if the browser action is enabled.

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

Syntax
------

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

### Parameters

`details`

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

`tabId` Optional

`integer`. ID of a tab to check.

`windowId` Optional

`integer`. ID of a window to check.

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

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

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

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

Examples
--------

Check the global state:

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

Check the state of the currently active tab:

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


browserAction.disable() - Mozilla

browserAction.disable()
=======================

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

Syntax
------

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

### Parameters

`tabId` Optional

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

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

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

Examples
--------

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

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

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

Disable the browser action only for the active tab:

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

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


browserAction.getTitle() - Mozilla

browserAction.getTitle()
========================

Gets the browser action's title.

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

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

Syntax
------

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

### Parameters

`details`

An object with the following properties:

`tabId` Optional

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

`windowId` Optional

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

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

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

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

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

Examples
--------

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

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

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

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


browserAction.setBadgeTextColor() - Mozilla

browserAction.setBadgeTextColor()
=================================

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

Syntax
------

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

### Parameters

`details`

An object with the following properties:

`color`

The color, specified as one of:

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

`tabId` Optional

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

`windowId` Optional

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

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

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

Examples
--------

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

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

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

Set the badge text color only for the active tab:

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

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

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


browserAction.ImageDataType - Mozilla

browserAction.ImageDataType
===========================

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

Type
----

An `ImageData` object.

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

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

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


pageAction.getTitle() - Mozilla

pageAction.getTitle()
=====================

Gets the title of the page action.

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

Syntax
------

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

### Parameters

`details`

`object`.

`tabId`

`integer`. The ID of the tab containing the page action whose title you want to get.

### Return value

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

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

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

Examples
--------

This example logs the page action's title when the user clicks its icon:

```js
function gotTitle(title) {
  console.log(`Title ${title}`);
}

browser.pageAction.onClicked.addListener((tab) => {
  let gettingTitle = browser.pageAction.getTitle({
    tabId: tab.id,
  });
  gettingTitle.then(gotTitle);
});
```

### Example extensions

* apply-css

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


pageAction.isShown() - Mozilla

pageAction.isShown()
====================

Returns `true` if the page action is being shown for the given tab.

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

Syntax
------

```js
let gettingIsShown = browser.pageAction.isShown(
  details // object
)
```

### Parameters

`details`

`object`. An object containing the `tabId` to check.

`tabId`

`integer`. ID of the tab to check.

### Return value

A `Promise` that will be fulfilled with `true` if the extension's page action is being shown for the given tab, and `false` otherwise.

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

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

Examples
--------

Check the state of the currently active tab:

```js
async function shownInActiveTab() {
  let tabs = await browser.tabs.query({
    currentWindow: true,
    active: true,
  });
  let shown = await browser.pageAction.isShown({
    tabId: tabs[0].id,
  });
  console.log(shown);
}
```


pageAction.getPopup() - Mozilla

pageAction.getPopup()
=====================

Gets the URL for the HTML document set as the popup for this page action.

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

Syntax
------

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

### Parameters

`details`

`object`.

`tabId`

`integer`. ID of the tab whose popup you want to get.

### Return value

A `Promise` that will be fulfilled with a string containing the popup's URL.

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

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

Examples
--------

Add a context menu item that logs the popup URL for the current tab. Note that you'll need the `contextMenus` permission in your manifest to create context menu items.

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

browser.contextMenus.create({
  id: "get-popup",
  title: "Get popup URL",
});

browser.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "get-popup") {
    let gettingPopup = browser.pageAction.getPopup({ tabId: tab.id });
    gettingPopup.then(gotPopup);
  }
});
```

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


pageAction.hide() - Mozilla

pageAction.hide()
=================

Hides the page action for a given tab.

`hide()` overrides pattern matching, so the page action will not be shown in the specified tab even if its URL is matched by `show_matches`.

Syntax
------

```js
browser.pageAction.hide(
  tabId // integer
)
```

### Parameters

`tabId`

`integer`. The ID of the tab for which you want to hide the page action.

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

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

Examples
--------

Hide the page action for the current tab when the user clicks it:

```js
browser.pageAction.onClicked.addListener((tab) => {
  browser.pageAction.hide(tab.id);
});
```

### Example extensions

* chill-out

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


pageAction.onClicked - Mozilla

pageAction.onClicked
====================

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

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

Syntax
------

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

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`tab`

A `tabs.Tab` object representing the tab whose page action was clicked.

`OnClickData`

An object containing information about the click.

`modifiers`

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

`button`

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

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

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

Examples
--------

When the user clicks the page action, hide it, and navigate the active tab to "https://giphy.com/explore/cat":

```js
let CATGIFS = "https://giphy.com/explore/cat";

browser.pageAction.onClicked.addListener((tab) => {
  browser.pageAction.hide(tab.id);
  browser.tabs.update({ url: CATGIFS });
});

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

### Example extensions

* apply-css
* chill-out

**Note:**

This API is based on Chromium's `chrome.pageAction` API. This documentation is derived from `page_action.json` in the Chromium code.


pageAction.openPopup() - Mozilla

pageAction.openPopup()
======================

Open the page action's popup.

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

Syntax
------

```js
browser.pageAction.openPopup()
```

### Parameters

None.

### Return value

A `Promise` that is resolved with no arguments.

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

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

Examples
--------

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

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

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

### Example extensions

* menu-remove-element


pageAction.show() - Mozilla

pageAction.show()
=================

Shows the `pageAction` for a given `tab`. The page action is shown whenever the given tab is the active tab.

`show()` overrides pattern matching, so the page action will be shown in the specified tab even if `show_matches` does not match the URL or `hide_matches` does.

Note that calling `show()` has no effect on a tab with no content loaded.

Syntax
------

```js
browser.pageAction.show(
  tabId // integer
)
```

### Parameters

`tabId`

`integer`. The ID of the `tab` for which you want to show the page action.

### Return value

A `Promise` that will be fulfilled with `undefined`.

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

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

Examples
--------

This example shows the `pageAction` for the active tab when the user selects a context menu item.

**Note:** You'll need the `contextMenus` permission in your manifest to create context menu items.

```js
browser.contextMenus.create({
  id: "show",
  title: "Show page action",
});

browser.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "show") {
    browser.pageAction.show(tab.id);
  }
});
```

### Example extensions

* apply-css
* chill-out
* history-deleter
* menu-remove-element

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


pageAction.setTitle() - Mozilla

pageAction.setTitle()
=====================

Sets the title of the page action. The title is displayed in a tooltip when the user hovers over the page action.

Syntax
------

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

### Parameters

`details`

`object`.

`tabId`

`integer`. The ID of the tab whose title you want to set.

`title`

`string` or `null`. The tooltip text.

If `null` is passed here, the title is reset to the title that was specified in the `page_action` manifest key.

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

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

Examples
--------

Whenever a tab is updated, show the page action for that tab, and set its title to show the tab's ID:

```js
browser.tabs.onUpdated.addListener((tabId, changeInfo, tabInfo) => {
  browser.pageAction.show(tabId);
  browser.pageAction.setTitle({
    tabId,
    title: `Tab ID: ${tabId}`,
  });
});
```

### Example extensions

* apply-css

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


pageAction.setIcon() - Mozilla

pageAction.setIcon()
====================

Sets the icon for the page action.

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

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

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

Syntax
------

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

### Parameters

`details`

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

`imageData` Optional

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

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

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

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

`path` Optional

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

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

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

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

If `path` is `null`, this will reset the page action's icon to the icon that was given in the `page_action` manifest key.

If `path` is `""`, this will reset the icon to the browser's global default icon (that is, the icon used if no icon is given in the `page_action` manifest key).

If `path` does not point to a valid icon, then no icon will be displayed.

`tabId`

`integer`. The ID of the tab whose icon you want to set.

### Return value

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

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

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

Examples
--------

Set the icon for the page action when the user clicks it:

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

### Example extensions

* apply-css

**Note:**

This API is based on Chromium's `chrome.pageAction` API. This documentation is derived from `page_action.json` in the Chromium code.


pageAction.ImageDataType - Mozilla

pageAction.ImageDataType
========================

Pixel data for an image.

Type
----

An `ImageData` object, e.g. from a `<canvas>` element.

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

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

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


pageAction.setPopup() - Mozilla

pageAction.setPopup()
=====================

Sets the HTML document to be opened as a popup when the user clicks on the page action's icon.

Syntax
------

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

### Parameters

`details`

`object`.

`tabId`

`integer`. The ID of the tab for which you want to set the popup.

`popup`

`string` or `null`. URL to the HTML file to show in a popup.

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

If `null` is passed here, the popup is reset to the popup that was specified in the `page_action` manifest key.

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

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

Examples
--------

Listen for `tabs.onUpdated` events, and switch the popup if the loading status changes:

```js
browser.tabs.onUpdated.addListener((tabId, changeInfo, tabInfo) => {
  if (changeInfo.status) {
    browser.pageAction.show(tabId);
    if (changeInfo.status === "loading") {
      browser.pageAction.setPopup({
        tabId,
        popup: "/popup/loading.html",
      });
    } else {
      browser.pageAction.setPopup({
        tabId,
        popup: "/popup/complete.html",
      });
    }
  }
});
```

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


pkcs11.getModuleSlots() - Mozilla

pkcs11.getModuleSlots()
=======================

Enumerate a module's slots. This function returns an array containing one entry for each slot. Each entry contains the slot's name and, if the slot contains a token, information about the token.

You can only call this for a module that is installed in Firefox.

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

Syntax
------

```js
let getting = browser.pkcs11.getModuleSlots(
  name              // string
)
```

### Parameters

`name`

`string`. Name of the module. This must match the `name` property in the PKCS #11 manifest for the module.

### Return value

A `Promise` that will be fulfilled with an array of objects, one for each slot that the module provides access to. Each object has two properties:

* `name`: the name of the slot
* `token`: if a token is present in this slot, a `Token` object. If no token is present in the slot, this property is `null`.

`Token` objects have the following properties:

`name`

`string`. Name of the token.

`manufacturer`

`string`. Name of the token's manufacturer.

`HWVersion`

`string`. Hardware version, as a PKCS #11 version number (two 32-bit integers separated with a dot, like "1.0".

`FWVersion`

`string`. Firmware version, as a PKCS #11 version number (two 32-bit integers separated with a dot, like "1.0".

`serial`

`string`. Serial number, whose format is defined by the token specification.

`isLoggedIn`

`boolean`: `true` if the token is logged on already, `false` otherwise.

If the module 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
--------

Installs a module, then lists its slots and list the tokens they contain:

```js
function onInstalled() {
  return browser.pkcs11.getModuleSlots("my\_module");
}

function onGotSlots(slots) {
  for (const slot of slots) {
    console.log(`Slot: ${slot.name}`);
    if (slot.token) {
      console.log(`Contains token: ${slot.token.name}`);
    } else {
      console.log("Is empty");
    }
  }
}

browser.pkcs11.installModule("my\_module").then(onInstalled).then(onGotSlots);
```


pkcs11.uninstallModule() - Mozilla

pkcs11.uninstallModule()
========================

Uninstalls the named PKCS #11 module from Firefox.

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

Syntax
------

```js
let uninstalling = browser.pkcs11.uninstallModule(
  name              // string
)
```

### Parameters

`name`

`string`. Name of the module to uninstall. This must match the `name` property in the PKCS #11 manifest for the module.

### Return value

A `Promise` that will be fulfilled with no arguments once the module is uninstalled.

If the module 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
--------

Uninstalls the module named "pkcs11\_module":

```js
browser.pkcs11.uninstallModule("pkcs11\_module");
```


pkcs11.isModuleInstalled() - Mozilla

pkcs11.isModuleInstalled()
==========================

Checks whether the named PKCS #11 module is currently installed in Firefox.

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

Syntax
------

```js
let checking = browser.pkcs11.isModuleInstalled(
  name              // string
)
```

### Parameters

`name`

`string`. Name of the module to check.

### Return value

A `Promise` that will be fulfilled with `true` if the module is installed, `false` otherwise.

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

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

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

Examples
--------

Checks whether the module named "pkcs11\_module" is installed:

```js
function logIsInstalled(isInstalled) {
  console.log(`Module is installed: ${isInstalled}`);
}

browser.pkcs11.isModuleInstalled("pkcs11\_module").then(logIsInstalled);
```


pkcs11.installModule() - Mozilla

pkcs11.installModule()
======================

Installs the named PKCS #11 module, making it available to Firefox.

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

Syntax
------

```js
let installing = browser.pkcs11.installModule(
  name,              // string
  flags              // integer
)
```

### Parameters

`name`

`string`. Name of the module to install. This must match the `name` property in the PKCS #11 manifest for the module.

`flags` Optional

`integer`. Flags to pass to the module.

### Return value

A `Promise` that will be fulfilled with no arguments once the module is installed.

If the module 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
--------

Installs a module, then lists its slots and list the tokens they contain:

```js
function onInstalled() {
  return browser.pkcs11.getModuleSlots("my\_module");
}

function onGotSlots(slots) {
  for (const slot of slots) {
    console.log(`Slot: ${slot.name}`);
    if (slot.token) {
      console.log(`Contains token: ${slot.token.name}`);
    } else {
      console.log("Is empty");
    }
  }
}

browser.pkcs11.installModule("my\_module").then(onInstalled).then(onGotSlots);
```


runtime.OnInstalledReason - Mozilla

runtime.OnInstalledReason
=========================

The reason that the `runtime.onInstalled` event is being dispatched.

Type
----

Values of this type are strings. Possible values are:

`"install"`

The extension was installed.

`"update"`

The extension was updated to a new version.

`"browser_update"` or, for Chrome, `"chrome_update"`

The browser was updated to a new version.

`"shared_module_update"`

Another extension, which contains a module used by this extension, was updated.

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


runtime.onSuspend - Mozilla

runtime.onSuspend
=================

Sent to the event page just before it is unloaded. This gives the extension an opportunity to do some cleanup. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete.

**Note:** If something prevents the event page from being unloaded, the `runtime.onSuspendCanceled` event will be sent and the page won't be unloaded.

Syntax
------

```js
browser.runtime.onSuspend.addListener(listener)
browser.runtime.onSuspend.removeListener(listener)
browser.runtime.onSuspend.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

The function called when this event occurs.

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

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

Examples
--------

Listen for suspend events:

```js
function handleSuspend() {
  console.log("Suspending event page");
  // handle cleanup
}

browser.runtime.onSuspend.addListener(handleSuspend);
```

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


runtime.onUpdateAvailable - Mozilla

runtime.onUpdateAvailable
=========================

Fired when an update to the extension is available. This event enables an extension to delay an update: for example, because it is in the middle of some operation which should not be interrupted.

If the extension is not listening for this event when an update becomes available, the extension is reloaded immediately and the update is applied. If the extension is listening, then the update will be applied the next time the extension is reloaded. This happens if:

* the browser is restarted
* the extension is disabled and re-enabled
* the extension explicitly reloads itself by calling `runtime.reload()`.
Syntax
------

```js
browser.runtime.onUpdateAvailable.addListener()
browser.runtime.onUpdateAvailable.removeListener(listener)
browser.runtime.onUpdateAvailable.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`details`

`object`. Contains a single property, a string named `version`, which represents the version number of the update.

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

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

Examples
--------

Listen for `UpdateAvailable` events:

```js
function handleUpdateAvailable(details) {
  console.log(details.version);
  // Proceed to upgrade the add-on
  browser.runtime.reload();
}

browser.runtime.onUpdateAvailable.addListener(handleUpdateAvailable);
```

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


runtime.onMessage - Mozilla

runtime.onMessage
=================

Use this event to listen for messages from another part of your extension.

Some example use cases are:

* **in a content script**, to listen for messages from a background script.
* **in a background script**, to listen for messages from a content script.
* **in an options page or popup script**, to listen for messages from a background script.
* **in a background script**, to listen for messages from an options page or popup script.

To send a message that is received by the `onMessage()` listener, use `runtime.sendMessage()` or (to send a message to a content script) `tabs.sendMessage()`.

**Note:** Avoid creating multiple `onMessage()` listeners for the same type of message, because the order in which multiple listeners will fire is not guaranteed.

If you want to guarantee the delivery of a message to a specific end point, use the connection-based approach to exchange messages.

Along with the message itself, the listener is passed:

* a `sender` object giving details about the message sender.
* a `sendResponse()` function that can be used to send a response back to the sender.

You can send a synchronous response to the message by calling the `sendResponse()` function inside your listener. See an example.

To send an asynchronous response, there are two options:

* return `true` from the event listener. This keeps the `sendResponse()` function valid after the listener returns, so you can call it later. See an example.
* return a `Promise` from the event listener, and resolve when you have the response (or reject it in case of an error). See an example.

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

Syntax
------

```js
browser.runtime.onMessage.addListener(listener)
browser.runtime.onMessage.removeListener(listener)
browser.runtime.onMessage.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

Checks whether at least one 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:

`message`

`object`. The message itself. This is a serializable object (see Data cloning algorithm).

`sender`

A `runtime.MessageSender` object representing the sender of the message.

`sendResponse`

A function to call, at most once, to send a response to the `message`. The function takes a single argument, which may be any serializable object (see Data cloning algorithm). This argument is passed back to the message sender.

If you have more than one `onMessage()` listener in the same document, then only one may send a response.

To send a response synchronously, call `sendResponse()` before the listener function returns.

To send a response asynchronously:

* either keep a reference to the `sendResponse()` argument and return `true` from the listener function. You will then be able to call `sendResponse()` after the listener function has returned.
* or return a `Promise` from the listener function and resolve the promise when the response is ready. This is a preferred way.

**Note:** Promise as a return value is not supported in Chrome until Chrome bug 1185241 is resolved. As an alternative, return true and use sendResponse.

The `listener` function can return either a Boolean or a `Promise`.

**Note:** If you pass an async function to `addListener()`, the listener will return a Promise for every message it receives, preventing other listeners from responding:

```js
// don't do this
browser.runtime.onMessage.addListener(async (data, sender) => {
  if (data.type === "handle\_me") {
    return "done";
  }
});
```

If you only want the listener to respond to messages of a certain type, you must define the listener as a non-`async` function, and return a Promise only for the messages the listener is meant to respond to — and otherwise return false or undefined:

```js
browser.runtime.onMessage.addListener((data, sender) => {
  if (data.type === "handle\_me") {
    return Promise.resolve("done");
  }
  return false;
});
```

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

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

Examples
--------

### Simple example

This content script listens for click events on the web page. If the click was on a link, it messages the background page with the target URL:

```js
// content-script.js

window.addEventListener("click", notifyExtension);

function notifyExtension(e) {
  if (e.target.tagName !== "A") {
    return;
  }
  browser.runtime.sendMessage({ url: e.target.href });
}
```

The background script listens for these messages and displays a notification using the `notifications` API:

```js
// background-script.js

browser.runtime.onMessage.addListener(notify);

function notify(message) {
  browser.notifications.create({
    type: "basic",
    iconUrl: browser.extension.getURL("link.png"),
    title: "You clicked a link!",
    message: message.url,
  });
}
```

### Sending a synchronous response

This content script sends a message to the background script when the user clicks on the page. It also logs any response sent by the background script:

```js
// content-script.js

function handleResponse(message) {
  console.log(`background script sent a response: ${message.response}`);
}

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

function sendMessage(e) {
  const sending = browser.runtime.sendMessage({
    content: "message from the content script",
  });
  sending.then(handleResponse, handleError);
}

window.addEventListener("click", sendMessage);
```

Here is a version of the corresponding background script, that sends a response synchronously, from inside in the listener:

```js
// background-script.js

function handleMessage(request, sender, sendResponse) {
  console.log(`content script sent a message: ${request.content}`);
  sendResponse({ response: "response from background script" });
}

browser.runtime.onMessage.addListener(handleMessage);
```

And here is another version which uses `Promise.resolve()`:

```js
// background-script.js

function handleMessage(request, sender, sendResponse) {
  console.log(`content script sent a message: ${request.content}`);
  return Promise.resolve({ response: "response from background script" });
}

browser.runtime.onMessage.addListener(handleMessage);
```

### Sending an asynchronous response using sendResponse

Here is an alternative version of the background script from the previous example. It sends a response asynchronously after the listener has returned. Note `return true;` in the listener: this tells the browser that you intend to use the `sendResponse` argument after the listener has returned.

```js
// background-script.js

function handleMessage(request, sender, sendResponse) {
  console.log(`content script sent a message: ${request.content}`);
  setTimeout(() => {
    sendResponse({ response: "async response from background script" });
  }, 1000);
  return true;
}

browser.runtime.onMessage.addListener(handleMessage);
```

**Warning:** Do not prepend `async` to the function. That changes the meaning to sending an asynchronous response using a promise, which is effectively the same as `sendResponse(true)`.

### Sending an asynchronous response using a Promise

**Note:** Promise as a return value is not supported in Chrome until Chrome bug 1185241 is resolved. As an alternative, return true and use `sendResponse`.

This content script gets the first `<a>` link on the page and sends a message asking if the link's location is bookmarked. It expects to get a Boolean response (`true` if the location is bookmarked, `false` otherwise):

```js
// content-script.js

const firstLink = document.querySelector("a");

function handleResponse(isBookmarked) {
  if (isBookmarked) {
    firstLink.classList.add("bookmarked");
  }
}

browser.runtime
  .sendMessage({
    url: firstLink.href,
  })
  .then(handleResponse);
```

Here is the background script. It uses ``bookmarks.search()`` to see if the link is bookmarked, which returns a `Promise`:

```js
// background-script.js

function isBookmarked(message, sender, response) {
  return browser.bookmarks
    .search({
      url: message.url,
    })
    .then((results) => results.length > 0);
}

browser.runtime.onMessage.addListener(isBookmarked);
```

If the asynchronous handler doesn't return a Promise, you can explicitly construct a promise. This rather contrived example sends a response after a 1-second delay, using `setTimeout()`:

```js
// background-script.js

function handleMessage(request, sender, sendResponse) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ response: "async response from background script" });
    }, 1000);
  });
}

browser.runtime.onMessage.addListener(handleMessage);
```

### Example extensions

* beastify
* content-script-register
* cookie-bg-picker
* devtools-panels
* export-helpers
* find-across-tabs
* imagify
* mocha-client-tests
* notify-link-clicks-i18n
* store-collected-images
* user-script-register
* webpack-modules

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


runtime.id - Mozilla

runtime.id
==========

The ID of the extension.

Syntax
------

```js
let myAddonId = browser.runtime.id;
```

### Value

A `string` representing the add-on ID. If the extension specifies an ID in its `browser_specific_settings` manifest.json key, `runtime.id` contains that value. Otherwise, `runtime.id` contains the ID that was generated for the extension.

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


runtime.requestUpdateCheck() - Mozilla

runtime.requestUpdateCheck()
============================

Checks to see if an update for the extension is available.

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

Syntax
------

```js
let requestingCheck = browser.runtime.requestUpdateCheck()
```

### Parameters

None.

### Return value

A `Promise` that is fulfilled with an object with the result of the update request.

`result`

An object with the following properties:

`status`

`runtime.RequestUpdateCheckStatus`. The result of the update check.

`version` Optional

`string`. The update's version, if `status` is `update_available`.

Examples
--------

Request an update and log the new version if one is available:

```js
function onRequested(result) {
  console.log(result.status);
  if (result.status === "update\_available") {
    console.log(result.version);
  }
}

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

let requestingCheck = browser.runtime.requestUpdateCheck();
requestingCheck.then(onRequested, onError);
```

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

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

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


runtime.RequestUpdateCheckStatus - Mozilla

runtime.RequestUpdateCheckStatus
================================

Result of a call to `runtime.requestUpdateCheck()`.

Type
----

Values of this type are strings. Possible values are:

`"throttled"`

Update is throttled.

`"no_update"`

No update is available.

`"update_available"`

An update of the extension is available.

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


runtime.getManifest() - Mozilla

runtime.getManifest()
=====================

Get the complete manifest.json file, deserialized from JSON to an object.

Syntax
------

```js
browser.runtime.getManifest()
```

### Parameters

None.

### Return value

An `object` representing the manifest.

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

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

Examples
--------

Get the manifest and log the "name" property:

```js
let manifest = browser.runtime.getManifest();
console.log(manifest.name);
```

### Example extensions

* runtime-examples

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


runtime.getPlatformInfo() - Mozilla

runtime.getPlatformInfo()
=========================

Returns information about the current platform. This can only be called in the background script context.

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

Syntax
------

```js
let getting = browser.runtime.getPlatformInfo()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with a `runtime.PlatformInfo` value representing the current platform.

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

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

Examples
--------

Get and log the platform OS:

```js
function gotPlatformInfo(info) {
  console.log(info.os);
}

let gettingInfo = browser.runtime.getPlatformInfo();
gettingInfo.then(gotPlatformInfo);
```

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


runtime.getURL() - Mozilla

runtime.getURL()
================

Given a relative path from the manifest.json to a resource packaged with the extension, return a fully-qualified URL.

This function does *not* check that the resource actually exists at that URL.

Syntax
------

```js
browser.runtime.getURL(
  path // string
)
```

### Parameters

`path`

`string`. A relative path from the manifest.json to a resource packaged with the extension.

### Return value

`string`. The fully-qualified URL to the resource.

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

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

Examples
--------

Given a file packaged with the extension at "beasts/frog.html", get the full URL like this:

```js
let fullURL = browser.runtime.getURL("beasts/frog.html");
console.log(fullURL);
// Returns something like:
// moz-extension://2c127fa4-62c7-7e4f-90e5-472b45eecfdc/beasts/frog.html
```

### Example extensions

* devtools-panels
* find-across-tabs
* permissions

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


runtime.sendNativeMessage() - Mozilla

runtime.sendNativeMessage()
===========================

Sends a single message from an extension to a native application.

This takes two mandatory parameters: the name of the native application and a JSON object which is the message to send it. The browser will launch the native application and deliver the message.

This is an asynchronous function that returns a `Promise`. The first message sent by the native application is treated as a response to the `sendNativeMessage()` call, and the promise will be fulfilled with this message as a parameter. Note that you can't use `runtime.onMessage` to get responses from the application: you must use the callback function instead.

A new instance of the application is launched for call to `runtime.sendNativeMessage()`. The browser will terminate the native application after getting a reply. To terminate a native application, the browser will close the pipe, give the process a few seconds to exit gracefully, and then kill it if it has not exited.

For more information, see Native messaging.

Syntax
------

```js
let sending = browser.runtime.sendNativeMessage(
  application,             // string
  message                  // object
)
```

### Parameters

`application`

`string`. The name of the native application. This must match the "name" property in the native application's manifest file.

`message`

`object`. A JSON object that will be sent to the native application.

### Return value

A `Promise`. If the sender sent a response, this will be fulfilled with the response as a JSON object. Otherwise it will be fulfilled with no arguments. If an error occurs while connecting to the native application, 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
--------

Here's a background script that sends a "ping" message to the "ping\_pong" app and logs the response, whenever the user clicks the browser action:

```js
function onResponse(response) {
  console.log(`Received ${response}`);
}

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

/\*
On a click on the browser action, send the app a message.
\*/
browser.browserAction.onClicked.addListener(() => {
  console.log("Sending: ping");
  let sending = browser.runtime.sendNativeMessage("ping\_pong", "ping");
  sending.then(onResponse, onError);
});
```

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


runtime.connectNative() - Mozilla

runtime.connectNative()
=======================

Connects the extension to a native application on the user's computer. This takes the name of a native application as a parameter. It starts the native application and returns a `runtime.Port` object to the caller. The caller can then use the `Port` to exchange messages with the native application using `Port.postMessage()` and `port.onMessage`. The native application will run until it exits itself, or the caller calls `Port.disconnect()`, or the page that created the `Port` is destroyed. Once the `Port` is disconnected the browser will give the process a few seconds to exit gracefully, and then kill it if it has not exited.

For more information, see Native messaging.

Syntax
------

```js
let port = browser.runtime.connectNative(
  application // string
)
```

### Parameters

`application`

`string`. The name of the native application to connect to. This must match the "name" property in the native application's manifest file.

### Return value

A `runtime.Port` object. The port which the caller can use to exchange messages with the native application.

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

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

Examples
--------

This example connects to the native application "ping\_pong" and starts listening for messages from it. It also sends the native application a message when the user clicks a browser action icon:

```js
/\*
On startup, connect to the "ping\_pong" app.
\*/
let port = browser.runtime.connectNative("ping\_pong");

/\*
Listen for messages from the app.
\*/
port.onMessage.addListener((response) => {
  console.log(`Received: ${response}`);
});

/\*
On a click on the browser action, send the app a message.
\*/
browser.browserAction.onClicked.addListener(() => {
  console.log("Sending: ping");
  port.postMessage("ping");
});
```

### Example extensions

* native-messaging

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


runtime.getBackgroundPage() - Mozilla

runtime.getBackgroundPage()
===========================

Retrieves the `Window` object for the background page running inside the current extension. If the background page is non-persistent (an event page) and it is not running, the background page is started.

This provides a convenient way for other privileged extension scripts to get direct access to the background script's scope. This enables them to access variables or call functions defined in that scope. "Privileged script" here includes scripts running in options pages, or scripts running in browser action or page action popups, but does *not* include content scripts.

Note that variables that were declared using `const` or `let` do not appear in the `Window` object returned by this function.

**Also note that this method cannot be used in a private window in Firefox**—it always returns `null`. For more info see related bug at bugzilla.

If the background page is an event page, the system will ensure it is loaded before resolving the promise.

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

**Note:** In Firefox, this method cannot be used in Private Browsing mode — it always returns `null`. For more info see Firefox bug 1329304.

In Chrome, this method is available only with persistent background pages, which are not available in Manifest V3, so consider using Manifest V2. See the this for details.

Consider using `runtime.sendMessage()` or `runtime.connect()`, which work correctly in both scenarios above.

Syntax
------

```js
let gettingPage = browser.runtime.getBackgroundPage()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with the `Window` object for the background page, if there is one. If the extension does not include a background page, the promise is rejected with an error message.

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

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

Examples
--------

Suppose a background script defines a function `foo()`:

```js
// background.js

function foo() {
  console.log("I'm defined in background.js");
}
```

A script running in a popup can call this function directly like this:

```js
// popup.js

function onGot(page) {
  page.foo();
}

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

let getting = browser.runtime.getBackgroundPage();
getting.then(onGot, onError);
```

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


runtime.PlatformOs - Mozilla

runtime.PlatformOs
==================

The operating system the browser is running on.

Type
----

Values of this type are strings. Possible values are:

`"mac"`

The underlying operating system is macOS.

`"ios"`

The underlying operating system is iOS/iPadOS.

`"win"`

The underlying operating system is Windows.

`"android"`

The underlying operating system is Android.

`"cros"`

The underlying operating system is ChromeOS.

`"linux"`

The underlying operating system is Linux.

`"openbsd"`

The underlying operating system is Open/FreeBSD.

`"fuchsia"`

The underlying operating system is Fuchsia.

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


runtime.onMessageExternal - Mozilla

runtime.onMessageExternal
=========================

Use this event to listen for messages from other extensions or web pages.

By default, an extension can receive messages from any other extension. However, the `externally_connectable` manifest key can be used to limit communication to specific extensions and enable communication with websites.

To send a message that is received by the `onMessageExternal` listener, use `runtime.sendMessage()`, passing the ID of the recipient in the `extensionId` parameter.

Along with the message itself, the listener is passed:

* a `sender` object giving details about the message sender
* a `sendResponse` function that the listener can use to send a response back to the sender.

This API can't be used in a content script.

Syntax
------

```js
browser.runtime.onMessageExternal.addListener()
browser.runtime.onMessageExternal.removeListener(listener)
browser.runtime.onMessageExternal.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`listener`

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

`message`

`object`. The message itself. This is a JSON-ifiable object.

`sender`

A `runtime.MessageSender` object representing the sender of the message.

`sendResponse`

A function to call, at most once, to send a response to the message. The function takes a single argument, which may be any JSON-ifiable object. This argument is passed back to the message sender.

If you have more than one `onMessageExternal` listener in the same document, then only one may send a response.

To send a response synchronously, call `sendResponse` before the listener function returns. To send a response asynchronously, do one of these:

* keep a reference to the `sendResponse` argument and return `true` from the listener function. You can then call `sendResponse` after the listener function has returned.
* return a `Promise` from the listener function and resolve the promise when the response is ready.

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

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

Examples
--------

In this example the extension "blue@mozilla.org" sends a message to the extension "red@mozilla.org":

```js
// sender: browser.runtime.id === "blue@mozilla.org"

// Send a message to the extension whose ID is "red@mozilla.org"
browser.runtime.sendMessage("red@mozilla.org", "my message");
```

```js
// recipient: browser.runtime.id === "red@mozilla.org"

function handleMessage(message, sender) {
  // check that the message is from "blue@mozilla.org"
  if (sender.id === "blue@mozilla.org") {
    // process message
  }
}

browser.runtime.onMessageExternal.addListener(handleMessage);
```

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


runtime.getFrameId() - Mozilla

runtime.getFrameId()
====================

Returns the frame ID of any window global or frame element when called from a content script or extension page, including background pages.

Syntax
------

```js
let gettingInfo = browser.runtime.getFrameId(
  target               // object
)
```

### Parameters

`target`

A WindowProxy or a browsing context container Element (iframe, frame, embed, or object) for the target frame.

### Return value

Returns the frame ID of the target frame, or -1 if the frame doesn't exist.

Examples
--------

This code recursively walks descendant frames and gets parent frame IDs.

```js
const parents = {};

function visit(win) {
  const frameId = browser.runtime.getFrameId(win);
  const parentId = browser.runtime.getFrameId(win.parent);
  parents[frameId] = win.parent !== win ? parentId : -1;

  try {
    const frameEl = browser.runtime.getFrameId(win.frameElement);
    browser.test.assertEq(frameId, frameEl, "frameElement id correct");
  } catch (e) {
    // Can't access a cross-origin .frameElement.
  }

  for (const frame of win.frames) {
    visit(frame);
  }
}
visit(window);
```

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

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

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


runtime.getBrowserInfo() - Mozilla

runtime.getBrowserInfo()
========================

Returns information about the browser in which the extension is installed.

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

Syntax
------

```js
let gettingInfo = browser.runtime.getBrowserInfo()
```

### Parameters

None.

### Return value

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

`name`

string value representing the browser name, for example "Firefox".

`vendor`

string value representing the browser's vendor, for example "Mozilla".

`version`

string representing the browser's version, for example "51.0" or "51.0a2".

`buildID`

string representing the specific build of the browser, for example "20161018004015".

Examples
--------

Get and log the browser's name:

```js
function gotBrowserInfo(info) {
  console.log(info.name);
}

let gettingInfo = browser.runtime.getBrowserInfo();
gettingInfo.then(gotBrowserInfo);
```

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

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

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


runtime.onStartup - Mozilla

runtime.onStartup
=================

Fired when a profile that has this extension installed first starts up. This event is not fired when a private browsing (incognito) profile is started, even if this extension is operating in 'split' incognito mode.

**Note:**
 When using an event page or background service worker, the extension must add a listener to `runtime.onStartup` on the event page for the event page to be executed at least once per browser session.

Syntax
------

```js
browser.runtime.onStartup.addListener(listener)
browser.runtime.onStartup.removeListener(listener)
browser.runtime.onStartup.hasListener(listener)
```

### Event Functions

All events have three functions:

`addListener(listener)`

Adds a `listener` to the calling event.

`removeListener(listener)`

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

`hasListener(listener)`

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

### Parameters

The only parameter is `listener`, used for any of the above functions.

`listener`

The function called when this event occurs.

Examples
--------

Open https://giphy.com/explore/cat when the browser starts up:

```js
function handleStartup() {
  browser.tabs.create({
    url: "https://giphy.com/explore/cat",
  });
}

browser.runtime.onStartup.addListener(handleStartup);
```

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


runtime.onConnect - Mozilla

runtime.onConnect
=================

Fired when a connection is made with either an extension process or a content script.

Syntax
------

```js
browser.runtime.onConnect.addListener(listener)
browser.runtime.onConnect.removeListener(listener)
browser.runtime.onConnect.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`function`

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

`port`

A `runtime.Port` object connecting the current script to the other context it is connecting to.

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

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

Examples
--------

This content script:

* connects to the background script, and stores the `Port` in a variable `myPort`
* listens for messages on `myPort`, and logs them
* sends messages to the background script, using `myPort`, when the user clicks the document

```js
// content-script.js

let myPort = browser.runtime.connect({ name: "port-from-cs" });
myPort.postMessage({ greeting: "hello from content script" });

myPort.onMessage.addListener((m) => {
  console.log("In content script, received message from background script: ");
  console.log(m.greeting);
});

document.body.addEventListener("click", () => {
  myPort.postMessage({ greeting: "they clicked the page!" });
});
```

The corresponding background script:

* listens for connection attempts from the content script
* when it receives a connection attempt:
    + stores the port in a variable named `portFromCS`
    + sends the content script a message using the port
    + starts listening to messages received on the port, and logs them
* sends messages to the content script, using `portFromCS`, when the user clicks the extension's browser action

```js
// background-script.js

let portFromCS;

function connected(p) {
  portFromCS = p;
  portFromCS.postMessage({ greeting: "hi there content script!" });
  portFromCS.onMessage.addListener((m) => {
    console.log("In background script, received message from content script");
    console.log(m.greeting);
  });
}

browser.runtime.onConnect.addListener(connected);

browser.browserAction.onClicked.addListener(() => {
  portFromCS.postMessage({ greeting: "they clicked the button!" });
});
```

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


runtime.onBrowserUpdateAvailable - Mozilla

runtime.onBrowserUpdateAvailable
================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Fired when an update for the browser is available, but it isn't installed immediately because a browser restart is required.

Syntax
------

```js
browser.runtime.onBrowserUpdateAvailable.addListener(listener)
browser.runtime.onBrowserUpdateAvailable.removeListener(listener)
browser.runtime.onBrowserUpdateAvailable.hasListener(listener)
```

Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

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

`hasListener(listener)`

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

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

### Parameters

`function`

The function called when this event occurs.

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

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

Examples
--------

Listen for this event:

```js
function handleBrowserUpdateAvailable() {
  // handle event
}

browser.runtime.onBrowserUpdateAvailable.addListener(
  handleBrowserUpdateAvailable,
);
```

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


runtime.reload() - Mozilla

runtime.reload()
================

Reloads the extension.

If there are any pending updates for the extension, that it has deferred by listening to `runtime.onUpdateAvailable`, then they will be applied on reload.

Syntax
------

```js
browser.runtime.reload()
```

### Parameters

None.

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

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

Examples
--------

Reload the extension when the user clicks a browser action's icon:

```js
browser.browserAction.onClicked.addListener((tab) => {
  browser.runtime.reload();
});
```

### Example extensions

* runtime-examples

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


runtime.PlatformInfo - Mozilla

runtime.PlatformInfo
====================

An object containing information about the current platform.

Type
----

Values of this type are objects, which contain the following properties:

`os`

`runtime.PlatformOs`. The platform's operating system.

`arch`

`runtime.PlatformArch`. The platform's processor architecture.

`nacl_arch`

`runtime.PlatformNaclArch`. The native client architecture. This may be different from `arch` on some platforms.

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


runtime.setUninstallURL() - Mozilla

runtime.setUninstallURL()
=========================

Sets the URL to be visited when the extension is uninstalled. This can be used to clean up server-side data, do analytics, or implement surveys. The URL can be up to 1023 characters. This limit used to be 255, see Browser compatibility for more details.

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

Syntax
------

```js
let settingUrl = browser.runtime.setUninstallURL(
  url             // string
)
```

### Parameters

`url`

`string`. URL to open after the extension is uninstalled. This URL must have an `http` or `https` scheme. Can be up to 1023 characters. Set to an empty string to not open a new tab when the extension is uninstalled.

### Return value

A `Promise` fulfilled with no arguments when the URL is set or rejected with an error message if the operation fails.

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

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

Examples
--------

```js
function onSetURL() {
  console.log("set uninstall URL");
}

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

let settingUrl = browser.runtime.setUninstallURL("https://example.org");
settingUrl.then(onSetURL, onError);
```

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


runtime.MessageSender - Mozilla

runtime.MessageSender
=====================

An object containing information about the sender of a message or connection request that is passed to the `runtime.onMessage()` listener.

It is also a property of `runtime.Port`, but only in the `Port` instance passed into the `runtime.onConnect()` or `runtime.onConnectExternal()` listeners.

Type
----

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

`documentId` Optional

`string`. A UUID of the document that opened the connection.

`documentLifecycle` Optional

`string`. The lifecycle state the document that opened the connection was in when the port was created. Note that the lifecycle state of the document may have changed since the port was created.

`frameId` Optional

`integer`. The frame that opened the connection. Zero for top-level frames, positive for child frames. This is only set when `tab` is set.

`id` Optional

`string`. The ID of the extension that sent the message, if the message was sent by an extension. If the sender has an ID explicitly set using the browser\_specific\_settings key in manifest.json, then `id` has this value. Otherwise, it has the ID that was generated for the sender.

`origin` Optional

`string`. The origin of the page or frame that opened the connection. It can differ from the `url` property (e.g., about:blank) or be opaque (e.g., sandboxed iframes). This is useful for identifying if the origin can be trusted if it isn't apparent from the URL.

`tab` Optional

`tabs.Tab`. The `tabs.Tab` which opened the connection. This property is only present when the connection was opened from a tab (including content scripts).

`tlsChannelId` Optional

`string`. The TLS channel ID of the page or frame that opened the connection, if requested by the extension and available.

`url` Optional

`string`. The URL of the page or frame hosting the script that sent the message.

If the sender is a script running in an extension page (such as a background page, an options page, or a browser action or page action popup), the URL is in the form `"moz-extension://<extension-internal-id>/path/to/page.html"`. If the sender is a background script and you haven't included a background page, it is `"moz-extension://<extension-internal-id>/_generated_background_page.html"`.

If the sender is a script running in a web page (including content and normal page scripts), then `url` is the web page URL. If the script is running in an iframe, `url` is the iframe's URL.

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

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

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