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/pageaction
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/pageaction/imagedatatype/index.md
--- title: pageAction.ImageDataType slug: Mozilla/Add-ons/WebExtensions/API/pageAction/ImageDataType page-type: webextension-api-type browser-compat: webextensions.api.pageAction.ImageDataType --- {{AddonSidebar}} Pixel data for an image. ## Type An [`ImageData`](/en-US/docs/Web/API/ImageData) object, e.g. from a {{htmlelement("canvas")}} element. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.pageAction`](https://developer.chrome.com/docs/extensions/reference/pageAction/#type-ImageDataType) API. This documentation is derived from [`page_action.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/page_action.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/identity/index.md
--- title: identity slug: Mozilla/Add-ons/WebExtensions/API/identity page-type: webextension-api browser-compat: webextensions.api.identity --- {{AddonSidebar}} Use the identity API to get an [OAuth2](https://oauth.net/2/) authorization code or access token, which an extension can then use to access user data from a service that supports OAuth2 access (such as Google or Facebook). OAuth2 flows vary between service provider so, to use this API with a particular service provider, consult their documentation. For example: - [Google](https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow) - [GitHub](https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps) The identity API provides the {{WebExtAPIRef("identity.launchWebAuthFlow()")}} function. This authenticates the user with the service, if necessary, and asks the user to authorize the extension to access data, if necessary. The function completes with an access token or authorization code, depending on the provider. The extension then completes the OAuth2 flow to get a validated access token, and uses the token in HTTPS requests to access the user's data according to the authorization the user gave. To use this API, you must have the "identity" [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions). ## Setup There's some setup you must do before publishing your extension. ### Getting the redirect URL The [redirect URL](https://www.oauth.com/oauth2-servers/redirect-uris/) represents the end point of {{WebExtAPIRef("identity.launchWebAuthFlow()")}}, in which the access token or authorization code is delivered to the extension. The browser extracts the result from the redirect URL without loading its response. You get the redirect URL by calling {{WebExtAPIRef("identity.getRedirectURL()")}}. This function derives a redirect URL from the add-on's ID. To simplify testing, set your add-on's ID explicitly using the [`browser_specific_settings`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) key (otherwise, each time you [temporarily install the add-on](https://extensionworkshop.com/documentation/develop/temporary-installation-in-firefox/), you get a different redirect URL). {{WebExtAPIRef("identity.getRedirectURL()")}} returns a URL at a fixed domain name and a subdomain derived from the add-on's ID. Some OAuth servers (such as Google) only accept domains with a verified ownership as the redirect URL. As the dummy domain cannot be controlled by extension developers, the default domain cannot always be used. However, loopback addresses are an accepted alternative that do not require domain validation (based on [RFC 8252, section 7.3](https://datatracker.ietf.org/doc/html/rfc8252#section-7.3)). Starting from Firefox 86, a loopback address with the format `http://127.0.0.1/mozoauth2/[subdomain of URL returned by identity.getRedirectURL()]` is permitted as a value for the redirect URL. > **Note:** Starting with Firefox 75, you must use the redirect URL returned by {{WebExtAPIRef("identity.getRedirectURL()")}}. Earlier versions allowed you to supply any redirect URL. > > Starting with Firefox 86, the special loopback address described above can be used too. You'll use the redirect URL in two places: - supply it when registering your extension as an OAuth2 client. - pass it into `identity.launchWebAuthFlow()`, as a URL parameter added to that function's `url` argument. ### Registering your extension Before you use OAuth2 with a service provider, you must register the extension with the provider as an OAuth2 client. This will tend to be specific to the service provider, but in general it means creating an entry for your extension on the provider's website. In this process you supply your redirect URL, and receive a client ID (and sometimes also a secret). You need to pass both of these into {{WebExtAPIRef("identity.launchWebAuthFlow()")}}. ## Functions - {{WebExtAPIRef("identity.getRedirectURL()")}} - : Gets the redirect URL. - {{WebExtAPIRef("identity.launchWebAuthFlow()")}} - : Launches WAF. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.identity`](https://developer.chrome.com/docs/extensions/reference/identity/) API. <!-- // 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/identity
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/identity/launchwebauthflow/index.md
--- title: identity.launchWebAuthFlow slug: Mozilla/Add-ons/WebExtensions/API/identity/launchWebAuthFlow page-type: webextension-api-function browser-compat: webextensions.api.identity.launchWebAuthFlow --- {{AddonSidebar}} Performs the first part of an [OAuth2](https://oauth.net/2/) flow, including user authentication and client authorization. This function's only mandatory parameter is the service provider's authorization URL, which must contain a number of URL parameters including the [redirect URL](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/identity#getting_the_redirect_url) and the extension's [client ID](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/identity#registering_your_add-on). The service provider then: - authenticates the user with the service provider, if necessary (that is: if they are not already signed in) - asks the user to authorize the extension to access the requested data, if necessary (that is: if the user has not already authorized the extension) Note that if neither authentication or authorization are needed, then this function will complete silently, without any user interaction. This function also takes an optional parameter `interactive`: if this is omitted or set to false, then the flow is forced to complete silently. In this case, if the user has to authenticate or authorize, then the operation will just fail. This function returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise): if authentication and authorization were successful, the promise is fulfilled with a redirect URL that contains a number of URL parameters. Depending on the OAuth2 flow implemented by the service provider in question, the extension will need to go through further steps to get a valid access code, which it can then use to access the user's data. If there's any error, the promise is rejected with an error message. Error conditions may include: - the service provider's URL could not be reached - the client ID did not match the ID of a registered client - the redirect URL did not match any redirect URLs registered for this client - the user did not authenticate successfully - the user did not authorize the extension - the `interactive` parameter was omitted or false, but user interaction would have been needed to authorize the extension. ## Syntax ```js-nolint let authorizing = browser.identity.launchWebAuthFlow( details // object ) ``` ### Parameters - `details` - : `object`. Options for the flow, containing the following properties: - `url` - : `string`. The URL offered by the OAuth2 service provider to get an access token. The details of this URL should be given in the documentation for the service provider in question, but the URL parameters should always include: - `redirect_uri` {{optional_inline}} - : `string`. This represents the URI your extension is redirected to when the flow has finished. Not required for the flow to work on the browser side if it matches the generated redirect URL. See [Getting the redirect URL](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/identity#getting_the_redirect_url). - `interactive` {{optional_inline}} - : `boolean`. If omitted or `false`, forces the flow to complete silently, without any user interaction. If the user is already signed in and has already granted access for the extension, then `launchWebAuthFlow()` can complete silently, without any user interaction. Otherwise (if the service provider needs the user to sign in, or to authorize the extension), then `launchWebAuthFlow()` will prompt the user: that is, the flow will be interactive. Extensions should not launch interactive flows except in response to a user action. However, sometimes extensions still want to access the user's data without a direct user action (for example, imagine an extension that wants to access data when the browser launches). This is the purpose of `interactive`: if you omit `interactive` or set it to `false`, then the flow is forced to conclude silently: if the service provider needs to interact with the user, the flow will just fail. So as a general rule: set `interactive` to `true` if you're launching the flow in response to a user action, and omit it otherwise. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). If the extension is authorized successfully, this will be fulfilled with a string containing the redirect URL. The URL will include a parameter that either is an access token or can be exchanged for an access token, using the documented flow for the particular service provider. ## Browser compatibility {{Compat}} ## Examples This function authorizes an extension to access a user's Google data, according to the documentation at <https://developers.google.com/identity/protocols/OAuth2UserAgent>. Validation of the returned access token isn't shown here: ```js function validate(redirectURL) { // validate the access token } function authorize() { const redirectURL = browser.identity.getRedirectURL(); const clientID = "664583959686-fhvksj46jkd9j5v96vsmvs406jgndmic.apps.googleusercontent.com"; const scopes = ["openid", "email", "profile"]; let authURL = "https://accounts.google.com/o/oauth2/auth"; authURL += `?client_id=${clientID}`; authURL += `&response_type=token`; authURL += `&redirect_uri=${encodeURIComponent(redirectURL)}`; authURL += `&scope=${encodeURIComponent(scopes.join(" "))}`; return browser.identity.launchWebAuthFlow({ interactive: true, url: authURL, }); } function getAccessToken() { return authorize().then(validate); } ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`identity`](https://developer.chrome.com/docs/extensions/reference/identity/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/identity
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/identity/getredirecturl/index.md
--- title: identity.getRedirectURL() slug: Mozilla/Add-ons/WebExtensions/API/identity/getRedirectURL page-type: webextension-api-function browser-compat: webextensions.api.identity.getRedirectURL --- {{AddonSidebar}} Generates a URL that you can use as a redirect URL. The URL is derived from your extension's ID, so if you use this function you should probably set your extension's ID explicitly using the [`browser_specific_settings`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) key (otherwise, each time you [temporarily install the extension](https://extensionworkshop.com/documentation/develop/temporary-installation-in-firefox/), you'll get a different redirect URL). See [Getting a redirect URL](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/identity#getting_the_redirect_url) for more information on redirect URLs. ## Syntax ```js-nolint let redirectURL = browser.identity.getRedirectURL() ``` ### Parameters None. ### Return value A string containing a redirect URL value. ## Browser compatibility {{Compat}} ## Examples Get the redirect URL: ```js let redirectURL = browser.identity.getRedirectURL(); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`identity`](https://developer.chrome.com/docs/extensions/reference/identity/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions/index.md
--- title: permissions slug: Mozilla/Add-ons/WebExtensions/API/permissions page-type: webextension-api browser-compat: webextensions.api.permissions --- {{AddonSidebar}} Enables extensions to request extra permissions at runtime, after they have been installed. Extensions need permissions to access more powerful WebExtension APIs. They can ask for permissions at install time, by including the permissions they need in the [`permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) manifest.json key. The main advantages of asking for permissions at install time are: - The user is only asked once, so it's less disruptive for them, and a simpler decision. - The extension can rely on the access to the APIs it needs, because if already running, the permissions have been granted. In most major browsers, users can see if their installed extensions request advanced permissions through the browser's extensions manager. With the permissions API, an extension can ask for additional permissions at runtime. These permissions need to be listed in the [`optional_permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) manifest.json key. Note that some permissions are not allowed in `optional_permissions`. The main advantages of this are: - The extension can run with a smaller set of permissions, except when it actually needs them. - The extension can handle permission denial in a graceful manner, instead of presenting the user with a global "all or nothing" choice at install time. You can still get a lot out of that map extension, without giving it access to your location, for example. - The extension may need [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions), but not know at install time which host permissions it needs. For example, the list of hosts may be a user setting. In this scenario, asking for a more specific range of hosts at runtime, can be an alternative to asking for "\<all_urls>" at install time. To use the permissions API, decide which permissions your extension can request at runtime, and list them in [`optional_permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions). After this, you can request any permissions that were included in `optional_permissions`. Requests may only be made in the handler for a user action (for example, a click handler). Starting with Firefox 84, users will be able to manage optional permissions of installed extensions from the Add-ons Manager. Extensions that use optional permissions should listen for [browser.permissions.onAdded](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/permissions/onAdded) and [browser.permissions.onRemoved](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/permissions/onRemoved) API events to know when a user grants or revokes these permissions. For advice on designing your request for runtime permissions, to maximize the likelihood that users grant them, see [Request permissions at runtime](https://extensionworkshop.com/documentation/develop/request-the-right-permissions/#request_permissions_at_runtime). ## Types - {{WebExtAPIRef("permissions.Permissions")}} - : Represents a set of permissions. ## Methods - {{WebExtAPIRef("permissions.contains()")}} - : Discover an extension's given set of permissions. - {{WebExtAPIRef("permissions.getAll()")}} - : Get all the permissions this extension currently has. - {{WebExtAPIRef("permissions.remove()")}} - : Give up a set of permissions. - {{WebExtAPIRef("permissions.request()")}} - : Ask for a set of permissions. ## Event handlers - {{WebExtAPIRef("permissions.onAdded")}} - : Fired when a new permission is granted. - {{WebExtAPIRef("permissions.onRemoved")}} - : Fired when a permission is removed. ## Browser compatibility {{Compat}} ## See also - `manifest.json` [`permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) property - `manifest.json` [`optional_permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) property {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.permissions`](https://developer.chrome.com/docs/extensions/reference/permissions/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions/remove/index.md
--- title: permissions.remove() slug: Mozilla/Add-ons/WebExtensions/API/permissions/remove page-type: webextension-api-function browser-compat: webextensions.api.permissions.remove --- {{AddonSidebar}} Ask to give up the permissions listed in the given {{WebExtAPIRef("permissions.Permissions")}} object. The `Permissions` argument may contain either an `origins` property, which is an array of [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions), or a `permissions` property, which is an array of [API permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions), or both. Permissions must come from the set of permissions defined in the [`optional_permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) manifest.json key. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.permissions.remove( permissions // Permissions object ) ``` ### Parameters - `permissions` - : A {{WebExtAPIRef("permissions.Permissions")}} object. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is fulfilled with `true` if the permissions listed in the `permissions` argument are now not granted to the extension, or `false` otherwise. ## Browser compatibility {{Compat}} ## Examples This code adds a click handler that removes a given permission. ```js const permissionToRemove = { permissions: ["history"], }; async function remove() { console.log("removing"); const removed = await browser.permissions.remove(permissionToRemove); console.log(removed); } document.querySelector("#remove").addEventListener("click", remove); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.permissions`](https://developer.chrome.com/docs/extensions/reference/permissions/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions/onadded/index.md
--- title: permissions.onAdded slug: Mozilla/Add-ons/WebExtensions/API/permissions/onAdded page-type: webextension-api-event browser-compat: webextensions.api.permissions.onAdded --- {{AddonSidebar}} Fired when the extension granted new permissions. ## Syntax ```js-nolint browser.permissions.onAdded.addListener(listener) browser.permissions.onAdded.removeListener(listener) browser.permissions.onAdded.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `permissions` - : {{WebExtAPIRef("permissions.Permissions")}} object containing the permissions that were granted. ## Browser compatibility {{Compat}} ## Examples ```js function handleAdded(permissions) { console.log(`New API permissions: ${permissions.permissions}`); console.log(`New host permissions: ${permissions.origins}`); } browser.permissions.onAdded.addListener(handleAdded); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.permissions`](https://developer.chrome.com/docs/extensions/reference/permissions/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions/contains/index.md
--- title: permissions.contains() slug: Mozilla/Add-ons/WebExtensions/API/permissions/contains page-type: webextension-api-function browser-compat: webextensions.api.permissions.contains --- {{AddonSidebar}} Check whether the extension has the permissions listed in the given {{WebExtAPIRef("permissions.Permissions")}} object. The `Permissions` argument may contain either an origins property, which is an array of [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions), or a `permissions` property, which is an array of [API permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions), or both. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). The promise is fulfilled with true only if all the extension currently has all the given permissions. For host permissions, if the extension's permissions [pattern-match](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) the permissions listed in `origins`, then they are considered to match. ## Syntax ```js-nolint let getContains = browser.permissions.contains( permissions // Permissions object ) ``` ### Parameters - `permissions` - : A {{WebExtAPIRef("permissions.Permissions")}} object. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with `true` if the extension already has all the permissions listed in the `permissions` argument, or `false` otherwise. ## Browser compatibility {{Compat}} ## Examples ```js // Extension permissions are: // "webRequest", "tabs", "*://*.mozilla.org/*" let testPermissions1 = { origins: ["*://mozilla.org/"], permissions: ["tabs"], }; const testResult1 = await browser.permissions.contains(testPermissions1); console.log(testResult1); // true let testPermissions2 = { origins: ["*://mozilla.org/"], permissions: ["tabs", "alarms"], }; const testResult2 = await browser.permissions.contains(testPermissions2); console.log(testResult2); // false, "alarms" doesn't match let testPermissions3 = { origins: ["https://developer.mozilla.org/"], permissions: ["tabs", "webRequest"], }; const testResult3 = await browser.permissions.contains(testPermissions3); console.log(testResult3); // true: "https://developer.mozilla.org/", matches: "*://*.mozilla.org/*" let testPermissions4 = { origins: ["https://example.org/"], }; const testResult4 = await browser.permissions.contains(testPermissions4); console.log(testResult4); // false: "https://example.org/", `origins` doesn't match ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.permissions`](https://developer.chrome.com/docs/extensions/reference/permissions/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions/request/index.md
--- title: permissions.request() slug: Mozilla/Add-ons/WebExtensions/API/permissions/request page-type: webextension-api-function browser-compat: webextensions.api.permissions.request --- {{AddonSidebar}} Ask for the set of permissions listed in the given {{WebExtAPIRef("permissions.Permissions")}} object. The `Permissions` argument may contain either an `origins` property, which is an array of [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions), or a `permissions` property, which is an array of [API permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions), or both. Permissions must come from the set of permissions defined in the [`optional_permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) manifest.json key. The `origins` property may include permissions that match a subset of the hosts matched by an optional permission: for example, if optional_permissions include "\*://mozilla.org/", then `permissions.origins` may include "https\://developer.mozilla.org/". The request can only be made inside the handler for a [user action](/en-US/docs/Mozilla/Add-ons/WebExtensions/User_actions). Depending on a circumstances, the browser will probably handle the request by asking the user whether to grant the requested permissions. Only a single request is made for all requested permissions: thus either all permissions are granted or none of them are. Any permissions granted are retained by the extension, even over upgrade and disable/enable cycling. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let requesting = browser.permissions.request( permissions // Permissions object ) ``` ### Parameters - `permissions` - : A {{WebExtAPIRef("permissions.Permissions")}} object. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is fulfilled with `true` if the extension is now granted all the permissions listed in the `permissions` argument, or `false` otherwise. ## Browser compatibility {{Compat}} ## Examples This code adds a click handler that asks for various permissions, then logs the result of the request and the extension's permissions after the request completed. ```js const permissionsToRequest = { permissions: ["bookmarks", "history"], origins: ["https://developer.mozilla.org/"], }; async function requestPermissions() { function onResponse(response) { if (response) { console.log("Permission was granted"); } else { console.log("Permission was refused"); } return browser.permissions.getAll(); } const response = await browser.permissions.request(permissionsToRequest); const currentPermissions = await onResponse(response); console.log(`Current permissions:`, currentPermissions); } document .querySelector("#request") .addEventListener("click", requestPermissions); ``` {{WebExtExamples}} > **Note:** Currently has a [bug with requesting origins](https://bugzil.la/1411873) and [requesting permissions on the about:addons page](https://bugzil.la/1382953). > **Note:** This API is based on Chromium's [`chrome.permissions`](https://developer.chrome.com/docs/extensions/reference/permissions/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions/permissions/index.md
--- title: Permissions slug: Mozilla/Add-ons/WebExtensions/API/permissions/Permissions page-type: webextension-api-type browser-compat: webextensions.api.permissions.Permissions --- {{AddonSidebar}} A `Permissions` object represents a collection of permissions. ## Type An {{jsxref("object")}} with the following properties: - `origins` {{optional_inline}} - : An array of [match patterns](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns), representing [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions). - `permissions` {{optional_inline}} - : An array of named permissions, including [API permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) and [clipboard permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#clipboard_access). ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.permissions`](https://developer.chrome.com/docs/extensions/reference/permissions/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions/getall/index.md
--- title: permissions.getAll() slug: Mozilla/Add-ons/WebExtensions/API/permissions/getAll page-type: webextension-api-function browser-compat: webextensions.api.permissions.getAll --- {{AddonSidebar}} Retrieve a {{WebExtAPIRef("permissions.Permissions")}} object containing all the permissions currently granted to the extension. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let gettingAll = browser.permissions.getAll() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef("permissions.Permissions")}} object containing all the permissions currently granted to the extension. This includes all permissions the extension has listed in the [`permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) key, and any permissions listed in [`optional_permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) that the extension has been granted by calling {{WebExtAPIRef("permissions.request()")}}. ## Browser compatibility {{Compat}} ## Examples ```js // Extension permissions are: // "webRequest", "tabs", "*://*.mozilla.org/*" const currentPermissions = await browser.permissions.getAll(); console.log(currentPermissions.permissions); // [ "webRequest", "tabs" ] console.log(currentPermissions.origins); // [ "*://*.mozilla.org/*" ] ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.permissions`](https://developer.chrome.com/docs/extensions/reference/permissions/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/permissions/onremoved/index.md
--- title: permissions.onRemoved slug: Mozilla/Add-ons/WebExtensions/API/permissions/onRemoved page-type: webextension-api-event browser-compat: webextensions.api.permissions.onRemoved --- {{AddonSidebar}} Fired when some permissions are removed from the extension. ## Syntax ```js-nolint browser.permissions.onRemoved.addListener(listener) browser.permissions.onRemoved.removeListener(listener) browser.permissions.onRemoved.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `permissions` - : {{WebExtAPIRef("permissions.Permissions")}} object containing the permissions that were removed. ## Browser compatibility {{Compat}} ## Examples ```js function handleRemoved(permissions) { console.log(`Removed API permissions: ${permissions.permissions}`); console.log(`Removed host permissions: ${permissions.origins}`); } browser.permissions.onRemoved.addListener(handleRemoved); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.permissions`](https://developer.chrome.com/docs/extensions/reference/permissions/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/idle/index.md
--- title: idle slug: Mozilla/Add-ons/WebExtensions/API/idle page-type: webextension-api browser-compat: webextensions.api.idle --- {{AddonSidebar}} Find out when the user's system is idle, locked, or active. To use this API you need to have the "idle" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). ## Types - {{WebExtAPIRef("idle.IdleState")}} - : String describing the device's idle state. ## Functions - {{WebExtAPIRef("idle.queryState()")}} - : Returns `"locked"` if the system is locked, `"idle"` if the user has not generated any input for a specified number of seconds, or `"active"` otherwise. - {{WebExtAPIRef("idle.setDetectionInterval()")}} - : Sets the interval used to determine when the system is in an idle state for {{WebExtAPIRef("idle.onStateChanged")}} events. ## Events - {{WebExtAPIRef("idle.onStateChanged")}} - : Fired when the system changes state. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.idle`](https://developer.chrome.com/docs/extensions/reference/idle/) API. This documentation is derived from [`idle.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/idle.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/idle
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/idle/setdetectioninterval/index.md
--- title: idle.setDetectionInterval() slug: Mozilla/Add-ons/WebExtensions/API/idle/setDetectionInterval page-type: webextension-api-function browser-compat: webextensions.api.idle.setDetectionInterval --- {{AddonSidebar}} Sets the interval, in seconds, used to determine when the system is in an idle state for {{WebExtAPIRef("idle.onStateChanged")}} events. The default interval is 60 seconds. The detection interval is specific to the extension that calls the method. Changing the interval in one extension will not affect the detection interval in another extension. ## Syntax ```js-nolint browser.idle.setDetectionInterval( intervalInSeconds // integer ) ``` ### Parameters - `intervalInSeconds` - : `integer`. Threshold, in seconds, used to determine when the system is in an idle state. The minimum value you can supply here is 15. ## Browser compatibility {{Compat}} ## Examples ```js browser.idle.setDetectionInterval(15); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.idle`](https://developer.chrome.com/docs/extensions/reference/idle/#method-setDetectionInterval) API. This documentation is derived from [`idle.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/idle.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/idle
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/idle/onstatechanged/index.md
--- title: idle.onStateChanged slug: Mozilla/Add-ons/WebExtensions/API/idle/onStateChanged page-type: webextension-api-event browser-compat: webextensions.api.idle.onStateChanged --- {{AddonSidebar}} Fired when the system changes to an active, idle or locked state. The event listener is passed a string that has one of three values: - "locked" if the screen is locked or the screensaver activates - "idle" if the system is unlocked and the user has not generated any input for a specified number of seconds. This number defaults to 60, but can be set using {{WebExtAPIRef("idle.setDetectionInterval()")}}. - "active" when the user generates input on an idle system. ## Syntax ```js-nolint browser.idle.onStateChanged.addListener(listener) browser.idle.onStateChanged.removeListener(listener) browser.idle.onStateChanged.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `newState` - : {{WebExtAPIRef('idle.IdleState')}}. The new idle state. ## Browser compatibility {{Compat}} ## Examples ```js function newState(state) { console.log(`New state: ${state}`); } browser.idle.onStateChanged.addListener(newState); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.idle`](https://developer.chrome.com/docs/extensions/reference/idle/#event-onStateChanged) API. This documentation is derived from [`idle.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/idle.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/idle
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/idle/idlestate/index.md
--- title: idle.IdleState slug: Mozilla/Add-ons/WebExtensions/API/idle/IdleState page-type: webextension-api-type browser-compat: webextensions.api.idle.IdleState --- {{AddonSidebar}} String describing the device's idle state. ## Type Values of this type are strings. Possible values are: `"active"`, `"idle"`, `"locked"`. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.idle`](https://developer.chrome.com/docs/extensions/reference/idle/#type-IdleState) API. This documentation is derived from [`idle.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/idle.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/idle
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/idle/querystate/index.md
--- title: idle.queryState() slug: Mozilla/Add-ons/WebExtensions/API/idle/queryState page-type: webextension-api-function browser-compat: webextensions.api.idle.queryState --- {{AddonSidebar}} Returns `"locked"` if the system is locked, `"idle"` if the user has not generated any input for a specified number of seconds, or `"active"` otherwise. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let querying = browser.idle.queryState( detectionIntervalInSeconds // integer ) ``` ### Parameters - `detectionIntervalInSeconds` - : `integer`. The system is considered idle if `detectionIntervalInSeconds` seconds have elapsed since the last user input detected. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an {{WebExtAPIRef('idle.IdleState')}} string, indicating the current state. ## Browser compatibility {{Compat}} ## Examples In this simple snippet, we call `queryState()` and then check if the returned `newState` is `idle` or `active`, logging a message as appropriate. Because we have specified a `detectionIntervalInSeconds` of 15, an `idle` state will only be reported if there has been no user activity for at least 15 seconds ```js function onGot(newState) { if (newState === "idle") { console.log("Please come back — we miss you!"); } else if (newState === "active") { console.log("Glad to still have you with us!"); } } let querying = browser.idle.queryState(15); querying.then(onGot); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.idle`](https://developer.chrome.com/docs/extensions/reference/idle/#method-queryState) API. This documentation is derived from [`idle.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/idle.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/storage/index.md
--- title: storage slug: Mozilla/Add-ons/WebExtensions/API/storage page-type: webextension-api browser-compat: webextensions.api.storage --- {{AddonSidebar}} Enables extensions to store and retrieve data, and listen for changes to stored items. The storage system is based on the [Web Storage API](/en-US/docs/Web/API/Web_Storage_API), with a few differences. Among other differences, these include: - It's asynchronous. - Values are scoped to the extension, not to a specific domain (i.e. the same set of key/value pairs are available to all scripts in the background context and content scripts). - The values stored can be any JSON-ifiable value, not just [`String`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String). Among other things, this includes: [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) and [`Object`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), but only when their contents can be represented as JSON, which does not include DOM nodes. You don't need to convert your values to JSON `Strings` prior to storing them, but they are represented as JSON internally, thus the requirement that they be JSON-ifiable. - Multiple key/value pairs can be set or retrieved in the same API call. To use this API you need to include the `"storage"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) in your [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file. Each extension has its own storage area, which can be split into different types of storage. Although this API is similar to {{domxref("Window.localStorage")}} it is recommended that you don't use `Window.localStorage` in the extension code to store extension-related data. Firefox will clear data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons, while data saved using the [`storage.local`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/local) API will be correctly persisted in these scenarios. You can examine the stored data under the Extension Storage item in the [Storage Inspector](https://firefox-source-docs.mozilla.org/devtools-user/storage_inspector/index.html) tab of the [developer toolbox](https://extensionworkshop.com/documentation/develop/debugging/), accessible from `about:debugging`. > **Note:** The storage area is not encrypted and shouldn't be used for storing confidential user information. ## Types - {{WebExtAPIRef("storage.StorageArea")}} - : An object representing a storage area. - {{WebExtAPIRef("storage.StorageChange")}} - : An object representing a change to a storage area. ## Properties `storage` has four properties, which represent the different types of available storage area. - {{WebExtAPIRef("storage.local")}} - : Represents the `local` storage area. Items in `local` storage are local to the machine the extension was installed on. - {{WebExtAPIRef("storage.managed")}} - : Represents the `managed` storage area. Items in `managed` storage are set by the domain administrator and are read-only for the extension. Trying to modify this namespace results in an error. - {{WebExtAPIRef("storage.session")}} - : Represents the `session` storage area. Items in `session` storage are stored in memory and are not persisted to disk. - {{WebExtAPIRef("storage.sync")}} - : Represents the `sync` storage area. Items in `sync` storage are synced by the browser, and are available across all instances of that browser that the user is logged into, across different devices. ## Events - {{WebExtAPIRef("storage.onChanged")}} - : Fired when one or more items change in any of the storage areas. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.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/storage
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/local/index.md
--- title: storage.local slug: Mozilla/Add-ons/WebExtensions/API/storage/local page-type: webextension-api-property browser-compat: webextensions.api.storage.local --- {{AddonSidebar}} Represents the `local` storage area. Items in `local` storage are local to the machine the extension is installed on. The browser may restrict the amount of data that an extension can store in the local storage area. For example: - In Chrome, an extension is limited to storing 5MB of data using this API unless it has the [`"unlimitedStorage"` permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#unlimited_storage). - In Firefox, the amount of data an extension can store is subjected to the same [storage limits](/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria#storage_limits) as applied to IndexedDB databases. Extensions that intend to store more data than this limit need the ["unlimitedStorage"](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#unlimited_storage) permission. However, extensions with the "unlimitedStorage" permission may get a quota exceeded error when the disk space used by storage exceeds the global limit. When the extension is uninstalled, its associated local storage is cleared. Also, in Firefox, you can prevent the browser from clearing local storage on uninstall by visiting `about:config` and setting these browser preferences to `true`: `"keepUuidOnUninstall"` and `"keepStorageOnUninstall"`. This feature is provided to help developers test their extensions. Extensions themselves are not able to change these preferences. Although this API is similar to {{domxref("Window.localStorage")}}, it is recommended that you don't use `Window.localStorage` in extension code. Firefox clears data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons. Data saved using the `storage.local` API is correctly persisted in these scenarios. ## Methods The `local` object implements the methods defined on the {{WebExtAPIRef("storage.StorageArea")}} type: - {{WebExtAPIRef("storage.StorageArea.get()", "storage.local.get()")}} - : Retrieves one or more items from the storage area. - {{WebExtAPIRef("storage.StorageArea.getBytesInUse()", "storage.local.getBytesInUse()")}} - : Gets the amount of storage space (in bytes) used for one or more items in the storage area. - {{WebExtAPIRef("storage.StorageArea.set()", "storage.local.set()")}} - : Stores one or more items in the storage area. If the item exists, its value is updated. - {{WebExtAPIRef("storage.StorageArea.remove()", "storage.local.remove()")}} - : Removes one or more items from the storage area. - {{WebExtAPIRef("storage.StorageArea.clear()", "storage.local.clear()")}} - : Removes all items from the storage area. ## Events The `local` object implements the events defined on the {{WebExtAPIRef("storage.StorageArea")}} type: - {{WebExtAPIRef("storage.StorageArea.onChanged", "storage.local.onChanged")}} - : Fires when one or more items in the storage area change. {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/#property-local) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.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/storage
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/onchanged/index.md
--- title: storage.onChanged slug: Mozilla/Add-ons/WebExtensions/API/storage/onChanged page-type: webextension-api-event browser-compat: webextensions.api.storage.onChanged --- {{AddonSidebar}} Fired when {{WebExtAPIRef('storage.StorageArea.set','storageArea.set')}}, {{WebExtAPIRef('storage.StorageArea.remove','storageArea.remove')}}, or {{WebExtAPIRef('storage.StorageArea.clear','storageArea.clear')}} executes against a storage area. When this event is triggered by {{WebExtAPIRef('storage.StorageArea.set','storageArea.set')}}, it's possible to receive a callback when there is no change to the underlying data. Also, the information returned includes all keys within the storage area {{WebExtAPIRef('storage.StorageArea.set','storageArea.set')}} ran against. The extension can determine the changes that occurred by examining the content of the `changes` argument received by the `onChanged` listeners. ## Syntax ```js-nolint browser.storage.onChanged.addListener(listener) browser.storage.onChanged.removeListener(listener) browser.storage.onChanged.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed these arguments: - `changes` - : `object`. Object describing the change. This object contains properties for all the keys in the storage area included in the {{WebExtAPIRef('storage.StorageArea.set','storageArea.set')}} call, even if key values are unchanged. The name of each property is the name of each key. The value of each key is a {{WebExtAPIRef('storage.StorageChange')}} object describing the change to that item. - `areaName` - : `string`. The name of the storage area (`"sync"`, `"local"`, or `"managed"`) to which the changes were made. ## Browser compatibility {{Compat}} ## Examples ```js /* Log the storage area that changed, then for each item changed, log its old value and its new value. */ function logStorageChange(changes, area) { console.log(`Change in storage area: ${area}`); const changedItems = Object.keys(changes); for (const item of changedItems) { console.log(`${item} has changed:`); console.log("Old value: ", changes[item].oldValue); console.log("New value: ", changes[item].newValue); } } browser.storage.onChanged.addListener(logStorageChange); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/#event-onChanged) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.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/storage
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagechange/index.md
--- title: storage.StorageChange slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageChange page-type: webextension-api-type browser-compat: webextensions.api.storage.StorageChange --- {{AddonSidebar}} `StorageChange` is an object representing a change to a storage area. ## Type `StorageChange` objects contain the following properties: - `oldValue` {{optional_inline}} - : The old value of the item, if there was an old value. This can be any data type. - `newValue` {{optional_inline}} - : The new value of the item, if there is a new value. This can be any data type. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/#type-StorageChange) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.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/storage
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea/index.md
--- title: storage.StorageArea slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea page-type: webextension-api-type browser-compat: webextensions.api.storage.StorageArea --- {{AddonSidebar}} StorageArea is an object representing a storage area. ## Type Values of this type are objects. ## Methods - {{WebExtAPIRef("storage.StorageArea.get()")}} - : Retrieves one or more items from the storage area. - {{WebExtAPIRef("storage.StorageArea.getBytesInUse()")}} - : Gets the amount of storage space (in bytes) used one or more items being stored in the storage area. - {{WebExtAPIRef("storage.StorageArea.set()")}} - : Stores one or more items in the storage area. If an item already exists, its value will be updated. - {{WebExtAPIRef("storage.StorageArea.setAccessLevel()")}} - : Sets the access level for the storage area. - {{WebExtAPIRef("storage.StorageArea.remove()")}} - : Removes one or more items from the storage area. - {{WebExtAPIRef("storage.StorageArea.clear()")}} - : Removes all items from the storage area. ## Events - {{WebExtAPIRef("storage.StorageArea.onChanged")}} - : Fires when one or more items in the storage area change. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/#type-StorageArea) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.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/storage/storagearea
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea/remove/index.md
--- title: StorageArea.remove() slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/remove page-type: webextension-api-function browser-compat: webextensions.api.storage.StorageArea.remove --- {{AddonSidebar}} Removes one or more items from the storage area. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removingItem = browser.storage.<storageType>.remove( keys // string, or array of strings ) ``` `<storageType>` is one of the writable storage types — {{WebExtAPIRef("storage.local")}}, {{WebExtAPIRef("storage.session")}}, or {{WebExtAPIRef("storage.sync")}}. ### Parameters - `keys` - : A string, or array of strings, representing the key(s) of the item(s) to be removed. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments if the operation succeeded. If the operation failed, the promise will be rejected with an error message. ## Browser compatibility {{Compat}} ## Examples Remove a single item: ```js function onRemoved() { console.log("OK"); } function onError(e) { console.log(e); } let removeKitten = browser.storage.sync.remove("kitten"); removeKitten.then(onRemoved, onError); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json) in the Chromium code.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea/onchanged/index.md
--- title: storage.StorageArea.onChanged slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/onChanged page-type: webextension-api-event browser-compat: webextensions.api.storage.StorageArea.onChanged --- {{AddonSidebar}} Fires when one or more items in a storage area change. Compared to {{WebExtAPIRef("storage.onChanged")}}, this event enables you to listen for changes in one of the storage areas: `local`, `managed`, `session`, and `sync`. ## Syntax ```js-nolint // local can also be sync, managed, or session browser.storage.local.onChanged.addListener(listener) browser.storage.local.onChanged.removeListener(listener) browser.storage.local.onChanged.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stops listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Checks 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: - `changes` - : `object`. Object describing the change. This contains one property for each key that changed. The name of the property is the name of the key that changed, and its value is a {{WebExtAPIRef('storage.StorageChange')}} object describing the change to that item. ## Examples ```js /* Log the old value and its new value of changes in the local storage. */ function logStorageChange(changes) { const changedItems = Object.keys(changes); for (const item of changedItems) { console.log(`${item} has changed:`); console.log("Old value: ", changes[item].oldValue); console.log("New value: ", changes[item].newValue); } } browser.storage.local.onChanged.addListener(logStorageChange); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/#event-StorageArea-onChanged) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.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/storage/storagearea
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea/get/index.md
--- title: StorageArea.get() slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/get page-type: webextension-api-function browser-compat: webextensions.api.storage.StorageArea.get --- {{AddonSidebar}} Retrieves one or more items from the storage area. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let results = browser.storage.<storageType>.get( keys // null, string, object or array of strings ) ``` `<storageType>` will be one of the writable storage types — {{WebExtAPIRef("storage.sync", "sync")}}, {{WebExtAPIRef("storage.local", "local")}}, or {{WebExtAPIRef("storage.managed", "managed")}}. ### Parameters - `keys` - : A key (`string`) or keys (an array of strings, _or_ an object specifying default values) to identify the item(s) to be retrieved from storage. If you pass an empty object or array here, an empty object will be retrieved. If you pass `null`, or an undefined value, the entire storage contents will be retrieved. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to a `results` object, containing every object in `keys` that was found in the storage area. If `keys` is an object, keys that are not found in the storage area will have their values given by the `keys` object. If the operation failed, the promise is rejected with an error message. If managed storage is not set, `undefined` will be returned. > **Warning:** When used within a content script in Firefox versions prior to 52, the Promise returned by `browser.storage.local.get()` is fulfilled with an Array containing one Object. The Object in the Array contains the `keys` found in the storage area, as described above. > > The Promise is correctly fulfilled with an Object when used in the background context (background scripts, popups, options pages, etc.). > > When this API is used as `chrome.storage.local.get()`, it correctly passes an Object to the callback function. ## Browser compatibility {{Compat}} ## Examples Suppose storage contains two items: ```js // storage contains two items, // "kitten" and "monster" browser.storage.local.set({ kitten: { name: "Mog", eats: "mice" }, monster: { name: "Kraken", eats: "people" }, }); ``` Define success and failure handlers for the promise: ```js function onGot(item) { console.log(item); } function onError(error) { console.log(`Error: ${error}`); } ``` With no `keys` argument, retrieve everything: ```js let gettingItem = browser.storage.local.get(); gettingItem.then(onGot, onError); // -> Object { kitten: Object, monster: Object } ``` With an empty `keys` argument, return nothing: ```js // with an empty array, retrieve nothing let gettingItem = browser.storage.local.get([]); gettingItem.then(onGot, onError); // -> Object { } ``` With the name of an object, retrieve the match: ```js let gettingItem = browser.storage.local.get("kitten"); gettingItem.then(onGot, onError); // -> Object { kitten: Object } ``` With an array of object names, retrieve all matches: ```js let gettingItem = browser.storage.local.get([ "kitten", "monster", "grapefruit", ]); gettingItem.then(onGot, onError); // -> Object { kitten: Object, monster: Object } ``` With an object with object names as keys and the default value as value: ```js let gettingItem = browser.storage.local.get({ kitten: "no kitten", monster: "no monster", grapefruit: { name: "Grape Fruit", eats: "Water", }, }); // -> Object { kitten: Object, monster: Object, grapefruit: Object } ``` {{WebExtExamples}} ### Chrome examples ```js chrome.storage.local.get("kitten", (items) => { console.log(items.kitten); // -> {name:"Mog", eats:"mice"} }); ``` Or with an arrow function ```js chrome.storage.local.get("kitten", (items) => { console.log(items.kitten); // -> {name:"Mog", eats:"mice"} }); ``` Or using a Promise ```js let gettingItem = new Promise((resolve) => chrome.storage.local.get("kitten", resolve), ); gettingItem.then(onGot); // -> Object { kitten: Object } ``` > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json) in the Chromium code.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea/set/index.md
--- title: StorageArea.set() slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/set page-type: webextension-api-function browser-compat: webextensions.api.storage.StorageArea.set --- {{AddonSidebar}} Stores one or more items in the storage area or updates stored items. When you store or update a value using this API, the {{WebExtAPIRef("storage.onChanged")}} event fires. Note that when storing items in the [`sync`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/sync) storage area, the browser enforces quotas on the amount of data each extension can store. See [Storage quotas for sync data](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/sync#storage_quotas_for_sync_data). This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let settingItem = browser.storage.<storageType>.set( keys // object ) ``` `<storageType>` is one of the writable storage types — {{WebExtAPIRef("storage.local")}}, {{WebExtAPIRef("storage.session")}}, or {{WebExtAPIRef("storage.sync")}}. ### Parameters - `keys` - : An object containing one or more key/value pairs to be stored. If an item is in storage, its value is updated. Values can be [primitive](/en-US/docs/Glossary/Primitive) (such as a number, boolean, or string), {{jsxref("Array")}}, or {{jsxref("Object")}} types. It's generally not possible to store other types, such as `Function`, `Date`, `RegExp`, `Set`, `Map`, `ArrayBuffer`, and so on. Some unsupported types restore as an empty object, while others cause `set()` to throw an error. The behavior is browser-specific. > **Note:** If you want to remove keys from storage, use {{WebExtAPIRef("storage.storageArea.remove")}}. If you want to overwrite a value with a void value, use `null`, i.e., `key: null`. ### Return value A {{jsxref("Promise")}} that is fulfilled with no arguments if the operation succeeds. If the operation fails, the promise is rejected with an error message. ## Examples ```js function setItem() { console.log("OK"); } function gotKitten(item) { console.log(`${item.kitten.name} has ${item.kitten.eyeCount} eyes`); } function gotMonster(item) { console.log(`${item.monster.name} has ${item.monster.eyeCount} eyes`); } function onError(error) { console.log(error); } // define 2 objects let monster = { name: "Kraken", tentacles: true, eyeCount: 10, }; let kitten = { name: "Moggy", tentacles: false, eyeCount: 2, }; // store the objects browser.storage.local.set({ kitten, monster }).then(setItem, onError); browser.storage.local.get("kitten").then(gotKitten, onError); browser.storage.local.get("monster").then(gotMonster, onError); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json) in the Chromium code.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea/getbytesinuse/index.md
--- title: StorageArea.getBytesInUse() slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/getBytesInUse page-type: webextension-api-function browser-compat: webextensions.api.storage.StorageArea.getBytesInUse --- {{AddonSidebar}} Gets the amount of storage space, in bytes, used one or more items being stored in the storage area. This function only exists in browser.storage.sync It does not exist in browser.storage.local See <https://bugzil.la/1385832> This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let gettingSpace = browser.storage.<storageType>.getBytesInUse( keys // null, string, or array of strings ) ``` `<storageType>` can only be {{WebExtAPIRef("storage.sync")}}, not {{WebExtAPIRef("storage.local")}} because of [this bug](https://bugzil.la/1385832). ### Parameters - `keys` - : A key (string) or keys (an array of strings) to identify the item(s) whose storage space you want to retrieve. If an empty array is passed in, 0 will be returned. If you pass `null` or `undefined` here, the function will return the space used by the entire storage area. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an integer, `bytesUsed`, representing the storage space used by the objects that were specified in `keys`. If the operation failed, the promise will be rejected with an error message. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json) in the Chromium code.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea/clear/index.md
--- title: StorageArea.clear() slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/clear page-type: webextension-api-function browser-compat: webextensions.api.storage.StorageArea.clear --- {{AddonSidebar}} Removes all items from the storage area. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let clearing = browser.storage.<storageType>.clear() ``` `<storageType>` is one of the writable storage types — {{WebExtAPIRef("storage.local")}}, {{WebExtAPIRef("storage.session")}}, or {{WebExtAPIRef("storage.sync")}} ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments if the operation succeeded. If the operation failed, the promise will be rejected with an error message. ## Browser compatibility {{Compat}} ## Examples ```js function onCleared() { console.log("OK"); } function onError(e) { console.log(e); } let clearStorage = browser.storage.local.clear(); clearStorage.then(onCleared, onError); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json) in the Chromium code.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/storagearea/setaccesslevel/index.md
--- title: StorageArea.setAccessLevel() slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/setAccessLevel page-type: webextension-api-function browser-compat: webextensions.api.storage.StorageArea.setAccessLevel --- {{AddonSidebar}} Sets the access level for the storage area. This method is only supported for the `storage.session` StorageArea. Unlike other storage areas, `storage.session` is only available to privileged (trusted) extension contexts. This `setAccessLevel` method is used to expose the session storage area to content scripts too. By default, all other storage areas are exposed to all extension contexts, including content scripts. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint await browser.storage.<storageType>.setAccessLevel( accessLevel // string ) ``` `<storageType>` can be the {{WebExtAPIRef("storage.session")}} storage type. ### Parameters - `accessLevel` - : `String`. The access level of the storage area. Possible values are `TRUSTED_CONTEXTS` or `TRUSTED_AND_UNTRUSTED_CONTEXTS`. ### Return value A {{jsxref("Promise")}} that is fulfilled with no arguments if the operation succeeded. If the operation failed, the promise is rejected with an error message. {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json) in the Chromium code.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/session/index.md
--- title: storage.session slug: Mozilla/Add-ons/WebExtensions/API/storage/session page-type: webextension-api-property browser-compat: webextensions.api.storage.session --- {{AddonSidebar}} Represents the `session` storage area. Items in `session` storage are stored in memory for the duration of the browser session and are not persisted to disk. By default, it's not exposed to content scripts, but this behavior can be changed through {{WebExtAPIRef("storage.StorageArea.setAccessLevel", "storage.session.setAccessLevel()")}}. The amount of data that an extension can store in the session storage area is limited to 10 MB, unless stated otherwise in the [browser compatibility table](#browser_compatibility). When the browser stops, all session storage is cleared. When the extension is uninstalled, its associated session storage is cleared. ## Methods The `session` object implements the methods defined on the {{WebExtAPIRef("storage.StorageArea")}} type: - {{WebExtAPIRef("storage.StorageArea.get()", "storage.session.get()")}} - : Retrieves one or more items from the storage area. - {{WebExtAPIRef("storage.StorageArea.getBytesInUse()", "storage.session.getBytesInUse()")}} - : Gets the amount of storage space (in bytes) used for one or more items in the storage area. - {{WebExtAPIRef("storage.StorageArea.set()", "storage.session.set()")}} - : Stores one or more items in the storage area. If the item exists, its value is updated. - {{WebExtAPIRef("storage.StorageArea.setAccessLevel", "storage.session.setAccessLevel()")}} - : Sets the access level for the storage area. - {{WebExtAPIRef("storage.StorageArea.remove()", "storage.session.remove()")}} - : Removes one or more items from the storage area. - {{WebExtAPIRef("storage.StorageArea.clear()", "storage.session.clear()")}} - : Removes all items from the storage area. ## Events The `session` object implements the events defined on the {{WebExtAPIRef("storage.StorageArea")}} type: - {{WebExtAPIRef("storage.StorageArea.onChanged", "storage.session.onChanged")}} - : Fires when one or more items in the storage area change. {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/#property-session) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.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/storage
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/managed/index.md
--- title: storage.managed slug: Mozilla/Add-ons/WebExtensions/API/storage/managed page-type: webextension-api-property browser-compat: webextensions.api.storage.managed --- {{AddonSidebar}} A {{WebExtAPIRef("storage.StorageArea")}} object that represents the `managed` storage area. Items in `managed` storage are set by the domain administrator or other native applications installed on the user's computer and are read-only for the extension. Trying to modify this storage area results in an error. ## Provisioning managed storage The procedure for provisioning managed storage varies between browsers. For Chrome instructions, see the ["Manifest for storage areas"](https://developer.chrome.com/docs/extensions/mv3/manifest/storage/) article. For Firefox, you need to create a JSON manifest file in a specific format and location. For the details of manifest syntax and location, see [Native manifests](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_manifests). Here's an example manifest: ```json { "name": "favourite-colour-examples@mozilla.org", "description": "ignored", "type": "storage", "data": { "colour": "management thinks it should be blue!" } } ``` Given this manifest, the [favourite-colour](https://github.com/mdn/webextensions-examples/tree/main/favourite-colour) extension could access the data using code like this: ```js let storageItem = browser.storage.managed.get("colour"); storageItem.then((res) => { console.log(`Managed colour is: ${res.colour}`); }); ``` ## Methods The `managed` object implements the methods defined on the {{WebExtAPIRef("storage.StorageArea")}} type: - {{WebExtAPIRef("storage.StorageArea.get()", "storage.managed.get()")}} - : Retrieves one or more items from the storage area. - {{WebExtAPIRef("storage.StorageArea.getBytesInUse()", "storage.managed.getBytesInUse()")}} - : Gets the amount of storage space (in bytes) used for one or more items in the storage area. ## Events The `managed` object implements the events defined on the {{WebExtAPIRef("storage.StorageArea")}} type: - {{WebExtAPIRef("storage.StorageArea.onChanged", "storage.managed.onChanged")}} - : Fires when one or more items in the storage area change. {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/#property-managed) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.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/storage
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/storage/sync/index.md
--- title: storage.sync slug: Mozilla/Add-ons/WebExtensions/API/storage/sync page-type: webextension-api-property browser-compat: webextensions.api.storage.sync --- {{AddonSidebar}} Represents the `sync` storage area. Items in `sync` storage are synced by the browser. The data is then available on all instances of the browser the user is logged into (for example, when using a Mozilla account on desktop versions of Firefox or a Google account on Chrome) across different devices. For desktop Firefox, a user must have `Add-ons` selected in the "Sync" section in `"about:preferences"`. Firefox for Android does not synchronize data with the user's account. See [Firefox bug 1316442](https://bugzil.la/1316442). The implementation of `storage.sync` in Firefox relies on the Add-on ID. If you use `storage.sync`, you must set an ID for your extension using the [`browser_specific_settings`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) manifest.json key. The main use case of this API is to store preferences about your extension and allow the user to sync them to different profiles. ## Storage quotas for sync data The browser enforces limits on the amount of data each extension is allowed to store in the sync area: <table class="standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Description</th> <th scope="col">Value in bytes</th> </tr> </thead> <tbody> <tr> <td>Maximum total size</td> <td> The maximum total amount of data that each extension is allowed to store in the sync storage area, as measured by the JSON stringification of every value plus every key's length. </td> <td>102400</td> </tr> <tr> <td>Maximum item size</td> <td> The maximum size of any one item that each extension is allowed to store in the sync storage area, as measured by the JSON stringification of the item's value plus the length of its key. </td> <td>8192</td> </tr> <tr> <td>Maximum number of items</td> <td> The maximum number of items that each extension can store in the sync storage area. </td> <td><p>512</p></td> </tr> </tbody> </table> If an extension attempts to store items that exceed these limits, calls to {{WebExtAPIRef("storage.StorageArea.set()", "storage.sync.set()")}} are rejected with an error. An extension can use {{WebExtAPIRef("storage.StorageArea.getBytesInUse()", "storage.sync.getBytesInUse()")}} to find out how much of its quota is in use. ## Synchronization process In Firefox, extension data is synced every 10 minutes or whenever the user selects **Sync Now** (in **Settings** > **Sync** or from the Mozilla account icon). When the browser performs a sync, for each key stored, it: - compares the value on the server with the value at the last sync; if they are different, the value from the server is written to the key in the browser's sync storage. - compares the browser's sync storage values with the value on the server; if they are different, writes the browser's key value to the server. This means that, for each key, a change on the server takes precedence over a change in the browser's sync storage. This mechanism is generally OK for data such as user preferences or other global settings changed by the user. However, a key's value can be updated on one browser and synchronized then updated on a second browser before the second browser is synchronized, resulting in the local update being overwritten during sync. This mechanism is, therefore, not ideal for data aggregated across devices, such as a count of page views or how many times an option is used. To handle such cases, use {{WebExtAPIRef("storage.StorageArea.onChanged", "storage.sync.onChanged")}} to listen for sync updates from the server (for example, a count of page views on another browser instance). Then adjust the value locally to take the remote value into account (for example, update the total views based on the remote count and new local count). ## Methods The `sync` object implements the methods defined on the {{WebExtAPIRef("storage.StorageArea")}} type: - {{WebExtAPIRef("storage.StorageArea.get()", "storage.sync.get()")}} - : Retrieves one or more items from the storage area. - {{WebExtAPIRef("storage.StorageArea.getBytesInUse()", "storage.sync.getBytesInUse()")}} - : Gets the amount of storage space (in bytes) used for one or more items in the storage area. - {{WebExtAPIRef("storage.StorageArea.set()", "storage.sync.set()")}} - : Stores one or more items in the storage area. If the item exists, its value is updated. - {{WebExtAPIRef("storage.StorageArea.remove()", "storage.sync.remove()")}} - : Removes one or more items from the storage area. - {{WebExtAPIRef("storage.StorageArea.clear()", "storage.sync.clear()")}} - : Removes all items from the storage area. ## Events The `sync` object implements the events defined on the {{WebExtAPIRef("storage.StorageArea")}} type: - {{WebExtAPIRef("storage.StorageArea.onChanged", "storage.sync.onChanged")}} - : Fires when one or more items in the storage area change. {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.storage`](https://developer.chrome.com/docs/extensions/reference/storage/#property-sync) API. This documentation is derived from [`storage.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.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/types/index.md
--- title: types slug: Mozilla/Add-ons/WebExtensions/API/types page-type: webextension-api --- {{AddonSidebar}} Defines the `BrowserSetting` type, which is used to represent a browser setting. ## Types - {{WebExtAPIRef("types.BrowserSetting")}} - : Represents a browser setting. ## Browser compatibility {{WebExtExamples("h2")}} > **Note:** > > This API is based on Chromium's [`chrome.types`](https://developer.chrome.com/docs/extensions/reference/types/) API. <!-- // 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/types
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/types/browsersetting/index.md
--- title: BrowserSetting slug: Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting page-type: webextension-api-type browser-compat: webextensions.api.types.BrowserSetting --- {{AddonSidebar}} A `BrowserSetting` is an object representing a browser setting. It provides methods to set and get the setting's underlying value, to clear any change you've made to it, and to listen for changes to its value. Note that while this object is based on the [ChromeSetting](https://developer.chrome.com/docs/extensions/reference/types/#type-ChromeSetting) type, this object does not distinguish between setting the value in normal browsing windows and in private browsing windows. This means that all parts of the API relating to private browsing (such as the `scope` option to `ChromeSetting.set()`) are not implemented. ## Methods - {{WebExtAPIRef("types.BrowserSetting.get()")}} - : Get the current value of the setting, and an enumeration representing how the setting is currently controlled. - {{WebExtAPIRef("types.BrowserSetting.set()")}} - : Set the setting to a new value. - {{WebExtAPIRef("types.BrowserSetting.clear()")}} - : Clear any change made to the setting by this extension. ## Events - {{WebExtAPIRef("types.BrowserSetting.onChange")}} - : Fired when the setting's value changes. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.types`](https://developer.chrome.com/docs/extensions/reference/types/) API. <!-- // 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/types/browsersetting
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/types/browsersetting/get/index.md
--- title: get() slug: Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting/get page-type: webextension-api-function --- {{AddonSidebar}} The `BrowserSetting.get()` method gets the current value of the browser setting, and an enumeration indicating how the setting's value is currently controlled. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let getting = setting.get( details // object ) ``` ### Parameters - `details` - : An empty object. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an object with the following properties: - `value` - : The value of the setting. The type of this property is determined by the particular setting. - `levelOfControl` - : `string`. This represents the way the setting is currently controlled. You can use it to check whether you can modify the setting. See [`BrowserSetting.set()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting/set) for details. Its value may be any of the following:<table class="fullwidth-table standard-table"> <tbody> <tr> <td><code>"not_controllable"</code></td> <td>Extensions are not allowed to modify this setting.</td> </tr> <tr> <td><code>"controlled_by_other_extensions"</code></td> <td> Another extension that was installed after this one has modified this setting. </td> </tr> <tr> <td><code>"controllable_by_this_extension"</code></td> <td>This extension is allowed to modify the setting.</td> </tr> <tr> <td><code>"controlled_by_this_extension"</code></td> <td>This extension has already modified the setting.</td> </tr> </tbody> </table> ## Browser compatibility See {{WebExtAPIRef("types.BrowserSetting")}}. ## Example Log the value and level of control for the `networkPredictionEnabled` property of the {{WebExtAPIRef("privacy.network")}} object, for private browsing windows. Note that this requires the "privacy" browser permission. ```js let getting = browser.privacy.network.networkPredictionEnabled.get({}); getting.then((got) => { console.log(`Value: ${got.value}`); console.log(`Control: ${got.levelOfControl}`); }); ``` {{WebExtExamples}} > **Note:** > > This API is based on Chromium's [`chrome.types`](https://developer.chrome.com/docs/extensions/reference/types/) API. <!-- // 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/types/browsersetting
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/types/browsersetting/set/index.md
--- title: set() slug: Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting/set page-type: webextension-api-function --- {{AddonSidebar}} Use `BrowserSetting.set()` to change the browser setting to a new value. There are some rules that can restrict when extensions are able to change settings: - some settings are locked, so they can't be changed by extensions at all - if multiple extensions try to modify the same setting, then extensions are given a precedence ordering based on when they were installed. More-recently installed extensions have precedence over less-recently installed extension. This means that if extension X tries to change a setting: 1. If the setting is locked, then the setting is not changed. However, X's change is remembered, and it is stored in a queue, ordered by X's precedence relative to any other extensions that tried to change the setting. If the setting becomes unlocked later on, the first extension in the queue gets to change the setting. 2. Otherwise, if no other extension has already changed the setting, then X succeeds in changing the setting, and is then said to "control" the setting. 3. Otherwise, if a lower-precedence extension Y has already changed the setting, then X succeeds in changing the setting, and now controls the setting. However, Y's change is remembered, and is stored in a queue in precedence order. If X subsequently clears its value, or if X is disabled or uninstalled, the first extension in the queue gets to make its change to the setting. 4. Otherwise, if a higher-precedence extension Z has already changed the setting, then X does not succeed in changing the setting, but its change is queued. If Z subsequently clears its value, or if Z is disabled or uninstalled, the first extension in the queue gets to make its change to the setting. An extension can find out which of these scenarios applies by examining the "`levelOfControl`" property returned from a call to [`BrowserSetting.get()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting/get). The `BrowserSetting.set()` method returns a Promise that resolves to a boolean: if an attempt to change a setting actually results in the setting being changed (scenarios 2 and 3 above) the boolean is `true`: otherwise it is `false`. ## Syntax ```js-nolint let setting = setting.set( details // object ) ``` ### Parameters - `details` - : An object that must contain the following property: - `value` - : `any`. The value you want to change the setting to. Its type depends on the particular setting. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a `boolean`: `true` if the setting was modified, `false` otherwise (for example, because the extension did not control the setting). ## Browser compatibility See {{WebExtAPIRef("types.BrowserSetting")}}. ## Example Modify the `hyperlinkAuditingEnabled` setting (this requires the "privacy" permission): ```js function onSet(result) { if (result) { console.log("Value was updated"); } else { console.log("Value was not updated"); } } browser.browserAction.onClicked.addListener(() => { let setting = browser.privacy.websites.hyperlinkAuditingEnabled.set({ value: false, }); setting.then(onSet); }); ``` {{WebExtExamples}} > **Note:** > > This API is based on Chromium's [`chrome.types`](https://developer.chrome.com/docs/extensions/reference/types/) API. <!-- // 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/types/browsersetting
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/types/browsersetting/onchange/index.md
--- title: BrowserSetting.onChange slug: Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting/onChange page-type: webextension-api-event browser-compat: webextensions.api.types.BrowserSetting.onChange --- {{AddonSidebar}} The `BrowserSetting.onChange` event is fired when the setting is changed. On Firefox, it doesn't fire if the change has been made through `about:config`. ## Syntax ```js-nolint BrowserSetting.onChange.addListener(listener) BrowserSetting.onChange.removeListener(listener) BrowserSetting.onChange.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: - `details` - : An `object` containing details of the change that occurred. Its properties are as follows: - `value` - : The new value of the setting. The type of this property is determined by the particular setting. - `levelOfControl` - : `string`. This represents the way the setting is currently controlled. You can use it to check whether you can modify the setting. See [`BrowserSetting.set()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting/set) for details. Its value may be any of the following:<table class="fullwidth-table standard-table"> <tbody> <tr> <td><code>"not_controllable"</code></td> <td>Extensions are not allowed to modify this setting.</td> </tr> <tr> <td><code>"controlled_by_other_extensions"</code></td> <td> Another extension that was installed after this one has modified this setting. </td> </tr> <tr> <td><code>"controllable_by_this_extension"</code></td> <td>This extension is allowed to modify the setting.</td> </tr> <tr> <td><code>controlled_by_this_extension"</code></td> <td>This extension has already modified the setting.</td> </tr> </tbody> </table> ## Browser compatibility {{Compat}} ## Examples {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.types`](https://developer.chrome.com/docs/extensions/reference/types/) API. <!-- // 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/types/browsersetting
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/types/browsersetting/clear/index.md
--- title: clear() slug: Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting/clear page-type: webextension-api-function --- {{AddonSidebar}} Use `BrowserSetting.clear()` to clear any changes the extension has made to the browser setting. The browser setting will revert to its previous value. The extension will also give up control of the setting, allowing an extension with lower precedence (that is, an extension that was installed before this one) to modify the setting. See [`BrowserSetting.set()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting/set) to learn more about controlling settings. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). If clearing the value failed, the promise resolves to `false`. If clearing the value succeeded it resolves to `true`. ## Syntax ```js-nolint let clearing = setting.clear( details // object ) ``` ### Parameters - `details` - : An empty object. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a `boolean`: `true` if the setting was cleared, `false` otherwise. ## Browser compatibility See {{WebExtAPIRef("types.BrowserSetting")}}. ## Example Clear the `webRTCIPHandlingPolicy` setting: ```js function onCleared(result) { if (result) { console.log("Setting was cleared"); } else { console.log("Setting was not cleared"); } } let clearing = browser.privacy.network.webRTCIPHandlingPolicy.clear({}); clearing.then(onCleared); ``` {{WebExtExamples}} > **Note:** > > This API is based on Chromium's [`chrome.types`](https://developer.chrome.com/docs/extensions/reference/types/) API. <!-- // 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/topsites/index.md
--- title: topSites slug: Mozilla/Add-ons/WebExtensions/API/topSites page-type: webextension-api browser-compat: webextensions.api.topSites --- {{AddonSidebar}} Use the topSites API to get an array containing pages that the user has visited frequently. Browsers maintain this to help the user get back to these places easily. For example, Firefox by default provides a list of the most-visited pages in the "New Tab" page. To use the topSites API you must have the "topSites" [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions). ## Types - {{WebExtAPIRef("topSites.MostVisitedURL")}} - : An object containing the title and URL of a website. ## Methods - {{WebExtAPIRef("topSites.get()")}} - : Gets an array containing all the sites listed in the browser's "New Tab" page. Note that the number of sites returned here is browser-specific, and the particular sites returned will probably be specific to the user, based on their browsing history. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.topSites`](https://developer.chrome.com/docs/extensions/reference/topSites/) API. <!-- // 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/topsites
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/topsites/get/index.md
--- title: topSites.get() slug: Mozilla/Add-ons/WebExtensions/API/topSites/get page-type: webextension-api-function browser-compat: webextensions.api.topSites.get --- {{AddonSidebar}} Gets an array containing information about pages that the user has visited often and recently. Browsers keep a list of pages that the user visits often and recently. They use this list to help the user get back to these places easily. For example, Firefox by default provides a list of the most-visited pages in the "New Tab" page. To determine which pages appear in the list, and the order in which they appear, the browser combines "frequency" - how often the user has visited the page - and "recency" - how recently the user visited the page. The browser may then apply further filtering to this list before presenting it to the user. For example, in Firefox the "New Tab" page only lists one page per domain, and the user is able to block pages from appearing in the list. The `topSites.get()` API enables an extension to get access to this list. Called without any options, it will provide the filtered list of pages - that is, the one that appears in the "New Tab" page. However, by providing various options it's possible for an extension to get the unfiltered list of pages. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). To use the topSites API you must have the "topSites" [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions). ## Syntax ```js-nolint let gettingTopSites = browser.topSites.get( options // object ) ``` ### Parameters - `options` - : `object`. Options to modify the list of pages returned. This may include any of the following properties: - `includeBlocked` {{optional_inline}} - : `Boolean`. Include pages that the user has removed from the "New Tab" page. Defaults to `false`. - `includeFavicon` {{optional_inline}} - : `Boolean`. Include favicons in the results, for pages where they are available. Defaults to `false`. - `includePinned` {{optional_inline}} - : `Boolean`. Includes sites that the user has pinned to the Firefox new tab. Defaults to `false`. - `includeSearchShortcuts` {{optional_inline}} - : `Boolean`. Includes search shortcuts that appear on the Firefox new tab. Defaults to `false`. - `limit` {{optional_inline}} - : `Integer`. The number of pages to return. This must be a number between 1 and 100, inclusive. Defaults to 12. - `newtab` {{optional_inline}} - : `Boolean`. If included, the method returns the list of pages returned when the user opens a new tab. If included, and set to `true`, the method ignores all other parameters except `limit` and `includeFavicon`. Defaults to `false`. - `onePerDomain` {{optional_inline}} - : `Boolean`. Only include one page per domain. Defaults to `true`. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). This will be fulfilled with an array of {{WebExtAPIRef("topSites.MostVisitedURL", "MostVisitedURL")}} objects, one for each page listed in the browser's "New Tab" page. If an error occurs, the promise will be rejected with an error message. ## Browser compatibility {{Compat}} ## Examples This code logs the title and URL for all pages in the "New Tab" page: ```js function logTopSites(topSitesArray) { for (const topSite of topSitesArray) { console.log(`Title: ${topSite.title}, URL: ${topSite.url}`); } } function onError(error) { console.error(error); } browser.topSites.get().then(logTopSites, onError); ``` This code logs the title and URL for all top pages, including ones the user has blocked, and potentially including multiple pages in the same domain: ```js function logTopSites(topSitesArray) { for (const topSite of topSitesArray) { console.log(`Title: ${topSite.title}, URL: ${topSite.url}`); } } function onError(error) { console.error(error); } browser.topSites .get({ includeBlocked: true, onePerDomain: false, }) .then(logTopSites, onError); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.topSites`](https://developer.chrome.com/docs/extensions/reference/topSites/) API. <!-- // 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/topsites
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/topsites/mostvisitedurl/index.md
--- title: topSites.MostVisitedURL slug: Mozilla/Add-ons/WebExtensions/API/topSites/MostVisitedURL page-type: webextension-api-type browser-compat: webextensions.api.topSites.MostVisitedURL --- {{AddonSidebar}} The `MostVisitedURL` type contains two properties: the title of a page and its URL. ## Type Values of this type are objects. They contain the following properties: - `favicon` {{optional_inline}} - : `String`. A data: URL containing the favicon for the page, if `includeFavicon` was given in {{WebExtAPIRef("topSites.get()")}} and the favicon was available. - `title` - : `String`. The page's title. - `url` - : `String`. The page's URL. ## Browser compatibility {{Compat}} ## Examples {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.topSites`](https://developer.chrome.com/docs/extensions/reference/topSites/) API. <!-- // 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/dns/index.md
--- title: dns slug: Mozilla/Add-ons/WebExtensions/API/dns page-type: webextension-api browser-compat: webextensions.api.dns --- {{AddonSidebar}} Enables an extension to resolve domain names. To use this API, an extension must request the "dns" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) in its [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file. > **Note:** DNS will fail with NS_ERROR_UNKNOWN_PROXY_HOST if proxying DNS over socks is enabled. ## Functions - {{WebExtAPIRef("dns.resolve()")}} - : Resolves the given hostname to a DNS record. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/dns
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/dns/resolve/index.md
--- title: dns.resolve() slug: Mozilla/Add-ons/WebExtensions/API/dns/resolve page-type: webextension-api-function browser-compat: webextensions.api.dns.resolve --- {{AddonSidebar}} Resolves the given hostname to a DNS record. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let resolving = browser.dns.resolve( hostname, // string flags // array of string ) ``` ### Parameters - `hostname` - : `string`. The hostname to resolve. - `flags` {{optional_inline}} - : `array` of `string`. Flags to modify the way the hostname is resolved. Any omitted flags default to `false`. You can pass zero or more of the following flags: - `"allow_name_collisions"`: Allow name collision results which are normally filtered out. - `"bypass_cache"`: Suppresses the internal DNS lookup cache. - `"canonical_name"`: The canonical name of the specified host will be queried. - `"disable_ipv4"`: Only IPv6 addresses will be returned. - `"disable_ipv6"`: Only IPv4 addresses will be returned. - `"disable_trr"`: Do not use the Trusted Recursive Resolver (TRR) for resolving the host name. A TRR enables resolving of host names using a dedicated [DNS-over-HTTPS](https://datatracker.ietf.org/doc/html/draft-ietf-doh-dns-over-https-02) server. - `"offline"`: Only literals and cached entries will be returned. - `"priority_low"`: The request is given lower priority. If "priority_medium" is also given, the query is given medium priority. - `"priority_medium"`: The request is given medium priority. If "priority_low" is also given, the query is given medium priority. - `"speculate"`: Indicates that the request is speculative. Speculative requests return errors if prefetching is disabled by the browser's configuration. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a `DNSRecord` object. This object can contain the following properties: - `addresses` - : `array` of `string`. The IP addresses associated with this DNS record. - `canonicalName` - : `string`. The canonical name for this record. This is only included in the response if the `"canonical_name"` flag was passed to `resolve()`. - `isTRR` - : `boolean`: `true` if the record was retrieved using a Trusted Recursive Resolver (TRR). ## Browser compatibility {{Compat}} ## Examples ```js function resolved(record) { console.log(record.addresses); } let resolving = browser.dns.resolve("example.com"); resolving.then(resolved); // > e.g. Array [ "192.0.2.172" ] ``` Bypass the cache, and ask for the canonical name: ```js function resolved(record) { console.log(record.canonicalName); console.log(record.addresses); } let resolving = browser.dns.resolve("developer.mozilla.org", [ "bypass_cache", "canonical_name", ]); resolving.then(resolved); // > e.g. xyz.us-west-2.elb.amazonaws.com // > e.g. Array [ "192.0.2.172", "198.51.100.45" ] ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/captiveportal/index.md
--- title: captivePortal slug: Mozilla/Add-ons/WebExtensions/API/captivePortal page-type: webextension-api browser-compat: webextensions.api.captivePortal --- {{AddonSidebar}} Determine the captive portal state of the user's connection. A captive portal is a web page displayed when a user first connects to a Wi-Fi network. The user provides information or acts on the captive portal web page to gain broader access to network resources, such as accepting terms and conditions or making a payment. To use this API you need to have the "captivePortal" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). ## Properties - {{WebExtAPIRef("captivePortal.canonicalURL")}} - : Return the canonical URL of the captive-portal detection page. Read-only. ## Functions - {{WebExtAPIRef("captivePortal.getLastChecked()")}} - : Returns the time, in milliseconds, since the last request was completed. - {{WebExtAPIRef("captivePortal.getState()")}} - : Returns the portal state as one of `unknown`, `not_captive`, `unlocked_portal`, or `locked_portal`. ## Events - {{WebExtAPIRef("captivePortal.onConnectivityAvailable")}} - : Fires when the captive portal service determines that the user can connect to the internet. - {{WebExtAPIRef("captivePortal.onStateChanged")}} - : Fires when the captive portal state changes. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} <!-- // 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/captiveportal
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/captiveportal/canonicalurl/index.md
--- title: captivePortal.canonicalURL slug: Mozilla/Add-ons/WebExtensions/API/captivePortal/canonicalURL page-type: webextension-api-property browser-compat: webextensions.api.captivePortal.canonicalURL --- {{AddonSidebar}} Return the canonical URL of the captive-portal detection page. Read-only. ## 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/captiveportal
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/captiveportal/onstatechanged/index.md
--- title: onStateChanged slug: Mozilla/Add-ons/WebExtensions/API/captivePortal/onStateChanged page-type: webextension-api-event browser-compat: webextensions.api.captivePortal.onStateChanged --- {{AddonSidebar}} Fires when the captive portal state changes. ## Syntax ```js-nolint browser.captivePortal.onStateChanged.addListener(listener) browser.captivePortal.onStateChanged.removeListener(listener) browser.captivePortal.onStateChanged.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `details` - : `string` The captive portal state, being one of `unknown`, `not_captive`, `unlocked_portal`, or `locked_portal`. ## Examples Handle a change in captive portal status: ```js function handlePortalStatus(portalstatusInfo) { console.log(`The portal status is now: ${portalstatusInfo.details}`); } browser.captivePortal.onStateChanged.addListener(handlePortalStatus); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/captiveportal
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/captiveportal/onconnectivityavailable/index.md
--- title: onConnectivityAvailable slug: Mozilla/Add-ons/WebExtensions/API/captivePortal/onConnectivityAvailable page-type: webextension-api-event browser-compat: webextensions.api.captivePortal.onConnectivityAvailable --- {{AddonSidebar}} Fires when the captive portal service determines that the user can connect to the internet. ## Syntax ```js-nolint browser.captivePortal.onConnectivityAvailable.addListener(listener) browser.captivePortal.onConnectivityAvailable.removeListener(listener) browser.captivePortal.onConnectivityAvailable.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: - `status` - : `string` The status of the service, being one of `captive` if there is an unlocked captive portal present or `clear` if no captive portal is detected. ## Examples Handle a change user's ability to connect to the internet: ```js function handleConnectivity(connectivityInfo) { console.log(`The captive portal status: ${connectivityInfo.status}`); } browser.captivePortal.onConnectivityAvailable.addListener(handleConnectivity); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/captiveportal
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/captiveportal/getlastchecked/index.md
--- title: getLastChecked slug: Mozilla/Add-ons/WebExtensions/API/captivePortal/getLastChecked page-type: webextension-api-function browser-compat: webextensions.api.captivePortal.getLastChecked --- {{AddonSidebar}} Returns the time since the last request was completed. ## Syntax ```js-nolint let state = browser.captivePortal.getLastChecked() ``` ### Return value A [Promise](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is fulfilled with an integer representing time in milliseconds. {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/captiveportal
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/captiveportal/getstate/index.md
--- title: getState slug: Mozilla/Add-ons/WebExtensions/API/captivePortal/getState page-type: webextension-api-function browser-compat: webextensions.api.captivePortal.getState --- {{AddonSidebar}} Returns the portal state as one of `unknown`, `not_captive`, `unlocked_portal`, or `locked_portal`. ## Syntax ```js-nolint let state = browser.captivePortal.getState() ``` ### Return value A [Promise](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is fulfilled with a string containing one of `unknown`, `not_captive`, `unlocked_portal`, or `locked_portal`. {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/notifications/index.md
--- title: notifications slug: Mozilla/Add-ons/WebExtensions/API/notifications page-type: webextension-api browser-compat: webextensions.api.notifications --- {{AddonSidebar}} Display notifications to the user, using the underlying operating system's notification mechanism. Because this API uses the operating system's notification mechanism, the details of how notifications appear and behave may differ according to the operating system and the user's settings. To use this API you need to have the "notifications" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). The notification looks the same on all desktop operating systems. Something like: ![Example notification with a bold title and regular text](notification.png) ## Types - {{WebExtAPIRef("notifications.NotificationOptions")}} - : Defines the content of a notification. - {{WebExtAPIRef("notifications.TemplateType")}} - : The type of notification. For example, this defines whether the notification can contain an image. ## Functions - {{WebExtAPIRef("notifications.clear()")}} - : Clear a specific notification, given its ID. - {{WebExtAPIRef("notifications.create()")}} - : Create and display a new notification. - {{WebExtAPIRef("notifications.getAll()")}} - : Get all notifications. - {{WebExtAPIRef("notifications.update()")}} - : Update a notification. ## Events - {{WebExtAPIRef("notifications.onButtonClicked")}} - : Fired when the user clicked a button in the notification. - {{WebExtAPIRef("notifications.onClicked")}} - : Fired when the user clicked the notification, but not on a button. - {{WebExtAPIRef("notifications.onClosed")}} - : Fired when a notification closed, either by the system or because the user dismissed it. - {{WebExtAPIRef("notifications.onShown")}} - : Fired immediately after a notification has been shown. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications/create/index.md
--- title: notifications.create() slug: Mozilla/Add-ons/WebExtensions/API/notifications/create page-type: webextension-api-function browser-compat: webextensions.api.notifications.create --- {{AddonSidebar}} Creates and displays a notification. Pass a {{WebExtAPIRef("notifications.NotificationOptions")}} to define the notification's content and behavior. You can optionally provide an ID for the notification. If you omit the ID, an ID will be generated. You can use the ID to {{WebExtAPIRef("notifications.update()", "update")}} or {{WebExtAPIRef("notifications.clear()", "clear")}} the notification. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). > **Warning:** If you call `notifications.create()` more than once in rapid succession, Firefox may end up not displaying any notification at all. ## Syntax ```js-nolint let creating = browser.notifications.create( id, // optional string options // NotificationOptions ) ``` ### Parameters - `id` {{optional_inline}} - : `string`. This is used to refer to this notification in {{WebExtAPIRef("notifications.update()")}}, {{WebExtAPIRef("notifications.clear()")}}, and event listeners. If you omit this argument or pass an empty string, then a new ID will be generated for this notification. If the ID you provide matches the ID of an existing notification from this extension, then the other notification will be cleared. - `options` - : {{WebExtAPIRef('notifications.NotificationOptions')}}. Defines the notification's content and behavior. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled when the notification is created and the display process has been started, which is before the notification is actually displayed to the user. It is fulfilled with a string representing the notification's ID. ## Examples This example displays a notification periodically, using {{WebExtAPIRef("alarms", "alarm")}}. Clicking the browser action dismisses the notification. You need the "alarms" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) to create alarms (as well as the "notifications" permission to create notifications). ```js let cakeNotification = "cake-notification"; /* CAKE_INTERVAL is set to 6 seconds in this example. Such a short period is chosen to make the extension's behavior more obvious, but this is not recommended in real life. Note that in Chrome, alarms cannot be set for less than a minute. */ let CAKE_INTERVAL = 0.1; browser.alarms.create("", { periodInMinutes: CAKE_INTERVAL }); browser.alarms.onAlarm.addListener((alarm) => { browser.notifications.create(cakeNotification, { type: "basic", iconUrl: browser.runtime.getURL("icons/cake-96.png"), title: "Time for cake!", message: "Something something cake", }); }); browser.browserAction.onClicked.addListener(() => { const clearing = browser.notifications.clear(cakeNotification); clearing.then(() => { console.log("cleared"); }); }); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/#method-create) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications/notificationoptions/index.md
--- title: notifications.NotificationOptions slug: Mozilla/Add-ons/WebExtensions/API/notifications/NotificationOptions page-type: webextension-api-type browser-compat: webextensions.api.notifications.NotificationOptions --- {{AddonSidebar}} This type contains all the data needed to: - create a notification using {{WebExtAPIRef("notifications.create()")}}, - update an existing notification using {{WebExtAPIRef("notifications.update()")}}. ## Type Values of this type are objects. They contain the properties listed below. The first three properties - `type`, `title`, `message` - are mandatory in {{WebExtAPIRef("notifications.create()")}}, but optional in {{WebExtAPIRef("notifications.update()")}}. Firefox currently: only supports the `type`, `title`, `message`, and `iconUrl` properties; and the only supported value for `type` is `'basic'`. - `type` - : {{WebExtAPIRef("notifications.TemplateType")}}. The type of notification you want. Depending on your choice here, certain other properties are either mandatory or are not permitted. - `message` - : `string`. The notification's main content. - `title` - : `string`. The notification's title. - `iconUrl` {{optional_inline}} - : `string`. A URL pointing to an icon to display in the notification. The URL can be: a data URL, a blob URL, a http or https URL, or the [relative URL of a file within the extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#relative_urls). When using an SVG image, ensure that the image includes height and width attributes, for example, `<svg width="96" height="96"…`. Otherwise, the image may not display. - `contextMessage` {{optional_inline}} - : `string`. Supplementary content to display. - `priority` {{optional_inline}} - : `number`. The notification's priority: may be 0, 1, or 2. Defaults to 0 if omitted. - `eventTime` {{optional_inline}} - : `number`. A timestamp for the notification in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `buttons` {{optional_inline}} - : `array` of `button`. An array of up to 2 buttons to include in the notification. You can listen for button clicks using {{WebExtAPIRef("notifications.onButtonClicked")}}. Each button is specified as an object with the following properties: - `title` - : `string`. Title for the button. - `iconUrl` {{optional_inline}} - : `string`. URL pointing to an icon for the button. - `imageUrl` - : `string`. A URL pointing to an image to use in the notification. The URL can be: a data URL, a blob URL, or the [relative URL](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#relative_urls) of a file within the extension. When using an SVG image, ensure that the image includes height and width attributes, for example, `<svg width="96" height="96"…`. Otherwise, the image may not display. _This property is only permitted if `type` is `"image"`. In this case, it is mandatory if the `NotificationOptions` is used in {{WebExtAPIRef("notifications.create()")}}, and optional if it is used in {{WebExtAPIRef("notifications.update()")}}._ - `items` - : `array` of `item`. An array of items to include in the notification. Depending on the settings for the operating system's notification mechanism, some of the items you provide might not be displayed. Each item is specified as an object with the following properties: - `title` - : `string`. Title to display in the item. - `message` - : `string`. Message to display in the item. _This property is only permitted if `type` is `"list"`. In this case, it is mandatory if the `NotificationOptions` is used in {{WebExtAPIRef("notifications.create()")}}, and optional if it is used in {{WebExtAPIRef("notifications.update()")}}._ - `progress` - : `integer`. An integer between 0 and 100, used to represent the current progress in a progress indicator. _This property is only permitted if `type` is `"progress"`. In this case, it is mandatory if the `NotificationOptions` is used in {{WebExtAPIRef("notifications.create()")}}, and optional if it is used in {{WebExtAPIRef("notifications.update()")}}._ Note that `appIconMaskUrl` and `isClickable` are not supported. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications/onclicked/index.md
--- title: notifications.onClicked slug: Mozilla/Add-ons/WebExtensions/API/notifications/onClicked page-type: webextension-api-event browser-compat: webextensions.api.notifications.onClicked --- {{AddonSidebar}} Fired when the user clicks a notification, but not on any of the notification's buttons (for that, see {{WebExtAPIRef("notifications.onButtonClicked")}}). ## Syntax ```js-nolint browser.notifications.onClicked.addListener(listener) browser.notifications.onClicked.removeListener(listener) browser.notifications.onClicked.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `notificationId` - : `string`. ID of the notification that the user clicked. ## Browser compatibility {{Compat}} ## Examples In this simple example we add a listener to the {{WebExtAPIRef("notifications.onClicked")}} event to listen for system notifications being clicked. When this occurs, we log an appropriate message to the console. ```js browser.notifications.onClicked.addListener((notificationId) => { console.log(`Notification ${notificationId} was clicked by the user`); }); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications/clear/index.md
--- title: notifications.clear() slug: Mozilla/Add-ons/WebExtensions/API/notifications/clear page-type: webextension-api-function browser-compat: webextensions.api.notifications.clear --- {{AddonSidebar}} Clears a notification, 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 clearing = browser.notifications.clear( id // string ) ``` ### Parameters - `id` - : `string`. The ID of the notification to clear. This is the same as the ID passed into {{WebExtAPIRef('notifications.create()')}}'s callback. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a boolean: `true` if the notification was cleared, or `false` if it was not (for example, because the notification referenced by `id` did not exist). ## Browser compatibility {{Compat}} ## Examples This example shows a notification when the user clicks a browser action, unless the notification was already being shown, in which case it clears the notification: ```js let myNotification = "my-notification"; function toggleAlarm(all) { if (myNotification in all) { browser.notifications.clear(myNotification); } else { browser.notifications.create(myNotification, { type: "basic", iconUrl: browser.runtime.getURL("icons/cake-48.png"), title: "Am imposing title", message: "Some interesting content", }); } } function handleClick() { let gettingAll = browser.notifications.getAll(); gettingAll.then(toggleAlarm); } browser.browserAction.onClicked.addListener(handleClick); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications/update/index.md
--- title: notifications.update() slug: Mozilla/Add-ons/WebExtensions/API/notifications/update page-type: webextension-api-function browser-compat: webextensions.api.notifications.update --- {{AddonSidebar}} Updates a notification, 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 updating = browser.notifications.update( id, // string options // NotificationOptions ) ``` ### Parameters - `id` - : `string`. The ID of the notification to update. This is the same as the ID passed into {{WebExtAPIRef('notifications.create()')}}'s callback. - `options` - : {{WebExtAPIRef('notifications.NotificationOptions')}}. Defines the notification's new content and behavior. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a boolean: `true` if the notification was updated, or `false` if it was not (for example, because the notification referenced by `id` did not exist). ## Browser compatibility {{Compat}} ## Examples This example uses `update()` to update a progress notification. Clicking the browser action shows the notification and starts an {{WebExtAPIRef("alarms", "alarm")}}, which we use to update the notification's progress indicator. Note that you'll need the "alarms" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) to create alarms (as well as the "notifications" permission to create notifications). Also note that Firefox does not support the `progress` attribute. ```js let cakeNotification = "cake-notification"; /* CAKE_INTERVAL is set to 0.3 seconds in this example. Such a short period is chosen to make the extension's behavior more obvious, but this is not recommended in real life. Note that in Chrome, alarms cannot be set for less than a minute. */ let CAKE_PREP_INTERVAL = 0.005; let progress = 0; browser.alarms.onAlarm.addListener((alarm) => { progress += 10; if (progress > 100) { browser.notifications.clear(cakeNotification); browser.alarms.clear("cake-progress"); } else { browser.notifications.update(cakeNotification, { progress }); } }); browser.browserAction.onClicked.addListener(() => { browser.notifications.getAll((all) => { if (all.length > 0) { browser.notifications.clear(cakeNotification); return; } progress = 0; browser.notifications.create(cakeNotification, { type: "progress", iconUrl: browser.extension.getURL("icons/cake-48.png"), title: "Your cake is being prepared…", message: "Something something cake", progress, }); browser.alarms.create("cake-progress", { periodInMinutes: CAKE_PREP_INTERVAL, }); }); }); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications/templatetype/index.md
--- title: notifications.TemplateType slug: Mozilla/Add-ons/WebExtensions/API/notifications/TemplateType page-type: webextension-api-type browser-compat: webextensions.api.notifications.TemplateType --- {{AddonSidebar}} This is a string, and represents the type of notification to create. There are four types of notification: "basic", "image", "list", "progress". This is passed into {{WebExtAPIRef("notifications.create()")}} and {{WebExtAPIRef("notifications.update()")}} as the `type` property of {{WebExtAPIRef("notifications.NotificationOptions", "NotificationOptions")}}. ## Type Values of this type are strings. Possible values are: - `"basic"`: the notification includes: - a title (`NotificationOptions.title`) - a message (`NotificationOptions.message`) - an icon (`NotificationOptions.iconUrl`) {{optional_inline}} - an extra message (`NotificationOptions.contextMessage`) {{optional_inline}} - up to two buttons (`NotificationOptions.buttons`) {{optional_inline}} - `"image"`: everything in `"basic"` and also: - an image (`NotificationOptions.imageUrl`) - `"list"`: everything in `"basic"` and also: - a list of items (`NotificationOptions.items`) - `"progress"`: everything in `"basic"` and also: - a progress indicator (`NotificationOptions.progress`) Currently Firefox only supports "basic" here. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications/onshown/index.md
--- title: notifications.onShown slug: Mozilla/Add-ons/WebExtensions/API/notifications/onShown page-type: webextension-api-event browser-compat: webextensions.api.notifications.onShown --- {{AddonSidebar}} Fired immediately after a notification has been shown. ## Syntax ```js-nolint browser.notifications.onShown.addListener(listener) browser.notifications.onShown.removeListener(listener) browser.notifications.onShown.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: - `notificationId` - : `string`. ID of the notification that has been shown. ## Browser compatibility {{Compat}} ## Examples Add a listener to the {{WebExtAPIRef("notifications.onShown")}} event and log its details: ```js function logShown(itemId) { console.log(`shown: ${itemId}`); browser.notifications.getAll().then((all) => { console.log(all[itemId]); }); } browser.notifications.onShown.addListener(logShown); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications/onclosed/index.md
--- title: notifications.onClosed slug: Mozilla/Add-ons/WebExtensions/API/notifications/onClosed page-type: webextension-api-event browser-compat: webextensions.api.notifications.onClosed --- {{AddonSidebar}} Fired when a notification is closed, either by the system or by the user. ## Syntax ```js-nolint browser.notifications.onClosed.addListener(listener) browser.notifications.onClosed.removeListener(listener) browser.notifications.onClosed.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed these arguments: - `notificationId` - : `string`. ID of the notification that closed. - `byUser` - : `boolean`. `true` if the notification was closed by the user, or `false` if it was closed by the system. This argument is not supported in Firefox. ## Browser compatibility {{Compat}} ## Examples In this simple example we add a listener to the {{WebExtAPIRef("notifications.onClosed")}} event to listen for system notifications being closed. When this occurs, we log an appropriate message to the console. ```js browser.notifications.onClosed.addListener((notificationId) => { console.log(`Notification ${notificationId} has closed.`); }); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications/getall/index.md
--- title: notifications.getAll() slug: Mozilla/Add-ons/WebExtensions/API/notifications/getAll page-type: webextension-api-function browser-compat: webextensions.api.notifications.getAll --- {{AddonSidebar}} Gets all currently active notifications created by the extension. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let gettingAll = browser.notifications.getAll() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an object. Each currently active notification is a property of this object: the name of the property is the ID of the notification, and the value of the property is a {{WebExtAPIRef("notifications.NotificationOptions")}} object describing that notification. Note that you can define an ID for a notification explicitly by passing it into {{WebExtAPIRef("notifications.create()")}}. If you don't do this, the browser will generate one. Explicitly-specified IDs are strings, but generated IDs are numbers. ## Browser compatibility {{Compat}} ## Examples This example shows a notification when the user clicks a browser action, unless the notification was already being shown, in which case it clears the notification. It uses getAll() to figure out whether the notification is being shown: ```js const myNotification = "my-notification"; function toggleAlarm(all) { const ids = Object.keys(all); if (ids.includes(myNotification)) { browser.notifications.clear(myNotification); } else { console.log("showing"); browser.notifications.create(myNotification, { type: "basic", title: "Am imposing title", message: "Some interesting content", }); } } function handleClick() { console.log("clicked"); browser.notifications.getAll().then(toggleAlarm); } browser.browserAction.onClicked.addListener(handleClick); ``` This example logs the title of all active notifications: ```js function logNotifications(all) { for (const id in all) { console.log(`Title: ${all[id].title}`); } } browser.notifications.getAll().then(logNotifications); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/notifications/onbuttonclicked/index.md
--- title: notifications.onButtonClicked slug: Mozilla/Add-ons/WebExtensions/API/notifications/onButtonClicked page-type: webextension-api-event browser-compat: webextensions.api.notifications.onButtonClicked --- {{AddonSidebar}} Fired when the user clicks one of the notification's buttons. ## Syntax ```js-nolint browser.notifications.onButtonClicked.addListener(listener) browser.notifications.onButtonClicked.removeListener(listener) browser.notifications.onButtonClicked.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed these arguments: - `notificationId` - : `string`. ID of the notification whose button was clicked. - `buttonIndex` - : `integer`. The [zero-based](https://en.wikipedia.org/wiki/Zero-based_numbering) index of the button that was clicked. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.notifications`](https://developer.chrome.com/docs/extensions/reference/notifications/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/index.md
--- title: declarativeNetRequest slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest page-type: webextension-api browser-compat: webextensions.api.declarativeNetRequest --- {{AddonSidebar}} This API enables extensions to specify conditions and actions that describe how network requests should be handled. These declarative rules enable the browser to evaluate and modify network requests without notifying extensions about individual network requests. ## Permissions To use this API, an extension must request the `"declarativeNetRequest"` or `"declarativeNetRequestWithHostAccess"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) in its [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file. The `"declarativeNetRequest"` permission allows extensions to block and upgrade requests without any [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions). Host permissions are required if the extension wants to redirect requests or modify headers on requests or when the `"declarativeNetRequestWithHostAccess"` permission is used instead of the `"declarativeNetRequest"` permission. To act on requests in these cases, host permissions are required for the request URL. For all requests, except for navigation requests (i.e., resource type `main_frame` and `sub_frame`), host permissions are also required for the request's initiator. The initiator of a request is usually the document or worker that triggered the request. Some requests are restricted and cannot be matched by extensions. These include privileged browser requests, requests to or from [restricted domains](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#restricted_domains), and requests from other extensions. The `"declarativeNetRequestFeedback"` permission is required to use {{WebExtAPIRef("declarativeNetRequest.getMatchedRules","getMatchedRules")}} and {{WebExtAPIRef("declarativeNetRequest.onRuleMatchedDebug","onRuleMatchedDebug")}} as they return information on declarative rules matched. See [Testing](#testing) for more information. ## Rules The declarative rules are defined by four fields: - `id` – An ID that uniquely identifies a rule within a ruleset. Mandatory and should be >= 1. - `priority` – The rule priority. When specified, it should be >= 1. Defaults to 1. See [Matching precedents](#matching_precedents) for details on how priority affects which rules are applied. - `condition` – The {{WebExtAPIRef("declarativeNetRequest.RuleCondition","condition")}} under which this rule is triggered. - `action` – The {{WebExtAPIRef("declarativeNetRequest.RuleAction","action")}} to take when the rule is matched. Rules can do one of these things: - block a network request. - redirect a network request. - modify headers from a network request. - prevent another matching rule from being applied. > **Note:** > A redirect action does not redirect the request, and the request continues as usual when: > > - the action does not change the request. > - the redirect URL is invalid (e.g., the value of {{WebExtAPIRef("declarativeNetRequest.redirect","redirect.regexSubstitution")}} is not a valid URL). This is an example rule that blocks all script requests originating from `"foo.com"` to any URL with `"abc"` as a substring: ```json { "id": 1, "priority": 1, "action": { "type": "block" }, "condition": { "urlFilter": "abc", "initiatorDomains": ["foo.com"], "resourceTypes": ["script"] } } ``` The `urlFilter` field of a rule condition is used to specify the pattern matched against the request URL. See {{WebExtAPIRef("declarativeNetRequest.RuleCondition","RuleCondition")}} for details. Some examples of URL filters are: <table> <tbody> <tr> <th><code>urlFilter</code></th> <th>Matches</th> <th>Does not match</th> </tr> <tr> <td><code>"abc"</code></td> <td>https://abcd.com<br />https://example.com/abcd</td> <td>https://ab.com</td> </tr> <tr> <td><code>"abc*d"</code></td> <td>https://abcd.com<br />https://example.com/abcxyzd</td> <td>https://abc.com</td> </tr> <tr> <td><code>"||a.example.com"</code></td> <td>https://a.example.com/<br />https://b.a.example.com/xyz</td> <td>https://example.com/</td> </tr> <tr> <td><code>"|https*"</code></td> <td>https://example.com</td> <td>http://example.com/<br />http://https.com</td> </tr> </tbody> </table> ## Rulesets Rules are organized into rulesets: - **static rulesets**: collections of rules defined with the [`"declarative_net_request"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request) manifest key and stored in the extension. An extension can enable and disable static rulesets using {{WebExtAPIRef("declarativeNetRequest.updateEnabledRulesets","updateEnabledRulesets")}}. The set of enabled static rulesets is persisted across sessions but not across extension updates. The static rulesets enabled on extension installation and update are determined by the content of the `"declarative_net_request"` manifest key. - **dynamic ruleset**: rules added or removed using {{WebExtAPIRef("declarativeNetRequest.updateDynamicRules","updateDynamicRules")}}. These rules persist across sessions and extension updates. - **session ruleset**: rules added or removed using {{WebExtAPIRef("declarativeNetRequest.updateSessionRules","updateSessionRules")}}. These rules do not persist across browser sessions. > **Note:** > Errors and warnings about invalid static rules are only displayed during [testing](#testing). Invalid static rules in permanently installed extensions are ignored. Therefore, it's important to verify that your static rulesets are valid by testing. ## Limits ### Static ruleset limits An extension can: - specify static rulesets as part of the [`"declarative_net_request"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request) manifest key up to the value of {{WebExtAPIRef("declarativeNetRequest.MAX_NUMBER_OF_STATIC_RULESETS","MAX_NUMBER_OF_STATIC_RULESETS")}}. - enable static rulesets up to at least the value of {{WebExtAPIRef("declarativeNetRequest.GUARANTEED_MINIMUM_STATIC_RULES","GUARANTEED_MINIMUM_STATIC_RULES")}}, and the number of enabled static rulesets must not exceed the value of {{WebExtAPIRef("declarativeNetRequest.MAX_NUMBER_OF_ENABLED_STATIC_RULESETS","MAX_NUMBER_OF_ENABLED_STATIC_RULESETS")}}. In addition, the number of rules in enabled static rulesets for all extensions must not exceed the global limit. Extensions shouldn't depend on the global limit having a specific value and should instead use {{WebExtAPIRef("declarativeNetRequest.getAvailableStaticRuleCount","getAvailableStaticRuleCount")}} to find the number of additional rules they can enable. ### Dynamic and session-scoped rules The number of dynamic and session-scoped rules an extension can add is limited to the value of {{WebExtAPIRef("declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES","MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES")}}. ## Matching precedents When the browser evaluates how to handle requests, it checks each extension's rules that have a condition that matches the request and chooses the one to consider applying as follows: 1. the rule priority, where 1 is the lowest priority (and rules default to 1 where priority is not set).<br> If this doesn't result in one rule to apply: 2. the rule action, in the following order of precedence: 1. "allow" which means any other remaining rules are ignored. 2. "allowAllRequests" (for main_frame and sub_frame resourceTypes only) has the same effect as allow but also applies to future subresource loads in the document (including descendant frames) generated from the request. 3. "block" cancels the request. 4. "upgradeScheme" upgrades the scheme of the request. 5. "redirect" redirects the request. 6. "modifyHeaders" rewrites request or response headers or both. > **Note:** When multiple matching rules have the same rule priority and rule action type, the outcome can be ambiguous when the matched action support additional properties. These properties can result in outcomes that cannot be combined. For example: > > - The "block" action does not support additional properties, and therefore there is no ambiguity: all matching "block" actions would result in the same outcome. > - The "redirect" action redirects a request to one destination. When multiple "redirect" actions match, all but one "redirect" action is ignored. It is still possible to redirect repeatedly when the redirected request matches another rule condition. > - Multiple "modifyHeaders" actions can be applied independently when they touch different headers. The result is ambiguous when they touch the same header, because some combination of operations are not allowed (as explained at {{WebExtAPIRef("declarativeNetRequest.ModifyHeaderInfo")}}). The evaluation order of "modifyHeaders" actions is therefore important. > > To control the order in which actions are applied, assign distinct `priority` values to rules whose order of precedence is important. > **Note:** After rule priority and rule action, Firefox considers the ruleset the rule belongs to, in this order of precedence: session > dynamic > session rulesets. > This cannot be relied upon across browsers, see [WECG issue 280](https://github.com/w3c/webextensions/issues/280). If only one extension provides a rule for the request, that rule is applied. However, where more than one extension has a matching rule, the browser chooses the one to apply in this order of precedence: 1. "block" 2. "redirect" and "upgradeScheme" 3. "allow" and "allowAllRequests" If the request was not blocked or redirected, the matching `modifyHeaders` actions are applied, as documented in {{WebExtAPIRef("declarativeNetRequest.ModifyHeaderInfo")}}. ## Testing {{WebExtAPIRef("declarativeNetRequest.testMatchOutcome","testMatchOutcome")}}, {{WebExtAPIRef("declarativeNetRequest.getMatchedRules","getMatchedRules")}}, and {{WebExtAPIRef("declarativeNetRequest.onRuleMatchedDebug","onRuleMatchedDebug")}} are available to assist with testing rules and rulesets. These APIs require the `"declarativeNetRequestFeedback"` [permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). In addition: - in Chrome, these APIs are only available to unpacked extensions. - in Firefox, these APIs are only available after setting the `extensions.dnr.feedback` preference to `true`. Set this preference using `about:config` or the [`--pref` flag of the `web-ext` CLI tool](https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#pref). ## Comparison with the webRequest API - The declarativeNetRequest API evaluates network requests in the browser itself. This makes it more performant than the webRequest API, where each network request is evaluated in JavaScript in the extension process. - Because the requests are not intercepted by the extension process, declarativeNetRequest removes the need for extensions to have a background page. - Unlike the webRequest API, blocking or upgrading requests using the declarativeNetRequest API requires no host permissions when used with the `declarativeNetRequest` permission. - The declarativeNetRequest API provides better privacy to users because extensions do not read the network requests made on the user's behalf. - (Chrome only:) Unlike the webRequest API, any images or iframes blocked using the declarativeNetRequest API are automatically collapsed in the DOM. - While deciding whether a request is to be blocked or redirected, the declarativeNetRequest API is given priority over the webRequest API because it allows for synchronous interception. Similarly, any headers removed through declarativeNetRequest API are not made visible to web request extensions. - The webRequest API is more flexible than the declarativeNetRequest API because it allows extensions to evaluate a request programmatically. ## Types - {{WebExtAPIRef("declarativeNetRequest.MatchedRule")}} - : Details of a matched rule. - {{WebExtAPIRef("declarativeNetRequest.ModifyHeaderInfo")}} - : The request or response headers to modify for the request. - {{WebExtAPIRef("declarativeNetRequest.Redirect")}} - : Details of how the redirect should be performed. Only valid for redirect rules. - {{WebExtAPIRef("declarativeNetRequest.ResourceType")}} - : The resource type of a request. - {{WebExtAPIRef("declarativeNetRequest.Rule")}} - : An object containing details of a rule. - {{WebExtAPIRef("declarativeNetRequest.RuleAction")}} - : An object defining the action to take if a rule is matched. - {{WebExtAPIRef("declarativeNetRequest.RuleCondition")}} - : An object defining the condition under which a rule is triggered. - {{WebExtAPIRef("declarativeNetRequest.URLTransform")}} - : An object containing details of a URL transformation to perform for a redirect action. ## Properties - {{WebExtAPIRef("declarativeNetRequest.DYNAMIC_RULESET_ID")}} - : Ruleset ID for the dynamic rules added by the extension. - {{WebExtAPIRef("declarativeNetRequest.GETMATCHEDRULES_QUOTA_INTERVAL")}} - : The time interval within which {{WebExtAPIRef("declarativeNetRequest.MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL")}} {{WebExtAPIRef("declarativeNetRequest.getMatchedRules")}} calls can be made. - {{WebExtAPIRef("declarativeNetRequest.GUARANTEED_MINIMUM_STATIC_RULES")}} - : The minimum number of static rules guaranteed to an extension across its enabled static rulesets. - {{WebExtAPIRef("declarativeNetRequest.MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL")}} - : The number of times {{WebExtAPIRef("declarativeNetRequest.getMatchedRules")}} can be called within a period of {{WebExtAPIRef("declarativeNetRequest.GETMATCHEDRULES_QUOTA_INTERVAL")}}. - {{WebExtAPIRef("declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES")}} - : The maximum number of combined dynamic and session scoped rules an extension can add. - {{WebExtAPIRef("declarativeNetRequest.MAX_NUMBER_OF_ENABLED_STATIC_RULESETS")}} - : The maximum number of static rulesets an extension can enable. - {{WebExtAPIRef("declarativeNetRequest.MAX_NUMBER_OF_REGEX_RULES")}} - : The maximum number of regular expression rules that an extension can add. - {{WebExtAPIRef("declarativeNetRequest.MAX_NUMBER_OF_STATIC_RULESETS")}} - : The maximum number of static rulesets an extension can specify as part of the [`declarative_net_request.rule_resources`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request) manifest key. - {{WebExtAPIRef("declarativeNetRequest.SESSION_RULESET_ID")}} - : The ruleset ID for the session-scoped rules added by the extension. ## Functions - {{WebExtAPIRef("declarativeNetRequest.getAvailableStaticRuleCount()")}} - : Returns the number of static rules an extension can enable before the global static rule limit is reached. - {{WebExtAPIRef("declarativeNetRequest.getDynamicRules()")}} - : Returns the set of dynamic rules for the extension. - {{WebExtAPIRef("declarativeNetRequest.getEnabledRulesets()")}} - : Returns the IDs for the set of enabled static rulesets. - {{WebExtAPIRef("declarativeNetRequest.getMatchedRules()")}} - : Returns all the rules matched for the extension. - {{WebExtAPIRef("declarativeNetRequest.getSessionRules()")}} - : Returns the set of session scoped rules for the extension. - {{WebExtAPIRef("declarativeNetRequest.isRegexSupported()")}} - : Checks if a regular expression is supported as a {{WebExtAPIRef("declarativeNetRequest.RuleCondition")}}`.regexFilter` rule condition. - {{WebExtAPIRef("declarativeNetRequest.setExtensionActionOptions()")}} - : Configures how the action count for tabs are handled. - {{WebExtAPIRef("declarativeNetRequest.testMatchOutcome()")}} - : Checks if any of the extension's `declarativeNetRequest` rules would match a hypothetical request. - {{WebExtAPIRef("declarativeNetRequest.updateDynamicRules()")}} - : Modifies the active set of dynamic rules for the extension. - {{WebExtAPIRef("declarativeNetRequest.updateEnabledRulesets()")}} - : Updates the set of active static rulesets for the extension. - {{WebExtAPIRef("declarativeNetRequest.updateSessionRules()")}} - : Modifies the set of session scoped rules for the extension. ## Events - {{WebExtAPIRef("declarativeNetRequest.onRuleMatchedDebug")}} - : Fired when a rule is matched with a request when debugging an extension with the "declarativeNetRequestFeedback" permission. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/updatesessionrules/index.md
--- title: declarativeNetRequest.updateSessionRules slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/updateSessionRules page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.updateSessionRules --- {{AddonSidebar}} Modifies the set of scoped rules for the extension. The rules with IDs listed in `options.removeRuleIds` are first removed, and then the rules given in `options.addRules` are added. Note that: - This update happens as an atomic operation: either all specified rules are added and removed, or an error is returned. - These rules are not persisted across browser sessions. - {{WebExtAPIRef("declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES","MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES")}} is the maximum number of dynamic and session rules an extension can add. ## Syntax ```js-nolint let updatedRuleset = browser.declarativeNetRequest.updateSessionRules( options // object ); ``` ### Parameters - `options` - : An object containing details of the rules to add or delete from the dynamic rules. - `addRules` {{optional_inline}} - : An array of {{WebExtAPIRef("declarativeNetRequest.Rule")}}. Details of the rules to add. - `removeRuleIds` {{optional_inline}} - : An array of `number`. IDs of the rules to remove. Any invalid IDs are ignored. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) If the request was successful, the promise is fulfilled with no arguments. If the request fails, the promise is rejected with an error message. ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/resourcetype/index.md
--- title: declarativeNetRequest.ResourceType slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/ResourceType page-type: webextension-api-type browser-compat: webextensions.api.declarativeNetRequest.ResourceType --- {{AddonSidebar}} The resource type of a request. Comparable to {{WebExtAPIRef('webRequest.ResourceType')}}. ## Type Values of this type are strings. Possible values are: - `beacon` - : Requests sent through the [Beacon API](/en-US/docs/Web/API/Beacon_API). - `csp_report` - : Requests sent to the {{CSP("report-uri")}} given in the {{HTTPHeader("Content-Security-Policy")}} header, when an attempt to violate the policy is detected. - `font` - : Web fonts loaded for a {{cssxref("@font-face")}} CSS rule. - `image` - : Resources loaded to be rendered as image, except for `imageset` on browsers that support that type (see browser compatibility below). - `imageset` - : Images loaded by a {{HTMLElement("picture")}} element or given in an `<img>` element's [`srcset`](/en-US/docs/Web/HTML/Element/img#srcset) attribute. - `main_frame` - : Top-level documents loaded into a tab. - `media` - : Resources loaded by a {{HTMLElement("video")}} or {{HTMLElement("audio")}} element. - `object` - : Resources loaded by an {{HTMLElement("object")}} or {{HTMLElement("embed")}} element. Browsers that don't have a dedicated `object_subrequest` type (see browser compatibility below), also label subsequent requests sent by the plugin as `object`. - `object_subrequest` - : Requests sent by plugins. - `ping` - : Requests sent to the URL given in a hyperlink's [`ping`](/en-US/docs/Web/HTML/Element/a#ping) attribute, when the hyperlink is followed. Browsers that don't have a dedicated `beacon` type (see browser compatibility below), also label requests sent through the Beacon API as `ping`. - `script` - : Code that is loaded to be executed by a {{HTMLElement("script")}} element or running in a [Worker](/en-US/docs/Web/API/Web_Workers_API). - `speculative` - : In a speculative connection, the browser has determined that a request to a URI may be coming soon, so it starts a TCP and/or TLS handshake immediately, so it is ready more quickly when the resource is actually requested. Note that this type of connection does not provide valid tab information, so request details such as `tabId`, `frameId`, `parentFrameId`, etc. are inaccurate. - `stylesheet` - : [CSS](/en-US/docs/Web/CSS) stylesheets loaded to describe the representation of a document. - `sub_frame` - : Documents loaded into an {{HTMLElement("iframe")}} or {{HTMLElement("frame")}} element. - `web_manifest` - : [Web App Manifests](/en-US/docs/Web/Manifest) loaded for websites that can be installed to the homescreen. - `webbundle` - : Requests initiating a connection to a server through a Web Bundle or [packaged website](https://github.com/WICG/webpackage). - `websocket` - : Requests initiating a connection to a server through the [WebSocket API](/en-US/docs/Web/API/WebSockets_API). - `webtransport` - : Requests initiating a connection to a server through the [WebTransport API](/en-US/docs/Web/API/WebTransport_API). - `xml_dtd` - : [DTDs](/en-US/docs/Glossary/Doctype) loaded for an XML document. - `xmlhttprequest` - : Requests sent by an {{domxref("XMLHttpRequest")}} object or through the [Fetch API](/en-US/docs/Web/API/Fetch_API). - `xslt` - : [XSLT](/en-US/docs/Web/XSLT) stylesheets loaded for transforming an XML document. - `other` - : Resources that aren't covered by any other available type. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/ruleaction/index.md
--- title: declarativeNetRequest.RuleAction slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/RuleAction page-type: webextension-api-type browser-compat: webextensions.api.declarativeNetRequest.RuleAction --- {{AddonSidebar}} Details of the action to take if a rule is matched, as the `action` property of a {{WebExtAPIRef("declarativeNetRequest.Rule")}}. ## Type Values of this type are objects. They contain these properties: - `redirect` {{optional_inline}} - : {{WebExtAPIRef("declarativeNetRequest.Redirect")}}. Describes how the redirect should be performed. Only valid for redirect rules. - `requestHeaders` {{optional_inline}} - : {{WebExtAPIRef("declarativeNetRequest.ModifyHeaderInfo")}}. The request headers to modify for the request. Only valid if `type` is `"modifyHeaders"`. - `responseHeaders` {{optional_inline}} - : {{WebExtAPIRef("declarativeNetRequest.ModifyHeaderInfo")}}. The response headers to modify for the request. Only valid if `type` is `"modifyHeaders"`. - `type` - : A `string`. The type of action to perform. Possible values are `"block"`, `"redirect"`, `"allow"`, `"upgradeScheme"`, `"modifyHeaders"`, and `"allowAllRequests"`. The use of the `"redirect"` and `"modifyHeaders"` actions require [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the request and request initiator. The "block" and "upgradeScheme" actions also require host permissions unless the "declarativeNetRequest" permission is specified. Without these permissions, matching rules are ignored. See [Permissions at declarativeNetRequest](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest#permissions) for more information. More details about the effects of rule actions are provided in [Matching precedents](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest#matching_precedents). {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/dynamic_ruleset_id/index.md
--- title: declarativeNetRequest.DYNAMIC_RULESET_ID slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/DYNAMIC_RULESET_ID page-type: webextension-api-property browser-compat: webextensions.api.declarativeNetRequest.DYNAMIC_RULESET_ID --- {{AddonSidebar}} Ruleset ID for the dynamic rules added by the extension using {{WebExtAPIRef("declarativeNetRequest.updateDynamicRules","updateDynamicRules")}}. Its value is `"_dynamic"`. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/redirect/index.md
--- title: declarativeNetRequest.Redirect slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/Redirect page-type: webextension-api-type browser-compat: webextensions.api.declarativeNetRequest.Redirect --- {{AddonSidebar}} Details describing how a redirect should be performed, as the `redirect` property of a {{WebExtAPIRef("declarativeNetRequest.RuleAction", "RuleAction")}}. Only valid for redirect rules. > **Note:** > A redirect action does not redirect the request, and the request continues as usual when: > > - the action does not change the request. > - the redirect URL is invalid (e.g., the value of {{WebExtAPIRef("declarativeNetRequest.redirect","redirect.regexSubstitution")}} is not a valid URL). ## Type Values of this type are objects. They contain these properties: - `extensionPath` {{optional_inline}} - : A `string`. The path relative to the extension directory. Should start with '/'. The initiator of the request can only follow the redirect when the resource is listed in [`web_accessible_resources`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources). - `regexSubstitution` {{optional_inline}} - : A `string`. The substitution pattern for rules that specify a `regexFilter`. The first match of `regexFilter` within the URL is replaced with this pattern. Within `regexSubstitution`, backslash-escaped digits (`\1` to `\9`) are used to insert the corresponding capture groups. `\0` refers to the entire matching text. - `transform` {{optional_inline}} - : {{WebExtAPIRef("declarativeNetRequest.URLTransform")}}. The URL transformations to perform. - `url` {{optional_inline}} - : A `string`. The redirect URL. Redirects to JavaScript URLs are not allowed. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/onrulematcheddebug/index.md
--- title: declarativeNetRequest.onRuleMatchedDebug slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/onRuleMatchedDebug page-type: webextension-api-event browser-compat: webextensions.api.declarativeNetRequest.onRuleMatchedDebug --- {{AddonSidebar}} Fired when a rule is matched with a request. Only available extensions with the `"declarativeNetRequestFeedback"` permission, as this is intended for debugging purposes only. See [Testing](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest#testing) for details on how testing is enabled in each browser. ## Syntax ```js-nolint browser.declarativeNetRequest.onRuleMatchedDebug.addListener(listener) browser.declarativeNetRequest.onRuleMatchedDebug.removeListener(listener) browser.declarativeNetRequest.onRuleMatchedDebug.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: - `request` - : An object containing information about the request the rule matched. - `documentId` {{optional_inline}} - : A `string`. The unique identifier for the frame's document, if this request is for a frame. - `documentLifecycle` {{optional_inline}} - : A `string`. The lifecycle of the frame's document, if this request is for a frame. Possible values are: `"prerender"`, `"active"`, `"cached"`, or `"pending_deletion"`. - `frameId` - : A `number`. The value `0` indicates that the request happens in the main frame. A positive value indicates the ID of a subframe where the request happens. If the document of a (sub-)frame is loaded (type is `main_frame` or `sub_frame`), `frameId` indicates this frame's ID, not the outer frame's ID. Frame IDs are unique within a tab. - `frameType` {{optional_inline}} - : A `string`. The type of the frame, if this request is for a frame. Possible values are: `"outermost_frame"`, `"fenced_frame"`, or `"sub_frame"`. - `initiator` {{optional_inline}} - : A `string`. The origin where the request was initiated. This does not change through redirects. The string 'null' is used if this is an opaque origin. - `method` - : A `string`. A standard HTTP method. - `parentDocumentId` {{optional_inline}} - : A `string`. The unique identifier for the frame's parent document, if this request is for a frame and has a parent. - `parentFrameId` - : A `number`. The ID of the frame that wraps the frame which sent the request. Set to `-1` if there is no parent frame. - `requestId` - : A `string`. The ID of the request. Request IDs are unique within a browser session. - `tabId` - : A `number`. The ID of the tab in which the request takes place. Set to `-1` if the request is not related to a tab. - `type` - : {{WebExtAPIRef("declarativeNetRequest.ResourceType", "ResourceType")}}. The resource type of the request. - `url` - : A `string`. The URL of the request. - `rule` - : {{WebExtAPIRef("declarativeNetRequest.MatchedRule", "MatchedRule")}}. Details of a matched rule. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/updatedynamicrules/index.md
--- title: declarativeNetRequest.updateDynamicRules slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/updateDynamicRules page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.updateDynamicRules --- {{AddonSidebar}} Modifies the set of dynamic rules for the extension. The rules with IDs listed in `options.removeRuleIds` are first removed, and then the rules given in `options.addRules` are added. Note that: - This update happens as an atomic operation: either all specified rules are added and removed, or an error is returned. - These rules are persisted across browser sessions and across extension updates. - Static rules specified as part of the extension package can not be removed using this function. - {{WebExtAPIRef("declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES")}} is the maximum number of dynamic and session rules an extension can add. ## Syntax ```js-nolint let updatedRules = browser.declarativeNetRequest.updateDynamicRules( options // object ); ``` ### Parameters - `options` - : An object containing details of the rules to add or delete from the dynamic rules. - `addRules` {{optional_inline}} - : An array of {{WebExtAPIRef("declarativeNetRequest.Rule")}}. Details of the rules to add. - `removeRuleIds` {{optional_inline}} - : An array of `number`. IDs of the rules to remove. Any invalid IDs are ignored. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) If the request was successful, the promise is fulfilled with no arguments. If the request fails, the promise is rejected with an error message. ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/max_number_of_static_rulesets/index.md
--- title: declarativeNetRequest.MAX_NUMBER_OF_STATIC_RULESETS slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/MAX_NUMBER_OF_STATIC_RULESETS page-type: webextension-api-property browser-compat: webextensions.api.declarativeNetRequest.MAX_NUMBER_OF_STATIC_RULESETS --- {{AddonSidebar}} The maximum number of static rulesets an extension can specify as part of the [`declarative_net_request.rule_resources`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request) manifest key. Its value is `50`. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/max_number_of_dynamic_and_session_rules/index.md
--- title: declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES page-type: webextension-api-property browser-compat: webextensions.api.declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES --- {{AddonSidebar}} The maximum number of combined dynamic and session scoped rules an extension can add. In Chrome, this limit is enforced for the combination of dynamic and session scoped rules. In Firefox, each ruleset has its own quota. Its value is `5000`. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/max_number_of_regex_rules/index.md
--- title: declarativeNetRequest.MAX_NUMBER_OF_REGEX_RULES slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/MAX_NUMBER_OF_REGEX_RULES page-type: webextension-api-property browser-compat: webextensions.api.declarativeNetRequest.MAX_NUMBER_OF_REGEX_RULES --- {{AddonSidebar}} The maximum number of regular expression rules that an extension can add. In Chrome, its value is 1000, and this limit is evaluated separately for the set of dynamic and session rules, and those specified in the rule resources file. In Firefox, this limit is evaluated separately per ruleset. In Safari, there is no separate limit on the number of `regexFilter` rules. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/urltransform/index.md
--- title: declarativeNetRequest.URLTransform slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/URLTransform page-type: webextension-api-type browser-compat: webextensions.api.declarativeNetRequest.URLTransform --- {{AddonSidebar}} Details describing a URL transformation to perform for a redirect rule. This object can be specified at {{WebExtAPIRef("declarativeNetRequest.RuleAction", "rule.action")}}.redirect.transform. ## Type Values of this type are objects. They contain these properties: - `fragment` {{optional_inline}} - : A `string`. The new fragment for the request. Should be either empty, in which case the existing fragment is cleared; or should begin with '#'. - `host` {{optional_inline}} - : A `string`. The new host name for the request. - `password` {{optional_inline}} - : A `string`. The new password for the request. - `path` {{optional_inline}} - : A `string`. The new path for the request. If empty, the existing path is cleared. - `port` {{optional_inline}} - : A `string`. The new port for the request. If empty, the existing port is cleared. - `query` {{optional_inline}} - : A `string`. The new query for the request. Should be either empty, in which case the existing query is cleared; or should begin with '?'. - `queryTransform` {{optional_inline}} - : An object describing how to add, remove, or replace query key-value pairs. Cannot be specified if 'query' is specified. - `addOrReplaceParams` {{optional_inline}} - : An array of objects describing the list of query key-value pairs to be added or replaced. - `key` - : A `string`. The key value. - `replaceOnly` {{optional_inline}} - : A `boolean`. If true, the query key is replaced only if it's already present. Otherwise, the key is also added if it's missing. Defaults to false. - `value` - : A `string`. The value value. - `removeParams` {{optional_inline}} - : An array of `string`. The list of query keys to be removed. - `scheme` {{optional_inline}} - : A `string`. The new scheme for the request. Allowed values are `"http"`, `"https"`, and the scheme of the extension, for example, "moz-extension" in Firefox or "chrome-extension" in Chrome. When the extension scheme is used, the `host` must be specified to generate a meaningful redirection target. - `username` {{optional_inline}} - : A `string`. The new username for the request. ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/getmatchedrules/index.md
--- title: declarativeNetRequest.getMatchedRules slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/getMatchedRules page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.getMatchedRules --- {{AddonSidebar}} Returns all the rules matched for the extension. Callers can filter the list of matched rules by specifying a `filter`. This method is only available to extensions with the `"declarativeNetRequestFeedback"` permission or that have the `"activeTab"` permission granted for the `tabId` specified in `filter`. Rules not associated with an active document that were matched more than five minutes ago are not returned. ## Syntax ```js-nolint let gettingMatchedRules = browser.declarativeNetRequest.getMatchedRules( filter // object ); ``` ### Parameters - `filter` {{optional_inline}} - : An object to filter the list of matched rules. - `minTimeStamp` {{optional_inline}} - : A `number`. If specified, only matches rules after the specified timestamp. - `tabId` {{optional_inline}} - : A `number`. If specified, only matches rules for the specified tab. Matches rules not associated with any active tab if set to `-1`. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with an object with these properties: - `rule` - : {{WebExtAPIRef("declarativeNetRequest.MatchedRule")}}. Details of a matched rule. - `tabId` - : `number` The `tabId` of the tab the request originated from if the tab is still active. Otherwise, `-1`. - `timeStamp` - : `number` The time the rule was matched. Timestamps correspond to the JavaScript convention for times, i.e. the number of milliseconds since the epoch. If no rules are matched, the object is empty. If the request fail, the promise is rejected with an error message ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/testmatchoutcome/index.md
--- title: declarativeNetRequest.testMatchOutcome slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/testMatchOutcome page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.testMatchOutcome --- {{AddonSidebar}} Checks if any of the extension's `declarativeNetRequest` rules would match a hypothetical request. Only available while testing, as this is intended to be used during extension development. See [Testing](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest#testing) for details on how testing is enabled in each browser. ## Syntax ```js-nolint let result = await browser.declarativeNetRequest.testMatchOutcome( request, // object options // optional object ); ``` ### Parameters - `request` - : The details of the request to test. - `initiator` {{optional_inline}} - : A `string`. The initiator URL (if any) for the hypothetical request. - `method` {{optional_inline}} - : A `string`. The standard (lower case) HTTP method of the hypothetical request. Defaults to `"get"` for HTTP requests and is ignored for non-HTTP requests. - `tabId` {{optional_inline}} - : A `number`. The ID of the tab the hypothetical request takes place in. Does not need to correspond to a real tab ID. Default is `-1`, meaning that the request isn't related to a tab. - `type` - : {{WebExtAPIRef("declarativeNetRequest.ResourceType")}}. The resource type of the hypothetical request. - `url` - : A `string`. The URL of the hypothetical request. - `options` {{optional_inline}} - : Details of options for the request. - `includeOtherExtensions` {{optional_inline}} - : A `boolean`. Whether matching rules from other extensions are included in `matchedRules`. When rules from other extensions match, the resulting `matchedRule` has an `extensionId` property. Defaults to `false`. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with an object with these properties: - `matchedRules` - : {{WebExtAPIRef("declarativeNetRequest.MatchedRule")}}. Details of the rules (if any) that match the hypothetical request. If no rules match, the `matchedRules` array is empty. If the request fails, the promise is rejected with an error message. ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/updateenabledrulesets/index.md
--- title: declarativeNetRequest.updateEnabledRulesets slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/updateEnabledRulesets page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.updateEnabledRulesets --- {{AddonSidebar}} Updates the extension's set of static rulesets. The rulesets with IDs listed in `options.disableRulesetIds` are first deactivated, and then the rulesets listed in `options.enableRulesetIds` are activated. Note that the set of enabled static rulesets persists across sessions but not across extension updates, i.e. the [`declarative_net_request.rule_resources` manifest key](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request) determines the set of enabled static rulesets on each extension update. ## Syntax ```js-nolint let updatedRulesets = browser.declarativeNetRequest.updateEnabledRulesets( options // object ); ``` ### Parameters - `options` - : An object detailing the rulesets to activate or deactivate in the extension's static rulesets. - `disableRulesetIds` {{optional_inline}} - : An array of `string`. IDs of static Rulesets to deactivated. - `enableRulesetIds` {{optional_inline}} - : An array of `string`. IDs of static Rulesets to activated. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) If the request was successful, the promise is fulfilled with no arguments. If the request fails, the promise is rejected with an error message. ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/session_ruleset_id/index.md
--- title: declarativeNetRequest.SESSION_RULESET_ID slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/SESSION_RULESET_ID page-type: webextension-api-property browser-compat: webextensions.api.declarativeNetRequest.SESSION_RULESET_ID --- {{AddonSidebar}} The ruleset ID for the session-scoped rules added by the extension. Its value is `"_session"`. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/rule/index.md
--- title: declarativeNetRequest.Rule slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/Rule page-type: webextension-api-type browser-compat: webextensions.api.declarativeNetRequest.Rule --- {{AddonSidebar}} The object describing the actions to take for matching requests. These can be specified in the static rule resources linked by the [manifest.json's `declarative_net_request` key](Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request), or more dynamically through the {{WebExtAPIRef("declarativeNetRequest.updateDynamicRules")}} or {{WebExtAPIRef("declarativeNetRequest.updateSessionRules")}} methods. See [Rules](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest#rules) on the API overview page for more information about rules. ## Type Values of this type are objects. They contain these properties: - `action` - : {{WebExtAPIRef("declarativeNetRequest.RuleAction")}}. The action to take if this rule is matched. - `condition` - : {{WebExtAPIRef("declarativeNetRequest.RuleCondition")}}. The condition under which this rule is triggered. - `id` - : `number`. An ID that uniquely identifies a rule within a ruleset. Mandatory and should be >= 1. - `priority` {{optional_inline}} - : `number`. Rule priority. Defaults to 1. When specified, should be >= 1. See [Matching precedents](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest#matching_precedents) for details on how priority affects which rules are applied. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/modifyheaderinfo/index.md
--- title: declarativeNetRequest.ModifyHeaderInfo slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/ModifyHeaderInfo page-type: webextension-api-type browser-compat: - webextensions.api.declarativeNetRequest.RuleAction.requestHeaders - webextensions.api.declarativeNetRequest.RuleAction.responseHeaders --- {{AddonSidebar}} The request or response header to modify for a request, declared in the `rule.action.requestHeaders` array or `rule.action.responseHeaders` array for rules whose {{WebExtAPIRef("declarativeNetRequest.RuleAction", "rule.action")}}`.type` is "modifyHeaders". Each object describes one header modification. To modify multiple headers, multiple objects can be specified in these arrays, or across multiple rules. Matching `modifyHeaders` rules are applied in the order described at [Matching precedents](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest#matching_precedents). Within each extension, all `modifyHeaders` rules with a priority lower than or equal to matching `allow` or `allowAllRequests` rules are ignored. If multiple `modifyHeaders` rules specify the same header, the resulting modification for the header is determined based on the priority of each rule and the operations specified: - If a rule has been appended to a header, then lower-priority rules can only append to that header. `set` and `remove` operations are not permitted. - If a rule has set a header, lower priority rules cannot modify the header except for `append` rules from the same extension. - If a rule has removed a header, lower priority rules cannot modify the header. ## Type Values of this type are objects. They contain these properties: - `header` - : A `string`. The name of the header to be modified. - `operation` - : A `string`. The operation to be performed on a header. Possible values are `"append"`, `"set"`, and `"remove"`. - `value` {{optional_inline}} - : A `string`. The new value for the header. Must be specified for append and set operations. Not allowed for the "remove" operation. ## Header limits In Chrome, `"append"` is supported for the following request headers: - `Accept` - `Accept-Encoding` - `Accept-Language` - `Access-Control-Request-Headers` - `Cache-Control` - `Connection` - `Content-Language` - `Cookie` - `Forwarded` - `If-Match` - `If-None-Match` - `Keep-Alive` - `Range` - `Te` - `Trailer` - `Transfer-Encoding` - `Upgrade` - `Via` - `Want-Digest` - `X-Forwarded-For` In Firefox, the extension needs host permissions for the new value of the `Host` header. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/guaranteed_minimum_static_rules/index.md
--- title: declarativeNetRequest.GUARANTEED_MINIMUM_STATIC_RULES slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/GUARANTEED_MINIMUM_STATIC_RULES page-type: webextension-api-property browser-compat: webextensions.api.declarativeNetRequest.GUARANTEED_MINIMUM_STATIC_RULES --- {{AddonSidebar}} The minimum number of static rules guaranteed to an extension across its enabled static rulesets. Any rules above this limit are count towards the global static rule limit. Its value is `30000` on Chrome. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/getmatchedrules_quota_interval/index.md
--- title: declarativeNetRequest.GETMATCHEDRULES_QUOTA_INTERVAL slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/GETMATCHEDRULES_QUOTA_INTERVAL page-type: webextension-api-property browser-compat: webextensions.api.declarativeNetRequest.GETMATCHEDRULES_QUOTA_INTERVAL --- {{AddonSidebar}} The time interval within which {{WebExtAPIRef("declarativeNetRequest.MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL")}} {{WebExtAPIRef("declarativeNetRequest.getMatchedRules")}} calls can be made, specified in minutes. Additional calls fail immediately and result in a promise rejection. Calls associated with a user gesture are exempt from the quota. Its value is `10`. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/getsessionrules/index.md
--- title: declarativeNetRequest.getSessionRules slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/getSessionRules page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.getSessionRules --- {{AddonSidebar}} Returns the active set of session scoped rules for the extension. ## Syntax ```js-nolint let sessionRules = await browser.declarativeNetRequest.getSessionRules(); ``` ### Parameters This function takes no parameters. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) fulfilled with an array of {{WebExtAPIRef("declarativeNetRequest.Rule")}} objects. If no rules are active, the object is empty. If the request fails, the promise is rejected with an error message ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/max_number_of_enabled_static_rulesets/index.md
--- title: declarativeNetRequest.MAX_NUMBER_OF_ENABLED_STATIC_RULESETS slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/MAX_NUMBER_OF_ENABLED_STATIC_RULESETS page-type: webextension-api-property browser-compat: webextensions.api.declarativeNetRequest.MAX_NUMBER_OF_ENABLED_STATIC_RULESETS --- {{AddonSidebar}} The maximum number of static rulesets an extension can have enabled, i.e., the number of values in the [`declarative_net_request.rule_resources`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request) manifest key with `"enabled"` set to `true`. Static rulesets exceeding the limit are ignored. An extension can change the number of enabled rulesets using the {{WebExtAPIRef("declarativeNetRequest.updateEnabledRulesets", "updateEnabledRulesets")}} method. Its value is `10`. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/isregexsupported/index.md
--- title: declarativeNetRequest.isRegexSupported slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/isRegexSupported page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.isRegexSupported --- {{AddonSidebar}} Checks if a regular expression is supported as a {{WebExtAPIRef("declarativeNetRequest.RuleCondition")}}`.regexFilter` rule condition. ## Syntax ```js-nolint let count = browser.declarativeNetRequest.isRegexSupported( regexOptions // object ); ``` ### Parameters - `regexOptions` - : An object containing the regular expression to check. - `isCaseSensitive` {{optional_inline}} - : `boolean` Whether the regex specified is case sensitive. Default is `true`. - `regex` - : `string` The regular expression to check. - `requireCapturing` {{optional_inline}} - : `boolean` Whether the regex specified requires capturing. Capturing is only required for redirect rules that specify a regexSubstitution action. The default is false. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with an object with these properties: - `isSupported` - : `boolean` Whether the regular expression is supported. - `reason` {{optional_inline}} - : `string` Specifies the reason why the regular expression is not supported. Possible values are `"syntaxError"` and `"memoryLimitExceeded"`. Only provided if `isSupported` is false. If the request fails, the promise is rejected with an error message. ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/max_getmatchedrules_calls_per_interval/index.md
--- title: declarativeNetRequest.MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL page-type: webextension-api-property browser-compat: webextensions.api.declarativeNetRequest.MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL --- {{AddonSidebar}} The number of times {{WebExtAPIRef("declarativeNetRequest.getMatchedRules")}} can be called within a period of {{WebExtAPIRef("declarativeNetRequest.GETMATCHEDRULES_QUOTA_INTERVAL")}}. Its value is `20`. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/getenabledrulesets/index.md
--- title: declarativeNetRequest.getEnabledRulesets slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/getEnabledRulesets page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.getEnabledRulesets --- {{AddonSidebar}} Returns the IDs for the set of activated static rulesets. ## Syntax ```js-nolint let rulesetIds = await browser.declarativeNetRequest.getEnabledRulesets(); ``` ### Parameters This function takes no parameters. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) fulfilled with an array of string containing static rulesets IDs. If no rules are active, the array is empty. If the request fails, the promise is rejected with an error message. ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/getdynamicrules/index.md
--- title: declarativeNetRequest.getDynamicRules slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/getDynamicRules page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.getDynamicRules --- {{AddonSidebar}} Returns the set of dynamic rules for the extension. ## Syntax ```js-nolint let gettingDynamicRules = browser.declarativeNetRequest.getDynamicRules(); ``` ### Parameters This function takes no parameters. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is fulfilled with an array of {{WebExtAPIRef("declarativeNetRequest.Rule")}} objects. Each of these represents a rule that belongs to the extension. If no rules are active, the array is empty. If the request fails, the promise is rejected with an error message. ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/rulecondition/index.md
--- title: declarativeNetRequest.RuleCondition slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/RuleCondition page-type: webextension-api-type browser-compat: webextensions.api.declarativeNetRequest.RuleCondition --- {{AddonSidebar}} Details of the condition that determines whether a rule matches a request, as the `condition` property of a {{WebExtAPIRef("declarativeNetRequest.Rule")}}. ## Type Values of this type are objects. They contain these properties: - `domainType` {{optional_inline}} - : A `string`. Specifies whether the network request is first-party or third-party to the domain from where it originated. If omitted, all requests are accepted. Possible values are `"firstParty"` and `"thirdParty"`. - `domains` {{deprecated_inline}} {{optional_inline}} - : An array of `string`. Use [`initiatorDomains`](#initiatordomains) instead. The rule only matches network requests originating from this list of domains. - `excludedDomains` {{deprecated_inline}} {{optional_inline}} - : An array of `string`. Use [`excludedInitiatorDomains`](#excludedinitiatordomains) instead. The rule does not match network requests originating from this list of domains. - `initiatorDomains` {{optional_inline}} - : An array of `string`. The rule only matches network requests originating from this list of domains. If the list is omitted, the rule is applied to requests from all domains. An empty list is not allowed. A [canonical domain](#canonical_domain) should be used. This matches against the request initiator and not the request URL. - `excludedInitiatorDomains` {{optional_inline}} - : An array of `string`. The rule does not match network requests originating from this list of domains. If the list is empty or omitted, no domains are excluded. This takes precedence over `initiatorDomains`. A [canonical domain](#whocanonical_domain) should be used. This matches against the request initiator and not the request URL. - `isUrlFilterCaseSensitive` {{optional_inline}} - : A `boolean`. Whether the [`urlFilter`](#urlfilter) or [`regexFilter`](#regexfilter) (whichever is specified) is case sensitive. While there is consensus on defaulting to `false` across browsers in [WECG issue 269](https://github.com/w3c/webextensions/issues/269), the value used to be `true` in (older) versions of Chrome and Safari. See [Browser compatibility](#browser_compatibility) for details. - `regexFilter` {{optional_inline}} - : A `string`. Regular expression to match against the network request URL. Note that: - The supported format is not stable and varies across browsers, see ["Regular expressions in DNR API (regexFilter)" in WECG issue 344](https://github.com/w3c/webextensions/issues/344) for details. - Only one of [`urlFilter`](#urlfilter) or [`regexFilter`](#regexfilter) can be specified. - The [`regexFilter`](#regexfilter) must be composed of only {{Glossary("ASCII")}} characters. This is matched against a URL where the host is encoded in the [punycode](https://en.wikipedia.org/wiki/Punycode) format (in case of internationalized domains) and any other non-ascii characters are URL encoded in utf-8. - `requestDomains` {{optional_inline}} - : An array of `string`. The rule only matches network requests when the domain matches one from this list. If the list is omitted, the rule is applied to requests from all domains. An empty list is not allowed. A [canonical domain](#canonical_domain) should be used. - `excludedRequestDomains` {{optional_inline}} - : An array of `string`. The rule does not match network requests when the domains matches one from this list. If the list is empty or omitted, no domains are excluded. This takes precedence over `requestDomains`. A [canonical domain](#canonical_domain) should be used. - `requestMethods` {{optional_inline}} - : An array of `string`. List of HTTP request methods that the rule matches. An empty list is not allowed. Specifying a `requestMethods` rule condition also excludes non-HTTP(s) requests, whereas specifying [`excludedRequestMethods`](#excludedrequestmethods) does not. - `excludedRequestMethods` {{optional_inline}} - : An array of `string`. List of request methods that the rule does not match on. Only one of [`requestMethods`](#requestmethods) and `excludedRequestMethods` should be specified. If neither of them is specified, all request methods are matched. - `resourceTypes` {{optional_inline}} - : An array of {{WebExtAPIRef("declarativeNetRequest.ResourceType")}}. List of resource types that the rule matches with. An empty list is not allowed. This must be specified for `"allowAllRequests"` rules and may only include the `"sub_frame"` and `"main_frame"` resource types. - `excludedResourceTypes` {{optional_inline}} - : An array of {{WebExtAPIRef("declarativeNetRequest.ResourceType")}}. List of resource types that the rule does not match on. Only one of [`resourceTypes`](#resourcetypes) and `excludedResourceTypes` should be specified. If neither of them is specified, all resource types except `"main_frame"` are blocked. - `tabIds` {{optional_inline}} - : An array of `number`. List of {{WebExtAPIRef("tabs.Tab")}}.`id` that the rule should match. An ID of {{WebExtAPIRef("tabs.TAB_ID_NONE")}} matches requests that don't originate from a tab. An empty list is not allowed. Only supported for session-scoped rules. - `excludedTabIds` {{optional_inline}} - : An array of `number`. List of {{WebExtAPIRef("tabs.Tab")}}.`id` that the rule should not match. An ID of {{WebExtAPIRef("tabs.TAB_ID_NONE")}} excludes requests that do not originate from a tab. Only supported for session-scoped rules. - `urlFilter` {{optional_inline}} - : A `string`. The pattern that is matched against the network request URL. Supported constructs: - `*` : Wildcard: Matches any number of characters. - `|` : Left or right anchor: If used at either end of the pattern, specifies the beginning or end of the URL respectively. - `||` : Domain name anchor: If used at the beginning of the pattern, specifies the start of a (sub-)domain of the URL. - `^` : Separator character: This matches anything except a letter, a digit, or one of `_`, `-`, `.`, or `%`. The last `^` may also match the end of the URL instead of a separator character. `urlFilter` is composed of the following parts: (optional left/domain name anchor) + pattern + (optional right anchor). If omitted, all URLs are matched. An empty string is not allowed. A pattern beginning with `||*` is not allowed. Use `*` instead. Note that: - Only one of `urlFilter` or [`regexFilter`](#regexfilter) can be specified. - The `urlFilter` must be composed of only ASCII characters. This is matched against a URL where the host is encoded in the [punycode](https://en.wikipedia.org/wiki/Punycode) format (in case of internationalized domains) and any other non-ASCII characters are URL encoded in utf-8. For example, when the request URL is `http://abc.рф?q=ф`, the `urlFilter` is matched against the URL `http://abc.xn--p1ai/?q=%D1%84`. ### Canonical domain Domains specified in `initiatorDomains`, `excludedInitiatorDomains`, `requestDomains`, or `excludedRequestDomains` should comply with the following: - Sub-domains such as "a.example.com" are allowed. - The entries must consist of only _lowercase_ ASCII characters. - Use [Punycode](https://en.wikipedia.org/wiki/Punycode) encoding for internationalized domains. - IPv4 addresses must be represented as 4 numbers separated by a dot. - IPv6 addresses should be represented in their canonical form, wrapped in square brackets. To programmatically generate the canonical domain for a URL, use the [URL API](/en-US/docs/Web/API/URL) and read its `hostname` property, i.e., `new URL(url).hostname`. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/setextensionactionoptions/index.md
--- title: declarativeNetRequest.setExtensionActionOptions slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/setExtensionActionOptions page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.setExtensionActionOptions --- {{AddonSidebar}} Configures whether the action count for tabs is displayed as the extension action's badge text and provides a way for the action count to be incremented. ## Syntax ```js-nolint let count = browser.declarativeNetRequest.setExtensionActionOptions( extensionActionOptions, // object ); ``` ### Parameters - `extensionActionOptions` - : An object containing the configuration details for the action count for tabs. - `displayActionCountAsBadgeText` {{optional_inline}} - : `boolean` Whether to automatically display the action count for a page as the extension's badge text. This preference persists across sessions. - `tabUpdate` {{optional_inline}} - : `object`. Details of how the tab's action count should be adjusted. See the [tabUpdate](#tabupdate_2) section for more details. ## Additional objects ### tabUpdate - `increment` - : `number` The amount to increment the tab's action count by. Negative values decrement the count. - `tabId` - : `number` The tab to update the action count for. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with no arguments. If the request fails, the promise is rejected with an error message. ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/matchedrule/index.md
--- title: declarativeNetRequest.MatchedRule slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/MatchedRule page-type: webextension-api-type browser-compat: webextensions.api.declarativeNetRequest.MatchedRule --- {{AddonSidebar}} An object describing the matched rule. This type may be returned by the {{WebExtAPIRef("declarativeNetRequest.getMatchedRules")}} or {{WebExtAPIRef("declarativeNetRequest.testMatchOutcome")}} methods, or observed through the {{WebExtAPIRef("declarativeNetRequest.onRuleMatchedDebug")}} event. ## Type Values of this type are objects. They contain these properties: - `extensionId` - : A `string`. The ID of the extension, if this rule belongs to a different extension. This property is only available when used with {{WebExtAPIRef("declarativeNetRequest.testMatchOutcome")}}, with the `includeOtherExtensions` option set to `true`. - `ruleId` - : A `number`. The matching rule's ID. - `rulesetId` - : A `string`. The ID of the [ruleset](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest#rulesets) this rule belongs to. The value returned is: - For a rule originating from the set of static rules, the value specified in the "id" key of the ruleset in the [`declarative_net_request.rule_resources` manifest key](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request). - For a rule originating from the set of dynamic rules, the value defined in {{WebExtAPIRef("declarativeNetRequest.DYNAMIC_RULESET_ID")}}, i.e., `"_dynamic"`. - For a rule originating from the set of session rules, the value defined in {{WebExtAPIRef("declarativeNetRequest.SESSION_RULESET_ID")}}, i.e., `"_session"`. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} <!-- // 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/declarativenetrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/declarativenetrequest/getavailablestaticrulecount/index.md
--- title: declarativeNetRequest.getAvailableStaticRuleCount slug: Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/getAvailableStaticRuleCount page-type: webextension-api-function browser-compat: webextensions.api.declarativeNetRequest.getAvailableStaticRuleCount --- {{AddonSidebar}} Returns the number of static rules that can be activated before the global static rule limit is reached. ## Syntax ```js-nolint let count = await browser.declarativeNetRequest.getAvailableStaticRuleCount(); ``` ### Parameters This function takes no parameters. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) fulfilled with a number that indicates how many static rules can enable before the global static rule limit is reached. If the request fails, the promise is rejected with an error message. ## Examples {{WebExtExamples}} ## Browser compatibility {{Compat}} <!-- // 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/history/index.md
--- title: history slug: Mozilla/Add-ons/WebExtensions/API/history page-type: webextension-api browser-compat: webextensions.api.history --- {{AddonSidebar}} Use the `history` API to interact with the browser history. If you are looking for information about the browser session history, see the [History interface](/en-US/docs/Web/API/History). > **Note:** Downloads are treated as [`HistoryItem`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/HistoryItem) objects. Therefore, events such as [`history.onVisited`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/onVisited) fire for downloads. Browser history is a chronological record of pages the user has visited. The history API enables you to: - [search for pages that appear in the browser history](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/search) - [remove individual pages from the browser history](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/deleteUrl) - [add pages to the browser history](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/addUrl) - [remove all pages from the browser history](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/deleteAll). However, the user may have visited a single page multiple times, so the API also has the concept of "visits". So you can also use this API to: - [retrieve the complete set of visits the user made to a particular page](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/getVisits) - [remove visits to any pages made during a given time period](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/deleteRange). To use this API, an extension must request the "history" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) in its [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file. ## Types - {{WebExtAPIRef("history.TransitionType")}} - : Describes how the browser navigated to a particular page. - {{WebExtAPIRef("history.HistoryItem")}} - : Provides information about a particular page in the browser history. - {{WebExtAPIRef("history.VisitItem")}} - : Describes a single visit to a page. ## Functions - {{WebExtAPIRef("history.search()")}} - : Searches the browser history for [`history.HistoryItem`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/HistoryItem) objects matching the given criteria. - {{WebExtAPIRef("history.getVisits()")}} - : Retrieves information about visits to a given page. - {{WebExtAPIRef("history.addUrl()")}} - : Adds a record to the browser history of a visit to the given page. - {{WebExtAPIRef("history.deleteUrl()")}} - : Removes all visits to the given URL from the browser history. - {{WebExtAPIRef("history.deleteRange()")}} - : Removes all visits to pages that the user made during the given time range. - {{WebExtAPIRef("history.deleteAll()")}} - : Removes all visits from the browser history. ## Events - {{WebExtAPIRef("history.onTitleChanged")}} - : Fired when the title of a page visited by the user is recorded. - {{WebExtAPIRef("history.onVisited")}} - : Fired each time the user visits a page, providing the {{WebExtAPIRef("history.HistoryItem")}} data for that page. - {{WebExtAPIRef("history.onVisitRemoved")}} - : Fired when a URL is removed completely from the browser history. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.history`](https://developer.chrome.com/docs/extensions/reference/history/) API. This documentation is derived from [`history.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/history.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/history
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/history/onvisited/index.md
--- title: history.onVisited slug: Mozilla/Add-ons/WebExtensions/API/history/onVisited page-type: webextension-api-event browser-compat: webextensions.api.history.onVisited --- {{AddonSidebar}} Fired each time the user visits a page. A {{WebExtAPIRef("history.HistoryItem")}} object is passed to the listener. This event fires before the page has loaded. ## Syntax ```js-nolint browser.history.onVisited.addListener(listener) browser.history.onVisited.removeListener(listener) browser.history.onVisited.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `result` - : {{WebExtAPIRef('history.HistoryItem')}}. An object representing the item in the browser's history. At the time that this event is sent, the browser doesn't yet know the title of the page. If the browser has visited this page before and has remembered its old title, then the `HistoryItem.title` object will contain the old title of the page. If the browser doesn't have a record of the page's old title, then `HistoryItem.title` will be empty. To get the titles of pages as soon as they are known, listen for {{WebExtAPIRef("history.onTitleChanged")}}. ## Browser compatibility {{Compat}} ## Examples Listen for visits, and log the URL and visit time. ```js function onVisited(historyItem) { console.log(historyItem.url); console.log(new Date(historyItem.lastVisitTime)); } browser.history.onVisited.addListener(onVisited); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.history`](https://developer.chrome.com/docs/extensions/reference/history/#event-onVisited) API. This documentation is derived from [`history.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/history.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/history
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/history/historyitem/index.md
--- title: history.HistoryItem slug: Mozilla/Add-ons/WebExtensions/API/history/HistoryItem page-type: webextension-api-type browser-compat: webextensions.api.history.HistoryItem --- {{AddonSidebar}} A `HistoryItem` object provides information about a page in the browser history. ## Type This is an object with the following properties: - `id` - : `string`. Unique identifier for the item. - `url` {{optional_inline}} - : `string`. The URL of the page. - `title` {{optional_inline}} - : `string`. The title of the page. - `lastVisitTime` {{optional_inline}} - : `number`. The date and time the page was last loaded, represented in milliseconds since the epoch. - `visitCount` {{optional_inline}} - : `number`. The number of times the user has visited the page. - `typedCount` {{optional_inline}} - : `number`. The number of times the user has navigated to this page by typing in the address. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.history`](https://developer.chrome.com/docs/extensions/reference/history/#type-HistoryItem) API. This documentation is derived from [`history.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/history.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/history
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/history/onvisitremoved/index.md
--- title: history.onVisitRemoved slug: Mozilla/Add-ons/WebExtensions/API/history/onVisitRemoved page-type: webextension-api-event browser-compat: webextensions.api.history.onVisitRemoved --- {{AddonSidebar}} Fired when a page is removed completely from the browser history. - If all visits to a single page are removed (for example, using {{WebExtAPIRef("history.deleteUrl")}}), then this event is fired once. - If a range of visits is removed (for example, using {{WebExtAPIRef("history.deleteRange")}} or a browser feature like "Clear Recent History"), then it is fired once for each page _whose visits all fall within the cleared range_. - If the browser's entire history is cleared (for example, using {{WebExtAPIRef("history.deleteAll")}}), then it is fired only once. ## Syntax ```js-nolint browser.history.onVisitRemoved.addListener(listener) browser.history.onVisitRemoved.removeListener(listener) browser.history.onVisitRemoved.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `removed` - : `object`. Details of the removal. This is an object containing two properties: a boolean `allHistory` and an array `urls`. - If this event is firing because all history was cleared, `allHistory` will be `true` and `urls` will be an empty array. - Otherwise, `allHistory` will be `false` and `urls` will contain one item, which is the URL of the removed page. ## Browser compatibility {{Compat}} ## Examples ```js function onRemoved(removed) { if (removed.allHistory) { console.log("All history removed"); } else if (removed.urls.length) { console.log(`URL removed: ${removed.urls[0]}`); } } browser.history.onVisitRemoved.addListener(onRemoved); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.history`](https://developer.chrome.com/docs/extensions/reference/history/#event-onVisitRemoved) API. This documentation is derived from [`history.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/history.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/history
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/history/search/index.md
--- title: history.search() slug: Mozilla/Add-ons/WebExtensions/API/history/search page-type: webextension-api-function browser-compat: webextensions.api.history.search --- {{AddonSidebar}} Searches the browser's history for {{WebExtAPIRef("history.HistoryItem")}} objects matching the given criteria. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let searching = browser.history.search( query // object ) ``` ### Parameters - `query` - : An object which indicates what to look for in the browser's history. This object has the following fields: - `text` - : `string`. Search history items by URL and title. The string is split up into separate search terms at space boundaries. Each search term is matched case-insensitively against the history item's URL and title. The history item will be returned if all search terms match. For example, consider this item: URL: `"http://example.org"` Title: `"Example Domain"` ```plain "http" -> matches "domain" -> matches "MAIN ample" -> matches "main tt" -> matches "main https" -> does not match ``` Specify an empty string (`""`) to retrieve all {{WebExtAPIRef("history.HistoryItem")}} objects that meet all the other criteria. - `startTime` {{optional_inline}} - : `number` or `string` or `object`. A value indicating a date and time. This can be represented as: a [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object, an [ISO 8601 date string](https://www.iso.org/iso-8601-date-and-time-format.html), or the number of milliseconds since the epoch. If it is supplied, this option excludes results whose `lastVisitTime` is earlier than this time. If it is omitted, the search is limited to the last 24 hours. - `endTime` {{optional_inline}} - : `number` or `string` or `object`. A value indicating a date and time. This can be represented as: a [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object, an [ISO 8601 date string](https://www.iso.org/iso-8601-date-and-time-format.html), or the number of milliseconds since the epoch. If it is supplied, this option limits results to those visited before this date. If it is omitted, then all entries are considered from the start time onwards. - `maxResults` {{optional_inline}} - : `number`. The maximum number of results to retrieve. Defaults to 100, with a minimum value of 1. The function will throw an error if you pass it a `maxResults` value less than 1. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) will be fulfilled with an array of objects of type {{WebExtAPIRef("history.HistoryItem")}}, each describing a single matching history item. Items are sorted in reverse chronological order. ## Examples Logs the URL and last visit time for all history items visited in the last 24 hours: ```js function onGot(historyItems) { for (const item of historyItems) { console.log(item.url); console.log(new Date(item.lastVisitTime)); } } browser.history.search({ text: "" }).then(onGot); ``` Logs the URL and last visit time for all history items ever visited: ```js function onGot(historyItems) { for (const item of historyItems) { console.log(item.url); console.log(new Date(item.lastVisitTime)); } } browser.history .search({ text: "", startTime: 0, }) .then(onGot); ``` Logs the URL and last visit time of the most recent visit to a page that contain the string "mozilla": ```js function onGot(historyItems) { for (const item of historyItems) { console.log(item.url); console.log(new Date(item.lastVisitTime)); } } browser.history .search({ text: "mozilla", startTime: 0, maxResults: 1, }) .then(onGot); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.history`](https://developer.chrome.com/docs/extensions/reference/history/#method-search) API. This documentation is derived from [`history.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/history.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/history
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/history/getvisits/index.md
--- title: history.getVisits() slug: Mozilla/Add-ons/WebExtensions/API/history/getVisits page-type: webextension-api-function browser-compat: webextensions.api.history.getVisits --- {{AddonSidebar}} Retrieves information about all visits to the given URL. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let getting = browser.history.getVisits( details // object ) ``` ### Parameters - `details` - : An object with the following properties: - `url` - : `string`. The URL for which to retrieve visit information. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) will be fulfilled with an array of `{{WebExtAPIRef('history.VisitItem')}}` objects each representing a visit to the given URL. Visits are sorted in reverse chronological order. ## Browser compatibility {{Compat}} ## Examples List all visits to the most recently-visited page: ```js function gotVisits(visits) { console.log(`Visit count: ${visits.length}`); for (const visit of visits) { console.log(visit.visitTime); } } function listVisits(historyItems) { if (historyItems.length) { console.log(`URL ${historyItems[0].url}`); const gettingVisits = browser.history.getVisits({ url: historyItems[0].url, }); gettingVisits.then(gotVisits); } } let searching = browser.history.search({ text: "", startTime: 0, maxResults: 1, }); searching.then(listVisits); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.history`](https://developer.chrome.com/docs/extensions/reference/history/#method-getVisits) API. This documentation is derived from [`history.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/history.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/history
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/history/visititem/index.md
--- title: history.VisitItem slug: Mozilla/Add-ons/WebExtensions/API/history/VisitItem page-type: webextension-api-type browser-compat: webextensions.api.history.VisitItem --- {{AddonSidebar}} An object describing a single visit to a page. ## Type Values of this type are objects. They contain the following properties: - `id` - : `string`. The unique identifier for the {{WebExtAPIRef("history.HistoryItem")}} associated with this visit. - `visitId` - : `string`. The unique identifier for this visit. - `visitTime` {{optional_inline}} - : `number`. When this visit occurred, represented in milliseconds since the epoch. - `referringVisitId` - : `string`. The visit ID of the referrer. - `transition` - : {{WebExtAPIRef('history.TransitionType')}}. Describes how the browser navigated to the page on this occasion. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.history`](https://developer.chrome.com/docs/extensions/reference/history/#type-VisitItem) API. This documentation is derived from [`history.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/history.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/history
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/history/deleterange/index.md
--- title: history.deleteRange() slug: Mozilla/Add-ons/WebExtensions/API/history/deleteRange page-type: webextension-api-function browser-compat: webextensions.api.history.deleteRange --- {{AddonSidebar}} Removes all visits to pages that the user made during the given time range. If this removes all visits made to a given page, then the page will be no longer appear in the browser history and {{WebExtAPIRef("history.onVisitRemoved")}} will fire for it. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let deletingRange = browser.history.deleteRange( range // object ) ``` ### Parameters - `range` - : `object`. Specification of the time range for which to delete visits. - `startTime` - : `number` or `string` or `object`. A value indicating a date and time. This can be represented as: a [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object, an [ISO 8601 date string](https://www.iso.org/iso-8601-date-and-time-format.html), or the number of [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). Specifies the start time for the range. - `endTime` - : `number` or `string` or `object`. A value indicating a date and time. This can be represented as: a [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object, an [ISO 8601 date string](https://www.iso.org/iso-8601-date-and-time-format.html), or the number of [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). Specifies the end time for the range. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) will be fulfilled with no parameters when the range has been deleted. ## Browser compatibility {{Compat}} ## Examples Delete all visits made in the last minute: ```js const MINUTE = 60 * 1000; function oneMinuteAgo() { return Date.now() - MINUTE; } browser.history.deleteRange({ startTime: oneMinuteAgo(), endTime: Date.now(), }); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.history`](https://developer.chrome.com/docs/extensions/reference/history/#method-deleteRange) API. This documentation is derived from [`history.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/history.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/history
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/history/deleteall/index.md
--- title: history.deleteAll() slug: Mozilla/Add-ons/WebExtensions/API/history/deleteAll page-type: webextension-api-function browser-compat: webextensions.api.history.deleteAll --- {{AddonSidebar}} Deletes all visits from the browser's history. This function triggers {{WebExtAPIRef("history.onVisitRemoved")}} just once, with `allHistory` set to `true` and an empty `urls` argument. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let deletingAll = browser.history.deleteAll() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) will be fulfilled with no parameters when all history has been deleted. ## Browser compatibility {{Compat}} ## Examples Delete all history when the user clicks a browser action: ```js function onDeleteAll() { console.log("Deleted all history"); } function deleteAllHistory() { let deletingAll = browser.history.deleteAll(); deletingAll.then(onDeleteAll); } deleteAllHistory(); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.history`](https://developer.chrome.com/docs/extensions/reference/history/#method-deleteAll) API. This documentation is derived from [`history.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/history.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/history
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/history/ontitlechanged/index.md
--- title: history.onTitleChanged slug: Mozilla/Add-ons/WebExtensions/API/history/onTitleChanged page-type: webextension-api-event browser-compat: webextensions.api.history.onTitleChanged --- {{AddonSidebar}} Fired when the title of a page visited by the user is recorded. To listen for visits to a page you use {{WebExtAPIRef("history.onVisited")}}. However, the {{WebExtAPIRef("history.HistoryItem")}} that this event passes to its listener does not include the page title, because the page title is typically not known at the time `history.onVisited` is sent. Instead, the stored {{WebExtAPIRef("history.HistoryItem")}} is updated with the page title after the page has loaded, once the title is known. The `history.onTitleChanged` event is fired at that time. So if you need to know the titles of pages as they are visited, listen for `history.onTitleChanged`. ## Syntax ```js-nolint browser.history.onTitleChanged.addListener(listener) browser.history.onTitleChanged.removeListener(listener) browser.history.onTitleChanged.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed an object with these properties: - `id` - : `String`. The unique identifier for the {{WebExtAPIRef("history.HistoryItem")}} associated with this visit. - `url` - : `String`. URL of the page visited. - `title` - : `String`. Title of the page visited. ## Browser compatibility {{Compat}} ## Examples Listen for title change events, and log the ID, URL, and title of the visited pages. ```js function handleTitleChanged(item) { console.log(item.id); console.log(item.title); console.log(item.url); } browser.history.onTitleChanged.addListener(handleTitleChanged); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.history`](https://developer.chrome.com/docs/extensions/reference/history/#event-onVisited) API. This documentation is derived from [`history.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/history.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