repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/reload/index.md | ---
title: tabs.reload()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/reload
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.reload
---
{{AddonSidebar}}
Reload a tab, optionally bypassing the local web cache.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let reloading = browser.tabs.reload(
tabId, // optional integer
reloadProperties // optional object
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab to reload. Defaults to the selected tab of the current window.
- `reloadProperties` {{optional_inline}}
- : An object with the following properties:
- `bypassCache` {{optional_inline}}
- : `boolean`. Bypass the local web cache. Default is `false`.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the tab has been reloaded. If any error occurs, the promise will be rejected with an error message.
## Examples
Reload the active tab of the current window:
```js
browser.tabs.reload();
```
Reload the active tab of the current window, bypassing the cache:
```js
browser.tabs.reload({ bypassCache: true });
```
Reload the tab whose ID is 2, bypassing the cache and calling a callback when done:
```js
function onReloaded() {
console.log(`Reloaded`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
let reloading = browser.tabs.reload(2, { bypassCache: true });
reloading.then(onReloaded, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-reload) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/goforward/index.md | ---
title: tabs.goForward()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/goForward
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.goForward
---
{{AddonSidebar}}
Navigate to the next page in tab's history, if available.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let goingForward = browser.tabs.goForward(
tabId, // optional integer
callback // optional function
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab to navigate. Defaults to the active tab of the current window.
- `callback` {{optional_inline}}
- : `function`. When the page navigation finishes, this function is called without parameters.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is fulfilled when the page navigation finishes.
## Browser compatibility
{{Compat}}
## Examples
Go forward to the next page in the current tab:
```js
function onGoForward() {
console.log("Gone forward");
}
function onError(error) {
console.log(`Error: ${error}`);
}
let goingForward = browser.tabs.goForward();
goingForward.then(onGoForward, onError);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-getZoomSettings) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/getselected/index.md | ---
title: tabs.getSelected()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/getSelected
page-type: webextension-api-function
status:
- deprecated
browser-compat: webextensions.api.tabs.getSelected
---
{{AddonSidebar}}
> **Warning:** This method has been deprecated. Use {{WebExtAPIRef("tabs.query", "tabs.query({active: true})")}} instead.
Gets the tab that is selected in the specified window.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingSelected = browser.tabs.getSelected(
windowId // optional integer
)
```
### Parameters
- `windowId` {{optional_inline}}
- : `integer`. Defaults to the current window.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a [`tabs.Tab`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/Tab) object containing information about the selected tab. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-getSelected) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/getzoom/index.md | ---
title: tabs.getZoom()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/getZoom
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.getZoom
---
{{AddonSidebar}}
Gets the current zoom factor for the specified tab.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingZoom = browser.tabs.getZoom(
tabId // optional integer
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab to get the current zoom factor from. Defaults to the active tab of the current window.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with the tab's current zoom factor, as a number between 0.3 and 5. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.
## Examples
Get the zoom factor for the current tab:
```js
function onGot(zoom) {
console.log(zoom);
}
function onError(error) {
console.log(`Error: ${error}`);
}
let gettingZoom = browser.tabs.getZoom();
gettingZoom.then(onGot, onError);
```
Get the zoom factor for the tab whose ID is 2:
```js
function onGot(zoom) {
console.log(zoom);
}
function onError(error) {
console.log(`Error: ${error}`);
}
let gettingZoom = browser.tabs.getZoom(2);
gettingZoom.then(onGot, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-getZoom) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/setzoomsettings/index.md | ---
title: tabs.setZoomSettings()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/setZoomSettings
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.setZoomSettings
---
{{AddonSidebar}}
Sets zoom settings for the specified tab. These settings are reset to the default settings upon navigating the tab.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let settingZoomSettings = browser.tabs.setZoomSettings(
tabId, // optional integer
zoomSettings // ZoomSettings
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab to change the zoom settings for. Defaults to the active tab of the current window.
- `zoomSettings`
- : {{WebExtAPIRef('tabs.ZoomSettings')}}. Defines how zoom changes are handled and at what scope.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments after the zoom settings have been changed. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.getZoom
## Examples
Disable zooming for the current tab:
```js
function onSet() {
console.log(`Set zoom factor`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
let setting = browser.tabs.setZoomSettings({ mode: "disabled" });
setting.then(onSet, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-setZoomSettings) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/zoomsettingsscope/index.md | ---
title: tabs.ZoomSettingsScope
slug: Mozilla/Add-ons/WebExtensions/API/tabs/ZoomSettingsScope
page-type: webextension-api-type
browser-compat: webextensions.api.tabs.ZoomSettingsScope
---
{{AddonSidebar}}
Defines whether zoom changes will persist for the page's origin, or only take effect in this tab. This defaults to `per-origin` when {{WebExtAPIRef("tabs.zoomSettingsMode")}} is "automatic", and is always `per-tab` otherwise.
## Type
Values of this type are strings. Possible values are:
- "per-origin"
- : All other tabs with the same origin as this tab will have the zoom changes applied to them. This scope is only available if {{WebExtAPIRef("tabs.zoomSettingsMode")}} is "automatic".
- "per-tab"
- : Zoom changes only take effect in this tab, and zoom changes in other tabs will not affect the zooming of this tab. Also:
- in Firefox the zoom level persists across page loads and navigation within the tab.
- in Chrome-based browsers zoom changes are reset on navigation; navigating a tab will always load pages with their per-origin zoom factors.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#type-ZoomSettingsScope) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onzoomchange/index.md | ---
title: tabs.onZoomChange
slug: Mozilla/Add-ons/WebExtensions/API/tabs/onZoomChange
page-type: webextension-api-event
browser-compat: webextensions.api.tabs.onZoomChange
---
{{AddonSidebar}}
Fired when a tab is zoomed.
## Syntax
```js-nolint
browser.tabs.onZoomChange.addListener(listener)
browser.tabs.onZoomChange.removeListener(listener)
browser.tabs.onZoomChange.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `ZoomChangeInfo`
- : `object`. Information about the zoom event. See the [ZoomChangeInfo](#zoomchangeinfo_2) section for more details.
## Additional objects
### ZoomChangeInfo
- `tabId`
- : `integer`. ID of the tab that was zoomed.
- `oldZoomFactor`
- : `number`. The previous zoom factor.
- `newZoomFactor`
- : `number`. The new zoom factor.
- `zoomSettings`
- : {{WebExtAPIRef('tabs.ZoomSettings')}}. Zoom settings for the tab.
## Examples
Listen for zoom events and log the info:
```js
function handleZoomed(zoomChangeInfo) {
console.log(`Tab: ${zoomChangeInfo.tabId} zoomed`);
console.log(`Old zoom: ${zoomChangeInfo.oldZoomFactor}`);
console.log(`New zoom: ${zoomChangeInfo.newZoomFactor}`);
}
browser.tabs.onZoomChange.addListener(handleZoomed);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onZoomChange) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/tab/index.md | ---
title: tabs.Tab
slug: Mozilla/Add-ons/WebExtensions/API/tabs/Tab
page-type: webextension-api-type
browser-compat: webextensions.api.tabs.Tab
---
{{AddonSidebar}}
The type **`tabs.Tab`** contains information about a tab. This provides access to information about what content is in the tab, how large the content is, what special states or restrictions are in effect, and so forth.
## Type
Values of this type are objects. They contain the following properties:
- `active`
- : `boolean`. Whether the tab is active in its window. This may be true even if the tab's window is not currently focused.
The active tab is usually the selected one. However, on Firefox for Android, extension popups open in a new tab. When this popup tab is selected, the active tab will instead be the one in which the popup opened.
- `attention` {{optional_inline}}
- : `boolean`. Indicates whether the tab is drawing attention. For example, when the tab displays a modal dialog, `attention` will be `true`.
- `audible` {{optional_inline}}
- : `boolean`. Indicates whether the tab is producing sound. However, the user will not hear the sound if the tab is muted (see the `mutedInfo` property).
- `autoDiscardable` {{optional_inline}}
- : `boolean`. Whether the tab can be discarded by the browser. The default value is `true`. When set to `false`, the browser cannot automatically discard the tab. However, the tab can be discarded by {{WebExtAPIRef("tabs.discard")}}.
- `cookieStoreId` {{optional_inline}}
- : `string`. The cookie store of the tab. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information.
- `discarded` {{optional_inline}}
- : `boolean`. Whether the tab is discarded. A discarded tab is one whose content has been unloaded from memory, but is still visible in the tab strip. Its content gets reloaded the next time it's activated.
- `favIconUrl` {{optional_inline}}
- : `string`. The URL of the tab's favicon. Only present if the extension has the `"tabs"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions). It may also be `undefined` if the page has no favicon, or an empty string if the tab is loading.
- `height` {{optional_inline}}
- : `integer`. The height of the tab in pixels.
- `hidden`
- : `boolean`. Whether the tab is hidden.
- `highlighted`
- : `boolean`. Whether the tab is highlighted, i.e. part of the current tab selection. An active tab is always highlighted, but some browsers may allow additional tabs to be highlighted, for example by clicking them while holding <kbd>Ctrl</kbd>, <kbd>Shift</kbd> or <kbd>⌘ Command</kbd> keys.
Firefox for Android doesn't support highlighting multiple tabs.
- `id` {{optional_inline}}
- : `integer`. The tab's ID. Tab IDs are unique within a browser session. The tab ID may also be set to {{WebExtAPIRef('tabs.TAB_ID_NONE')}} for browser windows that don't host content tabs (for example, devtools windows).
- `incognito`
- : `boolean`. Whether the tab is in a private browsing window.
- `index`
- : `integer`. The zero-based index of the tab within its window.
- `isArticle`
- : `boolean`. True if the tab can be [rendered in Reader Mode](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/toggleReaderMode), false otherwise.
- `isInReaderMode`
- : `boolean`. True if the tab is currently being [rendered in Reader Mode](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/toggleReaderMode), false otherwise.
- `lastAccessed` {{optional_inline}}
- : `double`. Time at which the tab was last accessed, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
- `mutedInfo` {{optional_inline}}
- : {{WebExtAPIRef('tabs.MutedInfo')}}. The current muted state for the tab and the reason for the last state change.
- `openerTabId` {{optional_inline}}
- : `integer`. The ID of the tab that opened this tab, if any. This property is only present if the opener tab still exists and is in the same window.
- `pinned`
- : `boolean`. Whether the tab is pinned.
- `selected` {{deprecated_inline}}
- : `boolean`. Whether the tab is selected. This property has been replaced by `active` and `highlighted`.
- `sessionId` {{optional_inline}}
- : `string`. The session ID used to uniquely identify a `Tab` obtained from the {{WebExtAPIRef('sessions')}} API.
- `status` {{optional_inline}}
- : `string`. Either _loading_ or _complete_.
- `successorTabId` {{optional_inline}}
- : `integer` The ID of the tab's successor.
- `title` {{optional_inline}}
- : `string`. The title of the tab. Only present if the extension has the `"tabs"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) that matches the tab's URL.
- `url` {{optional_inline}}
- : `string`. The URL of the document that the tab is displaying. Only present if the extension has the `"tabs"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or a matching [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions).
- `width` {{optional_inline}}
- : `integer`. The width of the tab in pixels.
- `windowId`
- : `integer`. The ID of the window that hosts this tab.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#type-Tab) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/hide/index.md | ---
title: tabs.hide()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/hide
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.hide
---
{{AddonSidebar}}
Hides one or more tabs.
Hidden tabs are no longer visible in the browser's tabstrip. Hidden tabs are not automatically [discarded](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/discard): the code running in them continues to run. You can explicitly discard tabs whenever you hide them: although this is not appropriate in all situations, it will help to reduce the resources used by the browser.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
Not all tabs are eligible for being hidden:
- Tabs that are pinned cannot be hidden.
- Tabs that are sharing the screen, microphone or camera cannot be hidden.
- The current active tab cannot be hidden.
- Tabs that are in the process of being closed cannot be hidden.
The first time an extension hides a tab, the browser will tell the user that the tab is being hidden, show them how they can access the hidden tab, and give them the option of disabling the extension instead.
To use this API you must have the "tabHide" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions).
## Syntax
```js-nolint
let hiding = browser.tabs.hide(
tabIds // integer or integer array
)
```
### Parameters
- `tabIds`
- : `integer` or `array` of `integer`. The IDs of the tab or tabs to hide.
If any of these tabs are not eligible for being hidden, they will not be hidden, but the call will still succeed and eligible tabs will still be hidden. For example, if you pass `[1, 3]`, and `1` identifies the active tab, then only `3` will be hidden.
However, if any of the tab IDs are invalid, the call will fail and no tabs will be hidden.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an array containing the IDs of the tabs that were hidden. If any error occurs, the promise will be rejected with an error message.
## Examples
Hide a single tab:
```js
function onHidden() {
console.log(`Hidden`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
browser.tabs.hide(2).then(onHidden, onError);
```
Hide multiple tabs:
```js
function onHidden() {
console.log(`Hidden`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
browser.tabs.hide([15, 14, 1]).then(onHidden, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/printpreview/index.md | ---
title: tabs.printPreview()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/printPreview
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.printPreview
---
{{AddonSidebar}}
Opens print preview for the active tab.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). An extension can detect when print preview has been closed by listening to the [afterprint](/en-US/docs/Web/API/Window/afterprint_event) event:
```js
window.addEventListener("afterprint", resumeFunction, false);
```
## Syntax
```js-nolint
let openingPreview = browser.tabs.printPreview()
```
### Parameters
None.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the preview page has opened.
## Examples
In this example a background script listens for a click on a [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#browser_actions_2), then opens print preview for the currently active tab:
```js
browser.browserAction.onClicked.addListener(() => {
browser.tabs.printPreview().then(() => {
console.log("Entered print preview");
});
});
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/mutedinforeason/index.md | ---
title: tabs.MutedInfoReason
slug: Mozilla/Add-ons/WebExtensions/API/tabs/MutedInfoReason
page-type: webextension-api-type
browser-compat: webextensions.api.tabs.MutedInfoReason
---
{{AddonSidebar}}
Specifies the reason a tab was muted or unmuted.
## Type
Values of this type are strings. Possible values are:
- "capture"
- : Tab capture started, forcing a muted state change.
- "extension"
- : An extension set the muted state. If this is the reason, `extensionId` in {{WebExtAPIRef("tabs.mutedInfo")}} will contain the ID of the extension responsible.
- "user"
- : The user set the muted state.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#type-MutedInfoReason) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onhighlighted/index.md | ---
title: tabs.onHighlighted
slug: Mozilla/Add-ons/WebExtensions/API/tabs/onHighlighted
page-type: webextension-api-event
browser-compat: webextensions.api.tabs.onHighlighted
---
{{AddonSidebar}}
Fired when the set of highlighted tabs in a window changes.
Note that before version 63, Firefox didn't have the concept of highlighting multiple tabs, so this event was just an alias for {{WebExtAPIRef("tabs.onActivated")}}.
## Syntax
```js-nolint
browser.tabs.onHighlighted.addListener(listener)
browser.tabs.onHighlighted.removeListener(listener)
browser.tabs.onHighlighted.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `highlightInfo`
- : `object`. ID(s) of the highlighted tabs, and ID of their window. See the [highlightInfo](#highlightinfo_2) section for more details.
## Additional objects
### highlightInfo
- `windowId`
- : `integer`. ID of the window whose tabs changed.
- `tabIds`
- : `array` of `integer`. IDs of the highlighted tabs in the window.
## Examples
Listen for highlighting events, and log the IDs of highlighted tabs:
```js
function handleHighlighted(highlightInfo) {
console.log(`Highlighted tabs: ${highlightInfo.tabIds}`);
}
browser.tabs.onHighlighted.addListener(handleHighlighted);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onHighlighted) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/sendmessage/index.md | ---
title: tabs.sendMessage()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/sendMessage
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.sendMessage
---
{{AddonSidebar}}
Sends a single message from the extension's background scripts (or other privileged scripts, such as popup scripts or options page scripts) to any [content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) or extension pages/iframes that belong to the extension and are running in the specified tab.
The message will be received in the extension context by any listeners to the {{WebExtAPIRef("runtime.onMessage")}} event. Listeners may then optionally return something as a response back to the sender.
This is an asynchronous function that returns a {{jsxref("Promise")}}.
> **Note:** You can also use a [connection-based approach to exchange messages](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#connection-based_messaging).
## Syntax
```js-nolint
const sending = browser.tabs.sendMessage(
tabId, // integer
message, // any
options // optional object
)
```
### Parameters
- `tabId`
- : `integer`. ID of the tab whose content scripts we want to send a message to.
- `message`
- : `any`. An object that can be serialized (see [Data cloning algorithm](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#data_cloning_algorithm)).
- `options` {{optional_inline}}
- : `object`.
- `frameId` {{optional_inline}}
- : `integer`. Sends the message to a specific frame identified by `frameId` instead of all frames in the tab. Whether the content script is executed in all frames depends on the `all_frames` setting in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) section of `manifest.json`.
### Return value
A {{jsxref("Promise")}} that will be fulfilled with the response object sent by the handler of the message in the content script, or with no arguments if the content script did not send a response.
If an error occurs while connecting to the specified tab or any other error occurs, the promise will be rejected with an error message.
If several frames respond to the message, the promise is resolved to one of answers.
## Examples
Here's an example of a background script that sends a message to the content scripts running in the active tab when the user clicks the browser action. The background script also expects the content script to send a response:
```js
// background-script.js
"use strict";
function onError(error) {
console.error(`Error: ${error}`);
}
function sendMessageToTabs(tabs) {
for (const tab of tabs) {
browser.tabs
.sendMessage(tab.id, { greeting: "Hi from background script" })
.then((response) => {
console.log("Message from the content script:");
console.log(response.response);
})
.catch(onError);
}
}
browser.browserAction.onClicked.addListener(() => {
browser.tabs
.query({
currentWindow: true,
active: true,
})
.then(sendMessageToTabs)
.catch(onError);
});
```
Here's the corresponding content script:
```js
// content-script.js
"use strict";
browser.runtime.onMessage.addListener((request) => {
console.log("Message from the background script:");
console.log(request.greeting);
return Promise.resolve({ response: "Hi from content script" });
});
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-sendMessage) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/oncreated/index.md | ---
title: tabs.onCreated
slug: Mozilla/Add-ons/WebExtensions/API/tabs/onCreated
page-type: webextension-api-event
browser-compat: webextensions.api.tabs.onCreated
---
{{AddonSidebar}}
Fired when a tab is created.
Note that the tab's URL may not be given its final value at the time this event fired. In particular, Firefox opens a new tab with the URL "about:blank" before loading the new page into it. You can listen to {{WebExtAPIRef("tabs.onUpdated")}} events to be notified when a URL is set.
## Syntax
```js-nolint
browser.tabs.onCreated.addListener(listener)
browser.tabs.onCreated.removeListener(listener)
browser.tabs.onCreated.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `tab`
- : {{WebExtAPIRef('tabs.Tab')}}. Details of the tab that was created.
## Examples
Log the IDs of newly created tabs:
```js
function handleCreated(tab) {
console.log(tab.id);
}
browser.tabs.onCreated.addListener(handleCreated);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onCreated) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/print/index.md | ---
title: tabs.print()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/print
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.print
---
{{AddonSidebar}}
Call this function to print the contents of the active tab. If this function is called, the user will be presented with the print dialog from the underlying platform, and will have the chance to change the print settings and then print the currently active tab.
## Syntax
```js-nolint
browser.tabs.print()
```
### Parameters
None.
### Return value
None.
## Examples
In this example a background script listens for a click on a [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#browser_actions_2), then tries to print the currently active tab:
```js
browser.browserAction.onClicked.addListener(() => {
browser.tabs.print();
});
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/update/index.md | ---
title: tabs.update()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/update
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.update
---
{{AddonSidebar}}
Navigate the tab to a new URL, or modify other properties of the tab.
To use this function, pass the ID of the tab to update, and an `updateProperties` object containing the properties you want to update. Properties that are not specified in `updateProperties` are not modified.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let updating = browser.tabs.update(
tabId, // optional integer
updateProperties // object
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. Defaults to the selected tab of the current window.
- `updateProperties`
- : `object`. The set of properties to update for this tab. To learn more about these properties, see the {{WebExtAPIRef("tabs.Tab")}} documentation.
- `active` {{optional_inline}}
- : `boolean`. Whether the tab should become active. Does not affect whether the window is focused (see {{WebExtAPIRef('windows.update')}}). If `true`, non-active highlighted tabs will stop being highlighted. If `false`, does nothing.
- `autoDiscardable` {{optional_inline}}
- : `boolean`. Whether the tab can be discarded by the browser. The default value is `true`. When set to `false`, the browser cannot automatically discard the tab. However, the tab can be discarded by {{WebExtAPIRef("tabs.discard")}}.
- `highlighted` {{optional_inline}}
- : `boolean`. Adds or removes the tab from the current selection. If `true` and the tab is not highlighted, it will become active by default.
If you only want to highlight the tab without activating it, Firefox accepts setting `highlighted` to `true` and `active` to `false`. Other browsers may activate the tab even in this case.
- `loadReplace` {{optional_inline}}
- : `boolean`. Whether the new URL should replace the old URL in the tab's navigation history, as accessed via the "Back" button.
For example, suppose the user creates a new tab using Ctrl+T. By default, in Firefox, this would load "about:newtab". If your extension then updates this page using {{WebExtAPIRef("tabs.update")}}, without `loadReplace`, the "Back" button will be enabled and will take the user back to "about:newtab". If the extension sets `loadReplace`, then the "Back" button will be disabled and it will be just as if the URL supplied by the extension was the first page visited in that tab.
Note though that the original URL will still appear in the browser's global history.
- `muted` {{optional_inline}}
- : `boolean`. Whether the tab should be muted.
- `openerTabId` {{optional_inline}}
- : `integer`. The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as this tab.
- `pinned` {{optional_inline}}
- : `boolean`. Whether the tab should be pinned.
- `selected` {{deprecated_inline}} {{optional_inline}}
- : `boolean`. Whether the tab should be selected. This property has been replaced by `active` and `highlighted`.
- `successorTabId` {{optional_inline}}
- : `integer`. The id of the tab's successor.
- `url` {{optional_inline}}
- : `string`. A URL to navigate the tab to.
For security reasons, in Firefox, this may not be a privileged URL. So passing any of the following URLs will fail, with {{WebExtAPIRef("runtime.lastError")}} being set to an error message:
- chrome: URLs
- javascript: URLs
- data: URLs
- file: URLs (i.e., files on the filesystem. However, to use a file packaged inside the extension, see below)
- privileged about: URLs (for example, `about:config`, `about:addons`, `about:debugging`, `about:newtab`). Non-privileged URLs (e.g., `about:blank`) are allowed.
To load a page that's packaged with your extension, specify an absolute URL starting at the extension's manifest.json file. For example: '/path/to/my-page.html'. If you omit the leading '/', the URL is treated as a relative URL, and different browsers may construct different absolute URLs.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('tabs.Tab')}} object containing details about the updated tab. The {{WebExtAPIRef('tabs.Tab')}} object doesn't contain `url`, `title` and `favIconUrl` unless matching [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) or the `"tabs"` permission has been requested. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.
## Examples
Navigate the active tab in the current window to `https://developer.mozilla.org`:
```js
function onUpdated(tab) {
console.log(`Updated tab: ${tab.id}`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
let updating = browser.tabs.update({ url: "https://developer.mozilla.org" });
updating.then(onUpdated, onError);
```
Activate the first tab in the current window, and navigate it to `https://developer.mozilla.org`:
```js
function onUpdated(tab) {
console.log(`Updated tab: ${tab.id}`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
function updateFirstTab(tabs) {
let updating = browser.tabs.update(tabs[0].id, {
active: true,
url: "https://developer.mozilla.org",
});
updating.then(onUpdated, onError);
}
let querying = browser.tabs.query({ currentWindow: true });
querying.then(updateFirstTab, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-update) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/getcurrent/index.md | ---
title: tabs.getCurrent()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/getCurrent
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.getCurrent
---
{{AddonSidebar}}
Get a {{WebExtAPIRef("tabs.Tab")}} containing information about the tab that this script is running in.
> **Note:** This function is only useful in contexts where there is a browser tab, such as an [options page](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#options_pages).
>
> If you call it from a background script or a popup, it will return `undefined`.
This is an asynchronous function that returns a {{jsxref("Promise")}}.
## Syntax
```js-nolint
const gettingCurrent = browser.tabs.getCurrent()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that will be fulfilled with a {{WebExtAPIRef('tabs.Tab')}} object containing information about the current tab. If any error occurs the promise will be rejected with an error message.
## Examples
Get information about the current tab:
```js
function onGot(tabInfo) {
console.log(tabInfo);
}
function onError(error) {
console.log(`Error: ${error}`);
}
const gettingCurrent = browser.tabs.getCurrent();
gettingCurrent.then(onGot, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-getCurrent) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/tab_id_none/index.md | ---
title: tabs.TAB_ID_NONE
slug: Mozilla/Add-ons/WebExtensions/API/tabs/TAB_ID_NONE
page-type: webextension-api-property
browser-compat: webextensions.api.tabs.TAB_ID_NONE
---
{{AddonSidebar}}
A special ID value given to tabs that are not browser tabs (for example, tabs in devtools windows).
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#property-TAB_ID_NONE) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/zoomsettings/index.md | ---
title: tabs.ZoomSettings
slug: Mozilla/Add-ons/WebExtensions/API/tabs/ZoomSettings
page-type: webextension-api-type
browser-compat: webextensions.api.tabs.ZoomSettings
---
{{AddonSidebar}}
Defines zoom settings for a tab: {{WebExtAPIRef("tabs.ZoomSettingsMode", "mode")}}, {{WebExtAPIRef("tabs.ZoomSettingsScope", "scope")}}, and default zoom factor.
## Type
Values of this type are objects. They contain the following properties:
- `defaultZoomFactor` {{optional_inline}}
- : `number`. The default zoom level for the current tab. Note that this is only used in {{WebExtAPIRef("tabs.getZoomSettings")}}.
- `mode` {{optional_inline}}
- : {{WebExtAPIRef('tabs.ZoomSettingsMode')}}. Defines whether zoom changes are handled by the browser, by the extension, or are disabled.
- `scope` {{optional_inline}}
- : {{WebExtAPIRef('tabs.ZoomSettingsScope')}}. Defines whether zoom changes will persist for the page's origin, or only take effect in this tab.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#type-ZoomSettings) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/saveaspdf/index.md | ---
title: tabs.saveAsPDF()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/saveAsPDF
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.saveAsPDF
---
{{AddonSidebar}}
Saves the current page as a PDF file. This will open a dialog, supplied by the underlying operating system, asking the user where they want to save the PDF file.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let saving = browser.tabs.saveAsPDF(
pageSettings // object
)
```
### Parameters
- `pageSettings`
- : `object`. Settings for the saved page, as a {{WebExtAPIRef("tabs.PageSettings")}} object. This object must be given, but all its properties are optional. Any properties not specified here will get the default values listed in the {{WebExtAPIRef("tabs.PageSettings", "PageSettings")}} documentation.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a status string when the dialog has closed. The string may be any of:
- "saved"
- "replaced"
- "canceled"
- "not_saved"
- "not_replaced"
## Examples
In this example a background script listens for a click on a [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#browser_actions_2), then tries to save the currently active tab as a PDF file, then logs the result:
```js
browser.browserAction.onClicked.addListener(() => {
browser.tabs.saveAsPDF({}).then((status) => {
console.log(status);
});
});
```
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onupdated/index.md | ---
title: tabs.onUpdated
slug: Mozilla/Add-ons/WebExtensions/API/tabs/onUpdated
page-type: webextension-api-event
browser-compat: webextensions.api.tabs.onUpdated
---
Fired when a tab is updated.
When the user navigates to a new URL in a tab, this typically generates several `onUpdated` events as various properties of the {{WebExtAPIRef("tabs.Tab")}} object are updated. This includes the `url`, but also potentially the `title` and `favIconUrl` properties. The `status` property will cycle through `"loading"` and `"complete"`.
This event also fires for changes to a tab's properties that don't involve navigation, such as pinning and unpinning (which updates the `pinned` property) and muting or unmuting (which updates the `audible` and `mutedInfo` properties).
You can filter this event, making it only fire for tabs whose URLs match specific [patterns](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns), changes to particular properties, changes to a tab or window, or any combinations of these restrictions.
## Syntax
```js-nolint
browser.tabs.onUpdated.addListener(
listener, // function
filter // optional object
)
browser.tabs.onUpdated.removeListener(listener)
browser.tabs.onUpdated.hasListener(listener)
```
Events have three functions:
- `addListener(callback, filter)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed these arguments:
- `tabId`
- : `integer`. The ID of the updated tab.
- `changeInfo`
- : `object`. Properties of the tab that changed. See the [changeInfo](#changeinfo_2) section for more details.
- `tab`
- : {{WebExtAPIRef('tabs.Tab')}}. The new state of the tab.
- `filter` {{optional_inline}}
- : `object`. A set of filters that restrict the events sent to this listener. This object can have one or more of these properties. Events are only sent if they satisfy all the filters provided.
- `urls`
- : `Array`. An array of [match patterns](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns). Fires the event only for tabs whose current `url` property matches any one of the patterns.
- `properties`
- : `Array`. An array of strings consisting of supported {{WebExtAPIRef("tabs.Tab")}} object property names. Fires the event only for changes to one of the properties named in the array. These properties can be used:
- "attention"
- "autoDiscardable"
- "audible"
- "discarded"
- "favIconUrl"
- "hidden"
- "isArticle"
- "mutedInfo"
- "pinned"
- "status"
- "title"
- "url"
> **Note:** The "url" value has been supported since Firefox 88. In Firefox 87 and earlier, "url" changes can be observed by filtering by "status".
- `tabId`
- : `Integer`. Fires this event only for the tab identified by this ID.
- `windowId`
- : `Integer`. Fires this event only for tabs in the window identified by this ID.
## Additional objects
### changeInfo
Lists the changes to the state of the tab that is updated. To learn more about these properties, see the {{WebExtAPIRef("tabs.Tab")}} documentation. Note that not all {{WebExtAPIRef("tabs.Tab")}} properties are supported.
- `attention` {{optional_inline}}
- : `boolean`. Indicates whether the tab is drawing attention. For example, `attention` is `true` when the tab displays a modal dialog.
- `audible` {{optional_inline}}
- : `boolean`. The tab's new audible state.
- `autoDiscardable` {{optional_inline}}
- : `boolean`. Whether the tab can be discarded by the browser. The default value is `true`. When set to `false`, the browser cannot automatically discard the tab. However, the tab can be discarded by {{WebExtAPIRef("tabs.discard")}}.
- `discarded` {{optional_inline}}
- : `boolean`. Whether the tab is discarded. A discarded tab is one whose content has been unloaded from memory but is visible in the tab strip. Its content gets reloaded the next time it's activated.
- `favIconUrl` {{optional_inline}}
- : `string`. The tab's new favicon URL. Not included when a tab loses its favicon (navigating from a page with a favicon to a page without one). Check `favIconUrl` in [tab](#tab) instead.
- `hidden` {{optional_inline}}
- : `boolean`. True if the tab is {{WebExtAPIRef("tabs.hide()", "hidden")}}.
- `isArticle` {{optional_inline}}
- : `boolean`. True if the tab is an article and is therefore eligible for display in {{WebExtAPIRef("tabs.toggleReaderMode()", "Reader Mode")}}.
- `mutedInfo` {{optional_inline}}
- : {{WebExtAPIRef('tabs.MutedInfo')}}. The tab's new muted state and the reason for the change.
- `pinned` {{optional_inline}}
- : `boolean`. The tab's new pinned state.
- `status` {{optional_inline}}
- : `string`. The status of the tab. Can be either _loading_ or _complete_.
- `title` {{optional_inline}}
- : `string`. The tab's new title.
- `url` {{optional_inline}}
- : `string`. The tab's URL, if it has changed.
## Examples
Listen for and log all the change info and new state:
```js
function handleUpdated(tabId, changeInfo, tabInfo) {
console.log(`Updated tab: ${tabId}`);
console.log("Changed attributes: ", changeInfo);
console.log("New tab Info: ", tabInfo);
}
browser.tabs.onUpdated.addListener(handleUpdated);
```
Log changes to URLs:
```js
function handleUpdated(tabId, changeInfo, tabInfo) {
if (changeInfo.url) {
console.log(`Tab: ${tabId} URL changed to ${changeInfo.url}`);
}
}
browser.tabs.onUpdated.addListener(handleUpdated);
```
### Filtering examples
Log changes only to tabs whose `url` property is [matched](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) by `https://developer.mozilla.org/*` or `https://mozilla.social/@mdn`:
```js
const pattern1 = "https://developer.mozilla.org/*";
const pattern2 = "https://mozilla.social/@mdn";
const filter = {
urls: [pattern1, pattern2],
};
function handleUpdated(tabId, changeInfo, tabInfo) {
console.log(`Updated tab: ${tabId}`);
console.log("Changed attributes: ", changeInfo);
console.log("New tab Info: ", tabInfo);
}
browser.tabs.onUpdated.addListener(handleUpdated, filter);
```
Log changes only to the `pinned` property of tabs (that is, pin and unpin actions):
```js
const filter = {
properties: ["pinned"],
};
function handleUpdated(tabId, changeInfo, tabInfo) {
console.log(`Updated tab: ${tabId}`);
console.log("Changed attributes: ", changeInfo);
console.log("New tab Info: ", tabInfo);
}
browser.tabs.onUpdated.addListener(handleUpdated, filter);
```
Combine both the previous filters, log only when the `pinned` property of tabs changes for tabs whose `url` property is [matched](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) by `https://developer.mozilla.org/*` or `https://mozilla.social/@mdn`:
```js
const pattern1 = "https://developer.mozilla.org/*";
const pattern2 = "https://mozilla.social/@mdn";
const filter = {
urls: [pattern1, pattern2],
properties: ["pinned"],
};
function handleUpdated(tabId, changeInfo, tabInfo) {
console.log(`Updated tab: ${tabId}`);
console.log("Changed attributes: ", changeInfo);
console.log("New tab Info: ", tabInfo);
}
browser.tabs.onUpdated.addListener(handleUpdated, filter);
```
Log changes only when the `pinned` property of tabs changes for tabs whose `url` property is [matched](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) by `https://developer.mozilla.org/*` or `https://mozilla.social/@mdn` where the tab was part of the current browser window when the update event fired:
```js
const pattern1 = "https://developer.mozilla.org/*";
const pattern2 = "https://mozilla.social/@mdn";
const filter = {
urls: [pattern1, pattern2],
properties: ["pinned"],
windowId: browser.windows.WINDOW_ID_CURRENT,
};
function handleUpdated(tabId, changeInfo, tabInfo) {
console.log(`Updated tab: ${tabId}`);
console.log("Changed attributes: ", changeInfo);
console.log("New tab Info: ", tabInfo);
}
browser.tabs.onUpdated.addListener(handleUpdated, filter);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onUpdated) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
{{AddonSidebar}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onhighlightchanged/index.md | ---
title: tabs.onHighlightChanged
slug: Mozilla/Add-ons/WebExtensions/API/tabs/onHighlightChanged
page-type: webextension-api-event
status:
- deprecated
browser-compat: webextensions.api.tabs.onHighlightChanged
---
{{AddonSidebar}}
> **Warning:** This event is deprecated. Use {{WebExtAPIRef("tabs.onHighlighted")}} instead.
Fired when the highlighted or selected tabs in a window changes.
## Syntax
```js-nolint
browser.tabs.onHighlightChanged.addListener(listener)
browser.tabs.onHighlightChanged.removeListener(listener)
browser.tabs.onHighlightChanged.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `selectInfo`
- : `object`. See the [selectInfo](#selectinfo_2) section for more details.
## Additional objects
### selectInfo
- `windowId`
- : `integer`. The window whose tabs changed.
- `tabIds`
- : `array` of `integer`. All highlighted tabs in the window.
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onHighlightChanged) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/duplicate/index.md | ---
title: tabs.duplicate()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/duplicate
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.duplicate
---
{{AddonSidebar}}
Duplicates a tab, given its ID.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let duplicating = browser.tabs.duplicate(
tabId, // integer
duplicateProperties // optional object
)
```
### Parameters
- `tabId`
- : `integer`. The ID of the tab to be duplicated.
- `duplicateProperties` Optional
- : `object`. An object describing how the tab is duplicated. It contains the following properties:
- `index` Optional
- : `integer`. The position of the new tab in the window. The value is constrained to the range zero to the number of tabs in the window.
- `active` Optional
- : `boolean`. Whether the tab becomes the active tab in the window. Does not affect whether the window is focused. Defaults to `true`.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('tabs.Tab')}} object containing details about the duplicated tab. The `Tab` object only contains `url`, `title` and `favIconUrl` if the extension has the [`"tabs"` permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or matching [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions). If any error occurs the promise will be rejected with an error message.
> **Note:** Beginning with Firefox 68, the promise returned by browser.tabs.duplicate() resolves as soon as the tab has been duplicated. Previously, the promise only resolved once the tab had fully been loaded.
## Examples
Duplicate the first tab, and then log the ID of the newly created tab:
```js
function onDuplicated(tabInfo) {
console.log(tabInfo.id);
}
function onError(error) {
console.log(`Error: ${error}`);
}
// Duplicate the first tab in the array
function duplicateFirstTab(tabs) {
console.log(tabs);
if (tabs.length > 0) {
let duplicating = browser.tabs.duplicate(tabs[0].id);
duplicating.then(onDuplicated, onError);
}
}
// Query for all open tabs
let querying = browser.tabs.query({});
querying.then(duplicateFirstTab, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-duplicate) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/setzoom/index.md | ---
title: tabs.setZoom()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/setZoom
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.setZoom
---
{{AddonSidebar}}
Zooms the specified tab.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let zooming = browser.tabs.setZoom(
tabId, // optional integer
zoomFactor // number
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab to zoom. Defaults to the active tab of the current window.
- `zoomFactor`
- : `number`. The new zoom factor. Use a value of 0 here to set the tab to its current default zoom factor. Otherwise, this must be a number between 0.3 and 5, specifying a zoom factor.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments after the zoom factor has been changed. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.
## Examples
Set the zoom factor for the current tab to 2:
```js
function onError(error) {
console.log(`Error: ${error}`);
}
let setting = browser.tabs.setZoom(2);
setting.then(null, onError);
```
Set the zoom factor for the tab whose ID is 16 tab to 0.5:
```js
function onError(error) {
console.log(`Error: ${error}`);
}
let setting = browser.tabs.setZoom(16, 0.5);
setting.then(null, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-setZoom) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/executescript/index.md | ---
title: tabs.executeScript()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/executeScript
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.executeScript
---
{{AddonSidebar}}
Injects JavaScript code into a page.
> **Note:** When using Manifest V3 or higher, use {{WebExtAPIRef("scripting.executeScript()")}} to execute scripts.
You can inject code into pages whose URL can be expressed using a [match pattern](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns). To do so, its scheme must be one of: `http`, `https`, or `file`.
You must have the permission for the page's URL—either explicitly, as a [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions)—or, via the [activeTab permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission). Note that some special pages do not allow this permission, including reader view, view-source, and PDF viewer pages.
You can also inject code into pages packaged with your own extension:
```js
browser.tabs.create({ url: "/my-page.html" }).then(() => {
browser.tabs.executeScript({
code: `console.log('location:', window.location.href);`,
});
});
```
You don't need any special permissions to do this.
You _cannot_ inject code into any of the browser's built-in pages, such as: `about:debugging`, `about:addons`, or the page that opens when you open a new empty tab.
The scripts you inject are called [content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts).
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let executing = browser.tabs.executeScript(
tabId, // optional integer
details // object
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab in which to run the script.
Defaults to the active tab of the current window.
- `details`
- : An object describing the script to run.
It contains the following properties:
- `allFrames` {{optional_inline}}
- : `boolean`. If `true`, the code will be injected into all frames of the current page.
If `true` and `frameId` is set, then it will raise an error. (`frameId` and `allFrames` are mutually exclusive.)
If it is `false`, code is only injected into the top frame.
Defaults to `false`.
- `code` {{optional_inline}}
- : `string`. Code to inject, as a text string.
> **Warning:** Don't use this property to interpolate untrusted data into JavaScript, as this could lead to a security issue.
- `file` {{optional_inline}}
- : `string`. Path to a file containing the code to inject.
- In Firefox, relative URLs not starting at the extension root are resolved relative to the current page URL.
- In Chrome, these URLs are resolved relative to the extension's base URL.
To work cross-browser, you can specify the path as a relative URL, starting at the extension's root, like this: `"/path/to/script.js"`.
- `frameId` {{optional_inline}}
- : `integer`. The frame where the code should be injected.
Defaults to `0` (the top-level frame).
- `matchAboutBlank` {{optional_inline}}
- : `boolean`. If `true`, the code will be injected into embedded `about:blank` and `about:srcdoc` frames if your extension has access to their parent document. The code cannot be inserted in top-level `about:` frames.
Defaults to `false`.
- `runAt` {{optional_inline}}
- : {{WebExtAPIRef('extensionTypes.RunAt')}}. The soonest that the code will be injected into the tab.
Defaults to `"document_idle"`.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will resolve to an array of objects. The array's values represent the result of the script in every injected frame.
The result of the script is the last evaluated statement, which is similar to what would be output (the results, not any `console.log()` output) if you executed the script in the [Web Console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html). For example, consider a script like this:
```js
let foo = "my result";
foo;
```
Here the results array will contain the string "`my result`" as an element.
The result values must be [structured cloneable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) (see [Data cloning algorithm](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#data_cloning_algorithm)).
> **Note:** The last statement may be also a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), but this feature is unsupported by [webextension-polyfill](https://github.com/mozilla/webextension-polyfill#tabsexecutescript) library.
If any error occurs, the promise will be rejected with an error message.
## Examples
This example executes a one-line code snippet in the currently active tab:
```js
function onExecuted(result) {
console.log(`We made it green`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
const makeItGreen = 'document.body.style.border = "5px solid green"';
const executing = browser.tabs.executeScript({
code: makeItGreen,
});
executing.then(onExecuted, onError);
```
This example executes a script from a file (packaged with the extension) called `"content-script.js"`. The script is executed in the currently active tab. The script is executed in subframes as well as the main document:
```js
function onExecuted(result) {
console.log(`We executed in all subframes`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
const executing = browser.tabs.executeScript({
file: "/content-script.js",
allFrames: true,
});
executing.then(onExecuted, onError);
```
This example executes a script from a file (packaged with the extension) called `"content-script.js"`. The script is executed in the tab with an ID of `2`:
```js
function onExecuted(result) {
console.log(`We executed in tab 2`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
const executing = browser.tabs.executeScript(2, {
file: "/content-script.js",
});
executing.then(onExecuted, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-executeScript) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/getallinwindow/index.md | ---
title: tabs.getAllInWindow()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/getAllInWindow
page-type: webextension-api-function
status:
- deprecated
browser-compat: webextensions.api.tabs.getAllInWindow
---
{{AddonSidebar}}
> **Warning:** This method has been deprecated. Use {{WebExtAPIRef("tabs.query", "tabs.query({currentWindow: true})")}} instead.
Gets details about all tabs in the specified window.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let getting = browser.tabs.getAllInWindow(
windowId // optional integer
)
```
### Parameters
- `windowId` {{optional_inline}}
- : `integer`. Defaults to the current window.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an `array` of `{{WebExtAPIRef('tabs.Tab')}}` objects, containing information about all the tabs in the window. If the window could not be found or some other error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-getAllInWindow) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/mutedinfo/index.md | ---
title: tabs.MutedInfo
slug: Mozilla/Add-ons/WebExtensions/API/tabs/MutedInfo
page-type: webextension-api-type
browser-compat: webextensions.api.tabs.MutedInfo
---
{{AddonSidebar}}
This object contains a boolean indicating whether the tab is muted, and the reason for the last state change.
## Type
Values of this type are objects. They contain the following properties:
- `extensionId` {{optional_inline}}
- : `string`. The ID of the extension that last changed the muted state. Not set if an extension was not the reason the muted state last changed.
- `muted`
- : `boolean`. Whether the tab is currently muted. Equivalent to whether the muted audio indicator is showing.
- `reason` {{optional_inline}}
- : {{WebExtAPIRef('tabs.MutedInfoReason')}}. The reason the tab was muted or unmuted. Not set if the tab's muted state has never been changed.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#type-MutedInfo) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/insertcss/index.md | ---
title: tabs.insertCSS()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/insertCSS
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.insertCSS
---
{{AddonSidebar}}
Injects CSS into a page.
> **Note:** When using Manifest V3 or higher, use {{WebExtAPIRef("scripting.insertCSS()")}} and {{WebExtAPIRef("scripting.removeCSS()")}} to insert and remove CSS.
To use this API you must have the permission for the page's URL, either explicitly as a [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions), or using the [activeTab permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission).
You can only inject CSS into pages whose URL can be expressed using a [match pattern](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns): meaning, its scheme must be one of "http", "https", or "file". This means that you can't inject CSS into any of the browser's built-in pages, such as about:debugging, about:addons, or the page that opens when you open a new empty tab.
> **Note:** Firefox resolves URLs in injected CSS files relative to the CSS file itself, rather than to the page it's injected into.
The inserted CSS may be removed again by calling {{WebExtAPIRef("tabs.removeCSS()")}}.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) (on Firefox only).
## Syntax
```js-nolint
let inserting = browser.tabs.insertCSS(
tabId, // optional integer
details // object
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab in which to insert the CSS. Defaults to the active tab of the current window.
- `details`
- : An object describing the CSS to insert. It contains the following properties:
- `allFrames` {{optional_inline}}
- : `boolean`. If `true`, the CSS will be injected into all frames of the current page. If it is `false`, CSS is only injected into the top frame. Defaults to `false`.
- `code` {{optional_inline}}
- : `string`. Code to inject, as a text string.
- `cssOrigin` {{optional_inline}}
- : `string`. This can take one of two values: "user", to add the CSS as a user stylesheet or "author" to add it as an author stylesheet. If this option is omitted, the CSS is added as an author stylesheet.
- "user" enables you to prevent websites from overriding the CSS you insert: see [Cascading order](/en-US/docs/Web/CSS/Cascade#cascading_order).
- "author" stylesheets behave as if they appear after all author rules specified by the web page. This behavior includes any author stylesheets added dynamically by the page's scripts, even if that addition happens after the `insertCSS` call completes.
- `file` {{optional_inline}}
- : `string`. Path to a file containing the code to inject. In Firefox, relative URLs are resolved relative to the current page URL. In Chrome, these URLs are resolved relative to the extension's base URL. To work cross-browser, you can specify the path as an absolute URL, starting at the extension's root, like this: `"/path/to/stylesheet.css"`.
- `frameId` {{optional_inline}}
- : `integer`. The frame where the CSS should be injected. Defaults to `0` (the top-level frame).
- `matchAboutBlank` {{optional_inline}}
- : `boolean`. If `true`, the code will be injected into embedded "about:blank" and "about:srcdoc" frames if your extension has access to their parent document. The code cannot be inserted in top-level about: frames. Defaults to `false`.
- `runAt` {{optional_inline}}
- : {{WebExtAPIRef('extensionTypes.RunAt')}}. The soonest that the code will be injected into the tab. Defaults to "document_idle".
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when all the CSS has been inserted. If any error occurs, the promise will be rejected with an error message.
## Examples
This example inserts into the currently active tab CSS which is taken from a string.
```js
let css = "body { border: 20px dotted pink; }";
browser.browserAction.onClicked.addListener(() => {
function onError(error) {
console.log(`Error: ${error}`);
}
let insertingCSS = browser.tabs.insertCSS({ code: css });
insertingCSS.then(null, onError);
});
```
This example inserts CSS which is loaded from a file packaged with the extension. The CSS is inserted into the tab whose ID is 2:
```js
browser.browserAction.onClicked.addListener(() => {
function onError(error) {
console.log(`Error: ${error}`);
}
let insertingCSS = browser.tabs.insertCSS(2, { file: "content-style.css" });
insertingCSS.then(null, onError);
});
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-insertCSS) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onremoved/index.md | ---
title: tabs.onRemoved
slug: Mozilla/Add-ons/WebExtensions/API/tabs/onRemoved
page-type: webextension-api-event
browser-compat: webextensions.api.tabs.onRemoved
---
{{AddonSidebar}}
Fired when a tab is closed.
## Syntax
```js-nolint
browser.tabs.onRemoved.addListener(listener)
browser.tabs.onRemoved.removeListener(listener)
browser.tabs.onRemoved.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed these arguments:
- `tabId`
- : `integer`. ID of the tab that closed.
- `removeInfo`
- : `object`. The tab's window ID, and a boolean indicating whether the window is also being closed. See the [removeInfo](#removeinfo_2) section for more details.
## Additional objects
### removeInfo
- `windowId`
- : `integer`. The window whose tab is closed.
- `isWindowClosing`
- : `boolean`. `true` if the tab is being closed because its window is being closed.
## Examples
Listen for close events, and log the info:
```js
function handleRemoved(tabId, removeInfo) {
console.log(`Tab: ${tabId} is closing`);
console.log(`Window ID: ${removeInfo.windowId}`);
console.log(`Window is closing: ${removeInfo.isWindowClosing}`);
}
browser.tabs.onRemoved.addListener(handleRemoved);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onRemoved) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/ondetached/index.md | ---
title: tabs.onDetached
slug: Mozilla/Add-ons/WebExtensions/API/tabs/onDetached
page-type: webextension-api-event
browser-compat: webextensions.api.tabs.onDetached
---
{{AddonSidebar}}
Fired when a tab is detached from a window, for example because it is being moved between windows.
## Syntax
```js-nolint
browser.tabs.onDetached.addListener(listener)
browser.tabs.onDetached.removeListener(listener)
browser.tabs.onDetached.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed these arguments:
- `tabId`
- : `integer`. ID of the tab that was detached.
- `detachInfo`
- : `object`. ID of the previous window, and index of the tab within it. See the [detachInfo](#detachinfo_2) section for more details.
## Additional objects
### detachInfo
- `oldWindowId`
- : `integer`. ID of the previous window.
- `oldPosition`
- : `integer`. Index position that the tab had in the old window.
## Examples
Listen for detach events, and log the info:
```js
function handleDetached(tabId, detachInfo) {
console.log(`Tab: ${tabId} moved`);
console.log(`Old window: ${detachInfo.oldWindowId}`);
console.log(`Old index: ${detachInfo.oldPosition}`);
}
browser.tabs.onDetached.addListener(handleDetached);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onDetached) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/goback/index.md | ---
title: tabs.goBack()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/goBack
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.goBack
---
{{AddonSidebar}}
Navigate to the previous page in tab's history, if available.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let withGoingBack = browser.tabs.goBack(
tabId, // optional integer
callback // optional function
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab to navigate. Defaults to the active tab of the current window.
- `callback` {{optional_inline}}
- : `function`. When the page navigation finishes, this function is called without parameters.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is fulfilled when the page navigation finishes.
## Browser compatibility
{{Compat}}
## Examples
Go back to the previous page in the current tab:
```js
function onGoBack() {
console.log("Gone back");
}
function onError(error) {
console.log(`Error: ${error}`);
}
let goingBack = browser.tabs.goBack();
goingBack.then(onGoBack, onError);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-getZoomSettings) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/highlight/index.md | ---
title: tabs.highlight()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/highlight
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.highlight
---
{{AddonSidebar}}
Highlights (selects) one or more tabs. Tabs are specified using a window ID and a range of tab indices.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let highlighting = browser.tabs.highlight(
highlightInfo // object
)
```
### Parameters
- `highlightInfo`
- : `object`.
- `windowId` {{optional_inline}}
- : `integer`. ID of the window that contains the tabs.
- `populate` {{optional_inline}}
- : `boolean`. Defaults to `true`. If set to `false`, the {{WebExtAPIRef('windows.Window')}} object won't have a `tabs` property containing a list of {{WebExtAPIRef('tabs.Tab')}} objects representing the tabs open in the window.
> **Note:** Populating the window (the default behavior) can be an expensive operation if there are lots of tabs. For better performance it's recommended to manually set `populate` to `false` if you don't need tab details.
- `tabs`
- : `array` of integer values specifying one or more tab indices to highlight. Previously highlighted tabs not included in `tabs` will stop being highlighted. The first tab in `tabs` will become active.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('windows.Window')}} object containing details about the window whose tabs were highlighted. If the window could not be found or some other error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-highlight) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/pagesettings/index.md | ---
title: tabs.PageSettings
slug: Mozilla/Add-ons/WebExtensions/API/tabs/PageSettings
page-type: webextension-api-type
browser-compat: webextensions.api.tabs.PageSettings
---
{{AddonSidebar}}
The type **`tabs.PageSettings`** is used to control how a tab is rendered as a PDF by the {{WebExtAPIRef("tabs.saveAsPDF()")}} method.
All its properties are optional.
For setting headers and footers, you can include certain special characters in the strings you supply. These will be replaced in the rendered output as follows:
- "\&P": the page number, like "2"
- "\&PT": the page number and the total number of pages, like "2 of 3"
- "\&D": the current date/time
- "\&T": the page title
- "\&U": the page URL
## Type
Values of this type are objects. They contain the following properties:
- `edgeBottom` {{optional_inline}}
- : `number`. The spacing between the bottom of the footers and the bottom edge of the paper (inches). Default: 0.
- `edgeLeft` {{optional_inline}}
- : `number`. The spacing between the left header/footer and the left edge of the paper (inches). Default: 0.
- `edgeRight` {{optional_inline}}
- : `number`. The spacing between the right header/footer and the left edge of the paper (inches). Default: 0.
- `edgeTop` {{optional_inline}}
- : `number`. The spacing between the top of the headers and the top edge of the paper (inches). Default: 0
- `footerCenter` {{optional_inline}}
- : `string`. The text for the page's center footer. Default: ''.
- `footerLeft` {{optional_inline}}
- : `string`. The text for the page's left footer. Default: '\&PT'.
- `footerRight` {{optional_inline}}
- : `string`. The text for the page's right footer. Default: '\&D'.
- `headerCenter` {{optional_inline}}
- : `string`. The text for the page's center header. Default: ''.
- `headerLeft` {{optional_inline}}
- : `string`. The text for the page's left header. Default: '\&T'.
- `headerRight` {{optional_inline}}
- : `string`. The text for the page's right header. Default: '\&U'.
- `marginBottom` {{optional_inline}}
- : `number`. The margin between the page content and the bottom edge of the paper (inches). Default: 0.5.
- `marginLeft` {{optional_inline}}
- : `number`. The margin between the page content and the left edge of the paper (inches). Default: 0.5.
- `marginRight` {{optional_inline}}
- : `number`. The margin between the page content and the right edge of the paper (inches). Default: 0.5.
- `marginTop` {{optional_inline}}
- : `number`. The margin between the page content and the top edge of the paper (inches). Default: 0.5.
- `orientation` {{optional_inline}}
- : `integer`. Page orientation: 0 means "portrait", 1 means "landscape". Default: 0.
- `paperHeight` {{optional_inline}}
- : `number`. The paper height in paper size units. Default: 11.0.
- `paperSizeUnit` {{optional_inline}}
- : `integer`. The paper size unit: 0 = inches, 1 = millimeters. Default: 0.
- `paperWidth` {{optional_inline}}
- : `number`. The paper width in paper size units. Default: 8.5.
- `scaling` {{optional_inline}}
- : `number`. Page content scaling factor. 1 means 100% or normal size. Default: 1.
- `showBackgroundColors` {{optional_inline}}
- : `boolean`. Whether the page background colors should be shown. Default: false.
- `showBackgroundImages` {{optional_inline}}
- : `boolean`. Whether the page background images should be shown. Default: false.
- `shrinkToFit` {{optional_inline}}
- : `boolean`. Whether the page content should shrink to fit the page width (overrides scaling). Default: true.
- `toFileName` {{optional_inline}}
- : `string`. The name of the file the PDF is saved in, with or without the `.pdf` extension.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/show/index.md | ---
title: tabs.show()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/show
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.show
---
{{AddonSidebar}}
Shows one or more tabs that were previously hidden by a call to {{WebExtAPIRef("tabs.hide")}}.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let showing = browser.tabs.show(
tabIds // integer or integer array
)
```
### Parameters
- `tabIds`
- : `integer` or `array` of `integer`. The IDs of the tab or tabs to show.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments. If any error occurs, the promise will be rejected with an error message.
## Examples
Show a single tab:
```js
function onShown() {
console.log(`Shown`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
browser.tabs.show(2).then(onShown, onError);
```
Show multiple tabs:
```js
function onShown() {
console.log(`Shown`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
browser.tabs.show([15, 14, 1]).then(onShown, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/capturetab/index.md | ---
title: tabs.captureTab()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/captureTab
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.captureTab
---
{{AddonSidebar}}
Creates a data URL encoding the image of an area of the given tab. You must have the `<all_urls>` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) to use this method.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let capturing = browser.tabs.captureTab(
tabId, // optional integer
options // optional extensionTypes.ImageDetails
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. ID of the tab to capture. Defaults to the active tab in the current window.
- `options` {{optional_inline}}
- : {{WebExtAPIRef('extensionTypes.ImageDetails')}}.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a data URL which encodes the captured image. May be assigned to the 'src' property of an HTML Image element for display. If any error occurs the promise will be rejected with an error message.
## Examples
Capture an image of the active tab in the current window, with default settings:
```js
function onCaptured(imageUri) {
console.log(imageUri);
}
function onError(error) {
console.log(`Error: ${error}`);
}
browser.browserAction.onClicked.addListener(() => {
let capturing = browser.tabs.captureTab();
capturing.then(onCaptured, onError);
});
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-captureVisibleTab) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/removecss/index.md | ---
title: tabs.removeCSS()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/removeCSS
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.removeCSS
---
{{AddonSidebar}}
Removes from a page CSS which was previously injected by a call to {{WebExtAPIRef("tabs.insertCSS()")}}.
> **Note:** When using Manifest V3 or higher, use {{WebExtAPIRef("scripting.insertCSS()")}} and {{WebExtAPIRef("scripting.removeCSS()")}} to insert and remove CSS.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let removing = browser.tabs.removeCSS(
tabId, // optional integer
details // object
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab from which to remove the CSS. Defaults to the active tab of the current window.
- `details`
- : An object describing the CSS to remove from the page. It contains the following properties:
- `allFrames` {{optional_inline}}
- : `boolean`. If `true`, the code will be removed from all frames of the current page. If it is `false`, code is only removed from the top frame. Defaults to `false`.
- `code` {{optional_inline}}
- : `string`. CSS to remove, as a text string. This must exactly match a CSS string previously inserted into the page using {{WebExtAPIRef("tabs.insertCSS()")}}.
- `cssOrigin` {{optional_inline}}
- : `string`. This can take one of two values: "user", for CSS added as a user stylesheet, or "author" for CSS added as an author stylesheet. If this option was set previously by {{WebExtAPIRef("tabs.insertCSS()")}}, then it must exactly match.
- `file` {{optional_inline}}
- : `string`. Path to a file containing the CSS to remove. This must exactly match a CSS file previously inserted into the page using {{WebExtAPIRef("tabs.insertCSS()")}}.
- `frameId` {{optional_inline}}
- : `integer`. The frame from which to remove the CSS. Defaults to `0` (the top-level frame).
- `matchAboutBlank` {{optional_inline}}
- : `boolean`. If `true`, the CSS will be removed from embedded "about:blank" and "about:srcdoc" frames if your extension has access to their parent document. Defaults to `false`.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when all the CSS has been removed. If any error occurs, the promise will be rejected with an error message.
## Examples
This example adds some CSS using {{WebExtAPIRef("tabs.insertCSS")}}, then removes it again when the user clicks a browser action:
```js
let css = "body { border: 20px dotted pink; }";
function onError(error) {
console.log(`Error: ${error}`);
}
let insertingCSS = browser.tabs.insertCSS(2, { code: css });
insertingCSS.then(null, onError);
browser.browserAction.onClicked.addListener(() => {
let removing = browser.tabs.removeCSS(2, { code: css });
removing.then(null, onError);
});
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-insertCSS) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/warmup/index.md | ---
title: tabs.warmup()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/warmup
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.warmup
---
{{AddonSidebar}}
To optimize system resource usage, browsers may drop GPU resources associated with tabs that the user has not accessed for a certain amount of time. If a browser has done this for a tab, then reactivating the tab (for example, when the user switches to it) may take longer than it normally would.
The `tabs.warmup()` API enables an extension to start the process of rendering the resources for an inactive tab, if the extension expects that the user might switch to the tab soon. This then makes the actual tab switch faster than it would be otherwise.
Note this API does not work on discarded tabs and does not need to be called immediately prior to switching tabs. It is merely a performance improvement when the tab switch can be anticipated, such as when hovering over a button that when clicked would switch to the tab.
It is expected that this API would mostly be useful to tab management extensions.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let warming = browser.tabs.warmup(
tabId // integer
)
```
### Parameters
- `tabId`
- : `integer`. ID of the tab to warm up. If the argument passed here is not an integer (in particular, if it is `null` or `undefined`) then `warmup()` will throw an exception synchronously.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments if the tab identified by `tabId` is successfully warmed up. If `tabId` does not identify an open tab, or if warming up fails for some other reason, then the promise will be rejected with an error message.
## Examples
This code adds a listener to the `browserAction.onClicked` event. The listener retrieves all tabs in the current window that contain pages under "https\://developer.mozilla.org/" and warms up the first one that it finds.
```js
function onSuccess() {
console.log("success!");
}
function onFailure(error) {
// e.g. ID of a nonexistent tab
console.error(error);
}
async function warmupMDN() {
const mdnTabs = await browser.tabs.query({
currentWindow: true,
url: "https://developer.mozilla.org/*",
});
if (mdnTabs.length > 0) {
const warming = browser.tabs.warmup(mdnTabs[0].id);
warming.then(onSuccess, onFailure);
}
}
browser.browserAction.onClicked.addListener(warmupMDN);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/zoomsettingsmode/index.md | ---
title: tabs.ZoomSettingsMode
slug: Mozilla/Add-ons/WebExtensions/API/tabs/ZoomSettingsMode
page-type: webextension-api-type
browser-compat: webextensions.api.tabs.ZoomSettingsMode
---
{{AddonSidebar}}
Defines how zoom changes are handled. Extensions can pass this value into {{WebExtAPIRef("tabs.setZoomSettings()")}} to control how the browser handles attempts to change zoom settings for a tab. Defaults to "automatic".
## Type
Values of this type are strings. Possible values are:
- "automatic"
- : Zoom changes are handled normally by the browser.
- "disabled"
- : Disables all zooming in the tab. The tab will revert to the default zoom level, and all attempted zoom changes will be ignored.
- "manual"
- : The extension will handle zoom changes itself, by listening for the {{WebExtAPIRef("tabs.onZoomChange")}} event and scaling the page accordingly. This mode does not support `per-origin` zooming: it will ignore the `scope` {{WebExtAPIRef("tabs.zoomSettings", "zoom setting")}} and always use `per-tab`.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#type-ZoomSettingsMode) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/query/index.md | ---
title: tabs.query()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/query
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.query
---
{{AddonSidebar}}
Gets all tabs that have the specified properties, or all tabs if no properties are specified.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let querying = browser.tabs.query(queryObj)
```
### Parameters
- `queryObj`
- : `object`. The `query()` function will only get tabs whose properties match the properties included here.
See the {{WebExtAPIRef("tabs.Tab")}} documentation to learn more about these properties.
- `active` {{optional_inline}}
- : `boolean`. Whether the tabs are active in their windows.
- `audible` {{optional_inline}}
- : `boolean`. Whether the tabs are audible.
- `autoDiscardable` {{optional_inline}}
- : `boolean`. Whether the tab can be discarded by the browser. The default value is `true`. When set to `false`, the browser cannot automatically discard the tab. However, the tab can be discarded by {{WebExtAPIRef("tabs.discard")}}.
- `cookieStoreId` {{optional_inline}}
- : `string` or `array` of `string`. Use this to return tabs whose `tab.cookieStoreId` matches any of the `cookieStoreId` strings. This option is only available if the add-on has the `"cookies"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information.
- `currentWindow` {{optional_inline}}
- : `boolean`. Whether the tabs are in the current window.
- `discarded` {{optional_inline}}
- : `boolean`. Whether the tabs are discarded. A discarded tab is one whose content has been unloaded from memory, but is still visible in the tab strip. Its content gets reloaded the next time it's activated.
- `hidden` {{optional_inline}}
- : `boolean`. Whether the tabs are hidden.
- `highlighted` {{optional_inline}}
- : `boolean`. Whether the tabs are highlighted.
- `index` {{optional_inline}}
- : `integer`. The position of the tabs within their windows.
- `muted` {{optional_inline}}
- : `boolean`. Whether the tabs are muted.
- `lastFocusedWindow` {{optional_inline}}
- : `boolean`. Whether the tabs are in the last focused window.
- `pinned` {{optional_inline}}
- : `boolean`. Whether the tabs are pinned.
- `status` {{optional_inline}}
- : {{WebExtAPIRef('tabs.TabStatus')}}. Whether the tabs have completed loading.
- `title` {{optional_inline}}
- : `string`. Match page titles against a pattern. Requires the "tabs" permission or [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the tab to match.
- `url` {{optional_inline}}
- : `string` or `array` of `string`. Match tabs against one or more [match patterns](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns). Note that fragment identifiers are not matched. Requires the "tabs" permission or [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the tab to match.
- `windowId` {{optional_inline}}
- : `integer`. The `id` of the parent window, or {{WebExtAPIRef('windows.WINDOW_ID_CURRENT')}} for the current window.
- `windowType` {{optional_inline}}
- : {{WebExtAPIRef('tabs.WindowType')}}. The type of window the tabs are in.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an `array` of `{{WebExtAPIRef('tabs.Tab')}}` objects, containing information about each matching tab.
If any error occurs, the promise will be rejected with an error message.
## Examples
Get all tabs:
```js
function logTabs(tabs) {
for (const tab of tabs) {
// tab.url requires the `tabs` permission or a matching host permission.
console.log(tab.url);
}
}
function onError(error) {
console.error(`Error: ${error}`);
}
browser.tabs.query({}).then(logTabs, onError);
```
Get all tabs in the current window:
```js
function logTabs(tabs) {
for (const tab of tabs) {
// tab.url requires the `tabs` permission or a matching host permission.
console.log(tab.url);
}
}
function onError(error) {
console.error(`Error: ${error}`);
}
browser.tabs.query({ currentWindow: true }).then(logTabs, onError);
```
Get the active tab in the current window:
```js
function logTabs(tabs) {
// tabs[0].url requires the `tabs` permission or a matching host permission.
console.log(tabs[0].url);
}
function onError(error) {
console.error(`Error: ${error}`);
}
browser.tabs
.query({ currentWindow: true, active: true })
.then(logTabs, onError);
```
Get tabs for all HTTP and HTTPS URLs under `"mozilla.org"` or any of its subdomains:
```js
function logTabs(tabs) {
for (const tab of tabs) {
// tab.url requires the `tabs` permission or a matching host permission.
console.log(tab.url);
}
}
function onError(error) {
console.error(`Error: ${error}`);
}
browser.tabs.query({ url: "*://*.mozilla.org/*" }).then(logTabs, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-query) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onactivated/index.md | ---
title: tabs.onActivated
slug: Mozilla/Add-ons/WebExtensions/API/tabs/onActivated
page-type: webextension-api-event
browser-compat: webextensions.api.tabs.onActivated
---
{{AddonSidebar}}
Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to {{WebExtAPIRef("tabs.onUpdated")}} events to be notified when a URL is set.
## Syntax
```js-nolint
browser.tabs.onActivated.addListener(listener)
browser.tabs.onActivated.removeListener(listener)
browser.tabs.onActivated.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `activeInfo`
- : `object`. ID of the tab that was made active, and ID of its window. See the [activeInfo](#activeinfo_2) section for more details.
## Additional objects
### activeInfo
- `previousTabId`
- : `integer`. The ID of the previous activated tab, if that tab is still open.
- `tabId`
- : `integer`. The ID of the tab that has become active.
- `windowId`
- : `integer`. The ID of the tab's window.
## Examples
Listen for and log tab activation events:
```js
function handleActivated(activeInfo) {
console.log(`Tab ${activeInfo.tabId} was activated`);
}
browser.tabs.onActivated.addListener(handleActivated);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onActivated) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/getzoomsettings/index.md | ---
title: tabs.getZoomSettings()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/getZoomSettings
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.getZoomSettings
---
{{AddonSidebar}}
Gets the current zoom settings for a specified tab.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingZoomSettings = browser.tabs.getZoomSettings(
tabId // optional integer
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab to get the current zoom settings from. Defaults to the active tab of the current window.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('tabs.ZoomSettings')}} object representing the tab's current zoom settings. If the tab could not be found or some other error occurs, the promise will be rejected with an error message.
## Examples
Get the zoom settings for the current tab:
```js
function onGot(settings) {
console.log(settings);
}
function onError(error) {
console.log(`Error: ${error}`);
}
let gettingZoomSettings = browser.tabs.getZoomSettings();
gettingZoomSettings.then(onGot, onError);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-getZoomSettings) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/move/index.md | ---
title: tabs.move()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/move
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.move
---
{{AddonSidebar}}
Moves one or more tabs to a new position in the same window or to a different window.
You can only move tabs to and from windows whose {{WebExtAPIRef('windows.WindowType', 'WindowType')}} is `"normal"`.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let moving = browser.tabs.move(
tabIds, // integer or integer array
moveProperties // object
)
```
### Parameters
- `tabIds`
- : `integer` or `array` of `integer`. ID of the {{WebExtAPIRef('tabs.Tab', 'tab')}} to move, or an array of tab IDs.
- `moveProperties`
- : `object`. An object that specifies where to move the tab(s).
- `windowId` {{optional_inline}}
- : `integer`. The ID of the window to which you want to move the tab(s). If you omit this, then each tab in `tabIds` will be moved to `index` in its current window. If you include this, and `tabIds` contains more than one tab, then the first tab in `tabIds` will be moved to `index`, and the other tabs will follow it in the order given in `tabIds`.
- `index`
- : `integer`. The index position to move the tab to, starting at 0. A value of -1 will place the tab at the end of the window.
If you pass a value less than -1, the function will throw an error.
Note that you can't move pinned tabs to a position after any unpinned tabs in a window, or move any unpinned tabs to a position before any pinned tabs. For example, if you have one or more pinned tabs in the target window and `tabIds` refers to an unpinned tab, then you can't pass 0 here. If you try to do this, the function will silently fail (it will not throw an error).
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a `{{WebExtAPIRef('tabs.Tab')}}` object or an `array` of `{{WebExtAPIRef('tabs.Tab')}}` objects, containing details about the moved tabs. If no tabs were moved (for example, because you tried to move an unpinned tab before a pinned tab) this will be an empty array. If any error occurs, the promise will be rejected with an error message.
## Examples
Move the first tab in the current window to the last position in the current window:
```js
function onMoved(tab) {
console.log(`Moved: ${tab}`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
function firstToLast(windowInfo) {
if (windowInfo.tabs.length === 0) {
return;
}
let moving = browser.tabs.move(windowInfo.tabs[0].id, { index: -1 });
moving.then(onMoved, onError);
}
browser.browserAction.onClicked.addListener(() => {
let gettingCurrent = browser.windows.getCurrent({ populate: true });
gettingCurrent.then(firstToLast, onError);
});
```
Move all tabs served over HTTP or HTTPS from \*.mozilla.org to the end of their window:
```js
function onMoved(tab) {
console.log(`Moved: ${tab}`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
function moveMoz(tabs) {
let mozTabIds = tabs.map((tabInfo) => tabInfo.id);
let moving = browser.tabs.move(mozTabIds, { index: -1 });
moving.then(onMoved, onError);
}
browser.browserAction.onClicked.addListener(() => {
let gettingMozTabs = browser.tabs.query({ url: "*://*.mozilla.org/*" });
gettingMozTabs.then(moveMoz, onError);
});
```
Move all tabs served over HTTP or HTTPS from \*.mozilla.org to the window that hosts the first such tab, starting at position 0:
```js
function onMoved(tab) {
console.log(`Moved: ${tab}`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
function moveMoz(tabs) {
let mozTabIds = tabs.map((tabInfo) => tabInfo.id);
let targetWindow = tabs[0].windowId;
let moving = browser.tabs.move(mozTabIds, {
windowId: targetWindow,
index: 0,
});
moving.then(onMoved, onError);
}
browser.browserAction.onClicked.addListener(() => {
let gettingMozTabs = browser.tabs.query({ url: "*://*.mozilla.org/*" });
gettingMozTabs.then(moveMoz, onError);
});
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-move) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.getZoom
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onreplaced/index.md | ---
title: tabs.onReplaced
slug: Mozilla/Add-ons/WebExtensions/API/tabs/onReplaced
page-type: webextension-api-event
browser-compat: webextensions.api.tabs.onReplaced
---
{{AddonSidebar}}
Fired when a tab is replaced with another tab due to prerendering or instant.
This event may not be relevant for or supported by browsers other than Chrome.
## Syntax
```js-nolint
browser.tabs.onReplaced.addListener(listener)
browser.tabs.onReplaced.removeListener(listener)
browser.tabs.onReplaced.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed these arguments:
- `addedTabId`
- : `integer`. ID of the replacement tab.
- `removedTabId`
- : `integer`. ID of the tab that was replaced.
## Examples
Listen for replacement events, and log the associated info:
```js
function handleReplaced(addedTabId, removedTabId) {
console.log(`New tab: ${addedTabId}`);
console.log(`Old tab: ${removedTabId}`);
}
browser.tabs.onReplaced.addListener(handleReplaced);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onReplaced) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/togglereadermode/index.md | ---
title: tabs.toggleReaderMode()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/toggleReaderMode
page-type: webextension-api-function
browser-compat: webextensions.api.tabs.toggleReaderMode
---
{{AddonSidebar}}
Toggles Reader Mode for the given tab.
This function toggles Reader Mode for the given tab. It takes a tab ID as a parameter: if this is omitted, the currently active tab is toggled.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
Reader Mode, also known as Reader View, is a browser feature that makes it easier for the user to focus on an article by:
- hiding non-essential page elements like sidebars, footers, and ads
- changing the page's text size, contrast and layout for better readability.
Reader Mode is useful specifically for articles: meaning, pages that have a body of text content as their main feature. Pages that don't have an identifiable article are not eligible for display in Reader Mode. To find out whether a page is an article, check the `isArticle` property of {{WebExtAPIRef("tabs.Tab")}}.
To find out whether a tab is already in Reader Mode, check the `isInReaderMode` property of {{WebExtAPIRef("tabs.Tab")}}. To track tabs changing into or out of Reader Mode, you'll need to keep track of the current state of all tabs, and check when `isInReaderMode` changes:
```js
function handleUpdated(tabId, changeInfo, tabInfo) {
if (changeInfo.status === "complete") {
console.log(`Tab ${tabId} reader mode: ${tabInfo.isInReaderMode}`);
}
}
browser.tabs.onUpdated.addListener(handleUpdated);
```
## Syntax
```js-nolint
let toggling = browser.tabs.toggleReaderMode(
tabId // optional integer
)
```
### Parameters
- `tabId` {{optional_inline}}
- : `integer`. The ID of the tab to display in Reader Mode. Defaults to the selected tab of the current window.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the tab has been updated. If any error occurs (for example, because the page was not an article), the promise will be rejected with an error message.
## Examples
This code switches every new page into Reader Mode, if that page is eligible for it:
```js
function switchToReaderMode(tabId, changeInfo, tabInfo) {
if (changeInfo.isArticle) {
browser.tabs.toggleReaderMode(tabId);
}
}
browser.tabs.onUpdated.addListener(switchToReaderMode);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onmoved/index.md | ---
title: tabs.onMoved
slug: Mozilla/Add-ons/WebExtensions/API/tabs/onMoved
page-type: webextension-api-event
browser-compat: webextensions.api.tabs.onMoved
---
{{AddonSidebar}}
Fired when a tab is moved within a window.
Only one move event is fired, representing the tab the user directly moved. Move events are not fired for the other tabs that must move in response. This event is not fired when a tab is moved between windows. For that, see {{WebExtAPIRef('tabs.onDetached')}}.
## Syntax
```js-nolint
browser.tabs.onMoved.addListener(listener)
browser.tabs.onMoved.removeListener(listener)
browser.tabs.onMoved.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed these arguments:
- `tabId`
- : `integer`. ID of the tab the user moved.
- `moveInfo`
- : `object`. Information about the move. See the [moveInfo](#moveinfo_2) section for more details.
## Additional objects
### moveInfo
- `windowId`
- : `integer`. ID of this tab's window.
- `fromIndex`
- : `integer`. Initial index of this tab in the window.
- `toIndex`
- : `integer`. Final index of this tab in the window.
## Examples
Listen for and log move events:
```js
function handleMoved(tabId, moveInfo) {
console.log(
`Tab ${tabId} moved from ${moveInfo.fromIndex} to ${moveInfo.toIndex}`,
);
}
browser.tabs.onMoved.addListener(handleMoved);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onMoved) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/index.md | ---
title: webNavigation
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation
page-type: webextension-api
browser-compat: webextensions.api.webNavigation
---
{{AddonSidebar}}
Add event listeners for the various stages of a navigation. A navigation consists of a frame in the browser transitioning from one URL to another, usually (but not always) in response to a user action like clicking a link or entering a URL in the location bar.
Compared with the {{WebExtAPIRef("webRequest")}} API: navigations usually result in the browser making web requests, but the webRequest API is concerned with the lower-level view from the HTTP layer, while the webNavigation API is more concerned with the view from the browser UI itself.
Each event corresponds to a particular stage in the navigation. The sequence of events is like this:

- The primary flow is:
- `{{WebExtAPIRef("webNavigation.onBeforeNavigate", "onBeforeNavigate")}}`
- `{{WebExtAPIRef("webNavigation.onCommitted", "onCommitted")}}`
- `{{WebExtAPIRef("webNavigation.onDOMContentLoaded", "onDOMContentLoaded")}}`
- `{{WebExtAPIRef("webNavigation.onCompleted", "onCompleted")}}`.
- Additionally:
- `{{WebExtAPIRef("webNavigation.onCreatedNavigationTarget", "onCreatedNavigationTarget")}}` is fired before `onBeforeNavigate` if the browser needed to create a new tab or window for the navigation (for example, because the user opened a link in a new tab).
- {{WebExtAPIRef("webNavigation.onHistoryStateUpdated", "onHistoryStateUpdated")}} is fired if a page uses the [history API (2011)](http://diveintohtml5.info/history.html) to update the URL displayed in the browser's location bar.
- {{WebExtAPIRef("webNavigation.onReferenceFragmentUpdated", "onReferenceFragmentUpdated")}} is fired if the [fragment identifier](https://en.wikipedia.org/wiki/Fragment_identifier) for a page is changed.
- {{WebExtAPIRef("webNavigation.onErrorOccurred", "onErrorOccurred")}} can be fired at any point.
Each navigation is a URL transition in a particular browser frame. The browser frame is identified by a tab ID and a frame ID. The frame may be the top-level browsing context in the tab, or may be a nested browsing context implemented as an [iframe](/en-US/docs/Web/HTML/Element/iframe).
Each event's `addListener()` call accepts an optional filter parameter. The filter will specify one or more URL patterns, and the event will then only be fired for navigations in which the target URL matches one of the patterns.
The `onCommitted` event listener is passed two additional properties: a {{WebExtAPIRef("webNavigation.TransitionType","TransitionType")}} indicating the cause of the navigation (for example, because the user clicked a link, or because the user selected a bookmark), and a {{WebExtAPIRef("webNavigation.TransitionQualifier","TransitionQualifier")}} providing further information about the navigation.
To use this API you need to have the "webNavigation" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions).
## Types
- {{WebExtAPIRef("webNavigation.TransitionType")}}
- : Cause of the navigation: for example, the user clicked a link, or typed an address, or clicked a bookmark.
- {{WebExtAPIRef("webNavigation.TransitionQualifier")}}
- : Extra information about a transition.
## Functions
- {{WebExtAPIRef("webNavigation.getFrame()")}}
- : Retrieves information about a particular frame. A frame may be the top-level frame in a tab or a nested [iframe](/en-US/docs/Web/HTML/Element/iframe), and is uniquely identified by a tab ID and a frame ID.
- {{WebExtAPIRef("webNavigation.getAllFrames()")}}
- : Given a tab ID, retrieves information about all the frames it contains.
## Events
- {{WebExtAPIRef("webNavigation.onBeforeNavigate")}}
- : Fired when the browser is about to start a navigation event.
- {{WebExtAPIRef("webNavigation.onCommitted")}}
- : Fired when a navigation is committed. At least part of the new document has been received from the server and the browser has decided to switch to the new document.
- {{WebExtAPIRef("webNavigation.onDOMContentLoaded")}}
- : Fired when the [DOMContentLoaded](/en-US/docs/Web/API/Document/DOMContentLoaded_event) event is fired in the page.
- {{WebExtAPIRef("webNavigation.onCompleted")}}
- : Fired when a document, including the resources it refers to, is completely loaded and initialized. This is equivalent to the DOM [`load`](/en-US/docs/Web/API/Window/load_event) event.
- {{WebExtAPIRef("webNavigation.onErrorOccurred")}}
- : Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, or the user aborted the navigation.
- {{WebExtAPIRef("webNavigation.onCreatedNavigationTarget")}}
- : Fired when a new window, or a new tab in an existing window, is created to host a navigation: for example, if the user opens a link in a new tab.
- {{WebExtAPIRef("webNavigation.onReferenceFragmentUpdated")}}
- : Fired if the [fragment identifier](https://en.wikipedia.org/wiki/Fragment_identifier) for a page is changed.
- {{WebExtAPIRef("webNavigation.onTabReplaced")}}
- : Fired when the contents of the tab is replaced by a different (usually previously pre-rendered) tab.
- {{WebExtAPIRef("webNavigation.onHistoryStateUpdated")}}
- : Fired when the page used the [history API (2011)](http://diveintohtml5.info/history.html) to update the URL displayed in the browser's location bar.
## Browser compatibility
{{Compat}}
{{WebExtExamples("h2")}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/getallframes/index.md | ---
title: webNavigation.getAllFrames()
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/getAllFrames
page-type: webextension-api-function
browser-compat: webextensions.api.webNavigation.getAllFrames
---
{{AddonSidebar}}
Given a tab ID, retrieves information about all the frames it contains.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingFrames = browser.webNavigation.getAllFrames(
details // object
)
```
### Parameters
- `details`
- : `object`. Information about the tab to retrieve all frames from.
- `tabId`
- : `integer`. The ID of the tab.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an array of objects, each of which has the following properties:
- `errorOccurred`
- : `boolean`. True if the last navigation in this frame was interrupted by an error, i.e. the {{WebExtAPIRef("webNavigation.onErrorOccurred", "onErrorOccurred")}} event fired.
- `processId` {{optional_inline}} {{deprecated_inline}}
- : `integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.
- `frameId`
- : `integer`. The ID of the frame. If this is the main frame, then `frameId` is zero.
- `parentFrameId`
- : `integer`. ID of this frame's parent. This is -1 if there is no parent frame: that is, if this frame is the top-level browsing context in the tab.
- `url`
- : `string`. The URL currently associated with this frame.
If the tab is discarded, the promise will instead resolve with a `null` value. If the specified tab could not be found, or some other error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
This code logs the URLs of all frames in the active tab, when the user clicks a browser action:
```js
function logFrameInfo(framesInfo) {
for (const frameInfo of framesInfo) {
console.log(frameInfo);
}
}
function onError(error) {
console.error(`Error: ${error}`);
}
function logAllFrames(tabs) {
browser.webNavigation
.getAllFrames({
tabId: tabs[0].id,
})
.then(logFrameInfo, onError);
}
browser.browserAction.onClicked.addListener(() => {
browser.tabs
.query({
currentWindow: true,
active: true,
})
.then(logAllFrames, onError);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#method-getAllFrames) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/oncommitted/index.md | ---
title: webNavigation.onCommitted
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/onCommitted
page-type: webextension-api-event
browser-compat: webextensions.api.webNavigation.onCommitted
---
{{AddonSidebar}}
Fired when a navigation is committed. At least part of the new document has been received from the server and the browser has decided to switch to the new document.
## Syntax
```js-nolint
browser.webNavigation.onCommitted.addListener(
listener, // function
filter // optional object
)
browser.webNavigation.onCommitted.removeListener(listener)
browser.webNavigation.onCommitted.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `details`
- : `object`. Details about the navigation event. See the [details](#details_2) section for more information.
- `filter` {{optional_inline}}
- : `object`. An object containing a single property `url`, which is an `Array` of {{WebExtAPIRef("events.UrlFilter")}} objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.
## Additional objects
### details
- `tabId`
- : `integer`. The ID of the tab in which the navigation is about to occur.
- `url`
- : `string`. The URL to which the given frame will navigate.
- `processId` {{optional_inline}} {{deprecated_inline}}
- : `integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.
- `frameId`
- : `integer`. Frame in which the navigation will occur. `0` indicates that navigation happens in the tab's top-level browsing context, not in a nested {{HTMLElement("iframe")}}. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.
- `parentFrameId`
- : `integer`. ID of this frame's parent. Set to `-1` if this is a top-level frame.
- `timeStamp`
- : `number`. The time that the navigation was committed, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
- `transitionType`
- : {{WebExtAPIRef("webNavigation.transitionType", "transitionType")}}. The reason for the navigation. (For example, `"link"` if the user clicked a link, or `"reload"` if the user reloaded the page.)
- `transitionQualifiers`
- : `Array` of {{WebExtAPIRef("webNavigation.transitionQualifier", "transitionQualifier")}}. Extra information about the navigation: for example, whether there was a server or client redirect.
## Browser compatibility
{{Compat}}
## Examples
Logs the target URLs and extra transition information for `onCommitted`, if the target URL's hostname contains "example.com" or starts with "developer".
```js
const filter = {
url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};
function logOnCommitted(details) {
console.log(`target URL: ${details.url}`);
console.log(`transition type: ${details.transitionType}`);
console.log(`transition qualifiers: ${details.transitionQualifiers}`);
}
browser.webNavigation.onCommitted.addListener(logOnCommitted, filter);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#event-onBeforeNavigate) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/transitionqualifier/index.md | ---
title: webNavigation.TransitionQualifier
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/TransitionQualifier
page-type: webextension-api-type
browser-compat: webextensions.api.webNavigation.TransitionQualifier
---
{{AddonSidebar}}
Extra information about a transition. Note that many values here are not currently supported in Firefox: see the [browser compatibility table](#browser_compatibility) for details.
## Type
Values of this type are strings. Possible values are:
- "client_redirect"
- : Redirect(s) caused by JavaScript running in the page or a "refresh" pragma in the page's [meta](/en-US/docs/Web/HTML/Element/meta) tag.
- "server_redirect"
- : Redirect(s) caused by a [3XX HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection) sent from the server.
- "forward_back"
- : The user used the forward or back button to trigger the navigation.
- "from_address_bar"
- : The user triggered the navigation from the address bar.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#type-TransitionQualifier) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/onhistorystateupdated/index.md | ---
title: webNavigation.onHistoryStateUpdated
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/onHistoryStateUpdated
page-type: webextension-api-event
browser-compat: webextensions.api.webNavigation.onHistoryStateUpdated
---
{{AddonSidebar}}
Fired when the page used the [>history API](/en-US/docs/Web/API/History_API/Working_with_the_History_API) to update the URL displayed in the browser's location bar. All future events for this frame will use the updated URL.
## Syntax
```js-nolint
browser.webNavigation.onHistoryStateUpdated.addListener(
listener, // function
filter // optional object
)
browser.webNavigation.onHistoryStateUpdated.removeListener(listener)
browser.webNavigation.onHistoryStateUpdated.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `details`
- : `object`. Details about the navigation event. See the [details](#details_2) section for more information.
- `filter` {{optional_inline}}
- : `object`. An object containing a single property `url`, which is an `Array` of {{WebExtAPIRef("events.UrlFilter")}} objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.
## Additional objects
### details
- `tabId`
- : `integer`. The ID of the tab in which the navigation is about to occur.
- `url`
- : `string`. The URL to which the given frame will navigate.
- `processId` {{optional_inline}} {{deprecated_inline}}
- : `integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.
- `frameId`
- : `integer`. Frame in which the navigation will occur. `0` indicates that navigation happens in the tab's top-level browsing context, not in a nested {{HTMLElement("iframe")}}. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.
- `timeStamp`
- : `number`. The time that the URL was changed by the history API, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
- `transitionType`
- : `{{WebExtAPIRef("webNavigation.transitionType", "transitionType")}}`. The reason for the navigation: for example, `"link"` if the user clicked a link.
- `transitionQualifiers`
- : `Array` of {{WebExtAPIRef("webNavigation.transitionQualifier", "transitionQualifier")}}. Extra information about the navigation: for example, whether there was a server or client redirect.
## Browser compatibility
{{Compat}}
## Examples
Logs the target URLs and extra transition information for `onHistoryStateUpdated`, if the target URL's hostname contains "example.com" or starts with "developer".
```js
const filter = {
url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};
function logOnHistoryStateUpdated(details) {
console.log(`onHistoryStateUpdated: ${details.url}`);
console.log(`Transition type: ${details.transitionType}`);
console.log(`Transition qualifiers: ${details.transitionQualifiers}`);
}
browser.webNavigation.onHistoryStateUpdated.addListener(
logOnHistoryStateUpdated,
filter,
);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#event-onBeforeNavigate) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/onreferencefragmentupdated/index.md | ---
title: webNavigation.onReferenceFragmentUpdated
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/onReferenceFragmentUpdated
page-type: webextension-api-event
browser-compat: webextensions.api.webNavigation.onReferenceFragmentUpdated
---
{{AddonSidebar}}
Fired if the [fragment identifier](https://en.wikipedia.org/wiki/Fragment_identifier) for a page is changed. For example, if a page implements a table of contents using fragments, and the user clicks an entry in the table of contents, this event fires. All future events for this frame will use the updated URL.
## Syntax
```js-nolint
browser.webNavigation.onReferenceFragmentUpdated.addListener(
listener, // function
filter // optional object
)
browser.webNavigation.onReferenceFragmentUpdated.removeListener(listener)
browser.webNavigation.onReferenceFragmentUpdated.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `details`
- : `object`. Details about the navigation event. See the [details](#details_2) section for more information.
- `filter` {{optional_inline}}
- : `object`. An object containing a single property `url`, which is an `Array` of {{WebExtAPIRef("events.UrlFilter")}} objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.
## Additional objects
### details
- `tabId`
- : `integer`. The ID of the tab in which the navigation is about to occur.
- `url`
- : `string`. The URL to which the given frame will navigate.
- `processId` {{optional_inline}} {{deprecated_inline}}
- : `integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.
- `frameId`
- : `integer`. Frame in which the navigation will occur. `0` indicates that navigation happens in the tab's top-level browsing context, not in a nested {{HTMLElement("iframe")}}. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.
- `timeStamp`
- : `number`. The time that the fragment identifier for the page was changed, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
- `transitionType`
- : `{{WebExtAPIRef("webNavigation.transitionType", "transitionType")}}`. The reason for the navigation: for example, `"link"` if the user clicked a link.
- `transitionQualifiers`
- : `Array` of {{WebExtAPIRef("webNavigation.transitionQualifier", "transitionQualifier")}}. Extra information about the navigation: for example, whether there was a server or client redirect.
## Browser compatibility
{{Compat}}
## Examples
Logs the target URLs and extra transition information for `onReferenceFragmentUpdated`, if the target URL's hostname contains "example.com" or starts with "developer".
```js
const filter = {
url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};
function logOnReferenceFragmentUpdated(details) {
console.log(`onReferenceFragmentUpdated: ${details.url}`);
console.log(`Transition type: ${details.transitionType}`);
console.log(`Transition qualifiers: ${details.transitionQualifiers}`);
}
browser.webNavigation.onReferenceFragmentUpdated.addListener(
logOnReferenceFragmentUpdated,
filter,
);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#event-onBeforeNavigate) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/oncreatednavigationtarget/index.md | ---
title: webNavigation.onCreatedNavigationTarget
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/onCreatedNavigationTarget
page-type: webextension-api-event
browser-compat: webextensions.api.webNavigation.onCreatedNavigationTarget
---
{{AddonSidebar}}
Fired when a new window, or a new tab in an existing window, is created to host the target of a navigation. For example, this event is sent when:
- the user opens a link in a new tab or window
- a web page loads a resource into a new tab or window using {{domxref("window.open()")}} (but note that the event is not sent if the browser's popup blocker blocks the load).
The event is not sent if a tab or window is created without a navigation target (for example, if the user opens a new tab by pressing <kbd>Ctrl+T</kbd>).
If this event is fired, it will be fired before {{WebExtAPIRef("webNavigation.onBeforeNavigate")}}.
## Syntax
```js-nolint
browser.webNavigation.onCreatedNavigationTarget.addListener(
listener, // function
filter // optional object
)
browser.webNavigation.onCreatedNavigationTarget.removeListener(listener)
browser.webNavigation.onCreatedNavigationTarget.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `details`
- : `object`. Details about the navigation event. See the [details](#details_2) section for more information.
- `filter` {{optional_inline}}
- : `object`. An object containing a single property `url`, which is an `Array` of {{WebExtAPIRef("events.UrlFilter")}} objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions. Note that `filter` is not supported in Firefox.
## Additional objects
### details
- `sourceFrameId`
- : `integer`. ID of the frame from which the navigation is initiated. `0` indicates that the frame is the tab's top-level browsing context, not a nested {{HTMLElement("iframe")}}. A positive value indicates that navigation is initiated from a nested iframe. Frame IDs are unique for a given tab and process.
- `processId` {{optional_inline}} {{deprecated_inline}}
- : `integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process the navigation originated from.
- `sourceTabId`
- : `integer`. The ID of the tab from which the navigation is initiated. For example, if the user opens a link in a new tab, this will be the ID of the tab containing the link.
- `tabId`
- : `integer`. The ID of the newly created tab.
- `timeStamp`
- : `number`. The time when the browser created the navigation target, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
- `url`
- : `string`. The URL which will be loaded in the new tab.
- `windowId`
- : `number`. The ID of the window in which the new tab is created.
## Browser compatibility
{{Compat}}
## Examples
Logs the target URL, source Tab ID, and source frame ID for `onCreatedNavigationTarget`, if the target's hostname contains "example.com" or starts with "developer".
```js
const filter = {
url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};
function logOnCreatedNavigationTarget(details) {
console.log(`onCreatedNavigationTarget: ${details.url}`);
console.log(details.sourceTabId);
console.log(details.sourceFrameId);
}
browser.webNavigation.onCreatedNavigationTarget.addListener(
logOnCreatedNavigationTarget,
filter,
);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#event-onBeforeNavigate) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/oncompleted/index.md | ---
title: webNavigation.onCompleted
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/onCompleted
page-type: webextension-api-event
browser-compat: webextensions.api.webNavigation.onCompleted
---
{{AddonSidebar}}
Fired when a document, including the resources it refers to, is completely loaded and initialized. This is equivalent to the DOM [`load`](/en-US/docs/Web/API/Window/load_event) event.
## Syntax
```js-nolint
browser.webNavigation.onCompleted.addListener(
listener, // function
filter // optional object
)
browser.webNavigation.onCompleted.removeListener(listener)
browser.webNavigation.onCompleted.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `details`
- : `object`. Details about the navigation event. See the [details](#details_2) section for more information.
- `filter` {{optional_inline}}
- : `object`. An object containing a single property `url`, which is an `Array` of {{WebExtAPIRef("events.UrlFilter")}} objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.
## Additional objects
### details
- `tabId`
- : `integer`. The ID of the tab in which the navigation has occurred.
- `url`
- : `string`. The URL to which the given frame has navigated.
- `processId` {{optional_inline}} {{deprecated_inline}}
- : `integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.
- `frameId`
- : `integer`. Frame in which the navigation has occurred. `0` indicates that navigation happened in the tab's top-level browsing context, not in a nested {{HTMLElement("iframe")}}. A positive value indicates that navigation happened in a nested iframe. Frame IDs are unique for a given tab and process.
- `timeStamp`
- : `number`. The time at which the page finished loading, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
## Browser compatibility
{{Compat}}
## Examples
Logs the target URLs for `onCompleted`, if the target URL's hostname contains "example.com" or starts with "developer".
```js
const filter = {
url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};
function logOnCompleted(details) {
console.log(`onCompleted: ${details.url}`);
}
browser.webNavigation.onCompleted.addListener(logOnCompleted, filter);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#event-onBeforeNavigate) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/transitiontype/index.md | ---
title: webNavigation.TransitionType
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/TransitionType
page-type: webextension-api-type
browser-compat: webextensions.api.webNavigation.TransitionType
---
{{AddonSidebar}}
Cause of the navigation: for example, the user clicked a link, or typed an address, or clicked a bookmark.
Note that many values here are not currently supported in Firefox: see the [browser compatibility table](#browser_compatibility) for details.
## Type
Values of this type are strings. Possible values are:
- "link"
- : The user clicked a link in another page.
- "typed"
- : The user typed the URL into the address bar. This is also used if the user started typing into the address bar, then selected a URL from the suggestions it offered. See also "generated".
- "auto_bookmark"
- : The user clicked a bookmark or an item in the browser history.
- "auto_subframe"
- : Any nested iframes that are automatically loaded by their parent.
- "manual_subframe"
- : Any nested iframes that are loaded as an explicit user action. Loading such an iframe will generate an entry in the back/forward navigation list.
- "generated"
- : The user started typing in the address bar, then clicked on a suggested entry that didn't contain a URL.
- "start_page"
- : The page was passed to the command line or is the start page.
- "form_submit"
- : The user submitted a form. Note that in some situations, such as when a form uses a script to submit its contents, submitting a form does not result in this transition type.
- "reload"
- : The user reloaded the page, using the Reload button or by pressing Enter in the address bar. This is also used for session restore and reopening closed tabs.
- "keyword"
- : The URL was generated using a [keyword search](https://support.mozilla.org/en-US/kb/how-search-from-address-bar) configured by the user.
- "keyword_generated"
- : Corresponds to a visit generated for a keyword.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#type-TransitionType) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/getframe/index.md | ---
title: webNavigation.getFrame()
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/getFrame
page-type: webextension-api-function
browser-compat: webextensions.api.webNavigation.getFrame
---
{{AddonSidebar}}
Retrieves information about a particular frame. A frame may be the top-level frame in a tab or a nested [`<iframe>`](/en-US/docs/Web/HTML/Element/iframe), and is uniquely identified by a tab ID and a frame ID.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingFrame = browser.webNavigation.getFrame(
details // object
)
```
### Parameters
- `details`
- : `object`. Information about the frame to retrieve information about.
- `tabId`
- : `integer`. The ID of the tab in which the frame is.
- `processId` {{optional_inline}} {{deprecated_inline}}
- : `integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.
- `frameId`
- : `integer`. The ID of the frame in the given tab.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an object containing the following properties:
- `errorOccurred`
- : `boolean`. True if the last navigation in this frame was interrupted by an error, i.e. the {{WebExtAPIRef("webNavigation.onErrorOccurred", "onErrorOccurred")}} event fired.
- `url`
- : `string`. The URL currently associated with this frame, if the frame identified by `frameId` existed at one point in the tab identified by `tabId`. The fact that a URL is associated with a given `frameId` does not imply that the corresponding frame still exists.
- `parentFrameId`
- : `integer`. ID of this frame's parent. This is -1 if there is no parent frame: that is, if this frame is the top-level browsing context in the tab.
If the tab is discarded, the promise will instead resolve with a `null` value. If the specified tab or frame ID could not be found, or some other error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
```js
function onGot(frameInfo) {
console.log(frameInfo);
}
function onError(error) {
console.log(`Error: ${error}`);
}
let gettingFrame = browser.webNavigation.getFrame({
tabId: 19,
frameId: 1537,
});
// Edge specific - processId is required not optional, must be integer not null
//let gettingFrame = browser.webNavigation.getFrame({ tabId: 19, processId: 0, frameId: 1537 });
gettingFrame.then(onGot, onError);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#method-getFrame) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/ondomcontentloaded/index.md | ---
title: webNavigation.onDOMContentLoaded
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/onDOMContentLoaded
page-type: webextension-api-event
browser-compat: webextensions.api.webNavigation.onDOMContentLoaded
---
{{AddonSidebar}}
Fired when the [DOMContentLoaded](/en-US/docs/Web/API/Document/DOMContentLoaded_event) event is fired in the page. At this point the document is loaded and parsed, and the DOM is fully constructed, but linked resources such as images, stylesheets and subframes may not yet be loaded.
## Syntax
```js-nolint
browser.webNavigation.onDOMContentLoaded.addListener(
listener, // function
filter // optional object
)
browser.webNavigation.onDOMContentLoaded.removeListener(listener)
browser.webNavigation.onDOMContentLoaded.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `details`
- : `object`. Details about the navigation event. See the [details](#details_2) section for more information.
- `filter` {{optional_inline}}
- : `object`. An object containing a single property `url`, which is an {{jsxref("Array")}} of {{WebExtAPIRef("events.UrlFilter")}} objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.
## Additional objects
### details
- `tabId`
- : `integer`. The ID of the tab in which the navigation has occurred.
- `url`
- : `string`. The URL to which the given frame has navigated.
- `processId` {{optional_inline}} {{deprecated_inline}}
- : `integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.
- `frameId`
- : `integer`. Frame in which the navigation is occurring. `0` indicates that navigation happens in the tab's top-level browsing context, not in a nested {{HTMLElement("iframe")}}. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.
- `timeStamp`
- : `number`. The time at which `DOMContentLoaded` was fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
## Browser compatibility
{{Compat}}
## Examples
Logs the target URLs for `onDOMContentLoaded`, if the target URL's hostname contains "example.com" or starts with "developer".
```js
const filter = {
url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};
function logOnDOMContentLoaded(details) {
console.log(`onDOMContentLoaded: ${details.url}`);
}
browser.webNavigation.onDOMContentLoaded.addListener(
logOnDOMContentLoaded,
filter,
);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#event-onBeforeNavigate) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/onerroroccurred/index.md | ---
title: webNavigation.onErrorOccurred
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/onErrorOccurred
page-type: webextension-api-event
browser-compat: webextensions.api.webNavigation.onErrorOccurred
---
{{AddonSidebar}}
Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, or the user aborted the navigation.
## Syntax
```js-nolint
browser.webNavigation.onErrorOccurred.addListener(
listener, // function
filter // optional object
)
browser.webNavigation.onErrorOccurred.removeListener(listener)
browser.webNavigation.onErrorOccurred.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
`addListener(listener, filter)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs.
The `listener` function is called with these arguments:
- `details`
- : [`object`](#details). Details about the navigation event. **`details`** has the following properties:
- `tabId`
- : `integer`. The ID of the tab in which the navigation was happening.
- `url`
- : `string`. The URL to which the given frame was navigating.
- `processId` {{optional_inline}} {{deprecated_inline}}
- : `integer`. This value is never set in modern browsers. It used to represent the ID of the process running the renderer for this tab.
- `frameId`
- : `integer`. Frame in which the navigation was happening.
`0` indicates that navigation happened in the tab's top-level browsing context, not in a nested {{HTMLElement("iframe")}}.
A positive value indicates that navigation happened in a nested iframe.
Frame IDs are unique for a given tab and process.
- `timeStamp`
- : `number`. The time at which the error occurred, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
- `error`
- : `string`. The error code. This is an internal error code, and is not guaranteed to stay the same or be consistent from one browser to another.
- `filter` {{optional_inline}}
- : `object`. An object containing a single property `url`, which is an `Array` of {{WebExtAPIRef("events.UrlFilter")}} objects.
If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array.
If you omit this parameter, the event fires for all transitions.
## Browser compatibility
{{Compat}}
## Examples
Logs the target URLs for `onErrorOccurred`, if the target URL's `hostname` contains `"example.com"` or starts with `"developer"`.
```js
const filter = {
url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};
function logOnErrorOccurred(details) {
console.log(`onErrorOccurred: ${details.url}`);
console.log(details.error);
}
browser.webNavigation.onErrorOccurred.addListener(logOnErrorOccurred, filter);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#event-onBeforeNavigate) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/ontabreplaced/index.md | ---
title: webNavigation.onTabReplaced
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/onTabReplaced
page-type: webextension-api-event
browser-compat: webextensions.api.webNavigation.onTabReplaced
---
{{AddonSidebar}}
Fired when the contents of the tab is replaced by a different (usually previously pre-rendered) tab.
## Syntax
```js-nolint
browser.webNavigation.onTabReplaced.addListener(
listener, // function
filter // optional object
);
browser.webNavigation.onTabReplaced.removeListener(listener)
browser.webNavigation.onTabReplaced.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `details`
- : `object`. See the [details](#details_2) section for more information.
## Additional objects
### details
- `replacedTabId`
- : `integer`. The ID of the tab that was replaced.
- `tabId`
- : `integer`. The ID of the tab that replaced the old tab.
- `timeStamp`
- : `number`. The time when the replacement happened, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
## Browser compatibility
{{Compat}}
## Examples
```js
function logOnTabReplaced(details) {
console.log(`onTabReplaced ${details}`);
}
browser.webNavigation.onTabReplaced.addListener(logOnTabReplaced);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#event-onTabReplaced) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webnavigation/onbeforenavigate/index.md | ---
title: webNavigation.onBeforeNavigate
slug: Mozilla/Add-ons/WebExtensions/API/webNavigation/onBeforeNavigate
page-type: webextension-api-event
browser-compat: webextensions.api.webNavigation.onBeforeNavigate
---
{{AddonSidebar}}
Fired when the browser is about to start a navigation event.
## Syntax
```js-nolint
browser.webNavigation.onBeforeNavigate.addListener(
listener, // function
filter // optional object
)
browser.webNavigation.onBeforeNavigate.removeListener(listener)
browser.webNavigation.onBeforeNavigate.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `details`
- : `object`. Details about the navigation event. See the [details](#details_2) section for more information.
- `filter` {{optional_inline}}
- : `object`. An object containing a single property `url`, which is an `Array` of {{WebExtAPIRef("events.UrlFilter")}} objects. If you include this parameter, then the event fires only for transitions to URLs which match at least one `UrlFilter` in the array. If you omit this parameter, the event fires for all transitions.
## Additional objects
### details
- `tabId`
- : `integer`. The ID of the tab in which the navigation is about to occur.
- `url`
- : `string`. The URL to which the given frame will navigate.
- `processId` {{optional_inline}} {{deprecated_inline}}
- : `integer`. This value is not set in modern browsers. When it was set, it represented the ID of the process running the renderer for this tab.
- `frameId`
- : `integer`. Frame in which the navigation is about to occur. `0` indicates that navigation happens in the tab's top-level browsing context, not in a nested {{HTMLElement("iframe")}}. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.
- `parentFrameId`
- : `integer`. ID of this frame's parent. Set to `-1` if this is a top-level frame.
- `timeStamp`
- : `number`. The time when the browser is about to start the navigation, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
## Browser compatibility
{{Compat}}
## Examples
Logs the target URLs for `onBeforeNavigate`, if the target's hostname contains "example.com" or starts with "developer".
```js
const filter = {
url: [{ hostContains: "example.com" }, { hostPrefix: "developer" }],
};
function logOnBefore(details) {
console.log(`onBeforeNavigate to: ${details.url}`);
}
browser.webNavigation.onBeforeNavigate.addListener(logOnBefore, filter);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.webNavigation`](https://developer.chrome.com/docs/extensions/reference/webNavigation/#event-onBeforeNavigate) API. This documentation is derived from [`web_navigation.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/web_navigation.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/index.md | ---
title: runtime
slug: Mozilla/Add-ons/WebExtensions/API/runtime
page-type: webextension-api
browser-compat: webextensions.api.runtime
---
{{AddonSidebar}}
This module provides information about your extension and the environment it's running in.
It also provides messaging APIs enabling you to:
- Communicate between different parts of your extension. For advice on choosing between the messaging options, see [Choosing between one-off messages and connection-based messaging](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#choosing_between_one-off_messages_and_connection-based_messaging).
- Communicate with other extensions.
- Communicate with native applications.
## Types
- {{WebExtAPIRef("runtime.Port")}}
- : Represents one end of a connection between two specific contexts, which can be used to exchange messages.
- {{WebExtAPIRef("runtime.MessageSender")}}
- : Contains information about the sender of a message or connection request.
- {{WebExtAPIRef("runtime.PlatformOs")}}
- : Identifies the browser's operating system.
- {{WebExtAPIRef("runtime.PlatformArch")}}
- : Identifies the browser's processor architecture.
- {{WebExtAPIRef("runtime.PlatformInfo")}}
- : Contains information about the platform the browser is running on.
- {{WebExtAPIRef("runtime.RequestUpdateCheckStatus")}}
- : Result of a call to {{WebExtAPIRef("runtime.requestUpdateCheck()")}}.
- {{WebExtAPIRef("runtime.OnInstalledReason")}}
- : The reason that the {{WebExtAPIRef("runtime.onInstalled")}} event is being dispatched.
- {{WebExtAPIRef("runtime.OnRestartRequiredReason")}}
- : The reason that the {{WebExtAPIRef("runtime.onRestartRequired")}} event is being dispatched.
## Properties
- {{WebExtAPIRef("runtime.lastError")}}
- : This value is set when an asynchronous function has an error condition that it needs to report to its caller.
- {{WebExtAPIRef("runtime.id")}}
- : The ID of the extension.
## Functions
- {{WebExtAPIRef("runtime.getBackgroundPage()")}}
- : Retrieves the [Window](/en-US/docs/Web/API/Window) object for the background page running inside the current extension.
- {{WebExtAPIRef("runtime.openOptionsPage()")}}
- : Opens your extension's [options page](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages).
- {{WebExtAPIRef("runtime.getFrameId()")}}
- : Gets the frame ID of any window global or frame element.
- {{WebExtAPIRef("runtime.getManifest()")}}
- : Gets the complete [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file, serialized as an object.
- {{WebExtAPIRef("runtime.getURL()")}}
- : Given a relative path from the [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) to a resource packaged with the extension, returns a fully-qualified URL.
- {{WebExtAPIRef("runtime.setUninstallURL()")}}
- : Sets a URL to be visited when the extension is uninstalled.
- {{WebExtAPIRef("runtime.reload()")}}
- : Reloads the extension.
- {{WebExtAPIRef("runtime.requestUpdateCheck()")}}
- : Checks for updates to this extension.
- {{WebExtAPIRef("runtime.connect()")}}
- : Establishes a connection from a content script to the main extension process, or from one extension to a different extension.
- {{WebExtAPIRef("runtime.connectNative()")}}
- : Connects the extension to a native application on the user's computer.
- {{WebExtAPIRef("runtime.sendMessage()")}}
- : Sends a single message to event listeners within your extension or a different extension. Similar to {{WebExtAPIRef('runtime.connect')}} but only sends a single message, with an optional response.
- {{WebExtAPIRef("runtime.sendNativeMessage()")}}
- : Sends a single message from an extension to a native application.
- {{WebExtAPIRef("runtime.getPlatformInfo()")}}
- : Returns information about the current platform.
- {{WebExtAPIRef("runtime.getBrowserInfo()")}}
- : Returns information about the browser in which this extension is installed.
- {{WebExtAPIRef("runtime.getPackageDirectoryEntry()")}}
- : Returns a DirectoryEntry for the package directory.
## Events
- {{WebExtAPIRef("runtime.onStartup")}}
- : Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started.
- {{WebExtAPIRef("runtime.onInstalled")}}
- : Fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version.
- {{WebExtAPIRef("runtime.onSuspend")}}
- : Sent to the event page just before the extension is unloaded. This gives the extension an opportunity to do some cleanup.
- {{WebExtAPIRef("runtime.onSuspendCanceled")}}
- : Sent after {{WebExtAPIRef("runtime.onSuspend")}} to indicate that the extension won't be unloaded after all.
- {{WebExtAPIRef("runtime.onUpdateAvailable")}}
- : Fired when an update is available, but isn't installed immediately because the extension is currently running.
- {{WebExtAPIRef("runtime.onBrowserUpdateAvailable")}} {{deprecated_inline}}
- : Fired when an update for the browser is available, but isn't installed immediately because a browser restart is required.
- {{WebExtAPIRef("runtime.onConnect")}}
- : Fired when a connection is made with either an extension process or a content script.
- {{WebExtAPIRef("runtime.onConnectExternal")}}
- : Fired when a connection is made with another extension.
- {{WebExtAPIRef("runtime.onMessage")}}
- : Fired when a message is sent from either an extension process or a content script.
- {{WebExtAPIRef("runtime.onMessageExternal")}}
- : Fired when a message is sent from another extension. Cannot be used in a content script.
- {{WebExtAPIRef("runtime.onRestartRequired")}}
- : Fired when the device needs to be restarted.
## Browser compatibility
{{Compat}}
{{WebExtExamples("h2")}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/platformnaclarch/index.md | ---
title: runtime.PlatformNaclArch
slug: Mozilla/Add-ons/WebExtensions/API/runtime/PlatformNaclArch
page-type: webextension-api-type
browser-compat: webextensions.api.runtime.PlatformNaclArch
---
{{AddonSidebar}}
The native client architecture. This may be different from arch on some platforms.
## Type
Values of this type are strings. Possible values are: `"arm"`, `"x86-32"`, `"x86-64"`.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-PlatformNaclArch) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/getbackgroundpage/index.md | ---
title: runtime.getBackgroundPage()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/getBackgroundPage
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.getBackgroundPage
---
{{AddonSidebar}}
Retrieves the {{DOMxRef("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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#options_pages), or scripts running in [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#browser_actions_2) or [page action](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#page_actions) popups, but does _not_ include [content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#content_scripts).
Note that variables that were declared using [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const) or [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/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](https://bugzil.la/1329304).
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 {{JSxRef("Promise")}}.
> **Note:** In Firefox, this method cannot be used in Private Browsing mode — it always returns `null`. For more info see [Firefox bug 1329304](https://bugzil.la/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](https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/) for details.
>
> Consider using {{WebExtAPIRef("runtime.sendMessage","runtime.sendMessage()")}} or {{WebExtAPIRef("runtime.connect","runtime.connect()")}}, which work correctly in both scenarios above.
## Syntax
```js-nolint
let gettingPage = browser.runtime.getBackgroundPage()
```
### Parameters
None.
### Return value
A {{JSxRef("Promise")}} that will be fulfilled with the {{DOMxRef("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
{{Compat}}
## Examples
Suppose a [background script](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#background_scripts) defines a function `foo()`:
```js
// background.js
function foo() {
console.log("I'm defined in background.js");
}
```
A script running in a [popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#browser_actions_2) 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);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-getBackgroundPage) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/connect/index.md | ---
title: runtime.connect()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/connect
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.connect
---
{{AddonSidebar}}
Make a connection between different contexts inside the extension.
You can call this:
- in an extension's content scripts, to establish a connection with the extension's background scripts (or similarly privileged scripts, like popup scripts or options page scripts).
- in an extension's background scripts (or similarly privileged scripts), to establish a connection with a different extension.
Note that you can't use this function to connect an extension to its content scripts. To do this, use {{WebExtAPIRef('tabs.connect()')}}.
By default, this connection enables the extension to exchange messages with itself or any other extension (if `extensionId` is specified). However, the [`externally_connectable`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/externally_connectable) manifest key can be used to limit communication to specific extensions and enable communication with websites. Connections within the extension trigger the {{WebExtAPIRef('runtime.onConnect')}} event, connections from other extensions or web pages trigger the {{WebExtAPIRef('runtime.onConnectExternal')}} event.
## Syntax
```js-nolint
let port = browser.runtime.connect(
extensionId, // optional string
connectInfo // optional object
)
```
### Parameters
- `extensionId` {{optional_inline}}
- : `string`. The ID of the extension to connect to. If the target has set an ID explicitly using the [browser_specific_settings](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) key in manifest.json, then `extensionId` should have that value. Otherwise it should have the ID that was generated for the target.
- `connectInfo` {{optional_inline}}
- : `object`. Details of the connection:
- `name` {{optional_inline}}
- : `string`. Will be passed into {{WebExtAPIRef("runtime.onConnect")}} for processes that are listening for the connection event.
- `includeTlsChannelId` {{optional_inline}}
- : `boolean`. Whether the TLS channel ID will be passed into {{WebExtAPIRef("runtime.onConnectExternal")}} for processes that are listening for the connection event.
### Return value
{{WebExtAPIRef('runtime.Port')}}. Port through which messages can be sent and received. The port's `onDisconnect` event is fired if the extension does not exist.
## Browser compatibility
{{Compat}}
## Examples
This content script:
- connects to the background script and stores the `Port` in a variable called `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!" });
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-connect) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/connectnative/index.md | ---
title: runtime.connectNative()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/connectNative
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.connectNative
---
{{AddonSidebar}}
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 {{WebExtAPIRef("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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging).
## Syntax
```js-nolint
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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging#app_manifest).
### Return value
A {{WebExtAPIRef('runtime.Port')}} object. The port which the caller can use to exchange messages with the native application.
## Browser compatibility
{{Compat}}
## 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");
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-connectNative) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onmessageexternal/index.md | ---
title: runtime.onMessageExternal
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onMessageExternal
page-type: webextension-api-event
browser-compat: webextensions.api.runtime.onMessageExternal
---
{{AddonSidebar}}
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`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/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 {{WebExtAPIRef("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-nolint
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 {{WebExtAPIRef('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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) from the listener function and resolve the promise when the response is ready.
## Browser compatibility
{{Compat}}
## Examples
In this example the extension "blue\@mozilla.org" sends a message to the extension "red\@mozilla.org":
```js
// sender: browser.runtime.id === "[email protected]"
// Send a message to the extension whose ID is "[email protected]"
browser.runtime.sendMessage("[email protected]", "my message");
```
```js
// recipient: browser.runtime.id === "[email protected]"
function handleMessage(message, sender) {
// check that the message is from "[email protected]"
if (sender.id === "[email protected]") {
// process message
}
}
browser.runtime.onMessageExternal.addListener(handleMessage);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onMessageExternal) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/platformos/index.md | ---
title: runtime.PlatformOs
slug: Mozilla/Add-ons/WebExtensions/API/runtime/PlatformOs
page-type: webextension-api-type
browser-compat: webextensions.api.runtime.PlatformOs
---
{{AddonSidebar}}
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
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-PlatformOs) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/requestupdatecheck/index.md | ---
title: runtime.requestUpdateCheck()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/requestUpdateCheck
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.requestUpdateCheck
---
{{AddonSidebar}}
Checks to see if an update for the extension is available.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let requestingCheck = browser.runtime.requestUpdateCheck()
```
### Parameters
None.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is fulfilled with an object with the result of the update request.
- `result`
- : An object with the following properties:
- `status`
- : {{WebExtAPIRef('runtime.RequestUpdateCheckStatus')}}. The result of the update check.
- `version` {{optional_inline}}
- : `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);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-requestUpdateCheck) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/oninstalled/index.md | ---
title: runtime.onInstalled
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onInstalled
page-type: webextension-api-event
browser-compat: webextensions.api.runtime.onInstalled
---
{{AddonSidebar}}
Fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version.
Note that `runtime.onInstalled` is not the same as {{WebExtAPIRef("management.onInstalled")}}. The `runtime.onInstalled` event is fired only for your extension. The `browser.management.onInstalled` event is fired for any extensions.
## Syntax
```js-nolint
browser.runtime.onInstalled.addListener(listener)
browser.runtime.onInstalled.removeListener(listener)
browser.runtime.onInstalled.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 these arguments:
- `details`
- : An object with the following properties:
- `id` {{optional_inline}}
- : `string`. The ID of the imported shared module extension that updated. This is present only if the `reason` value is `shared_module_update`.
- `previousVersion` {{optional_inline}}
- : `string`. The previous version of the extension just updated. This is only present if the `reason` value is `update`.
- `reason`
- : An {{WebExtAPIRef('runtime.OnInstalledReason')}} value, stating the reason that this event is being dispatched.
- `temporary`
- : `boolean`. True if the add-on was installed temporarily. For example, using the "about:debugging" page in Firefox or using [web-ext run](https://extensionworkshop.com/documentation/develop/getting-started-with-web-ext/). False otherwise.
## Browser compatibility
{{Compat}}
## Examples
When the extension is installed, log the install reason and open <https://example.com>:
```js
function handleInstalled(details) {
console.log(details.reason);
browser.tabs.create({
url: "https://example.com",
});
}
browser.runtime.onInstalled.addListener(handleInstalled);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onInstalled) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onconnectexternal/index.md | ---
title: runtime.onConnectExternal
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onConnectExternal
page-type: webextension-api-event
browser-compat: webextensions.api.runtime.onConnectExternal
---
{{AddonSidebar}}
Fired when an extension receives a connection request from a different extension.
To send a message which will be received by the `onConnectExternal` listener, use {{WebExtAPIRef("runtime.connect()")}}, passing the ID of the recipient in the `extensionId` parameter.
The listener is passed a {{WebExtAPIRef('runtime.Port')}} object which it can then use to send and receive messages. The `Port` object also contains a `sender` property, which is a {{WebExtAPIRef("runtime.MessageSender")}} object, and which the recipient can use to check the sender's ID.
## Syntax
```js-nolint
browser.runtime.onConnectExternal.addListener(listener)
browser.runtime.onConnectExternal.removeListener(listener)
browser.runtime.onConnectExternal.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 {{WebExtAPIRef('runtime.Port')}} object connecting the current script to the other extension it is connecting to.
## Browser compatibility
{{Compat}}
## Examples
In this example the extension Hansel connects to the extension Gretel:
```js
console.log("connecting to Gretel");
let myPort = browser.runtime.connect("[email protected]");
myPort.onMessage.addListener((message) => {
console.log(`From Gretel: ${message.content}`);
});
browser.browserAction.onClicked.addListener(() => {
myPort.postMessage({ content: "Hello from Hansel" });
});
```
Gretel listens for the connection and checks that the sender is really Hansel:
```js
let portFromHansel;
browser.runtime.onConnectExternal.addListener((port) => {
console.log(port);
if (port.sender.id === "[email protected]") {
console.log("connection attempt from Hansel");
portFromHansel = port;
portFromHansel.onMessage.addListener((message) => {
console.log(`From Hansel: ${message.content}`);
});
}
});
browser.browserAction.onClicked.addListener(() => {
portFromHansel.postMessage({ content: "Message from Gretel" });
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onConnectExternal) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onmessage/index.md | ---
title: runtime.onMessage
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onMessage
page-type: webextension-api-event
browser-compat: webextensions.api.runtime.onMessage
---
{{AddonSidebar}}
Use this event to listen for messages from another part of your extension.
Some example use cases are:
- **in a [content script](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#content_scripts)**, to listen for messages from a [background script.](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#background_scripts)
- **in a background script**, to listen for messages from a content script.
- **in an [options page](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#options_pages) or [popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface#popups) 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 {{WebExtAPIRef("runtime.sendMessage()")}} or (to send a message to a content script) {{WebExtAPIRef("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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#connection-based_messaging).
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](#sending_a_synchronous_response).
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](#sending_an_asynchronous_response_using_sendresponse).
> **Warning:** Do not prepend `async` to the function. Prepending `async` changes the meaning to [sending an asynchronous response using a promise](#sending_an_asynchronous_response_using_a_promise), which is effectively the same as `sendResponse(true)`.
- 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](#sending_an_asynchronous_response_using_a_promise).
> **Note:** You can also use a [connection-based approach to exchange messages](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#connection-based_messaging).
## Syntax
```js-nolint
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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#data_cloning_algorithm)).
- `sender`
- : A {{WebExtAPIRef('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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#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 {{jsxref("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](https://crbug.com/1185241) is resolved. As an alternative, [return true and use sendResponse](#sending_an_asynchronous_response_using_sendresponse).
The `listener` function can return either a Boolean or a {{jsxref("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 example-bad
> // 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 example-good
> browser.runtime.onMessage.addListener((data, sender) => {
> if (data.type === "handle_me") {
> return Promise.resolve("done");
> }
> return false;
> });
> ```
## Browser compatibility
{{Compat}}
## 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`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/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 {{jsxref("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. Prepending `async` changes the meaning to [sending an asynchronous response using a promise](#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](https://crbug.com/1185241) is resolved. As an alternative, [return true and use `sendResponse`](#sending_an_asynchronous_response_using_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 `{{WebExtAPIRef("bookmarks.search()")}}` to see if the link is bookmarked, which returns a {{jsxref("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()`](/en-US/docs/Web/API/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);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onMessage) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/reload/index.md | ---
title: runtime.reload()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/reload
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.reload
---
{{AddonSidebar}}
Reloads the extension.
If there are any pending updates for the extension, that it has deferred by listening to {{WebExtAPIRef("runtime.onUpdateAvailable")}}, then they will be applied on reload.
## Syntax
```js-nolint
browser.runtime.reload()
```
### Parameters
None.
## Browser compatibility
{{Compat}}
## Examples
Reload the extension when the user clicks a browser action's icon:
```js
browser.browserAction.onClicked.addListener((tab) => {
browser.runtime.reload();
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-reload) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/port/index.md | ---
title: runtime.Port
slug: Mozilla/Add-ons/WebExtensions/API/runtime/Port
page-type: webextension-api-type
browser-compat: webextensions.api.runtime.Port
---
{{AddonSidebar}}
A `Port` object represents one end of a connection between two specific contexts, which can be used to exchange messages.
One side initiates the connection, using a `connect()` API. This returns a `Port` object. The other side listens for connection attempts using an `onConnect` listener. This is passed a corresponding `Port` object.
Once both sides have `Port` objects, they can exchange messages using `Port.postMessage()` and `Port.onMessage`. When they are finished, either end can disconnect using `Port.disconnect()`, which will generate a `Port.onDisconnect` event at the other end, enabling the other end to do any cleanup required.
A `Port` can also become disconnected in response to various events. See [Lifecycle](#lifecycle).
You can use this pattern to communicate between:
- different parts of your extension (for example, between [content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) and [background scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#background_scripts))
- between your extension and a [native application running on the user's computer](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging).
- between your extension and a different extension
You need to use different connection APIs for different sorts of connections, as detailed in the table below.
<table class="fullwidth-table standard-table">
<thead>
<tr>
<th scope="col">Connection type</th>
<th scope="col">Initiate connection attempt</th>
<th scope="col">Handle connection attempt</th>
</tr>
</thead>
<tbody>
<tr>
<td>Background script to content script</td>
<td>{{WebExtAPIRef("tabs.connect()")}}</td>
<td>{{WebExtAPIRef("runtime.onConnect")}}</td>
</tr>
<tr>
<td>Content script to background script</td>
<td>{{WebExtAPIRef("runtime.connect()")}}</td>
<td>{{WebExtAPIRef("runtime.onConnect")}}</td>
</tr>
<tr>
<td>Extension to native application</td>
<td>{{WebExtAPIRef("runtime.connectNative()")}}</td>
<td>
Not applicable (see
<a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging"
>Native messaging</a
>).
</td>
</tr>
<tr>
<td>Extension to Extension</td>
<td>{{WebExtAPIRef("runtime.connect()")}}</td>
<td>{{WebExtAPIRef("runtime.onConnectExternal")}}</td>
</tr>
</tbody>
</table>
## Type
Values of this type are objects. They contain the following properties:
- `name`
- : `string`. The port's name, defined in the {{WebExtAPIRef("runtime.connect()")}} or {{WebExtAPIRef("tabs.connect()")}} call that created it. If this port is connected to a native application, its name is the name of the native application.
- `disconnect`
- : `function`. Disconnects a port. Either end can call this when they have finished with the port. It will cause `onDisconnect` to be fired at the other end. This is useful if the other end is maintaining some state relating to this port, which can be cleaned up on disconnect. If this port is connected to a native application, this function will close the native application.
- `error`
- : `object`. If the port was disconnected due to an error, this will be set to an object with a string property `message`, giving you more information about the error. See `onDisconnect`.
- `onDisconnect`
- : `object`. This contains the `addListener()` and `removeListener()` functions common to all events for extensions built using WebExtension APIs. Listener functions will be called when the other end has called `Port.disconnect()`. This event will only be fired once for each port. The listener function will be passed the `Port` object. If the port was disconnected due to an error, then the `Port` argument will contain an `error` property giving more information about the error:
```js
port.onDisconnect.addListener((p) => {
if (p.error) {
console.log(`Disconnected due to an error: ${p.error.message}`);
}
});
```
Note that in Google Chrome `port.error` is not supported: instead, use {{WebExtAPIRef("runtime.lastError")}} to get the error message.
- `onMessage`
- : `object`. This contains the `addListener()` and `removeListener()` functions common to all events for extensions built using WebExtension APIs. Listener functions will be called when the other end has sent this port a message. The listener will be passed the value that the other end sent.
- `postMessage`
- : `function`. Send a message to the other end. This takes one argument, which is a serializable value (see [Data cloning algorithm](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#data_cloning_algorithm)) representing the message to send. It will be delivered to any script listening to the port's `onMessage` event, or to the native application if this port is connected to a native application.
- `sender` {{optional_inline}}
- : {{WebExtAPIRef('runtime.MessageSender')}}. Contains information about the sender of the message. This property will only be present on ports passed to `onConnect`/`onConnectExternal` listeners.
## Lifecycle
The lifecycle of a `Port` is described [in the Chrome docs](https://developer.chrome.com/docs/extensions/mv3/messaging/#port-lifetime).
There is, however, one important difference between Firefox and Chrome, stemming from the fact that the `runtime.connect` and `tabs.connect` APIs are broadcast channels. This means that there may be potentially more than one recipient, and this results in ambiguity when one of the contexts with a `runtime.onConnect` call is closed. In Chrome, a port stays active as long as there is any other recipient. In Firefox, the port closes when any of the contexts unloads. In other words, the disconnection condition,
- All frames that received the port (via `runtime.onConnect`) have unloaded.
which holds in Chrome, is replaced by
- _Any_ frame that received the port (via `runtime.onConnect`) has unloaded.
in Firefox (see [bug 1465514](https://bugzil.la/1465514)).
## Browser compatibility
{{Compat}}
## Examples
### Connecting from content scripts
This content script:
- connects to the background script and stores the `Port` in a variable called `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!" });
});
```
#### Multiple content scripts
If you have multiple content scripts communicating at the same time, you might want to store each connection in an array.
```js
// background-script.js
let ports = [];
function connected(p) {
ports[p.sender.tab.id] = p;
// …
}
browser.runtime.onConnect.addListener(connected);
browser.browserAction.onClicked.addListener(() => {
ports.forEach((p) => {
p.postMessage({ greeting: "they clicked the button!" });
});
});
```
### Connecting to native applications
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");
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-Port) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/sendnativemessage/index.md | ---
title: runtime.sendNativeMessage()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/sendNativeMessage
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.sendNativeMessage
---
{{AddonSidebar}}
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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/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 {{WebExtAPIRef("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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging).
## Syntax
```js-nolint
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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging#app_manifest).
- `message`
- : `object`. A JSON object that will be sent to the native application.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/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
{{Compat}}
## 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);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-sendNativeMessage) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/getbrowserinfo/index.md | ---
title: runtime.getBrowserInfo()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/getBrowserInfo
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.getBrowserInfo
---
{{AddonSidebar}}
Returns information about the browser in which the extension is installed.
This is an asynchronous function that returns a {{JSxRef("Promise")}}.
## Syntax
```js-nolint
let gettingInfo = browser.runtime.getBrowserInfo()
```
### Parameters
None.
### Return value
A {{JSxRef("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);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/sendmessage/index.md | ---
title: runtime.sendMessage()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/sendMessage
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.sendMessage
---
{{AddonSidebar}}
Sends a single message to event listeners within your extension or a different extension.
If sending to your extension, omit the `extensionId` argument. The {{WebExtAPIRef('runtime.onMessage')}} event will be fired in each page in your extension, except for the frame that called `runtime.sendMessage`.
If sending to a different extension, include the `extensionId` argument set to the other extension's ID. {{WebExtAPIRef('runtime.onMessageExternal')}} will be fired in the other extension. By default, your extension can exchange messages with itself and any other extension (defined by `extensionId`). However, the [`externally_connectable`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/externally_connectable) manifest key can be used to limit communication to specific extensions.
Extensions cannot send messages to content scripts using this method. To send messages to content scripts, use {{WebExtAPIRef('tabs.sendMessage')}}.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
> **Note:** You can also use a [connection-based approach to exchange messages](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#connection-based_messaging).
## Syntax
```js-nolint
let sending = browser.runtime.sendMessage(
extensionId, // optional string
message, // any
options // optional object
)
```
### Parameters
- `extensionId` {{optional_inline}}
- : `string`. The ID of the extension to send the message to. Include this to send the message to a different extension. If the intended recipient has set an ID explicitly using the [browser_specific_settings](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) key in manifest.json, then `extensionId` should have that value. Otherwise it should have the ID that was generated for the intended recipient.
If `extensionId` is omitted, the message is sent to your extension.
- `message`
- : `any`. An object that can be structured clone serialized (see [Data cloning algorithm](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#data_cloning_algorithm)).
- `options` {{optional_inline}}
- : `object`.
- `includeTlsChannelId` {{optional_inline}}
- : `boolean`. Whether the TLS channel ID will be passed into {{WebExtAPIRef('runtime.onMessageExternal')}} for processes that are listening for the connection event.
This option is only supported in Chromium-based browsers.
Depending on the arguments it is given, this API is sometimes ambiguous. The following rules are used:
- **if one argument is given**, it is the message to send, and the message will be sent internally.
- **if two arguments are given:**
- the arguments are interpreted as `(message, options)`, and the message is sent internally, if the second argument is any of the following:
1. a valid `options` object (meaning, it is an object which contains only the properties of `options` that the browser supports)
2. null
3. undefined
- otherwise, the arguments are interpreted as `(extensionId, message)`. The message will be sent to the extension identified by `extensionId`.
- **if three arguments are given**, the arguments are interpreted as `(extensionId, message, options)`. The message will be sent to the extension identified by `extensionId`.
Note that before Firefox 55, the rules were different in the 2-argument case. Under the old rules, if the first argument was a string, it was treated as the `extensionId`, with the message as the second argument. This meant that if you called `sendMessage()` with arguments like `("my-message", {})`, then it would send an empty message to the extension identified by "my-message". Under the new rules, with these arguments you would send the message "my-message" internally, with an empty options object.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). If the receiver sent a response, this will be fulfilled with the response. Otherwise it will be fulfilled with no arguments. If an error occurs while connecting to the extension, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
Here's a content script that sends a message to the background script when the user clicks the content window. The message payload is `{greeting: "Greeting from the content script"}`, and the sender also expects to get a response, which is handled in the `handleResponse` function:
```js
// content-script.js
function handleResponse(message) {
console.log(`Message from the background script: ${message.response}`);
}
function handleError(error) {
console.log(`Error: ${error}`);
}
function notifyBackgroundPage(e) {
const sending = browser.runtime.sendMessage({
greeting: "Greeting from the content script",
});
sending.then(handleResponse, handleError);
}
window.addEventListener("click", notifyBackgroundPage);
```
The corresponding background script looks like this:
```js
// background-script.js
function handleMessage(request, sender, sendResponse) {
console.log(`A content script sent a message: ${request.greeting}`);
sendResponse({ response: "Response from background script" });
}
browser.runtime.onMessage.addListener(handleMessage);
```
> **Note:** Instead of using `sendResponse()`, returning a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is the recommended approach for Firefox add-ons.
> Examples using a Promise are available in the [examples section](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage#examples) of the {{WebExtAPIRef('runtime.onMessage')}} listener.
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-sendMessage) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onupdateavailable/index.md | ---
title: runtime.onUpdateAvailable
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onUpdateAvailable
page-type: webextension-api-event
browser-compat: webextensions.api.runtime.onUpdateAvailable
---
{{AddonSidebar}}
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 {{WebExtAPIRef('runtime.reload()')}}.
## Syntax
```js-nolint
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
{{Compat}}
## 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);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onUpdateAvailable) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/platformarch/index.md | ---
title: runtime.PlatformArch
slug: Mozilla/Add-ons/WebExtensions/API/runtime/PlatformArch
page-type: webextension-api-type
browser-compat: webextensions.api.runtime.PlatformArch
---
{{AddonSidebar}}
The machine's processor architecture.
## Type
Values of this type are strings. Possible values are:
- `"arm"`
- : The platform is based on arm architecture.
- `"x86-32"`
- : The platform is based on x86 32-bit architecture.
- `"x86-64"`
- : The platform is based on x86 64-bit architecture.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-PlatformArch) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onconnect/index.md | ---
title: runtime.onConnect
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onConnect
page-type: webextension-api-event
browser-compat: webextensions.api.runtime.onConnect
---
{{AddonSidebar}}
Fired when a connection is made with either an extension process or a content script.
## Syntax
```js-nolint
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 {{WebExtAPIRef('runtime.Port')}} object connecting the current script to the other context it is connecting to.
## Browser compatibility
{{Compat}}
## 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!" });
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onConnect) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/platforminfo/index.md | ---
title: runtime.PlatformInfo
slug: Mozilla/Add-ons/WebExtensions/API/runtime/PlatformInfo
page-type: webextension-api-type
browser-compat: webextensions.api.runtime.PlatformInfo
---
{{AddonSidebar}}
An object containing information about the current platform.
## Type
Values of this type are objects, which contain the following properties:
- `os`
- : {{WebExtAPIRef('runtime.PlatformOs')}}. The platform's operating system.
- `arch`
- : {{WebExtAPIRef('runtime.PlatformArch')}}. The platform's processor architecture.
- `nacl_arch`
- : {{WebExtAPIRef('runtime.PlatformNaclArch')}}. The native client architecture. This may be different from `arch` on some platforms.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-PlatformInfo) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/getpackagedirectoryentry/index.md | ---
title: runtime.getPackageDirectoryEntry()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/getPackageDirectoryEntry
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.getPackageDirectoryEntry
---
{{AddonSidebar}}
Returns a `DirectoryEntry` object representing the package directory.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingEntry = browser.runtime.getPackageDirectoryEntry()
```
### Parameters
None.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a `DirectoryEntry` object representing the package directory.
## Browser compatibility
{{Compat}}
## Examples
```js
function gotDirectoryEntry(directoryEntry) {
console.log(directoryEntry);
}
let gettingEntry = browser.runtime.getPackageDirectoryEntry();
gettingEntry.then(gotDirectoryEntry);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-getPackageDirectoryEntry) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/getframeid/index.md | ---
title: runtime.getFrameId()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/getFrameId
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.getFrameId
---
{{AddonSidebar}}
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-nolint
let gettingInfo = browser.runtime.getFrameId(
target // object
)
```
### Parameters
- `target`
- : A {{glossary("WindowProxy")}} or a {{glossary("browsing context")}} container [Element](/en-US/docs/Web/API/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);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/oninstalledreason/index.md | ---
title: runtime.OnInstalledReason
slug: Mozilla/Add-ons/WebExtensions/API/runtime/OnInstalledReason
page-type: webextension-api-type
browser-compat: webextensions.api.runtime.OnInstalledReason
---
{{AddonSidebar}}
The reason that the {{WebExtAPIRef("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
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-OnInstalledReason) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/setuninstallurl/index.md | ---
title: runtime.setUninstallURL()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/setUninstallURL
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.setUninstallURL
---
{{AddonSidebar}}
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](#browser_compatibility) for more details.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) fulfilled with no arguments when the URL is set or rejected with an error message if the operation fails.
## Browser compatibility
{{Compat}}
## 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);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-setUninstallURL) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onrestartrequiredreason/index.md | ---
title: runtime.OnRestartRequiredReason
slug: Mozilla/Add-ons/WebExtensions/API/runtime/OnRestartRequiredReason
page-type: webextension-api-type
browser-compat: webextensions.api.runtime.OnRestartRequiredReason
---
{{AddonSidebar}}
The reason that the {{WebExtAPIRef("runtime.onRestartRequired", "onRestartRequired")}} event is being dispatched.
## Type
Values of this type are strings. Possible values are:
- `"app_update"`: The application is being updated to a newer version.
- `"os_update"`: The browser/OS is updated to a newer version.
- `"periodic"`: The system has run for more than the permitted uptime set in the enterprise policy.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-OnRestartRequiredReason) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/id/index.md | ---
title: runtime.id
slug: Mozilla/Add-ons/WebExtensions/API/runtime/id
page-type: webextension-api-property
browser-compat: webextensions.api.runtime.id
---
{{AddonSidebar}}
The ID of the extension.
## Syntax
```js-nolint
let myAddonId = browser.runtime.id;
```
### Value
A `string` representing the add-on ID. If the extension specifies an ID in its [`browser_specific_settings`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/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
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#property-id) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onsuspend/index.md | ---
title: runtime.onSuspend
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onSuspend
page-type: webextension-api-event
browser-compat: webextensions.api.runtime.onSuspend
---
{{AddonSidebar}}
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 {{WebExtAPIRef("runtime.onSuspendCanceled")}} event will be sent and the page won't be unloaded.
## Syntax
```js-nolint
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
{{Compat}}
## Examples
Listen for suspend events:
```js
function handleSuspend() {
console.log("Suspending event page");
// handle cleanup
}
browser.runtime.onSuspend.addListener(handleSuspend);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onSuspend) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onbrowserupdateavailable/index.md | ---
title: runtime.onBrowserUpdateAvailable
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onBrowserUpdateAvailable
page-type: webextension-api-event
status:
- deprecated
browser-compat: webextensions.api.runtime.onBrowserUpdateAvailable
---
{{AddonSidebar}}{{Deprecated_header}}
Fired when an update for the browser is available, but it isn't installed immediately because a browser restart is required.
## Syntax
```js-nolint
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
{{Compat}}
## Examples
Listen for this event:
```js
function handleBrowserUpdateAvailable() {
// handle event
}
browser.runtime.onBrowserUpdateAvailable.addListener(
handleBrowserUpdateAvailable,
);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onBrowserUpdateAvailable) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onrestartrequired/index.md | ---
title: runtime.onRestartRequired
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onRestartRequired
page-type: webextension-api-event
browser-compat: webextensions.api.runtime.onRestartRequired
---
{{AddonSidebar}}
Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at its earliest convenience to let the restart happen. If the app does nothing, a restart will be enforced after a 24-hour grace period has passed. Currently, this event is only fired for ChromeOS kiosk apps.
## Syntax
```js-nolint
browser.runtime.onRestartRequired.addListener(listener)
browser.runtime.onRestartRequired.removeListener(listener)
browser.runtime.onRestartRequired.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:
- `reason`
- : A {{WebExtAPIRef('runtime.OnRestartRequiredReason')}} value — the reason that the event is being dispatched.
## Browser compatibility
{{Compat}}
## Examples
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onRestartRequired) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/openoptionspage/index.md | ---
title: runtime.openOptionsPage()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/openOptionsPage
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.openOptionsPage
---
{{AddonSidebar}}
If your extension has an [options page](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages) defined, this method opens it.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let openingPage = browser.runtime.openOptionsPage()
```
### Parameters
None.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the options page has been created successfully, or rejected with an error message if the operation failed.
## Browser compatibility
{{Compat}}
## Examples
Open the options page when the user clicks a browser action's icon:
```js
function onOpened() {
console.log(`Options page opened`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
let opening = browser.runtime.openOptionsPage();
opening.then(onOpened, onError);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-openOptionsPage) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/getplatforminfo/index.md | ---
title: runtime.getPlatformInfo()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/getPlatformInfo
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.getPlatformInfo
---
{{AddonSidebar}}
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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let getting = browser.runtime.getPlatformInfo()
```
### Parameters
None.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('runtime.PlatformInfo')}} value representing the current platform.
## Browser compatibility
{{Compat}}
## Examples
Get and log the platform OS:
```js
function gotPlatformInfo(info) {
console.log(info.os);
}
let gettingInfo = browser.runtime.getPlatformInfo();
gettingInfo.then(gotPlatformInfo);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-getPlatformInfo) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/lasterror/index.md | ---
title: runtime.lastError
slug: Mozilla/Add-ons/WebExtensions/API/runtime/lastError
page-type: webextension-api-property
browser-compat: webextensions.api.runtime.lastError
---
{{AddonSidebar}}
This value is used to report an error message from an asynchronous API, when the asynchronous API is given a callback. This is useful for extensions that are using the callback-based version of the WebExtension APIs.
You don't need to check this property if you are using the promise-based version of the APIs: instead, pass an error handler to the promise:
```js
const gettingCookies = browser.cookies.getAll();
gettingCookies.then(onGot, onError);
```
The `runtime.lastError` property is set when an asynchronous function has an error condition that it needs to report to its caller.
If you call an asynchronous function that may set `lastError`, you are expected to check for the error when you handle the result of the function. If `lastError` has been set and you don't check it within the callback function, then an error will be raised.
## Syntax
```js-nolint
let myError = browser.runtime.lastError; // null or Error object
```
### Value
An {{jsxref("Error")}} object representing the error. The {{jsxref("Error.message", "message")}} property is a `string` with a human-readable description of the error. If `lastError` has not been set, the value is `null`.
## Examples
Set a cookie, using a callback to log the new cookie or report an error:
```js
function logCookie(c) {
if (browser.runtime.lastError) {
console.error(browser.runtime.lastError);
} else {
console.log(c);
}
}
browser.cookies.set({ url: "https://developer.mozilla.org/" }, logCookie);
```
The same, but using a promise to handle the result of `setCookie()`:
```js
function logCookie(c) {
console.log(c);
}
function logError(e) {
console.error(e);
}
const setCookie = browser.cookies.set({
url: "https://developer.mozilla.org/",
});
setCookie.then(logCookie, logError);
```
> **Note:** `runtime.lastError` is an alias for {{WebExtAPIRef("extension.lastError")}}. They are set together, and checking either one will work.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#property-lastError) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/requestupdatecheckstatus/index.md | ---
title: runtime.RequestUpdateCheckStatus
slug: Mozilla/Add-ons/WebExtensions/API/runtime/RequestUpdateCheckStatus
page-type: webextension-api-type
browser-compat: webextensions.api.runtime.RequestUpdateCheckStatus
---
{{AddonSidebar}}
Result of a call to {{WebExtAPIRef("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
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-RequestUpdateCheckStatus) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onstartup/index.md | ---
title: runtime.onStartup
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onStartup
page-type: webextension-api-event
browser-compat: webextensions.api.runtime.onStartup
---
{{AddonSidebar}}
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-nolint
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);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onStartup) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/getmanifest/index.md | ---
title: runtime.getManifest()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/getManifest
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.getManifest
---
{{AddonSidebar}}
Get the complete [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file, deserialized from JSON to an object.
## Syntax
```js-nolint
browser.runtime.getManifest()
```
### Parameters
None.
### Return value
An `object` representing the manifest.
## Browser compatibility
{{Compat}}
## Examples
Get the manifest and log the "name" property:
```js
let manifest = browser.runtime.getManifest();
console.log(manifest.name);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-getManifest) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/messagesender/index.md | ---
title: runtime.MessageSender
slug: Mozilla/Add-ons/WebExtensions/API/runtime/MessageSender
page-type: webextension-api-type
browser-compat: webextensions.api.runtime.MessageSender
---
{{AddonSidebar}}
An object containing information about the sender of a message or connection request that is passed to the {{WebExtAPIRef("runtime.onMessage()")}} listener.
It is also a property of {{WebExtAPIRef("runtime.Port")}}, but only in the `Port` instance passed into the {{WebExtAPIRef("runtime.onConnect()")}} or {{WebExtAPIRef("runtime.onConnectExternal()")}} listeners.
## Type
Values of this type are objects. They contain the following properties:
- `documentId` {{optional_inline}}
- : `string`. A UUID of the document that opened the connection.
- `documentLifecycle` {{optional_inline}}
- : `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_inline}}
- : `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_inline}}
- : `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](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/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_inline}}
- : `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_inline}}
- : {{WebExtAPIRef('tabs.Tab')}}. The {{WebExtAPIRef('tabs.Tab')}} which opened the connection. This property is only present when the connection was opened from a tab (including content scripts).
- `tlsChannelId` {{optional_inline}}
- : `string`. The TLS channel ID of the page or frame that opened the connection, if requested by the extension and available.
- `url` {{optional_inline}}
- : `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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#background_scripts), an [options page](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#options_pages), or a [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#browser_actions_2) or [page action](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#page_actions) 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.
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-MessageSender) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/geturl/index.md | ---
title: runtime.getURL()
slug: Mozilla/Add-ons/WebExtensions/API/runtime/getURL
page-type: webextension-api-function
browser-compat: webextensions.api.runtime.getURL
---
{{AddonSidebar}}
Given a relative path from the [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/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-nolint
browser.runtime.getURL(
path // string
)
```
### Parameters
- `path`
- : `string`. A relative path from the [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) to a resource packaged with the extension.
### Return value
`string`. The fully-qualified URL to the resource.
## Browser compatibility
{{Compat}}
## 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
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#method-getURL) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/runtime/onsuspendcanceled/index.md | ---
title: runtime.onSuspendCanceled
slug: Mozilla/Add-ons/WebExtensions/API/runtime/onSuspendCanceled
page-type: webextension-api-event
browser-compat: webextensions.api.runtime.onSuspendCanceled
---
{{AddonSidebar}}
Sent after {{WebExtAPIRef("runtime.onSuspend")}} to indicate that the app won't be unloaded after all.
## Syntax
```js-nolint
browser.runtime.onSuspendCanceled.addListener(listener)
browser.runtime.onSuspendCanceled.removeListener(listener)
browser.runtime.onSuspendCanceled.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
{{Compat}}
## Examples
Listen for `SuspendCanceled` events:
```js
function handleSuspendCanceled() {
console.log("Suspend canceled");
}
browser.runtime.onSuspendCanceled.addListener(handleSuspendCanceled);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.runtime`](https://developer.chrome.com/docs/extensions/reference/runtime/#event-onSuspendCanceled) API. This documentation is derived from [`runtime.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/menus/index.md | ---
title: menus
slug: Mozilla/Add-ons/WebExtensions/API/menus
page-type: webextension-api
browser-compat: webextensions.api.menus
---
{{AddonSidebar}}
Add items to the browser's menu system.
This API is modeled on Chrome's ["contextMenus"](https://developer.chrome.com/docs/extensions/reference/contextMenus/) API, which enables Chrome extensions to add items to the browser's context menu. The `browser.menus` API adds a few features to Chrome's API.
Before Firefox 55 this API was also originally named `contextMenus`, and that name has been retained as an alias, so you can use `contextMenus` to write code that works in Firefox and also in other browsers.
To use this API you need to have the `menus` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). You may also use the `contextMenus` alias instead of `menus`, but if you do, the APIs must be accessed as `browser.contextMenus` instead.
Except for [`menus.getTargetElement()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/getTargetElement), this API cannot be used from content scripts.
## Creating menu items
To create a menu item call the {{WebExtAPIRef("menus.create()")}} method. You pass this method an object containing options for the item, including the item ID, item type, and the contexts in which it should be shown.
In a Firefox extension using non-persistent [background pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/Background_scripts) (Event pages) or in any Chrome extension, you call `menus.create` from within a {{WebExtAPIRef("runtime.onInstalled")}} listener. In a Firefox extension using persistent background pages, you make a top-level call. See {{WebExtAPIRef("menus.create()")}} for more information.
Listen for clicks on your menu item by adding a listener to the {{WebExtAPIRef("menus.onClicked")}} event. This listener will be passed a {{WebExtAPIRef("menus.OnClickData")}} object containing the event's details.
You can create four different types of menu item, based on the value of the `type` property you supply in the options to `create()`:
- "normal": a menu item that just displays a label
- "checkbox": a menu item that represents a binary state. It displays a checkmark next to the label. Clicking the item toggles the checkmark. The click listener will be passed two extra properties: "checked", indicating whether the item is checked now, and "wasChecked", indicating whether the item was checked before the click event.
- "radio": a menu item that represents one of a group of choices. Just like a checkbox, this also displays a checkmark next to the label, and its click listener is passed "checked" and "wasChecked". However, if you create more than one radio item, then the items function as a group of radio items: only one item in the group can be checked, and clicking an item makes it the checked item.
- "separator": a line separating a group of items.
If you have created more than one context menu item or more than one tools menu item, then the items will be placed in a submenu. The submenu's parent will be labeled with the name of the extension. For example, here's an extension called "Menu demo" that's added two context menu items:

## Icons
If you've specified icons for your extension using the ["icons" manifest key](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons), your menu item will display the specified icon next to its label. The browser will try to choose a 16x16 pixel icon for a normal display or a 32x32 pixel icon for a high-density display:

Only for items in a submenu, you can specify custom icons by passing the `icons` option to {{WebExtAPIRef("menus.create()")}}:

## Example
Here's a context menu containing 4 items: a normal item, two radio items with separators on each side, and a checkbox. The radio items are given custom icons.

You could create a submenu like this using code like:
```js
browser.menus.create(
{
id: "remove-me",
title: browser.i18n.getMessage("menuItemRemoveMe"),
contexts: ["all"],
},
onCreated,
);
browser.menus.create(
{
id: "separator-1",
type: "separator",
contexts: ["all"],
},
onCreated,
);
browser.menus.create(
{
id: "greenify",
type: "radio",
title: browser.i18n.getMessage("menuItemGreenify"),
contexts: ["all"],
checked: true,
icons: {
16: "icons/paint-green-16.png",
32: "icons/paint-green-32.png",
},
},
onCreated,
);
browser.menus.create(
{
id: "bluify",
type: "radio",
title: browser.i18n.getMessage("menuItemBluify"),
contexts: ["all"],
checked: false,
icons: {
16: "icons/paint-blue-16.png",
32: "icons/paint-blue-32.png",
},
},
onCreated,
);
browser.menus.create(
{
id: "separator-2",
type: "separator",
contexts: ["all"],
},
onCreated,
);
let checkedState = true;
browser.menus.create(
{
id: "check-uncheck",
type: "checkbox",
title: browser.i18n.getMessage("menuItemUncheckMe"),
contexts: ["all"],
checked: checkedState,
},
onCreated,
);
```
## Types
- {{WebExtAPIRef("menus.ContextType")}}
- : The different contexts a menu can appear in.
- {{WebExtAPIRef("menus.ItemType")}}
- : The type of menu item: "normal", "checkbox", "radio", "separator".
- {{WebExtAPIRef("menus.OnClickData")}}
- : Information sent when a menu item is clicked.
## Properties
- {{WebExtAPIRef("menus.ACTION_MENU_TOP_LEVEL_LIMIT")}}
- : The maximum number of top level extension items that can be added to a menu item whose ContextType is "browser_action" or "page_action".
## Functions
- {{WebExtAPIRef("menus.create()")}}
- : Creates a new menu item.
- {{WebExtApiRef("menus.getTargetElement()")}}
- : Returns the element for a given `info.targetElementId`.
- {{WebExtApiRef("menus.overrideContext()")}}
- : Hide all default Firefox menu items in favor of providing a custom context menu UI.
- {{WebExtAPIRef("menus.refresh()")}}
- : Update a menu that's currently being displayed.
- {{WebExtAPIRef("menus.remove()")}}
- : Removes a menu item.
- {{WebExtAPIRef("menus.removeAll()")}}
- : Removes all menu items added by this extension.
- {{WebExtAPIRef("menus.update()")}}
- : Updates a previously created menu item.
## Events
- {{WebExtAPIRef("menus.onClicked")}}
- : Fired when a menu item is clicked.
- {{WebExtAPIRef("menus.onHidden")}}
- : Fired when the browser hides a menu.
- {{WebExtAPIRef("menus.onShown")}}
- : Fired when the browser shows a menu.
## Browser compatibility
{{WebExtExamples("h2")}}
{{Compat}}
> **Note:**
>
> This API is based on Chromium's [`chrome.contextMenus`](https://developer.chrome.com/docs/extensions/reference/contextMenus/) API. This documentation is derived from [`context_menus.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/context_menus.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/menus | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/menus/remove/index.md | ---
title: menus.remove()
slug: Mozilla/Add-ons/WebExtensions/API/menus/remove
page-type: webextension-api-function
browser-compat: webextensions.api.menus.remove
---
{{AddonSidebar}}
Removes a menu item.
For compatibility with other browsers, Firefox makes this method available via the `contextMenus` namespace as well as the `menus` namespace.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let removing = browser.menus.remove(
menuItemId // integer or string
)
```
### Parameters
- `menuItemId`
- : `integer` or `string`. The ID of the menu item to remove.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments if removal was successful, or rejected with an error message if removal failed (for example, because the item could not be found).
## Examples
This extension adds a menu item labeled "Remove me!". If you click the item, the extension removes it.
```js
function onRemoved() {
console.log("item removed successfully");
}
function onError() {
console.log("error removing item:", browser.runtime.lastError);
}
browser.menus.create({
id: "remove-me",
title: "Remove me!",
contexts: ["all"],
});
browser.menus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "remove-me") {
let removing = browser.menus.remove(info.menuItemId);
removing.then(onRemoved, onError);
}
});
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.contextMenus`](https://developer.chrome.com/docs/extensions/reference/contextMenus/#method-remove) API. This documentation is derived from [`context_menus.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/context_menus.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/menus | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/menus/create/index.md | ---
title: menus.create()
slug: Mozilla/Add-ons/WebExtensions/API/menus/create
page-type: webextension-api-function
browser-compat: webextensions.api.menus.create
---
{{AddonSidebar}}
Creates a menu item using an options object defining properties for the item.
Unlike other asynchronous functions, this one does not return a promise, but uses an optional callback to communicate success or failure. This is because its return value is the ID of the new item.
For compatibility with other browsers, Firefox makes this method available in the `contextMenus` namespace and `menus` namespace. However, it's not possible to create tools menu items (`contexts: ["tools_menu"]`) using the `contextMenus` namespace.
> **Creating menus in persistent and non-persistent extensions**
>
> How you create menu items depends on whether your extension uses:
>
> - non-persistent background pages (an event page), where menus persist across browser and extension restarts. You call `menus.create` (with a menu-specific ID) from within a {{WebExtAPIRef("runtime.onInstalled")}} listener. This avoids repeated attempts to create the menu item when the pages restart, which would occur with a top-level call.
> - persistent background pages:
> - in Chrome, menu items from persistent background pages are persisted. Create your menus in a {{WebExtAPIRef("runtime.onInstalled")}} listener.
> - in Firefox, menu items from persistent background pages are never persisted. Call `menus.create` unconditionally from the top level to register the menu items.
>
> See [Initialize the extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Background_scripts#initialize_the_extension) on the background scripts page and [Event-driven background scripts](https://extensionworkshop.com/documentation/develop/manifest-v3-migration-guide/#event-driven-background-scripts) on Extension Workshop for more information.
## Syntax
```js-nolint
browser.menus.create(
createProperties, // object
() => {/* … */} // optional function
)
```
### Parameters
- `createProperties`
- : `object`. Properties for the new menu item.
- `checked` {{optional_inline}}
- : `boolean`. The initial state of a checkbox or radio item: `true` for selected and `false` for unselected. Only one radio item can be selected at a time in a given group of radio items.
- `command` {{optional_inline}}
- : `string`. String describing an action that should be taken when the user clicks the item. The recognized values are:
- `"_execute_browser_action"`: simulate a click on the extension's browser action, opening its popup if it has one (Manifest V2 only)
- `"_execute_action"`: simulate a click on the extension's action, opening its popup if it has one (Manifest V3 only)
- `"_execute_page_action"`: simulate a click on the extension's page action, opening its popup if it has one
- `"_execute_sidebar_action"`: open the extension's sidebar
See the documentation of special shortcuts in the manifest.json key [`commands`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/commands#special_shortcuts) for details.
When one of the recognized values is specified, clicking the item does not trigger the {{WebExtAPIRef("menus.onClicked")}} event; instead, the default action triggers, such as opening a pop-up. Otherwise, clicking the item triggers {{WebExtAPIRef("menus.onClicked")}} and the event can be used to implement fallback behavior.
- `contexts` {{optional_inline}}
- : `array` of `{{WebExtAPIRef('menus.ContextType')}}`. Array of contexts in which this menu item will appear. If this option is omitted:
- if the item's parent has contexts set, then this item will inherit its parent's contexts
- otherwise, the item is given a context array of \["page"].
- `documentUrlPatterns` {{optional_inline}}
- : `array` of `string`. Lets you restrict the item to apply only to documents whose URL matches one of the given [match patterns](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns). This applies to frames as well.
- `enabled` {{optional_inline}}
- : `boolean`. Whether this menu item is enabled or disabled. Defaults to `true`.
- `icons` {{optional_inline}}
- : `object`. One or more custom icons to display next to the item. Custom icons can only be set for items appearing in submenus. This property is an object with one property for each supplied icon: the property's name should include the icon's size in pixels, and path is relative to the icon from the extension's root directory. The browser tries to choose a 16x16 pixel icon for a normal display or a 32x32 pixel icon for a high-density display. To avoid any scaling, you can specify icons like this:
```js
browser.menus.create({
icons: {
16: "path/to/geo-16.png",
32: "path/to/geo-32.png",
},
});
```
Alternatively, you can specify a single SVG icon, and it will be scaled appropriately:
```js
browser.menus.create({
icons: {
16: "path/to/geo.svg",
},
});
```
> **Note:** The top-level menu item uses the [icons](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons) specified in the manifest rather than what is specified with this key.
- `id` {{optional_inline}}
- : `string`. The unique ID to assign to this item. Is mandatory for non-persistent [background (event) pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/Background_scripts) in Manifest V2 and in Manifest V3. Cannot be the same as another ID for this extension.
- `onclick` {{optional_inline}}
- : `function`. The function called when the menu item is clicked. Event pages cannot use this: instead, they should register a listener for {{WebExtAPIRef('menus.onClicked')}}.
- `parentId` {{optional_inline}}
- : `integer` or `string`. The ID of a parent menu item; this makes the item a child of a previously added item. Note: If you have created more than one menu item, then the items will be placed in a submenu. The submenu's parent will be labeled with the name of the extension.
- `targetUrlPatterns` {{optional_inline}}
- : `array` of `string`. Similar to `documentUrlPatterns`, but lets you filter based on the `href` of anchor tags and the `src` attribute of img/audio/video tags. This parameter supports any URL scheme, even those that are usually not allowed in a match pattern.
- `title` {{optional_inline}}
- : `string`. The text to be displayed in the item. Mandatory unless `type` is "separator".
You can use "`%s`" in the string. If you do this in a menu item, and some text is selected in the page when the menu is shown, then the selected text will be interpolated into the title. For example, if `title` is "Translate '%s' to Pig Latin" and the user selects the word "cool", then activates the menu, then the menu item's title will be: "Translate 'cool' to Pig Latin".
If the title contains an ampersand "&" then the next character will be used as an access key for the item, and the ampersand will not be displayed. Exceptions to this are:
- If the next character is also an ampersand: then a single ampersand will be displayed and no access key will be set. In effect, "&&" is used to display a single ampersand.
- If the next characters are the interpolation directive "%s": then the ampersand will not be displayed and no access key will be set.
- If the ampersand is the last character in the title: then the ampersand will not be displayed and no access key will be set.
Only the first ampersand will be used to set an access key: subsequent ampersands will not be displayed but will not set keys. So "\&A and \&B" will be shown as "A and B" and set "A" as the access key.
In some localized versions of Firefox (Japanese and Chinese), the access key is surrounded by parentheses and appended to the menu label, _unless_ the menu title itself already ends with the access key (`"toolkit(&K)"` for example). For more details, see [Firefox bug 1647373](https://bugzil.la/1647373).
- `type` {{optional_inline}}
- : `{{WebExtAPIRef('menus.ItemType')}}`. The type of menu item: "normal", "checkbox", "radio", "separator". Defaults to "normal".
- `viewTypes` {{optional_inline}}
- : `{{WebExtAPIRef('extension.ViewType')}}`. List of view types where the menu item will be shown. Defaults to any view, including those without a `viewType`.
- `visible` {{optional_inline}}
- : `boolean`. Whether the item is shown in the menu. Defaults to `true`.
- `callback` {{optional_inline}}
- : `function`. Called when the item has been created. If there were any problems creating the item, details will be available in {{WebExtAPIRef('runtime.lastError')}}.
### Return value
`integer` or `string`. The `ID` of the newly created item.
## Examples
This example creates a context menu item that's shown when the user has selected some text in the page. It just logs the selected text to the console:
```js
browser.menus.create({
id: "log-selection",
title: "Log '%s' to the console",
contexts: ["selection"],
});
browser.menus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "log-selection") {
console.log(info.selectionText);
}
});
```
This example adds two radio items, which you can use to choose whether to apply a green or a blue border to the page. Note that this example will need the [activeTab permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission).
```js
function onCreated() {
if (browser.runtime.lastError) {
console.log("error creating item:", browser.runtime.lastError);
} else {
console.log("item created successfully");
}
}
browser.menus.create(
{
id: "radio-green",
type: "radio",
title: "Make it green",
contexts: ["all"],
checked: false,
},
onCreated,
);
browser.menus.create(
{
id: "radio-blue",
type: "radio",
title: "Make it blue",
contexts: ["all"],
checked: false,
},
onCreated,
);
let makeItBlue = 'document.body.style.border = "5px solid blue"';
let makeItGreen = 'document.body.style.border = "5px solid green"';
browser.menus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "radio-blue") {
browser.tabs.executeScript(tab.id, {
code: makeItBlue,
});
} else if (info.menuItemId === "radio-green") {
browser.tabs.executeScript(tab.id, {
code: makeItGreen,
});
}
});
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.contextMenus`](https://developer.chrome.com/docs/extensions/reference/contextMenus/#method-create) API. This documentation is derived from [`context_menus.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/context_menus.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
Subsets and Splits