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/privacy
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/privacy/websites/index.md
--- title: privacy.websites slug: Mozilla/Add-ons/WebExtensions/API/privacy/websites page-type: webextension-api-property browser-compat: webextensions.api.privacy.websites --- {{AddonSidebar}} The {{WebExtAPIRef("privacy.websites")}} property contains privacy-related settings controlling the way to browser interacts with websites. Each property is a {{WebExtAPIRef("types.BrowserSetting")}} object. Default values for these properties tend to vary across browsers. ## Properties - `cookieConfig` - : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is an object. The object has two properties: - `behavior`: a string which may take any of the following values: - "allow_all": accept all cookies - "reject_all": reject all cookies - "reject_third_party": reject all third-party cookies - "allow_visited": accept a third-party cookie only if the cookie's top-level domain already has at least one cookie. - "reject_trackers": reject tracking cookies - "reject_trackers_and_partition_foreign": reject trackers and partition third-party cookies. - `nonPersistentCookies` {{deprecated_inline}}: a boolean. If true, all cookies will be treated as session cookies. - `firstPartyIsolate` - : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is a boolean. If `true`, the `firstPartyIsolate` preference makes the browser associate all data (including cookies, HSTS data, cached images, and more) for any third party domains with the domain in the address bar. This prevents third party trackers from using directly stored information to identify the user across different websites, but may break websites where the user logs in with a third party account (such as a Facebook or Google account). Defaults to `false`. - `hyperlinkAuditingEnabled` - : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is a boolean. If `true`, the browser sends auditing pings when a website uses the `ping` attribute to request them. - `protectedContentEnabled` - : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is a boolean. Available on Windows only. If `true`, the browser provides a unique ID to plugins in order to run protected content. - `referrersEnabled` - : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is a boolean. If enabled, the browser sends [referer](/en-US/docs/Web/HTTP/Headers/Referer) headers with your requests. - `resistFingerprinting` - : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is a boolean. Browser fingerprinting is the practice by which websites use Web APIs to collect status or configuration data associated with the browser or the device it's running on. By doing this, they can build up a digital fingerprint that they can use to identify and track a particular user. If `true`, the `resistFingerprinting` preference makes the browser report generic spoofed information for data that's commonly used for fingerprinting. Such data includes the number of CPU cores, precision of JavaScript timers, and the local timezone. It will also disable features that are used in fingerprinting, such as GamePad support, and the WebSpeech and Navigator APIs. Defaults to `false`. - `thirdPartyCookiesAllowed` - : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is a boolean. If `false`, the browser blocks [third-party cookies](/en-US/docs/Web/HTTP/Cookies#third-party_cookies). - `trackingProtectionMode` - : "Tracking protection" is a browser feature that blocks requests made to domains that are known to engage in cross-site tracking of users. Sites that track users are most commonly third-party advertising and analytics sites. This setting is a {{WebExtAPIRef("types.BrowserSetting")}} object that determines whether the browser should enable tracking protection. Its underlying value is a string that may take one of three values: - `"always"`: tracking protection is on. - `"never"`: tracking protection is off. - `"private_browsing"`: tracking protection is on in private browsing windows only. ## Browser compatibility {{Compat}} ## Examples Set the `hyperlinkAuditingEnabled` property. ```js function onSet(result) { if (result) { console.log("success"); } else { console.log("failure"); } } browser.browserAction.onClicked.addListener(() => { let getting = browser.privacy.websites.hyperlinkAuditingEnabled.get({}); getting.then((got) => { console.log(got.value); if ( got.levelOfControl === "controlled_by_this_extension" || got.levelOfControl === "controllable_by_this_extension" ) { let setting = browser.privacy.websites.hyperlinkAuditingEnabled.set({ value: true, }); setting.then(onSet); } else { console.log("Not able to set hyperlinkAuditingEnabled"); } }); }); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.privacy`](https://developer.chrome.com/docs/extensions/reference/privacy/) API. This documentation is derived from [`privacy.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/privacy.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/i18n/index.md
--- title: i18n slug: Mozilla/Add-ons/WebExtensions/API/i18n page-type: webextension-api browser-compat: webextensions.api.i18n --- {{AddonSidebar}} Functions to internationalize your extension. You can use these APIs to get localized strings from locale files packaged with your extension, find out the browser's current language, and find out the value of its [Accept-Language header](/en-US/docs/Web/HTTP/Content_negotiation#the_accept-language_header). See the [Internationalization](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization) page for a guide on using this API. ## Types - {{WebExtAPIRef("i18n.LanguageCode")}} - : A [language tag](https://www.rfc-editor.org/rfc/rfc9110.html#name-language-tags) such as `"en-US"` or "`fr`". ## Functions - {{WebExtAPIRef("i18n.getAcceptLanguages()")}} - : Gets the [accept-languages](/en-US/docs/Web/HTTP/Content_negotiation#the_accept-language_header) of the browser. This is different from the locale used by the browser. To get the locale, use {{WebExtAPIRef('i18n.getUILanguage')}}. - {{WebExtAPIRef("i18n.getMessage()")}} - : Gets the localized string for the specified message. - {{WebExtAPIRef("i18n.getUILanguage()")}} - : Gets the UI language of the browser. This is different from {{WebExtAPIRef('i18n.getAcceptLanguages')}} which returns the preferred user languages. - {{WebExtAPIRef("i18n.detectLanguage()")}} - : Detects the language of the provided text using the [Compact Language Detector](https://github.com/CLD2Owners/cld2). ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.i18n`](https://developer.chrome.com/docs/extensions/reference/i18n/) API. This documentation is derived from [`i18n.json`](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/extensions/common/api/i18n.json) in the Chromium code. ## See also - [Internationalization](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization): a guide to using the WebExtension i18n system. - [Locale-Specific Message reference](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n/Locale-Specific_Message_reference): extensions supply locale-specific strings in files called `messages.json`. This page describes the format of `messages.json`. <!-- // 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/i18n
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/i18n/detectlanguage/index.md
--- title: i18n.detectLanguage() slug: Mozilla/Add-ons/WebExtensions/API/i18n/detectLanguage page-type: webextension-api-function browser-compat: webextensions.api.i18n.detectLanguage --- {{AddonSidebar}} Detects the language of the provided text using the [Compact Language Detector](https://github.com/CLD2Owners/cld2) (CLD). This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). See the [Internationalization](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization) page for a guide on using this function. ## Syntax ```js-nolint let detectingLanguages = browser.i18n.detectLanguage( text // string ) ``` ### Parameters - `text` - : `string`. User input string to be translated. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a result object. The result object has two properties: - `isReliable` - : `boolean`. Whether the language was detected reliably. - `languages` - : `array` of objects, each of which has two properties: - `language` - : {{WebExtAPIRef('i18n.LanguageCode')}}. The detected language. - `percentage` - : `integer`. The percentage of the input string that was in the detected language. ## Browser compatibility {{Compat}} ## Examples ```js function onLanguageDetected(langInfo) { for (const lang of langInfo.languages) { console.log(`Language is: ${lang.language}`); console.log(`Percentage is: ${lang.percentage}`); } } let text = "L'homme est né libre, et partout il est dans les fers."; let detecting = browser.i18n.detectLanguage(text); detecting.then(onLanguageDetected); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.i18n`](https://developer.chrome.com/docs/extensions/reference/i18n/#method-detectLanguage) API. This documentation is derived from [`i18n.json`](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/extensions/common/api/i18n.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/i18n
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/i18n/locale-specific_message_reference/index.md
--- title: Locale-specific message reference slug: Mozilla/Add-ons/WebExtensions/API/i18n/Locale-Specific_Message_reference page-type: guide --- {{AddonSidebar}} Each internationalized extension has at least one file named `messages.json` that provides locale-specific strings. This page describes the format of `messages.json` files. > **Note:** For information on how to internationalize your extensions, see our [i18n](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization) guide. ## messages.json example The following code shows an example `messages.json file`, taken from our [notify-link-clicks-i18n example](https://github.com/mdn/webextensions-examples/tree/main/notify-link-clicks-i18n) extension. Only the "_name_" and "message" fields are required. ```json { "extensionName": { "message": "Notify link clicks i18n", "description": "Name of the extension." }, "extensionDescription": { "message": "Shows a notification when the user clicks on links.", "description": "Description of the extension." }, "notificationTitle": { "message": "Click notification", "description": "Title of the click notification." }, "notificationContent": { "message": "You clicked $URL$.", "description": "Tells the user which link they clicked.", "placeholders": { "url": { "content": "$1", "example": "https://developer.mozilla.org" } } } } ``` ## Placement Your `messages.json` files need to be placed inside directories named after the locale each one is supporting — `en`, `de`, `ja`, etc. These in turn need to be placed inside a directory called `_locales`, inside the root of your extension. ## Member details This section describes each member that can appear in a `messages.json` file. ### name Each top-level member is named after the name of the message string you are localizing, for example `"extensionName"` or `"notificationContent"` in the example above. Each name is case-insensitive, and acts as a key allowing you to retrieve the localized message text. The name can include the following characters: - A-Z - a-z - 0-9 - \_ (underscore) - @ > **Note:** You shouldn't define names that start with @@. Such names are reserved for [predefined messages](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#predefined_messages). ### message At least this property must be set for every string. The `"message"` member contains a localized string that can contain [placeholders](#placeholders). You can use: - _$placeholder_name$_ (case insensitive) to insert a particular placeholder (for example $URL$ in the example above) into your string. - `$1`, `$2`, `$3`, etc. to directly insert values obtained from a {{WebExtAPIRef("i18n.getMessage()")}} call into your string. Other points to note: - Any number of consecutive dollar signs appearing in strings are replaced by the same number of dollar signs minus one. So, $$ > $, $$$ > $$, etc. - When the locale file is read, tokens matching `/\$([a-z0-9_@]+)\$/i` are replaced with the matching value from the string's "placeholders" object. These substitutions happen prior to processing any `/\$\d/` tokens in the message. - When a locale string is used, tokens matching `/\$\d+/` are replaced with the replacements passed to {{WebExtAPIRef("i18n.getMessage()")}}. - `getMessage()` won't process calls with more than 9 placeholders/substitutions. ### description {{optional_inline}} The `"description"` member should contain a description of the message string's contents, aimed to provide a translator with help to create the best translation possible of the string. ### placeholders {{optional_inline}} The `"placeholders"` member defines one or more placeholder substrings to be used within the message — these can be used to hardcode items that you don't want translated, or refer to variables. Each placeholder substring definition has a number of values of its own: ```json "url" : { "content" : "$1", "example" : "https://developer.mozilla.org" } ``` #### placeholder name The placeholder name is used to represent the placeholder in the substitution string (e.g. `"url"` becomes `$url$`). It is case insensitive and can contain the same characters as a message string [name](#name). #### content The "content" item defines the content of the placeholder. This can be a hardcoded string, such as "My placeholder", but it can also include values obtained from a {{WebExtAPIRef("i18n.getMessage()")}} call. This property is required. For more information, see [Retrieving message strings from JavaScript](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#retrieving_message_strings_from_javascript). #### example {{optional_inline}} The optional "example" item is again intended to help translators by showing them an example of how the placeholder would appear to end users, allowing them to make the best choice when localizing the file.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/i18n
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/i18n/getuilanguage/index.md
--- title: i18n.getUILanguage() slug: Mozilla/Add-ons/WebExtensions/API/i18n/getUILanguage page-type: webextension-api-function browser-compat: webextensions.api.i18n.getUILanguage --- {{AddonSidebar}} Gets the UI language of the browser. This is different from {{WebExtAPIRef('i18n.getAcceptLanguages')}} which returns the preferred user languages. See the [Internationalization](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization) page for a guide on using this function. ## Syntax ```js-nolint browser.i18n.getUILanguage() ``` ### Parameters None. ### Return value `string`. The browser UI language code as an {{WebExtAPIRef("i18n.LanguageCode")}}. ## Browser compatibility {{Compat}} ## Examples ```js let uiLanguage = browser.i18n.getUILanguage(); console.log(uiLanguage); //e.g. "fr" ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.i18n`](https://developer.chrome.com/docs/extensions/reference/i18n/#method-getUILanguage) API. This documentation is derived from [`i18n.json`](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/extensions/common/api/i18n.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/i18n
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/i18n/getmessage/index.md
--- title: i18n.getMessage() slug: Mozilla/Add-ons/WebExtensions/API/i18n/getMessage page-type: webextension-api-function browser-compat: webextensions.api.i18n.getMessage --- {{AddonSidebar}} Gets the localized string for the specified message. See the [Internationalization](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization) page for a guide on using this function. ## Syntax ```js-nolint browser.i18n.getMessage( messageName, // string substitutions // optional any ) ``` ### Parameters - `messageName` - : `string`. The name of the message, as specified in the messages.json file. If the message can't be found in messages.json: - Firefox returns "" and logs an error. - Chrome returns "" and does not log an error. - `substitutions` {{optional_inline}} - : `string` or `array` of `string`. A single substitution string, or an array of substitution strings. In Chrome, if you supply more than 9 substitution strings, `getMessage()` will return `undefined`. ### Return value `string`. Message localized for current locale. ## Browser compatibility {{Compat}} ## Examples Get the localized string for `"messageContent"`, with `target.url` substituted: ```js let message = browser.i18n.getMessage("messageContent", target.url); console.log(message); ``` This would work with a \_locales/en/messages.json file containing: ```json { "messageContent": { "message": "You clicked $URL$.", "description": "Tells the user which link they clicked.", "placeholders": { "url": { "content": "$1", "example": "https://developer.mozilla.org" } } } } ``` If `target.url` is "https\://developer.mozilla.org", then the value of message, in the "en" locale, would be: ```plain "You clicked https://developer.mozilla.org." ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.i18n`](https://developer.chrome.com/docs/extensions/reference/i18n/#method-getMessage) API. This documentation is derived from [`i18n.json`](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/extensions/common/api/i18n.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/i18n
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/i18n/languagecode/index.md
--- title: i18n.LanguageCode slug: Mozilla/Add-ons/WebExtensions/API/i18n/LanguageCode page-type: webextension-api-type browser-compat: webextensions.api.i18n.LanguageCode --- {{AddonSidebar}} A [language tag](https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.10) such as `"en-US"` or "`fr`". ## Type Values of this type are strings. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.i18n`](https://developer.chrome.com/docs/extensions/reference/i18n/#type-LanguageCode) API. This documentation is derived from [`i18n.json`](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/extensions/common/api/i18n.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/i18n
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/i18n/getacceptlanguages/index.md
--- title: i18n.getAcceptLanguages() slug: Mozilla/Add-ons/WebExtensions/API/i18n/getAcceptLanguages page-type: webextension-api-function browser-compat: webextensions.api.i18n.getAcceptLanguages --- {{AddonSidebar}} Gets the [accept-languages](/en-US/docs/Web/HTTP/Content_negotiation#the_accept-language_header) of the browser. This is different from the locale used by the browser. To get the locale, use {{WebExtAPIRef('i18n.getUILanguage')}}. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). See the [Internationalization](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization) page for a guide on using this function. ## Syntax ```js-nolint let gettingAcceptLanguages = browser.i18n.getAcceptLanguages() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an `array` of `{{WebExtAPIRef('i18n.LanguageCode')}}` objects. ## Browser compatibility {{Compat}} ## Examples ```js function onGot(languages) { console.log(languages); //e.g. Array [ "en-US", "en" ] } let gettingAcceptLanguages = browser.i18n.getAcceptLanguages(); gettingAcceptLanguages.then(onGot); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.i18n`](https://developer.chrome.com/docs/extensions/reference/i18n/#method-getAcceptLanguages) API. This documentation is derived from [`i18n.json`](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/extensions/common/api/i18n.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/webrequest/index.md
--- title: webRequest slug: Mozilla/Add-ons/WebExtensions/API/webRequest page-type: webextension-api browser-compat: webextensions.api.webRequest --- {{AddonSidebar}} Add event listeners for the various stages of making an HTTP request, which includes websocket requests on `ws://` and `wss://`. The event listener receives detailed information about the request and can modify or cancel the request. Each event is fired at a particular stage of the request. The typical sequence of events is like this: ![Order of requests is onBeforeRequest, onBeforeSendHeader, onSendHeaders, onHeadersReceived, onResponseStarted, and onCompleted. The onHeadersReceived can cause an onBeforeRedirect and an onAuthRequired. Events caused by onHeadersReceived start at the beginning onBeforeRequest. Events caused by onAuthRequired start at onBeforeSendHeader.](webrequest-flow.png) {{WebExtAPIRef("webRequest.onErrorOccurred", "onErrorOccurred")}} can fire at any time during the request. Also, note that sometimes the sequence of events may differ from this. For example, in Firefox, on an [HSTS](/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) upgrade, the `onBeforeRedirect` event is triggered immediately after `onBeforeRequest`. `onErrorOccurred` is also fired if [Firefox Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop) blocks a request. All events – _except_ `onErrorOccurred` – can take three arguments to `addListener()`: - the listener itself - a {{WebExtAPIRef("webRequest.RequestFilter", "filter")}} object, so you can only be notified for requests made to particular URLs or for particular types of resource - an optional `extraInfoSpec` object. You can use this to pass additional event-specific instructions. The listener function is passed a `details` object containing information about the request. This includes a request ID, which is provided to enable an add-on to correlate events associated with a single request. It is unique within a browser session and the add-on's context. It stays the same throughout a request, even across redirections and authentication exchanges. To use the `webRequest` API for a given host, an extension must have the `"webRequest"` [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) and the [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for that host. To use the `"blocking"` feature, the extension must also have the `"webRequestBlocking"` API permission. To intercept resources loaded by a page (such as images, scripts, or stylesheets), the extension must have the host permission for the resource as well as for the main page requesting the resource. For example, if a page at `https://developer.mozilla.org` loads an image from `https://mdn.mozillademos.org`, then an extension must have both host permissions if it is to intercept the image request. ## Modifying requests On some of these events, you can modify the request. Specifically, you can: - cancel the request in: - {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} - {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} - {{WebExtAPIRef("webRequest.onAuthRequired", "onAuthRequired")}} - redirect the request in: - {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} - {{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}} - modify request headers in: - {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} - modify response headers in: - {{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}} - supply authentication credentials in: - {{WebExtAPIRef("webRequest.onAuthRequired", "onAuthRequired")}} To do this, you need to pass an option with the value `"blocking"` in the `extraInfoSpec` argument to the event's `addListener()`. This makes the listener synchronous. In the listener, you can then return a {{WebExtAPIRef("webRequest.BlockingResponse", "BlockingResponse")}} object, which indicates the modification you need to make: for example, the modified request header you want to send. ## Requests at browser startup When a listener is registered with the `"blocking"` option and is registered during the extension startup, if a request is made during the browser startup that matches the listener the extension starts early. This enables the extension to observe the request at browser startup. If you don't take these steps, requests made at startup could be missed. ## Speculative requests The browser can make speculative connections, where it determines that a request to a URI may be coming soon. This type of connection does not provide valid tab information, so request details such as `tabId`, `frameId`, `parentFrameId`, etc. are inaccurate. These connections have a {{WebExtAPIRef("webRequest.ResourceType")}} of `speculative`. ## Accessing security information In the {{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}} listener you can access the [TLS](/en-US/docs/Glossary/TLS) properties of a request by calling {{WebExtAPIRef("webRequest.getSecurityInfo()", "getSecurityInfo()")}}. To do this you must also pass "blocking" in the `extraInfoSpec` argument to the event's `addListener()`. You can read details of the TLS handshake, but can't modify them or override the browser's trust decisions. ## Modifying responses To modify the HTTP response bodies for a request, call {{WebExtAPIRef("webRequest.filterResponseData")}}, passing it the ID of the request. This returns a {{WebExtAPIRef("webRequest.StreamFilter")}} object that you can use to examine and modify the data as it is received by the browser. To do this, you must have the `"webRequestBlocking"` API permission as well as the `"webRequest"` [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) and the [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the relevant host. ## Types - {{WebExtAPIRef("webRequest.BlockingResponse")}} - : An object of this type is returned by event listeners that have set `"blocking"` in their `extraInfoSpec` argument. By setting particular properties in `BlockingResponse`, the listener can modify network requests. - {{WebExtAPIRef("webRequest.CertificateInfo")}} - : An object describing a single X.509 certificate. - {{WebExtAPIRef("webRequest.HttpHeaders")}} - : An array of HTTP headers. Each header is represented as an object with two properties: `name` and either `value` or `binaryValue`. - {{WebExtAPIRef("webRequest.RequestFilter")}} - : An object describing filters to apply to `webRequest` events. - {{WebExtAPIRef("webRequest.ResourceType")}} - : Represents a particular kind of resource fetched in a web request. - {{WebExtAPIRef("webRequest.SecurityInfo")}} - : An object describing the security properties of a particular web request. - {{WebExtAPIRef("webRequest.StreamFilter")}} - : An object that can be used to monitor and modify HTTP responses while they are being received. - {{WebExtAPIRef("webRequest.UploadData")}} - : Contains data uploaded in a URL request. ## Properties - {{WebExtAPIRef("webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES", "webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES")}} - : The maximum number of times that {{WebExtAPIRef("WebRequest.handlerBehaviorChanged", "handlerBehaviorChanged()")}} can be called in a 10 minute period. ## Methods - {{WebExtAPIRef("webRequest.handlerBehaviorChanged()")}} - : This method can be used to ensure that event listeners are applied correctly when pages are in the browser's in-memory cache. - {{WebExtAPIRef("webRequest.filterResponseData()")}} - : Returns a {{WebExtAPIRef("webRequest.StreamFilter")}} object for a given request. - {{WebExtAPIRef("webRequest.getSecurityInfo()")}} - : Gets detailed information about the [TLS](/en-US/docs/Glossary/TLS) connection associated with a given request. ## Events - {{WebExtAPIRef("webRequest.onBeforeRequest")}} - : Fired when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel or redirect the request. - {{WebExtAPIRef("webRequest.onBeforeSendHeaders")}} - : Fired before sending any HTTP data, but after HTTP headers are available. This is a good place to listen if you want to modify HTTP request headers. - {{WebExtAPIRef("webRequest.onSendHeaders")}} - : Fired just before sending headers. If your add-on or some other add-on modified headers in `{{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}}`, you'll see the modified version here. - {{WebExtAPIRef("webRequest.onHeadersReceived")}} - : Fired when the HTTP response headers associated with a request have been received. You can use this event to modify HTTP response headers. - {{WebExtAPIRef("webRequest.onAuthRequired")}} - : Fired when the server asks the client to provide authentication credentials. The listener can do nothing, cancel the request, or supply authentication credentials. - {{WebExtAPIRef("webRequest.onResponseStarted")}} - : Fired when the first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available. - {{WebExtAPIRef("webRequest.onBeforeRedirect")}} - : Fired when a server-initiated redirect is about to occur. - {{WebExtAPIRef("webRequest.onCompleted")}} - : Fired when a request is completed. - {{WebExtAPIRef("webRequest.onErrorOccurred")}} - : Fired when an error occurs. ## Browser compatibility {{Compat}} [Additional notes on Chrome incompatibilities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#webrequest_api). {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/onresponsestarted/index.md
--- title: webRequest.onResponseStarted slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onResponseStarted page-type: webextension-api-event browser-compat: webextensions.api.webRequest.onResponseStarted --- {{AddonSidebar}} Fired when the first byte of the response body is received. This event is informational only. ## Syntax ```js-nolint browser.webRequest.onResponseStarted.addListener( listener, // function filter, // object extraInfoSpec // optional array of strings ) browser.webRequest.onResponseStarted.removeListener(listener) browser.webRequest.onResponseStarted.hasListener(listener) ``` Events have three functions: - `addListener(listener, filter, extraInfoSpec)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `details` - : `object`. Details about the request. See the [details](#details_2) section for more information. - `filter` - : {{WebExtAPIRef('webRequest.RequestFilter')}}. A filter that restricts the events that is sent to this listener. - `extraInfoSpec` {{optional_inline}} - : `array` of `string`. Extra options for the event. You can pass just one value: - `"responseHeaders"`: include `responseHeaders` in the `details` object passed to the listener ## Additional objects ### details - `cookieStoreId` - : `string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. - `documentUrl` - : `string`. URL of the document in which the resource will be loaded. For example, if the web page at "https\://example.com" contains an image or an iframe, then the `documentUrl` for the image or iframe will be "https\://example.com". For a top-level document, `documentUrl` is undefined. - `frameId` - : `integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. - `fromCache` - : `boolean`. Indicates if this response was fetched from disk cache. - `incognito` - : `boolean`. Whether the request is from a private browsing window. - `ip` - : `string`. The IP address of the server the request was sent to. It may be a literal IPv6 address. - `method` - : `string`. Standard HTTP method: for example, "GET" or "POST". - `originUrl` - : `string`. URL of the resource which triggered the request. For example, if "https\://example.com" contains a link, and the user clicks the link, then the `originUrl` for the resulting request is "https\://example.com". The `originUrl` is often but not always the same as the `documentUrl`. For example, if a page contains an iframe, and the iframe contains a link that loads a new document into the iframe, then the `documentUrl` for the resulting request will be the iframe's parent document, but the `originUrl` will be the URL of the document in the iframe that contained the link. - `parentFrameId` - : `integer`. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists. - `proxyInfo` - : `object`. This property is present only if the request is being proxied. It contains the following properties: - `host` - : `string`. The hostname of the proxy server. - `port` - : `integer`. The port number of the proxy server. - `type` - : `string`. The type of proxy server. One of: - "http": HTTP proxy (or SSL CONNECT for HTTPS) - "https": HTTP proxying over TLS connection to proxy - "socks": SOCKS v5 proxy - "socks4": SOCKS v4 proxy - "direct": no proxy - "unknown": unknown proxy - `username` - : `string`. Username for the proxy service. - `proxyDNS` - : `boolean`. True if the proxy will perform domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup. - `failoverTimeout` - : `integer`. Failover timeout in seconds. If the proxy connection fails, the proxy will not be used again for this period. - `requestId` - : `string`. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request. - `responseHeaders` {{optional_inline}} - : {{WebExtAPIRef('webRequest.HttpHeaders')}}. The HTTP response headers that were received along with this response. - `statusCode` - : `integer`. Standard HTTP status code returned by the server. - `statusLine` - : `string`. HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers. - `tabId` - : `integer`. The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. - `thirdParty` - : `boolean`. Indicates whether the request and its content window hierarchy are third party. - `timeStamp` - : `number`. The time when this event fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `type` - : {{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", "stylesheet". - `url` - : `string`. Target of the request. - `urlClassification` - : `object`. The type of tracking associated with the request, if with the request has been classified by [Firefox Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop). This is an object with the following properties: - `firstParty` - : `array` of `strings`. Classification flags for the request's first party. - `thirdParty` - : `array` of `strings`. Classification flags for the request or its window hierarchy's third parties. The classification flags include: - `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin that has been found to fingerprint but is not considered to participate in tracking, such as a payment provider. - `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources. - `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request, the `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker. - `any_basic_tracking`: a meta flag that combines any tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`. - `any_strict_tracking`: a meta flag that combines any tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`. - `any_social_tracking`: a meta flag that combines any social tracking flags. ## Browser compatibility {{Compat}} ## Examples ```js let target = "https://developer.mozilla.org/*"; /* e.g. "https://developer.mozilla.org/en-US/Firefox/Releases" 200 HTTP/1.1 200 OK */ function logResponse(responseDetails) { console.log(responseDetails.url); console.log(responseDetails.statusCode); console.log(responseDetails.statusLine); } browser.webRequest.onResponseStarted.addListener(logResponse, { urls: [target], }); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onResponseStarted) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/uploaddata/index.md
--- title: webRequest.UploadData slug: Mozilla/Add-ons/WebExtensions/API/webRequest/UploadData page-type: webextension-api-type browser-compat: webextensions.api.webRequest.UploadData --- {{AddonSidebar}} Contains data uploaded in a URL request. ## Type Values of this type are objects. They contain the following properties: - `bytes` {{optional_inline}} - : `any`. An ArrayBuffer with a copy of the data. - `file` {{optional_inline}} - : `string`. A string with the file's path and name. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#type-UploadData) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/onbeforeredirect/index.md
--- title: webRequest.onBeforeRedirect slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRedirect page-type: webextension-api-event browser-compat: webextensions.api.webRequest.onBeforeRedirect --- {{AddonSidebar}} Fired when a server-initiated redirect is about to occur. Note that you can't pass `"blocking"` for this event, so you can't modify or cancel the request from this event: it's informational only. ## Syntax ```js-nolint browser.webRequest.onBeforeRedirect.addListener( listener, // function filter, // object extraInfoSpec // optional array of strings ) browser.webRequest.onBeforeRedirect.removeListener(listener) browser.webRequest.onBeforeRedirect.hasListener(listener) ``` Events have three functions: - `addListener(listener, filter, extraInfoSpec)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `details` - : `object`. Details about the request. See the [details](#details_2) section for more information. - `filter` - : {{WebExtAPIRef('webRequest.RequestFilter')}}. A filter that restricts the events that is sent to this listener. - `extraInfoSpec` {{optional_inline}} - : `array` of `string`. Extra options for the event. You can pass just one value: - `"responseHeaders"`: include `responseHeaders` in the `details` object passed to the listener ## Additional objects ### details - `cookieStoreId` - : `string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. - `documentUrl` - : `string`. URL of the document in which the resource will be loaded. For example, if the web page at "https\://example.com" contains an image or an iframe, then the `documentUrl` for the image or iframe will be "https\://example.com". For a top-level document, `documentUrl` is undefined. - `frameId` - : `integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. - `fromCache` - : `boolean`. Indicates if this response was fetched from disk cache. - `incognito` - : `boolean`. Whether the request is from a private browsing window. - `ip` - : `string`. The IP address of the server the request was sent to. It may be a literal IPv6 address. - `method` - : `string`. Standard HTTP method: for example, "GET" or "POST". - `originUrl` - : `string`. URL of the resource which triggered the request. For example, if "https\://example.com" contains a link, and the user clicks the link, then the `originUrl` for the resulting request is "https\://example.com". The `originUrl` is often but not always the same as the `documentUrl`. For example, if a page contains an iframe, and the iframe contains a link that loads a new document into the iframe, then the `documentUrl` for the resulting request will be the iframe's parent document, but the `originUrl` will be the URL of the document in the iframe that contained the link. - `parentFrameId` - : `integer`. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists. - `proxyInfo` - : `object`. This property is present only if the request is being proxied. It contains the following properties: - `host` - : `string`. The hostname of the proxy server. - `port` - : `integer`. The port number of the proxy server. - `type` - : `string`. The type of proxy server. One of: - "http": HTTP proxy (or SSL CONNECT for HTTPS) - "https": HTTP proxying over TLS connection to proxy - "socks": SOCKS v5 proxy - "socks4": SOCKS v4 proxy - "direct": no proxy - "unknown": unknown proxy - `username` - : `string`. Username for the proxy service. - `proxyDNS` - : `boolean`. True if the proxy will perform domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup. - `failoverTimeout` - : `integer`. Failover timeout in seconds. If the proxy connection fails, the proxy will not be used again for this period. - `redirectUrl` - : `string`. The new URL. - `requestId` - : `string`. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request. - `responseHeaders` - : {{WebExtAPIRef('webRequest.HttpHeaders')}}. The HTTP response headers that were received along with this redirect. - `statusCode` - : `integer`. Standard HTTP status code returned by the server. - `statusLine` - : `string`. HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers. - `tabId` - : `integer`. The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. - `thirdParty` - : `boolean`. Indicates whether the request and its content window hierarchy are third party. - `timeStamp` - : `number`. The time when this event fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `type` - : {{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", "stylesheet". - `url` - : `string`. Target of the request. - `urlClassification` - : `object`. The type of tracking associated with the request, if with the request has been classified by [Firefox Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop). This is an object with the following properties: - `firstParty` - : `array` of `strings`. Classification flags for the request's first party. - `thirdParty` - : `array` of `strings`. Classification flags for the request or its window hierarchy's third parties. The classification flags include: - `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin that has been found to fingerprint but is not considered to participate in tracking, such as a payment provider. - `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources. - `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request, the `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker. - `any_basic_tracking`: a meta flag that combines any tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`. - `any_strict_tracking`: a meta flag that combines any tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`. - `any_social_tracking`: a meta flag that combines any social tracking flags. ## Browser compatibility {{Compat}} ## Examples ```js let target = "https://developer.mozilla.org/*"; /* e.g. "https://developer.mozilla.org/" "https://developer.mozilla.org/en-US/" */ function logResponse(responseDetails) { console.log(responseDetails.url); console.log(responseDetails.redirectUrl); } browser.webRequest.onBeforeRedirect.addListener(logResponse, { urls: [target], }); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onBeforeRedirect) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/securityinfo/index.md
--- title: webRequest.SecurityInfo slug: Mozilla/Add-ons/WebExtensions/API/webRequest/SecurityInfo page-type: webextension-api-type browser-compat: webextensions.api.webRequest.SecurityInfo --- {{AddonSidebar}} An object describing the security properties of a particular web request. An object of this type is returned from the {{WebExtAPIRef("webRequest.getSecurityInfo()")}} API. If the request is not secured using [TLS](/en-US/docs/Glossary/TLS), then this object will contain only the property `state`, whose value will be `"insecure"`. ## Type Values of this type are objects. They contain the following properties: - `certificates` - : `Array` of {{WebExtAPIRef("webRequest.CertificateInfo", "CertificateInfo")}}. If {{WebExtAPIRef("webRequest.getSecurityInfo()")}} was called with the `certificateChain` option present and set to `true`, this will contain a `CertificateInfo` object for every certificate in the chain, from the server certificate up to and including the trust root. Otherwise it will contain a single `CertificateInfo` object, for the server certificate. - `certificateTransparencyStatus` {{optional_inline}} - : `String`. Indicates the [Certificate Transparency](https://certificate.transparency.dev/) status for the connection. This may take any one of the following values: - "not_applicable" - "policy_compliant" - "policy_not_enough_scts" - "policy_not_diverse_scts" - `cipherSuite` {{optional_inline}} - : `String`. Cipher suite used for the connection, formatted as per the [TLS specification](https://datatracker.ietf.org/doc/html/rfc5246#appendix-A.5): for example, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". - `errorMessage` {{optional_inline}} - : `String`. If there was a problem with the TLS handshake (for example, the certificate had expired, or a trusted root could not be found, or a certificate was revoked) then `status` will be "broken" and the `errorMessage` property will contain a string describing the error, taken from Firefox's internal list of error codes. Note though that at present you can only call `getSecurityInfo()` in the `onHeaderReceived` listener, and the `onHeaderReceived` event is not fired when the handshake fails. So in practice this will never be set. - `hsts` {{optional_inline}} - : `Boolean`. `true` if the host uses [Strict Transport Security](/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security), `false` otherwise. - `isDomainMismatch` {{optional_inline}} - : `Boolean`. `true` if the server's domain name does not match the domain name in its certificate, `false` otherwise. - `isExtendedValidation` {{optional_inline}} - : `Boolean`. `true` if the server has an [Extended Validation Certificate](https://en.wikipedia.org/wiki/Extended_Validation_Certificate), `false` otherwise. - `isNotValidAtThisTime` {{optional_inline}} - : `Boolean`. `true` if the current time falls outside the server certificate's validity period (i.e. the certificate has expired or is not yet valid), `false` otherwise. - `isUntrusted` {{optional_inline}} - : `Boolean`. `true` if a chain back to a trusted root certificate could not be constructed, `false` otherwise. - `keaGroupName` {{optional_inline}} - : `String`. If `state` is "secure" this describes the key exchange algorithm used in this request. - `protocolVersion` {{optional_inline}} - : `String`. Version of the TLS protocol used. One of: - "TLSv1" - "TLSv1.1" - "TLSv1.2" - "TLSv1.3" - "unknown" (if the version is not valid) - `secretKeyLength` {{optional_inline}} - : `Number`. The length of the secret key in bits. - `signatureSchemeName` {{optional_inline}} - : `String`. If `state` is "secure" this describes the signature scheme used in this request. - `state` - : `String`. State of the connection. One of: - "broken": the TLS handshake failed (for example, the certificate had expired) - "insecure": the connection is not a TLS connection - "secure": the connection is a secure TLS connection - "weak": the connection is a TLS connection but is considered weak. You can examine `weaknessReasons` to find out the problem. Note though that at present you can only call `getSecurityInfo()` in the `onHeaderReceived` listener, and the `onHeaderReceived` event is not fired when the handshake fails. So in practice this will never be set to "broke". - `usedDelegatedCredentials` {{optional_inline}} - : `Boolean`. `true` if the connection used Delegated Credentials, `false` otherwise. - `usedEch` {{optional_inline}} - : `Boolean`. `true` if the connection used ECH (Encrypted Client Hello), `false` otherwise. - `usedOcsp` {{optional_inline}} - : `Boolean`. `true` if the connection made an OCSP (Online Certificate Status Protocol) request, `false` otherwise. - `usedPrivateDns` {{optional_inline}} - : `Boolean`. `true` if the connection made a private DNS lookup, such as with DoH (DNS over HTTPS), `false` otherwise. - `weaknessReasons` {{optional_inline}} - : `String`. If `state` is "weak", this indicates the reason. Currently this may contain only a single value "cipher", indicating that the negotiated cipher suite is considered weak. ## Browser compatibility {{Compat}} {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/resourcetype/index.md
--- title: webRequest.ResourceType slug: Mozilla/Add-ons/WebExtensions/API/webRequest/ResourceType page-type: webextension-api-type browser-compat: webextensions.api.webRequest.ResourceType --- {{AddonSidebar}} This type is a string, which represents the context in which a resource was fetched in a web request. It's used to [filter](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/RequestFilter) the requests you listen to using the webRequest API. For example: you can listen to requests only for images, or only for scripts. ## 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. - `websocket` - : Requests initiating a connection to a server through the [WebSocket API](/en-US/docs/Web/API/WebSockets_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. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#type-ResourceType) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/blockingresponse/index.md
--- title: webRequest.BlockingResponse slug: Mozilla/Add-ons/WebExtensions/API/webRequest/BlockingResponse page-type: webextension-api-type browser-compat: webextensions.api.webRequest.BlockingResponse --- {{AddonSidebar}} An object of this type is returned by event listeners that have set `"blocking"` in their `extraInfoSpec` argument. By setting particular properties in `BlockingResponse`, the listener can modify network requests. Note that you can't set all this object's properties in every listener: the properties you can set are dependent on the event that triggered this listener, as detailed below. ## Type Values of this type are objects. They contain the following properties: - `authCredentials` {{optional_inline}} - : `object`. If set, the request is made using the given credentials. You can only set this property in {{WebExtAPIRef("webRequest.onAuthRequired", "onAuthRequired")}}. The `authCredentials` property is an object with the following properties: - `username` - : `string`. Username to supply. - `password` - : `string`. Password to supply. - `cancel` {{optional_inline}} - : `boolean`. If `true`, the request is cancelled. You can only set this property in {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}}, {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}}, {{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}}, and {{WebExtAPIRef("webRequest.onAuthRequired", "onAuthRequired")}}. - `redirectUrl` {{optional_inline}} - : `string`. This is a URL, and if set, the original request is redirected to that URL. You can only set this property in {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} or {{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}}. Redirections to non-HTTP schemes such as data: are allowed, but they are not currently supported ([Firefox bug 707624](https://bugzil.la/707624)). Redirects use the same request method as the original request unless initiated from `onHeadersReceived` stage, in which case the redirect uses the GET method. If an extension wants to redirect a public (e.g. HTTPS) URL to an [extension page](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages), the extension's manifest.json file must contain a [web_accessible_resources](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources) key that lists the URL for the extension page. - `requestHeaders` {{optional_inline}} - : {{WebExtAPIRef('webRequest.HttpHeaders')}}. This is an {{WebExtAPIRef('webRequest.HttpHeaders', "HttpHeaders")}} object, an array in which each object represents a header. If set, the request is made with these headers rather than the original headers. You can only set this property in {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} . - `responseHeaders` {{optional_inline}} - : {{WebExtAPIRef('webRequest.HttpHeaders')}}. This is an {{WebExtAPIRef('webRequest.HttpHeaders', "HttpHeaders")}} object, an array in which each object represents a header. If set, the server is assumed to have responded with these response headers instead of the originals. You can only set this property in {{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}}. If multiple extensions attempt to set the same header (for example, `Content-Security-Policy`), only one of the changes will be successful. - `upgradeToSecure` {{optional_inline}} - : `boolean`. If set to `true` and the original request is an HTTP request, this will prevent the original request from being sent and instead make a secure (HTTPS) request. If any extension returns `redirectUrl` in `onBeforeRequest`, then `upgradeToSecure` will be ignored for that request. You can only set this property in {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}}. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#type-BlockingResponse) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/httpheaders/index.md
--- title: webRequest.HttpHeaders slug: Mozilla/Add-ons/WebExtensions/API/webRequest/HttpHeaders page-type: webextension-api-type browser-compat: webextensions.api.webRequest.HttpHeaders --- {{AddonSidebar}} An array of HTTP headers. Each header is represented as an object with two properties: `name` and either `value` or `binaryValue`. ## Type An `array` of `object`s. Each object has the following properties: - `name` - : `string`. Name of the HTTP header. - `value` {{optional_inline}} - : `string`. Value of the HTTP header if it can be represented by UTF-8. Either this property or `binaryValue` must be present. - `binaryValue` {{optional_inline}} - : `array` of `integer`. Value of the HTTP header if it cannot be represented by UTF-8, represented as bytes (0..255). Either this property or `value` must be present. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#type-HttpHeaders) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/handlerbehaviorchanged/index.md
--- title: webRequest.handlerBehaviorChanged() slug: Mozilla/Add-ons/WebExtensions/API/webRequest/handlerBehaviorChanged page-type: webextension-api-function browser-compat: webextensions.api.webRequest.handlerBehaviorChanged --- {{AddonSidebar}} This function can be used to ensure that event listeners are applied correctly when pages are in the browser's in-memory cache. If the browser has loaded a page, and the page is reloaded, the browser may reload the page from its in-memory cache, and in this case, events will not be triggered for the request. Suppose an extension's job is to block web requests against a pattern, and the following scenario happens: - The user loads a page that includes a particular request, and the pattern permits the request. - The resource is loaded and cached in memory. - The extension's patterns are updated, in such a way that the resource would no longer be permitted. - The user reloads the page. Because the page will be reloaded from the memory cache, the listener may not be called again, and the request will be loaded despite the extension's new policy. The `handlerBehaviorChanged()` function is designed to address this problem. It flushes the in-memory cache, so that page reloads will trigger event listeners. Because `handlerBehaviorChanged()` flushes the cache, it can be expensive and bad for performance. The webRequest module defines a read-only property {{WebExtAPIRef("webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES", "MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES")}}: making more calls than this number in 10 minutes will have no effect. The implementation of caching, hence the need for this function, varies from one browser to another, so in some browsers this function does nothing. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let flushingCache = browser.webRequest.handlerBehaviorChanged() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments, when the operation has completed. ## Browser compatibility {{Compat}} ## Examples In the following snippet, we flush the in-memory cache via a call to `handlerBehaviorChanged()`, and report this action by logging an appropriate message to the console. ```js function onFlushed() { console.log(`In-memory cache flushed`); } function onError(error) { console.log(`Error: ${error}`); } let flushingCache = browser.webRequest.handlerBehaviorChanged(); flushingCache.then(onFlushed, onError); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#method-handlerBehaviorChanged) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/onbeforesendheaders/index.md
--- title: webRequest.onBeforeSendHeaders slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeSendHeaders page-type: webextension-api-event browser-compat: webextensions.api.webRequest.onBeforeSendHeaders --- {{AddonSidebar}} This event is triggered before sending any HTTP data, but after all HTTP headers are available. This is a good place to listen if you want to modify HTTP request headers. To have the request headers passed into the listener along with the rest of the request data, pass `"requestHeaders"` in the `extraInfoSpec` array. To modify the headers synchronously: pass `"blocking"` in `extraInfoSpec`, then in your event listener, return a [`BlockingResponse`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/BlockingResponse) with a property named `requestHeaders`, whose value is the set of request headers to send. To modify the headers asynchronously: pass `"blocking"` in `extraInfoSpec`, then in your event listener, return a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which is resolved with a `BlockingResponse`. If you use `"blocking"`, you must have the ["webRequestBlocking" API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) in your manifest.json. It is possible for extensions to conflict here. If two extensions listen to `onBeforeSendHeaders` for the same request, then the second listener will see modifications made by the first listener, and will be able to undo any changes made by the first listener. For example, if the first listener adds a `Cookie` header, and the second listener strips all `Cookie` headers, then the first listener's modifications will be lost. If you want to see the headers that are actually sent, without the risk that another extension will subsequently alter them, use {{WebExtAPIRef("webRequest.onSendHeaders", "onSendHeaders")}}, although you can't modify headers on this event. Not all headers actually sent are always included in `requestHeaders`. In particular, headers related to caching (for example, `Cache-Control`, `If-Modified-Since`, `If-None-Match`) are never sent. Also, behavior here may differ across browsers. According to the specification, header names are case-insensitive. This means that to match a particular header, the listener should lowercase the name before comparing it: ```js for (const header of e.requestHeaders) { if (header.name.toLowerCase() === desiredHeader) { // process header } } ``` The browser preserves the original case of the header name as generated by the browser. If the extension's listener changes the case, this change will not be kept. ## Syntax ```js-nolint browser.webRequest.onBeforeSendHeaders.addListener( listener, // function filter, // object extraInfoSpec // optional array of strings ) browser.webRequest.onBeforeSendHeaders.removeListener(listener) browser.webRequest.onBeforeSendHeaders.hasListener(listener) ``` Events have three functions: - `addListener(listener, filter, extraInfoSpec)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `details` - : `object`. Details of the request. This includes request headers if you have included `"requestHeaders"` in `extraInfoSpec`. See the [details](#details_2) section for more information. Returns: {{WebExtAPIRef('webRequest.BlockingResponse')}}. If `"blocking"` is specified in the `extraInfoSpec` parameter, the event listener should return a `BlockingResponse` object, and can set its `requestHeaders` property. - `filter` - : {{WebExtAPIRef('webRequest.RequestFilter')}}. A set of filters that restricts the events that is sent to this listener. - `extraInfoSpec` {{optional_inline}} - : `array` of `string`. Extra options for the event. You can pass any of the following values: - `"blocking"`: make the request synchronous, so you can modify request headers - `"requestHeaders"`: include the request headers in the `details` object passed to the listener ## Additional objects ### details - `cookieStoreId` - : `string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. - `documentUrl` - : `string`. URL of the document in which the resource will be loaded. For example, if the web page at "https\://example.com" contains an image or an iframe, then the `documentUrl` for the image or iframe will be "https\://example.com". For a top-level document, `documentUrl` is undefined. - `frameAncestors` - : `array`. Contains information for each document in the frame hierarchy up to the top-level document. The first element in the array contains information about the immediate parent of the document being requested, and the last element contains information about the top-level document. If the load is actually for the top-level document, then this array is empty. - `url` - : `string`. The URL that the document was loaded from. - `frameId` - : `integer`. The `frameId` of the document. `details.frameAncestors[0].frameId` is the same as `details.parentFrameId`. - `frameId` - : `integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. - `incognito` - : `boolean`. Whether the request is from a private browsing window. - `method` - : `string`. Standard HTTP method: for example, "GET" or "POST". - `originUrl` - : `string`. URL of the resource which triggered the request. For example, if "https\://example.com" contains a link, and the user clicks the link, then the `originUrl` for the resulting request is "https\://example.com". The `originUrl` is often but not always the same as the `documentUrl`. For example, if a page contains an iframe, and the iframe contains a link that loads a new document into the iframe, then the `documentUrl` for the resulting request will be the iframe's parent document, but the `originUrl` will be the URL of the document in the iframe that contained the link. - `parentFrameId` - : `integer`. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists. - `proxyInfo` - : `object`. This property is present only if the request is being proxied. It contains the following properties: - `host` - : `string`. The hostname of the proxy server. - `port` - : `integer`. The port number of the proxy server. - `type` - : `string`. The type of proxy server. One of: - "http": HTTP proxy (or SSL CONNECT for HTTPS) - "https": HTTP proxying over TLS connection to proxy - "socks": SOCKS v5 proxy - "socks4": SOCKS v4 proxy - "direct": no proxy - "unknown": unknown proxy - `username` - : `string`. Username for the proxy service. - `proxyDNS` - : `boolean`. True if the proxy will perform domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup. - `failoverTimeout` - : `integer`. Failover timeout in seconds. If the proxy connection fails, the proxy will not be used again for this period. - `requestHeaders` {{optional_inline}} - : {{WebExtAPIRef('webRequest.HttpHeaders')}}. The HTTP request headers that will be sent with this request. - `requestId` - : `string`. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request. - `tabId` - : `integer`. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. - `thirdParty` - : `boolean`. Indicates whether the request and its content window hierarchy are third party. - `timeStamp` - : `number`. The time when this event fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `type` - : {{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", "stylesheet". - `url` - : `string`. Target of the request. - `urlClassification` - : `object`. The type of tracking associated with the request, if with the request has been classified by [Firefox Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop). This is an object with the following properties: - `firstParty` - : `array` of `strings`. Classification flags for the request's first party. - `thirdParty` - : `array` of `strings`. Classification flags for the request or its window hierarchy's third parties. The classification flags include: - `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin that has been found to fingerprint but is not considered to participate in tracking, such as a payment provider. - `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources. - `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request, the `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker. - `any_basic_tracking`: a meta flag that combines any tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`. - `any_strict_tracking`: a meta flag that combines any tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`. - `any_social_tracking`: a meta flag that combines any social tracking flags. ## Browser compatibility {{Compat}} ## Examples This code changes the "User-Agent" header so the browser identifies itself as Opera 12.16, but only when visiting pages under `https://httpbin.org/`. ```js "use strict"; /* This is the page for which we want to rewrite the User-Agent header. */ const targetPage = "https://httpbin.org/*"; /* Set UA string to Opera 12 */ const ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16"; /* Rewrite the User-Agent header to "ua". */ function rewriteUserAgentHeader(e) { for (const header of e.requestHeaders) { if (header.name.toLowerCase() === "user-agent") { header.value = ua; } } return { requestHeaders: e.requestHeaders }; } /* Add rewriteUserAgentHeader as a listener to onBeforeSendHeaders, only for the target page. Make it "blocking" so we can modify the headers. */ browser.webRequest.onBeforeSendHeaders.addListener( rewriteUserAgentHeader, { urls: [targetPage] }, ["blocking", "requestHeaders"], ); ``` This code is exactly like the previous example, except that the listener is asynchronous, returning a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which is resolved with the new headers: ```js "use strict"; /* This is the page for which we want to rewrite the User-Agent header. */ const targetPage = "https://httpbin.org/*"; /* Set UA string to Opera 12 */ const ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16"; /* Rewrite the User-Agent header to "ua". */ function rewriteUserAgentHeaderAsync(e) { const asyncRewrite = new Promise((resolve, reject) => { setTimeout(() => { for (const header of e.requestHeaders) { if (header.name.toLowerCase() === "user-agent") { header.value = ua; } } resolve({ requestHeaders: e.requestHeaders }); }, 2000); }); return asyncRewrite; } /* Add rewriteUserAgentHeader as a listener to onBeforeSendHeaders, only for the target page. Make it "blocking" so we can modify the headers. */ browser.webRequest.onBeforeSendHeaders.addListener( rewriteUserAgentHeaderAsync, { urls: [targetPage] }, ["blocking", "requestHeaders"], ); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onBeforeSendHeaders) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/filterresponsedata/index.md
--- title: webRequest.filterResponseData() slug: Mozilla/Add-ons/WebExtensions/API/webRequest/filterResponseData page-type: webextension-api-function browser-compat: webextensions.api.webRequest.filterResponseData --- {{AddonSidebar}} Use this function to create a {{WebExtAPIRef("webRequest.StreamFilter")}} object for a request. The stream filter gives the web extension full control over the stream, with the ability to monitor and modify the response. It's the extension's responsibility to write and close or disconnect the stream, as the default behavior is to keep the request open without a response. You typically call this function from a `webRequest` event listener. Firefox uses an optimized byte cache for script requests. This optimized byte cache overrides the normal request caching. Data from this cache is not available in a form useful to extensions. If your extension needs to filter scripts, create your filter in {{WebExtAPIRef("webRequest.onBeforeRequest")}}. Doing this ensures that the filter is created prior to the attempt to load from cache, thereby avoiding the optimized cache. ## Permissions To use this API, you must have the `"webRequest"` and `"webRequestBlocking"` [API permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions), and for the event listener, the [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the host. In addition: - From Firefox 95, to use this API to intercept requests related to the loading of service worker scripts, the `"webRequestFilterResponse.serviceWorkerScript"` permission is also required. - From Firefox 110, Manifest V3 extensions must also request the `"webRequestFilterResponse"` permission to use this API. ## Syntax ```js-nolint let filter = browser.webRequest.filterResponseData( requestId // string ) ``` ### Parameters - `requestId` - : `string`. ID of the request to filter. You can get this from the `details` object that is passed into any `webRequest` event listeners. ### Return value A {{WebExtAPIRef("webRequest.StreamFilter")}} object that you can use to monitor and modify the response. ## Examples This example shows a minimal implementation that passes through the stream data and closes the filter stream when the stream finishes receiving data. The code would be called from a {{WebExtAPIRef("webRequest")}} event listener and the event listener provides `details`. ```js let filter = browser.webRequest.filterResponseData(details.requestId); filter.ondata = (event) => { console.log(`filter.ondata received ${event.data.byteLength} bytes`); filter.write(event.data); }; filter.onstop = (event) => { // The extension should always call filter.close() or filter.disconnect() // after creating the StreamFilter, otherwise the response is kept alive forever. // If processing of the response data is finished, use close. If any remaining // response data should be processed by Firefox, use disconnect. filter.close(); }; ``` This example, taken from the [http-response](https://github.com/mdn/webextensions-examples/tree/main/http-response) example extension, creates a filter in {{WebExtAPIRef("webRequest.onBeforeRequest")}} and uses it, to modify the first chunk of the response: ```js function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); let decoder = new TextDecoder("utf-8"); let encoder = new TextEncoder(); filter.ondata = (event) => { let str = decoder.decode(event.data, { stream: true }); // Just change any instance of Example in the HTTP response // to WebExtension Example. str = str.replace(/Example/g, "WebExtension Example"); filter.write(encoder.encode(str)); filter.disconnect(); }; return {}; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/*"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}} > **Note:** The example above only works for small requests that aren't chunked or streamed. More advanced examples are documented with {{WebExtAPIRef("webRequest.StreamFilter.ondata")}}. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/requestfilter/index.md
--- title: webRequest.RequestFilter slug: Mozilla/Add-ons/WebExtensions/API/webRequest/RequestFilter page-type: webextension-api-type browser-compat: webextensions.api.webRequest.RequestFilter --- {{AddonSidebar}} An object describing filters to apply to webRequest events. ## Type Values of this type are objects. They contain the following properties: - `urls` - : `array` of `string`. An array of [match patterns](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns). The listener will only be called for requests whose targets match any of the given patterns. Only requests made using HTTP or HTTPS will trigger events, other protocols (such as data: and file:) supported by pattern matching do not trigger events. `view-source:` requests may be matched based on its inner URL. - `types` {{optional_inline}} - : `array` of `{{WebExtAPIRef('webRequest.ResourceType')}}`. A list of resource types (for example, stylesheets, images, scripts). The listener will only be called for requests for resources which are one of the given types. - `tabId` {{optional_inline}} - : `integer`. The listener will only be called for requests from the {{WebExtAPIRef("tabs.Tab", "tab")}} identified by this ID. - `windowId` {{optional_inline}} - : `integer`. The listener will only be called for requests from the {{WebExtAPIRef("windows.Window", "window")}} identified by this ID. - `incognito` {{optional_inline}} - : `boolean`. If provided, requests that do not match the incognito state (`true` or `false`) will be filtered out. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#type-RequestFilter) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/certificateinfo/index.md
--- title: webRequest.CertificateInfo slug: Mozilla/Add-ons/WebExtensions/API/webRequest/CertificateInfo page-type: webextension-api-type browser-compat: webextensions.api.webRequest.CertificateInfo --- {{AddonSidebar}} An object describing a single [X.509 certificate](https://datatracker.ietf.org/doc/html/rfc5280). The {{WebExtAPIRef("webRequest.SecurityInfo", "SecurityInfo")}} object returned from the {{WebExtAPIRef("webRequest.getSecurityInfo()")}} API includes a `certificates` property which is an array of these objects. ## Type Values of this type are objects. They contain the following properties: - `fingerprint` - : `Object`. An object with the following properties: - `sha1` - : `String`. SHA-1 hash of the certificate's DER encoding. - `sha256` - : `String`. SHA-256 hash of the certificate's DER encoding. - `isBuiltInRoot` - : `Boolean`. `true` if the certificate is one of the trust roots installed in the browser, `false` otherwise. - `issuer` - : `String`. Name of the organization that issued this certificate, represented as a Distinguished Name and formatted as a comma-separated list of Relative Distinguished Names, each of the form "type=value". For example: "CN=DigiCert SHA2 Secure Server CA,O=DigiCert Inc,C=US". - `rawDER` - : `Array` of `Number`. If [`webRequest.getSecurityInfo()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/getSecurityInfo) was called with the `rawDER` option present and set to `true`, this will contain the DER encoding of the certificate. - `serialNumber` - : `String`. The certificate's [serial number](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.2). - `subject` - : `String`. Name of the organization that issued this certificate, represented as a Distinguished Name and formatted as a comma-separated list of Relative Distinguished Names, each of the form "type=value". For example: "CN=\*.cdn.mozilla.net,O=Mozilla Corporation,L=Mountain View,ST=California,C=US". - `subjectPublicKeyInfoDigest` - : `Object`. An object containing the following properties: - `sha256` - : `String`. Base64 encoded SHA-256 hash of the DER-encoded [public key info](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.7). - `validity` - : `Object`. Validity period for the certificate. An object containing the following properties: - `start` - : `Number`. The start of the certificate's validity period, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `end` - : `Number`. The end of the certificate's validity period, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). ## Browser compatibility {{Compat}} {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/index.md
--- title: webRequest.StreamFilter slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter page-type: webextension-api-type browser-compat: webextensions.api.webRequest.StreamFilter --- {{AddonSidebar}} A `StreamFilter` is an object you use to monitor and modify HTTP responses. To create a `StreamFilter`, call {{WebExtAPIRef("webRequest.filterResponseData()")}}, passing the ID of the web request you want to filter. You can think of the stream filter as sitting between the networking stack and the browser's rendering engine. The filter is passed HTTP response data as it's received from the network. It can examine and modify the data before passing it along to the rendering engine, where it is parsed and rendered. The filter has full control over the response body, and the default behavior without any listeners or write calls is to have a stream without content that never closes. The filter generates four different events: - {{WebEXTAPIRef("webRequest.StreamFilter.onstart", "onstart")}} when the filter is about to start receiving response data. - {{WebEXTAPIRef("webRequest.StreamFilter.ondata", "ondata")}} when some response data has been received by the filter and is available to be examined or modified. - {{WebEXTAPIRef("webRequest.StreamFilter.onstop", "onstop")}} when the filter has finished receiving response data. - {{WebEXTAPIRef("webRequest.StreamFilter.onerror", "onerror")}} if an error has occurred in initializing and operating the filter. You can listen to each event by assigning a listener function to its attribute: ```js filter.onstart = (event) => { console.log("started"); }; ``` Note that the request is blocked during the execution of any event listeners. The filter provides a {{WebExtAPIRef("webRequest.StreamFilter.write()", "write()")}} function. At any time from the `onstart` event onwards you can use this function to write data to the output stream. If you assign listeners to any of the filter's events, all the response data passed to the rendering engine is supplied through calls you make to `write()`. So, if you add a listener and don't call `write()` the rendered page is blank. Once you have finished interacting with the response, call either of the following: - {{WebEXTAPIRef("webRequest.StreamFilter.disconnect()", "disconnect()")}}: This disconnects the filter from the request, so the rest of the response is processed normally. - {{WebEXTAPIRef("webRequest.StreamFilter.close()", "close()")}}: This closes the request, so no additional response data will be processed. The filter also provides functions to {{WebEXTAPIRef("webRequest.StreamFilter.suspend()", "suspend()")}} and {{WebEXTAPIRef("webRequest.StreamFilter.resume()", "resume()")}} the request. ## Methods - {{WebExtAPIRef("webRequest.StreamFilter.close()")}} - : Closes the request. - {{WebExtAPIRef("webRequest.StreamFilter.disconnect()")}} - : Disconnects the filter from the request. - {{WebExtAPIRef("webRequest.StreamFilter.resume()")}} - : Resumes processing of the request. - {{WebExtAPIRef("webRequest.StreamFilter.suspend()")}} - : Suspends processing of the request. - {{WebExtAPIRef("webRequest.StreamFilter.write()")}} - : Writes some data to the output stream. ## Properties - {{WebExtAPIRef("webRequest.StreamFilter.ondata")}} - : Event handler which is called when incoming data is available. - {{WebExtAPIRef("webRequest.StreamFilter.onerror")}} - : Event handler which is called when an error has occurred. - {{WebExtAPIRef("webRequest.StreamFilter.onstart")}} - : Event handler which is called when the stream is about to start receiving data. - {{WebExtAPIRef("webRequest.StreamFilter.onstop")}} - : Event handler which is called when the stream has no more data to deliver and has closed. - {{WebExtAPIRef("webRequest.StreamFilter.error")}} - : When {{WebExtAPIRef("webRequest.StreamFilter.onerror")}} is called, this will describe the error. - {{WebExtAPIRef("webRequest.StreamFilter.status")}} - : Describes the current status of the stream. ## Browser compatibility {{Compat}} ## Examples This code listens for `onstart`, `ondata`, and `onstop`. It logs those events, and the response data as an {{jsxref("ArrayBuffer")}} itself: ```js function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); filter.onstart = (event) => { console.log("started"); }; filter.ondata = (event) => { console.log(event.data); filter.write(event.data); }; filter.onstop = (event) => { console.log("finished"); filter.disconnect(); }; //return {}; // not needed } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.org/"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/onstop/index.md
--- title: webRequest.StreamFilter.onstop slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/onstop page-type: webextension-api-event browser-compat: webextensions.api.webRequest.StreamFilter.onstop --- {{AddonSidebar}} An event handler that will be called when the stream has no more data to deliver. In the event handler you can still call filter functions such as {{WebExtAPIRef("webRequest.StreamFilter.write()", "write()")}}, {{WebExtAPIRef("webRequest.StreamFilter.disconnect()", "disconnect()")}}, or {{WebExtAPIRef("webRequest.StreamFilter.close()", "close()")}}. ## Browser compatibility {{Compat}} ## Examples This example will append "extra stuff" to the response: ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const encoder = new TextEncoder(); filter.ondata = (event) => { // pass through all the response data filter.write(event.data); }; filter.onstop = (event) => { filter.write(encoder.encode("extra stuff")); filter.disconnect(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/*"], types: ["main_frame"] }, ["blocking"], ); ``` Here's another version of the example above: ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const encoder = new TextEncoder(); const data = []; filter.ondata = (event) => { data.push(event.data); }; filter.onstop = (event) => { for (const buffer of data) { filter.write(buffer); } filter.write(encoder.encode("extra stuff")); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/resume/index.md
--- title: webRequest.StreamFilter.resume() slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/resume page-type: webextension-api-function browser-compat: webextensions.api.webRequest.StreamFilter.resume --- {{AddonSidebar}} Resumes a request that was previously suspended through a call to {{WebExtAPIRef("webRequest.StreamFilter.suspend()", "suspend()")}}. You can't call this function until after the {{WebExtAPIRef("webRequest.StreamFilter.onstart", "onstart")}} event has fired. ## Syntax ```js-nolint StreamFilter.resume() ``` ### Parameters None. ### Return value None. ## Browser compatibility {{Compat}} ## Examples This example uses suspend/resume to delay a web request. ```js function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); filter.onstart = (event) => { filter.suspend(); setTimeout(() => { filter.resume(); filter.disconnect(); }, 1000); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.org/"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/status/index.md
--- title: webRequest.StreamFilter.status slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/status page-type: webextension-api-property browser-compat: webextensions.api.webRequest.StreamFilter.status --- {{AddonSidebar}} A string that describes the current status of the request. It will be one of the following values: - `"uninitialized"` - : The filter is not fully initialized. No filter functions may be called. - `"transferringdata"` - : The underlying channel is currently transferring data, which will be routed to the extension in one or more {{WebExtAPIRef("webRequest.StreamFilter.ondata", "ondata")}} events. The extension can call filter functions such as {{WebExtAPIRef("webRequest.StreamFilter.write()", "write()")}}, {{WebExtAPIRef("webRequest.StreamFilter.close()", "close()")}}, or {{WebExtAPIRef("webRequest.StreamFilter.disconnect()", "disconnect()")}}. - `"finishedtransferringdata"` - : The underlying channel has finished transferring data. In this state the extension can still write response data using the filter's {{WebExtAPIRef("webRequest.StreamFilter.write()", "write()")}} function. - `"suspended"` - : Data transfer is currently suspended. In this state the extension can resume the request by calling the filter's {{WebExtAPIRef("webRequest.StreamFilter.resume()", "resume()")}} function, and can write response data using the filter's {{WebExtAPIRef("webRequest.StreamFilter.write()", "write()")}} function. - `"closed"` - : The extension has closed the request by calling the filter's {{WebExtAPIRef("webRequest.StreamFilter.close()", "close()")}} function. The filter will not fire any more events, and the extension may not call any filter functions. - `"disconnected"` - : The extension has disconnected the filter from the request by calling the filter's {{WebExtAPIRef("webRequest.StreamFilter.disconnect()", "disconnect()")}} function. All further data will be delivered directly, without passing through the filter. The filter will not fire any more events, and the extension may not call any filter functions. - `"failed"` - : An error has occurred and the filter has been disconnected from the request. The extension can find an error message in {{WebExtAPIRef("webRequest.StreamFilter.error", "error")}}, and may not call any filter functions. ## Browser compatibility {{Compat}} ## Examples ```js function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); console.log(filter.status); // uninitialized filter.onstart = (event) => { console.log(filter.status); // transferringdata }; filter.ondata = (event) => { console.log(filter.status); // transferringdata // pass through the response data filter.write(event.data); }; filter.onstop = (event) => { console.log(filter.status); // finishedtransferringdata filter.disconnect(); console.log(filter.status); // disconnected }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/*"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/error/index.md
--- title: webRequest.StreamFilter.error slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/error page-type: webextension-api-property browser-compat: webextensions.api.webRequest.StreamFilter.error --- {{AddonSidebar}} A string that will contain an error message after the {{WebExtAPIRef("webRequest.StreamFilter.onerror", "onerror")}} event has fired. ## Browser compatibility {{Compat}} ## Examples This example adds an {{WebExtAPIRef("webRequest.StreamFilter.onerror", "onerror")}} listener which logs the value of `error`. ```js function listener(details) { let filter = browser.webRequest.filterResponseData("12345"); filter.onerror = (event) => { console.log(`Error: ${filter.error}`); }; //return {}; // not needed } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["<all_urls>"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/write/index.md
--- title: webRequest.StreamFilter.write() slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/write page-type: webextension-api-function browser-compat: webextensions.api.webRequest.StreamFilter.write --- {{AddonSidebar}} Writes some response data to the output stream. You can only call this function after the {{WebExtAPIRef("webRequest.StreamFilter.onstart", "onstart")}} event has fired. ## Syntax ```js-nolint filter.write( data // ArrayBuffer or Uint8Array ) ``` ### Parameters - `data` - : [`Uint8Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) or [`ArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer): array of bytes containing the data to pass to the browser's rendering engine. ### Return value None. ## Browser compatibility {{Compat}} ## Examples This example uses `write()`, to replace "Example" in the first chunk of the response with "WebExtension Example". ```js function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); let decoder = new TextDecoder("utf-8"); let encoder = new TextEncoder(); filter.ondata = (event) => { let str = decoder.decode(event.data, { stream: true }); // Just change any instance of Example in the HTTP response // to WebExtension Example. str = str.replace(/Example/g, "WebExtension Example"); filter.write(encoder.encode(str)); filter.disconnect(); }; //return {}; // not needed } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/*"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/ondata/index.md
--- title: webRequest.StreamFilter.ondata slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/ondata page-type: webextension-api-event browser-compat: webextensions.api.webRequest.StreamFilter.ondata --- {{AddonSidebar}} An event handler called repeatedly when response data is available. The handler is passed an [`Event` object](/en-US/docs/Web/API/Event) with a `data` property. The `data` property includes a chunk of the response data as an {{jsxref("ArrayBuffer")}}. To decode the data, use either {{domxref("TextDecoder")}} or {{domxref("Blob")}}. Without an `ondata` listener, you don't receive the original response body, and the output stream is empty unless {{WebEXTAPIRef("webRequest.StreamFilter.write", "write")}} is called. ## Examples This example adds an `ondata` listener which replaces "Example" in the response with "WebExtension Example" using the {{jsxref("String.prototype.replaceAll()", "replaceAll()")}} method. > **Note:** This example only works for occurrences of "Example" that are entirely contained within a data chunk, and not ones that straddle two chunks (which might happen \~0.1% of the time for large documents). Additionally it only deals with UTF-8-coded documents. A real implementation of this would have to be more complex. ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const decoder = new TextDecoder("utf-8"); const encoder = new TextEncoder(); filter.ondata = (event) => { let str = decoder.decode(event.data, { stream: true }); // Just change any instance of Example in the HTTP response // to WebExtension Example. // Note that this will maybe not work as expected because the ending of the str can also // be "<h1>Examp" (because it is not the full response). So, it is better // to get the full response first and then doing the replace. str = str.replaceAll("Example", "WebExtension Example"); filter.write(encoder.encode(str)); // Doing filter.disconnect(); here would make us process only // the first chunk, and let the rest through unchanged. Note // that this would break multi-byte characters that occur on // the chunk boundary! }; filter.onstop = (event) => { filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/*"], types: ["main_frame"] }, ["blocking"], ); ``` Another example for handling large documents: ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const decoder = new TextDecoder("utf-8"); const encoder = new TextEncoder(); const data = []; filter.ondata = (event) => { data.push(event.data); }; filter.onstop = (event) => { let str = ""; if (data.length === 1) { str = decoder.decode(data[0]); } else { for (let i = 0; i < data.length; i++) { const stream = i !== data.length - 1; str += decoder.decode(data[i], { stream }); } } str = str.replaceAll("Example", "WebExtension $&"); filter.write(encoder.encode(str)); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/"], types: ["main_frame"] }, ["blocking"], ); ``` Here's another version: ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const decoder = new TextDecoder("utf-8"); const encoder = new TextEncoder(); const data = []; filter.ondata = (event) => { data.push(event.data); }; filter.onstop = (event) => { let str = ""; for (const buffer of data) { str += decoder.decode(buffer, { stream: true }); } str += decoder.decode(); // end-of-stream str = str.replaceAll("Example", "WebExtension $&"); filter.write(encoder.encode(str)); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/"], types: ["main_frame"] }, ["blocking"], ); ``` The above example can also be written like so: ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const decoder = new TextDecoder("utf-8"); const encoder = new TextEncoder(); const data = []; filter.ondata = (event) => { data.push(decoder.decode(event.data, { stream: true })); }; filter.onstop = (event) => { data.push(decoder.decode()); let str = data.join(""); str = str.replaceAll("Example", "WebExtension $&"); filter.write(encoder.encode(str)); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/"], types: ["main_frame"] }, ["blocking"], ); ``` This example uses a {{domxref("Blob")}}: ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const encoder = new TextEncoder(); const data = []; filter.ondata = (event) => { data.push(event.data); }; filter.onstop = async (event) => { const blob = new Blob(data, { type: "text/html" }); let str = await blob.text(); str = str.replaceAll("Example", "WebExtension $&"); filter.write(encoder.encode(str)); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/"], types: ["main_frame"] }, ["blocking"], ); ``` This example makes use of the {{domxref("DOMParser")}} interface: ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const encoder = new TextEncoder(); const parser = new DOMParser(); const data = []; filter.ondata = (event) => { data.push(event.data); }; filter.onstop = async (event) => { const blob = new Blob(data, { type: "text/html" }); const str = await blob.text(); const doc = parser.parseFromString(str, blob.type); const nodes = doc.querySelectorAll("title, h1"); for (const node of nodes) { node.innerText = node.innerText.replaceAll("Example", "WebExtension $&"); } filter.write(encoder.encode(doc.documentElement.outerHTML)); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/"], types: ["main_frame"] }, ["blocking"], ); ``` This example combines all buffers into a single buffer: ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const decoder = new TextDecoder("utf-8"); const encoder = new TextEncoder(); const data = []; filter.ondata = (event) => { data.push(new Uint8Array(event.data)); }; filter.onstop = (event) => { let combinedLength = 0; for (const buffer of data) { combinedLength += buffer.length; } const combinedArray = new Uint8Array(combinedLength); let writeOffset = 0; for (const buffer of data) { combinedArray.set(buffer, writeOffset); writeOffset += buffer.length; } let str = decoder.decode(combinedArray); str = str.replaceAll("Example", "WebExtension $&"); filter.write(encoder.encode(str)); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/"], types: ["main_frame"] }, ["blocking"], ); ``` The above example can also be written like so: ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const decoder = new TextDecoder("utf-8"); const encoder = new TextEncoder(); const data = []; filter.ondata = (event) => { data.push(event.data); }; filter.onstop = async (event) => { const blob = new Blob(data, { type: "text/html" }); const buffer = await blob.arrayBuffer(); let str = decoder.decode(buffer); str = str.replaceAll("Example", "WebExtension $&"); filter.write(encoder.encode(str)); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/"], types: ["main_frame"] }, ["blocking"], ); ``` This example demonstrates, how one can detect, if it's the final chunk in the response: ```js function listener(details) { const filter = browser.webRequest.filterResponseData(details.requestId); const encoder = new TextEncoder(); const decoder = new TextDecoder("utf-8"); let str = ""; filter.ondata = (event) => { let stream = true; const data = new Uint8Array(event.data.slice(-8, -1)); if (String.fromCharCode(...data) === "</html>") { stream = false; // end-of-stream } str += decoder.decode(event.data, { stream }); }; filter.onstop = (event) => { str = str.replaceAll("Example", "WebExtension $&"); filter.write(encoder.encode(str)); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.com/"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/suspend/index.md
--- title: webRequest.StreamFilter.suspend() slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/suspend page-type: webextension-api-function browser-compat: webextensions.api.webRequest.StreamFilter.suspend --- {{AddonSidebar}} Suspends a request. After this is called, no more data will be delivered until the request is resumed with a call to {{WebExtAPIRef("webRequest.StreamFilter.resume()", "resume()")}}. You can't call this function until after the {{WebExtAPIRef("webRequest.StreamFilter.onstart", "onstart")}} event has fired. ## Syntax ```js-nolint filter.suspend() ``` ### Parameters None. ### Return value None. ## Browser compatibility {{Compat}} ## Examples This example uses suspend/resume to delay a web request. ```js function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); filter.onstart = (event) => { filter.suspend(); setTimeout(() => { filter.resume(); filter.disconnect(); }, 1000); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.org/"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/disconnect/index.md
--- title: webRequest.StreamFilter.disconnect() slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/disconnect page-type: webextension-api-function browser-compat: webextensions.api.webRequest.StreamFilter.disconnect --- {{AddonSidebar}} Disconnects the filter from the request. After this, the browser will continue to process the response, but no more filter events will fire, and no more filter function calls will have any effect. Note the difference between this function and {{WebExtAPIRef("webRequest.StreamFilter.close()", "close()")}}. With `disconnect()`, the browser will continue to process any further response data, but it won't be accessible through the filter. With `close()`, the browser will ignore any response data that hasn't already been passed through to the rendering engine. You should always call `disconnect()` or `close()` once you don't need to interact with the response any further. You can't call this function until after the {{WebExtAPIRef("webRequest.StreamFilter.onstart", "onstart")}} event has fired. ## Syntax ```js-nolint filter.disconnect() ``` ### Parameters None. ### Return value None. ## Browser compatibility {{Compat}} ## Examples This example will prepend "preface text" to the response body. It then disconnects, so the original response body will load normally: ```js function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); filter.onstart = (event) => { console.log("started"); let encoder = new TextEncoder(); filter.write(encoder.encode("preface text")); filter.disconnect(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.org/"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/close/index.md
--- title: webRequest.StreamFilter.close() slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/close page-type: webextension-api-function browser-compat: webextensions.api.webRequest.StreamFilter.close --- {{AddonSidebar}} Closes the request. After this is called, no further response data will be passed to the browser's rendering engine and no more filter events will be given to the extension. Note the difference between this function and {{WebExtAPIRef("webRequest.StreamFilter.disconnect()", "disconnect()")}}. With `disconnect()`, the browser will continue to process any further response data, but it won't be accessible through the filter. With `close()`, the browser will ignore any response data that hasn't already been passed through to the rendering engine. You should always call `close()` or `disconnect()` once you don't need to interact with the response any further. You can't call this function until after the {{WebExtAPIRef("webRequest.StreamFilter.onstart", "onstart")}} event has fired. ## Syntax ```js-nolint filter.close() ``` ### Parameters None. ### Return value None. ## Browser compatibility {{Compat}} ## Examples This example will replace the page content with "replacement text": ```js function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); filter.onstart = (event) => { console.log("started"); let encoder = new TextEncoder(); filter.write(encoder.encode("replacement content")); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.org/"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/onstart/index.md
--- title: webRequest.StreamFilter.onstart slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/onstart page-type: webextension-api-event browser-compat: webextensions.api.webRequest.StreamFilter.onstart --- {{AddonSidebar}} An event handler that will be called when the stream is opened and is about to begin delivering data. From this point on, the extension may use filter functions like {{WebExtAPIRef("webRequest.StreamFilter.write()", "write()")}}, {{WebExtAPIRef("webRequest.StreamFilter.disconnect()", "disconnect()")}}, or {{WebExtAPIRef("webRequest.StreamFilter.close()", "close()")}}. ## Browser compatibility {{Compat}} ## Examples This example will replace the page content with "replacement text": ```js function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); filter.onstart = (event) => { console.log("started"); let encoder = new TextEncoder(); filter.write(encoder.encode("replacement content")); filter.close(); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["https://example.org/"], types: ["main_frame"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/streamfilter/onerror/index.md
--- title: webRequest.StreamFilter.onerror slug: Mozilla/Add-ons/WebExtensions/API/webRequest/StreamFilter/onerror page-type: webextension-api-event browser-compat: webextensions.api.webRequest.StreamFilter.onerror --- {{AddonSidebar}} An event handler that will be called when an error occurs. This is most often because an invalid request ID was passed into {{WebExtAPIRef("webRequest.filterResponseData()")}}. After this event is fired, the {{WebExtAPIRef("webRequest.StreamFilter.error")}} property will contain a message giving more information about the error. Note that this event is **not** triggered for network errors. ## Browser compatibility {{Compat}} ## Examples This example adds an `onerror` listener which logs the value of {{WebExtAPIRef("webRequest.StreamFilter.error")}}. ```js function listener(details) { // This example seems not useful because, // an extension would use "details.requestId" let filter = browser.webRequest.filterResponseData("12345"); filter.onerror = (event) => { console.log(`Error: ${filter.error}`); }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: ["<all_urls>"], types: ["main_frame"] }, ["blocking"], ); ``` This example uses no `"blocking"`. ```js function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); filter.onerror = (event) => { console.log(`Error: ${filter.error}`); // Error: Invalid request ID }; } browser.webRequest.onBeforeRequest.addListener(listener, { urls: ["<all_urls>"], types: ["main_frame"], }); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/oncompleted/index.md
--- title: webRequest.onCompleted slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onCompleted page-type: webextension-api-event browser-compat: webextensions.api.webRequest.onCompleted --- {{AddonSidebar}} Fired when a request has completed. This event is informational only. ## Syntax ```js-nolint browser.webRequest.onCompleted.addListener( listener, // function filter, // object extraInfoSpec // optional array of strings ) browser.webRequest.onCompleted.removeListener(listener) browser.webRequest.onCompleted.hasListener(listener) ``` Events have three functions: - `addListener(listener, filter, extraInfoSpec)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `details` - : `object`. Details about the request. See the [details](#details_2) section for more information. - `filter` - : {{WebExtAPIRef('webRequest.RequestFilter')}}. A filter that restricts the events that is sent to this listener. - `extraInfoSpec` {{optional_inline}} - : `array` of `string`. Extra options for the event. You can pass just one value: - `"responseHeaders"`: include `responseHeaders` in the `details` object passed to the listener ## Additional objects ### details - `cookieStoreId` - : `string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. - `documentUrl` - : `string`. URL of the document in which the resource will be loaded. For example, if the web page at "https\://example.com" contains an image or an iframe, then the `documentUrl` for the image or iframe will be "https\://example.com". For a top-level document, `documentUrl` is undefined. - `frameId` - : `integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. - `fromCache` - : `boolean`. Indicates if this response was fetched from disk cache. - `incognito` - : `boolean`. Whether the request is from a private browsing window. - `ip` - : `string`. The IP address of the server the request was sent to. It may be a literal IPv6 address. - `method` - : `string`. Standard HTTP method: for example, "GET" or "POST". - `originUrl` - : `string`. URL of the resource which triggered the request. For example, if "https\://example.com" contains a link, and the user clicks the link, then the `originUrl` for the resulting request is "https\://example.com". The `originUrl` is often but not always the same as the `documentUrl`. For example, if a page contains an iframe, and the iframe contains a link that loads a new document into the iframe, then the `documentUrl` for the resulting request will be the iframe's parent document, but the `originUrl` will be the URL of the document in the iframe that contained the link. - `parentFrameId` - : `integer`. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists. - `proxyInfo` - : `object`. This property is present only if the request is being proxied. It contains the following properties: - `host` - : `string`. The hostname of the proxy server. - `port` - : `integer`. The port number of the proxy server. - `type` - : `string`. The type of proxy server. One of: - "http": HTTP proxy (or SSL CONNECT for HTTPS) - "https": HTTP proxying over TLS connection to proxy - "socks": SOCKS v5 proxy - "socks4": SOCKS v4 proxy - "direct": no proxy - "unknown": unknown proxy - `username` - : `string`. Username for the proxy service. - `proxyDNS` - : `boolean`. True if the proxy will perform domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup. - `failoverTimeout` - : `integer`. Failover timeout in seconds. If the proxy connection fails, the proxy will not be used again for this period. - `requestId` - : `string`. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request. - `responseHeaders` {{optional_inline}} - : {{WebExtAPIRef('webRequest.HttpHeaders')}}. The HTTP response headers that were received along with this response. - `statusCode` - : `integer`. Standard HTTP status code returned by the server. - `statusLine` - : `string`. HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers. - `tabId` - : `integer`. The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. - `thirdParty` - : `boolean`. Indicates whether the request and its content window hierarchy are third party. - `timeStamp` - : `number`. The time when this event fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `type` - : {{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", "stylesheet". - `url` - : `string`. Target of the request. - `urlClassification` - : `object`. The type of tracking associated with the request, if with the request has been classified by [Firefox Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop). This is an object with the following properties: - `firstParty` - : `array` of `strings`. Classification flags for the request's first party. - `thirdParty` - : `array` of `strings`. Classification flags for the request or its window hierarchy's third parties. The classification flags include: - `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin that has been found to fingerprint but is not considered to participate in tracking, such as a payment provider. - `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources. - `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request, the `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker. - `any_basic_tracking`: a meta flag that combines any tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`. - `any_strict_tracking`: a meta flag that combines any tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`. - `any_social_tracking`: a meta flag that combines any social tracking flags. ## Browser compatibility {{Compat}} ## Examples ```js let target = "https://developer.mozilla.org/*"; /* e.g. "https://developer.mozilla.org/en-US/" 200 or: "https://developer.mozilla.org/en-US/xfgkdkjdfhs" 404 */ function logResponse(responseDetails) { console.log(responseDetails.url); console.log(responseDetails.statusCode); } browser.webRequest.onCompleted.addListener(logResponse, { urls: [target] }); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onCompleted) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/onheadersreceived/index.md
--- title: webRequest.onHeadersReceived slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onHeadersReceived page-type: webextension-api-event browser-compat: webextensions.api.webRequest.onHeadersReceived --- {{AddonSidebar}} Fired when the HTTP response headers for a request are received. Use this event to modify HTTP response headers. To have the response headers passed into the listener, along with the rest of the request data, pass `"responseHeaders"` in the `extraInfoSpec` array. If you use `"blocking"`, you must have the ["webRequestBlocking" API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) in your manifest.json. It is possible for extensions to make conflicting requests. If two extensions listen to `onHeadersReceived` for the same request and return `responseHeaders` to set the same header (for example, `Set-Cookie`) not present in the original response, only one of the changes will succeed. However, the `Content-Security-Policy` header is treated differently; its values are combined to apply all the specified policies. But, if two extensions set a CSP value that conflicts, the CSP service makes the restriction more strict to resolve the conflict. For example, if one extension sets `img-src: example.com`, and another extension sets `img-src: example.org`, the result is `img-src: 'none'`. Merged modifications always lean towards being more restrictive, though an extension may remove the original CSP header. If you want to see the headers that are processed by the system, without the risk that another extension will alter them, use {{WebExtAPIRef("webRequest.onResponseStarted")}}, although you can't modify headers on this event. ## Syntax ```js-nolint browser.webRequest.onHeadersReceived.addListener( listener, // function filter, // object extraInfoSpec // optional array of strings ) browser.webRequest.onHeadersReceived.removeListener(listener) browser.webRequest.onHeadersReceived.hasListener(listener) ``` Events have three functions: - `addListener(listener, filter, extraInfoSpec)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `details` - : [`object`](#details_2). Details of the request. This will include response headers if you have included `"responseHeaders"` in `extraInfoSpec`. Returns: {{WebExtAPIRef('webRequest.BlockingResponse')}}. If `"blocking"` is specified in the `extraInfoSpec` parameter, the event listener will return a `BlockingResponse` object, and can set its `responseHeaders` property. In Firefox, the return value can be a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to a `BlockingResponse`. - `filter` - : {{WebExtAPIRef('webRequest.RequestFilter')}}. A set of filters that restricts the events that are sent to this listener. - `extraInfoSpec` {{optional_inline}} - : `array` of `string`. Extra options for the event. You can pass any of the following values: - `"blocking"` to make the request synchronous, so you can modify request and response headers - `"responseHeaders"` to include the response headers in the `details` object passed to the listener ## Additional objects ### details - `cookieStoreId` - : `string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. - `documentUrl` - : `string`. URL of the document in which the resource will be loaded. For example, if the web page at "https\://example.com" contains an image or an iframe, then the `documentUrl` for the image or iframe will be "https\://example.com". For a top-level document, `documentUrl` is undefined. - `frameAncestors` - : `array`. Information for each document in the frame hierarchy up to the top-level document. The first element in the array contains information about the immediate parent of the document being requested, and the last element contains information about the top-level document. If the load is for the top-level document, then this array is empty. - `url` - : `string`. The URL that the document was loaded from. - `frameId` - : `integer`. The `frameId` of the document. `details.frameAncestors[0].frameId` is the same as `details.parentFrameId`. - `frameId` - : `integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. - `fromCache` - : `boolean`. Whether the response is fetched from disk cache. - `incognito` - : `boolean`. Whether the request is from a private browsing window. - `ip` - : `string`. The IP address of the server the request was sent to. It may be a literal IPv6 address. - `method` - : `string`. Standard HTTP method: for example, "GET" or "POST". - `originUrl` - : `string`. URL of the resource that triggered the request. For example, if "https\://example.com" contains a link, and the user clicks the link, then the `originUrl` for the resulting request is "https\://example.com". The `originUrl` is often but not always the same as the `documentUrl`. For example, if a page contains an iframe, and the iframe contains a link that loads a new document into the iframe, then the `documentUrl` for the resulting request is the iframe's parent document, but the `originUrl` is the URL of the document in the iframe that contained the link. - `parentFrameId` - : `integer`. ID of the frame that contains the frame that sent the request. Set to -1 if no parent frame exists. - `proxyInfo` - : `object`. This property is present only if the request is being proxied. It contains the following properties: - `host` - : `string`. The hostname of the proxy server. - `port` - : `integer`. The port number of the proxy server. - `type` - : `string`. The type of proxy server. One of: - "http": HTTP proxy (or SSL CONNECT for HTTPS) - "https": HTTP proxying over TLS connection to proxy - "socks": SOCKS v5 proxy - "socks4": SOCKS v4 proxy - "direct": no proxy - "unknown": unknown proxy - `username` - : `string`. Username for the proxy service. - `proxyDNS` - : `boolean`. True if the proxy will perform domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup. - `failoverTimeout` - : `integer`. Failover timeout in seconds. If the proxy connection fails, the proxy will not be used again for this period. - `requestId` - : `string`. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request. - `responseHeaders` {{optional_inline}} - : {{WebExtAPIRef('webRequest.HttpHeaders')}}. The HTTP response headers that were received for this request. - `statusCode` - : `integer`. Standard HTTP status code returned by the server. - `statusLine` - : `string`. HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (that is, responses that lack a status line). - `tabId` - : `integer`. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. - `thirdParty` - : `boolean`. Indicates whether the request and its content window hierarchy are third party. - `timeStamp` - : `number`. The time when this event fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `type` - : {{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", "stylesheet". - `url` - : `string`. Target of the request. - `urlClassification` - : `object`. The type of tracking associated with the request, if with the request has been classified by [Firefox Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop). This is an object with the following properties: - `firstParty` - : `array` of `strings`. Classification flags for the request's first party. - `thirdParty` - : `array` of `strings`. Classification flags for the request or its window hierarchy's third parties. The classification flags include: - `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin that has been found to fingerprint but is not considered to participate in tracking, such as a payment provider. - `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources. - `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request, the `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker. - `any_basic_tracking`: a meta flag that combines any tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`. - `any_strict_tracking`: a meta flag that combines any tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`. - `any_social_tracking`: a meta flag that combines any social tracking flags. ## Browser compatibility {{Compat}} ## Examples This code sets an extra cookie when requesting a resource from the target URL: ```js let targetPage = "https://developer.mozilla.org/en-US/Firefox/Developer_Edition"; // Add the new header to the original array, // and return it. function setCookie(e) { const setMyCookie = { name: "Set-Cookie", value: "my-cookie1=my-cookie-value1", }; e.responseHeaders.push(setMyCookie); return { responseHeaders: e.responseHeaders }; } // Listen for onHeaderReceived for the target page. // Set "blocking" and "responseHeaders". browser.webRequest.onHeadersReceived.addListener( setCookie, { urls: [targetPage] }, ["blocking", "responseHeaders"], ); ``` This code does the same thing the previous example, except that the listener is asynchronous, returning a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which is resolved with the new headers: ```js const targetPage = "https://developer.mozilla.org/en-US/Firefox/Developer_Edition"; // Return a Promise that sets a timer. // When the timer fires, resolve the promise with // modified set of response headers. function setCookieAsync(e) { const asyncSetCookie = new Promise((resolve, reject) => { setTimeout(() => { const setMyCookie = { name: "Set-Cookie", value: "my-cookie1=my-cookie-value1", }; e.responseHeaders.push(setMyCookie); resolve({ responseHeaders: e.responseHeaders }); }, 2000); }); return asyncSetCookie; } // Listen for onHeaderReceived for the target page. // Set "blocking" and "responseHeaders". browser.webRequest.onHeadersReceived.addListener( setCookieAsync, { urls: [targetPage] }, ["blocking", "responseHeaders"], ); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onHeadersReceived) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/onbeforerequest/index.md
--- title: webRequest.onBeforeRequest slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest page-type: webextension-api-event browser-compat: webextensions.api.webRequest.onBeforeRequest --- {{AddonSidebar}} This event is triggered when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel or redirect the request. To cancel or redirect the request, first include `"blocking"` in the `extraInfoSpec` array argument to `addListener()`. Then, in the listener function, return a {{WebExtAPIRef("webRequest.BlockingResponse", "BlockingResponse")}} object, setting the appropriate property: - to cancel the request, include a property `cancel` with the value `true`. - to redirect the request, include a property `redirectUrl` with the value set to the URL to which you want to redirect. If an extension wants to redirect a public (e.g. HTTPS) URL to an [extension page](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages), the extension's manifest.json file must contain a [web_accessible_resources](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources) key that lists the URL for the extension page. When multiple blocking handlers modify a request, only one set of modifications take effect. Redirects and cancellations have the same precedence. So if you canceled a request, you might see another request with the same `requestId` again if another blocking handler redirected the request. From Firefox 52 onwards, instead of returning `BlockingResponse`, the listener can return a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which is resolved with a `BlockingResponse`. This enables the listener to process the request asynchronously. If you use `"blocking"`, you must have the ["webRequestBlocking" API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) in your manifest.json. ## Syntax ```js-nolint browser.webRequest.onBeforeRequest.addListener( listener, // function filter, // object extraInfoSpec // optional array of strings ) browser.webRequest.onBeforeRequest.removeListener(listener) browser.webRequest.onBeforeRequest.hasListener(listener) ``` Events have three functions: - `addListener(listener, filter, extraInfoSpec)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `details` - : `object`. Details about the request. See the [details](#details_2) section for more information. Returns: {{WebExtAPIRef('webRequest.BlockingResponse')}}. If `"blocking"` is specified in the `extraInfoSpec` parameter, the event listener should return a `BlockingResponse` object, and can set either its `cancel` or its `redirectUrl` properties. From Firefox 52 onwards, instead of returning `BlockingResponse`, the listener can return a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which is resolved with a `BlockingResponse`. This enables the listener to process the request asynchronously. - `filter` - : {{WebExtAPIRef('webRequest.RequestFilter')}}. A filter that restricts the events that is sent to this listener. - `extraInfoSpec` {{optional_inline}} - : `array` of `string`. Extra options for the event. You can pass any of the following values: - `"blocking"`: make the request synchronous, so you can cancel or redirect the request - `"requestBody"`: include `requestBody` in the `details` object passed to the listener ## Additional objects ### details - `cookieStoreId` - : `string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. - `documentUrl` - : `string`. URL of the document in which the resource will be loaded. For example, if the web page at "https\://example.com" contains an image or an iframe, then the `documentUrl` for the image or iframe will be "https\://example.com". For a top-level document, `documentUrl` is undefined. - `frameAncestors` - : `array`. Contains information for each document in the frame hierarchy up to the top-level document. The first element in the array contains information about the immediate parent of the document being requested, and the last element contains information about the top-level document. If the load is actually for the top-level document, then this array is empty. - `url` - : `string`. The URL that the document was loaded from. - `frameId` - : `integer`. The `frameId` of the document. `details.frameAncestors[0].frameId` is the same as `details.parentFrameId`. - `frameId` - : `integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. - `incognito` - : `boolean`. Whether the request is from a private browsing window. - `method` - : `string`. Standard HTTP method: for example, "GET" or "POST". - `originUrl` - : `string`. URL of the resource which triggered the request. For example, if "https\://example.com" contains a link, and the user clicks the link, then the `originUrl` for the resulting request is "https\://example.com". The `originUrl` is often but not always the same as the `documentUrl`. For example, if a page contains an iframe, and the iframe contains a link that loads a new document into the iframe, then the `documentUrl` for the resulting request will be the iframe's parent document, but the `originUrl` will be the URL of the document in the iframe that contained the link. - `parentFrameId` - : `integer`. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists. - `proxyInfo` - : `object`. This property is present only if the request is being proxied. It contains the following properties: - `host` - : `string`. The hostname of the proxy server. - `port` - : `integer`. The port number of the proxy server. - `type` - : `string`. The type of proxy server. One of: - "http": HTTP proxy (or SSL CONNECT for HTTPS) - "https": HTTP proxying over TLS connection to proxy - "socks": SOCKS v5 proxy - "socks4": SOCKS v4 proxy - "direct": no proxy - "unknown": unknown proxy - `username` - : `string`. Username for the proxy service. - `proxyDNS` - : `boolean`. True if the proxy will perform domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup. - `failoverTimeout` - : `integer`. Failover timeout in seconds. If the proxy connection fails, the proxy will not be used again for this period. - `requestBody` {{optional_inline}} - : `object`. Contains the HTTP request body data. Only provided if `extraInfoSpec` contains `"requestBody"`. - `error` {{optional_inline}} - : `string`. This is set if any errors were encountered when obtaining request body data. - `formData` {{optional_inline}} - : `object`. This object is present if the request method is POST and the body is a sequence of key-value pairs encoded in UTF-8 as either "multipart/form-data" or "application/x-www-form-urlencoded". It is a dictionary in which each key contains the list of all values for that key. For example: `{'key': ['value1', 'value2']}`. If the data is of another media type, or if it is malformed, the object is not present. - `raw` {{optional_inline}} - : `array` of `{{WebExtAPIRef('webRequest.UploadData')}}`. If the request method is PUT or POST, and the body is not already parsed in `formData`, then this array contains the unparsed request body elements. - `requestId` - : `string`. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request. - `tabId` - : `integer`. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. - `thirdParty` - : `boolean`. Indicates whether the request and its content window hierarchy are third party. - `timeStamp` - : `number`. The time when this event fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `type` - : {{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", "stylesheet". - `url` - : `string`. Target of the request. - `urlClassification` - : `object`. The type of tracking associated with the request, if with the request has been classified by [Firefox Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop). This is an object with the following properties: - `firstParty` - : `array` of `strings`. Classification flags for the request's first party. - `thirdParty` - : `array` of `strings`. Classification flags for the request or its window hierarchy's third parties. The classification flags include: - `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin that has been found to fingerprint but is not considered to participate in tracking, such as a payment provider. - `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources. - `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request, the `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker. - `any_basic_tracking`: a meta flag that combines any tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`. - `any_strict_tracking`: a meta flag that combines any tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`. - `any_social_tracking`: a meta flag that combines any social tracking flags. ## Browser compatibility {{Compat}} ### DNS resolution ordering when BlockingResponse is used Regarding DNS resolution when BlockingResponse is used with OnBeforeRequest: In HTTP Channel, onBeforeRequest with blocking response does happen prior to DNS resolution and also prior to speculative connect. For other channels, speculative connect may cause DNS requests to happen before onBeforeRequest. This ordering is not something an extension developer ought to rely on as it may vary across browsers, and from one browser version to another, let alone one request channel to another. Refer [BugZilla issue clarification provided by Mozilla developers on DNS resolution ordering](https://bugzil.la/1466099) ## Examples This code logs the URL for every resource requested which matches the [\<all_urls>](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns#all_urls) pattern: ```js function logURL(requestDetails) { console.log(`Loading: ${requestDetails.url}`); } browser.webRequest.onBeforeRequest.addListener(logURL, { urls: ["<all_urls>"], }); ``` This code cancels requests for images that are made to URLs under "https\://developer.mozilla.org/" (to see the effect, visit any page on MDN that contains images, such as [webRequest](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest)): ```js // match pattern for the URLs to redirect let pattern = "https://developer.mozilla.org/*"; // cancel function returns an object // which contains a property `cancel` set to `true` function cancel(requestDetails) { console.log(`Canceling: ${requestDetails.url}`); return { cancel: true }; } // add the listener, // passing the filter argument and "blocking" browser.webRequest.onBeforeRequest.addListener( cancel, { urls: [pattern], types: ["image"] }, ["blocking"], ); ``` This code replaces, by redirection, all network requests for images that are made to URLs under "https\://developer.mozilla.org/" (to see the effect, visit any page on MDN that contains images, such as [webRequest](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest)): ```js // match pattern for the URLs to redirect let pattern = "https://developer.mozilla.org/*"; // redirect function // returns an object with a property `redirectURL` // set to the new URL function redirect(requestDetails) { console.log(`Redirecting: ${requestDetails.url}`); return { redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif", }; } // add the listener, // passing the filter argument and "blocking" browser.webRequest.onBeforeRequest.addListener( redirect, { urls: [pattern], types: ["image"] }, ["blocking"], ); ``` This code is exactly like the previous example, except that the listener handles the request asynchronously. It returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that sets a timer, and resolves with the redirect URL when the timer expires: ```js // match pattern for the URLs to redirect let pattern = "https://developer.mozilla.org/*"; // URL we will redirect to let redirectUrl = "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"; // redirect function returns a Promise // which is resolved with the redirect URL when a timer expires function redirectAsync(requestDetails) { console.log(`Redirecting async: ${requestDetails.url}`); return new Promise((resolve, reject) => { setTimeout(() => { resolve({ redirectUrl }); }, 2000); }); } // add the listener, // passing the filter argument and "blocking" browser.webRequest.onBeforeRequest.addListener( redirectAsync, { urls: [pattern], types: ["image"] }, ["blocking"], ); ``` Another example, that redirects all images to a data URL: ```js let pattern = "https://developer.mozilla.org/*"; let image = ` <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"> <rect style="stroke-width: 10; stroke: #666;" width="100%" height="100%" fill="#d4d0c8" /> <text transform="translate(0, 9)" x="50%" y="50%" width="100%" fill="#666" height="100%" style="text-anchor: middle; font: bold 10pt 'Segoe UI', Arial, Helvetica, Sans-serif;">Blocked</text> </svg> `; function listener(details) { const redirectUrl = `data:image/svg+xml,${encodeURIComponent(image)}`; return { redirectUrl }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: [pattern], types: ["image"] }, ["blocking"], ); ``` Here's another version: ```js function randomColor() { return `#${Math.floor(Math.random() * 16777215).toString(16)}`; } const pattern = "https://developer.mozilla.org/*"; let image = ` <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"> <rect width="100%" height="100%" fill="${randomColor()}"/> </svg> `; function listener(details) { const redirectUrl = `data:image/svg+xml,${encodeURIComponent(image)}`; return { redirectUrl }; } browser.webRequest.onBeforeRequest.addListener( listener, { urls: [pattern], types: ["image"] }, ["blocking"], ); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onBeforeRequest) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/max_handler_behavior_changed_calls_per_10_minutes/index.md
--- title: webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES slug: Mozilla/Add-ons/WebExtensions/API/webRequest/MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES page-type: webextension-api-property browser-compat: webextensions.api.webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES --- {{AddonSidebar}} The maximum number of times that `{{WebExtAPIRef("webRequest.handlerBehaviorChanged", "handlerBehaviorChanged()")}}` can be called in a 10 minute period. This property is read-only. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#property-MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/getsecurityinfo/index.md
--- title: webRequest.getSecurityInfo() slug: Mozilla/Add-ons/WebExtensions/API/webRequest/getSecurityInfo page-type: webextension-api-function browser-compat: webextensions.api.webRequest.getSecurityInfo --- {{AddonSidebar}} Use this function to get detailed information about the [TLS](/en-US/docs/Glossary/TLS) connection associated with a particular request. You pass this function the `requestId` for the request in question, and some optional extra parameters. It returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which will resolve to a {{WebExtAPIRef("webRequest.SecurityInfo", "SecurityInfo")}} object. You can only call this function from inside the {{WebExtAPIRef("webRequest.onHeadersReceived")}} listener. The `requestId` can be found in the `details` object which is passed into the listener. You must also pass the "blocking" option to `webRequest.onHeadersReceived.addListener()`. So to use this API you must have the "webRequestBlocking" [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions), as well as the normal permissions needed for using `webRequest` listeners (the "webRequest" permission and the [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the host). ## Syntax ```js-nolint let gettingInfo = browser.webRequest.getSecurityInfo( requestId, // string options // object ) ``` ### Parameters - `requestId` - : `string`. ID of the request for which you want security info. You can get this from the `details` object that is passed into any `webRequest` event listeners. - `options` - : `object`. An object which may contain any of the following properties, all optional: - `certificateChain` {{optional_inline}} - : `boolean`. If `true`, the {{WebExtAPIRef("webRequest.SecurityInfo", "SecurityInfo")}} object returned will include the entire certificate chain up to and including the trust root. If `false`, it will include only the server certificate. Defaults to `false`. - `rawDER` {{optional_inline}} - : `boolean`. If true, every {{WebExtAPIRef("webRequest.CertificateInfo", "CertificateInfo")}} in the {{WebExtAPIRef("webRequest.SecurityInfo", "SecurityInfo.certificates")}} property will contain a property `rawDER`. This contains the DER-encoded ASN.1 that comprises the certificate data. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves to a {{WebExtAPIRef("webRequest.SecurityInfo", "SecurityInfo")}} object. ## Browser compatibility {{Compat}} ## Examples This example listens for all HTTPS requests to "mozilla.org" or its subdomains, and logs the subject name in the server certificate: ```js async function logSubject(details) { try { let securityInfo = await browser.webRequest.getSecurityInfo( details.requestId, {}, ); console.log(details.url); if (securityInfo.state === "secure" || securityInfo.state === "weak") { console.log(securityInfo.certificates[0].subject); } } catch (error) { console.error(error); } } browser.webRequest.onHeadersReceived.addListener( logSubject, { urls: ["https://*.mozilla.org/*"] }, ["blocking"], ); ``` This example listens for all HTTPS requests to "mozilla.org" or its subdomains, and logs the name in the trusted root certificate: ```js async function logRoot(details) { try { let securityInfo = await browser.webRequest.getSecurityInfo( details.requestId, { certificateChain: true }, ); console.log(details.url); if (securityInfo.state === "secure" || securityInfo.state === "weak") { console.log( securityInfo.certificates[securityInfo.certificates.length - 1].issuer, ); } } catch (error) { console.error(error); } } browser.webRequest.onHeadersReceived.addListener( logRoot, { urls: ["https://*.mozilla.org/*"] }, ["blocking"], ); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/onerroroccurred/index.md
--- title: webRequest.onErrorOccurred slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onErrorOccurred page-type: webextension-api-event browser-compat: webextensions.api.webRequest.onErrorOccurred --- {{AddonSidebar}} Fired when a request could not be processed due to an error: for example, a lack of Internet connectivity. The error is passed to the listener as the `error` property of the [`details`](#details) object. Note that this event is not fired for HTTP errors (4XX or 5XX responses): these will go through the normal stages of a request, calling any event listeners, and setting `details.statusCode` to report the error. This event is informational only. ## Syntax ```js-nolint browser.webRequest.onErrorOccurred.addListener( listener, // function filter // object ) browser.webRequest.onErrorOccurred.removeListener(listener) browser.webRequest.onErrorOccurred.hasListener(listener) ``` Events have three functions: - `addListener(listener, filter)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `details` - : `object`. Details about the request. See the [details](#details_2) section for more information. - `filter` - : {{WebExtAPIRef('webRequest.RequestFilter')}}. A filter that restricts the events that is sent to this listener. ## Additional objects ### details - `cookieStoreId` - : `string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. - `documentUrl` - : `string`. URL of the document in which the resource will be loaded. For example, if the web page at "https\://example.com" contains an image or an iframe, then the `documentUrl` for the image or iframe will be "https\://example.com". For a top-level document, `documentUrl` is undefined. - `error` - : `string`. The error description. This string is an internal error string, may vary from one browser to another, and is not guaranteed to stay the same between releases. - `frameId` - : `integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. - `fromCache` - : `boolean`. Indicates if this response was fetched from disk cache. - `incognito` - : `boolean`. Whether the request is from a private browsing window. - `ip` - : `string`. The IP address of the server the request was sent to. It may be a literal IPv6 address. - `method` - : `string`. Standard HTTP method: for example, "GET" or "POST". - `originUrl` - : `string`. URL of the resource which triggered the request. For example, if "https\://example.com" contains a link, and the user clicks the link, then the `originUrl` for the resulting request is "https\://example.com". The `originUrl` is often but not always the same as the `documentUrl`. For example, if a page contains an iframe, and the iframe contains a link that loads a new document into the iframe, then the `documentUrl` for the resulting request will be the iframe's parent document, but the `originUrl` will be the URL of the document in the iframe that contained the link. - `parentFrameId` - : `integer`. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists. - `proxyInfo` - : `object`. This property is present only if the request is being proxied. It contains the following properties: - `host` - : `string`. The hostname of the proxy server. - `port` - : `integer`. The port number of the proxy server. - `type` - : `string`. The type of proxy server. One of: - "http": HTTP proxy (or SSL CONNECT for HTTPS) - "https": HTTP proxying over TLS connection to proxy - "socks": SOCKS v5 proxy - "socks4": SOCKS v4 proxy - "direct": no proxy - "unknown": unknown proxy - `username` - : `string`. Username for the proxy service. - `proxyDNS` - : `boolean`. True if the proxy will perform domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup. - `failoverTimeout` - : `integer`. Failover timeout in seconds. If the proxy connection fails, the proxy will not be used again for this period. - `requestId` - : `string`. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request. - `tabId` - : `integer`. The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. - `thirdParty` - : `boolean`. Indicates whether the request and its content window hierarchy are third party. - `timeStamp` - : `number`. The time when this event fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `type` - : {{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", "stylesheet". - `url` - : `string`. Target of the request. - `urlClassification` - : `object`. The type of tracking associated with the request, if with the request has been classified by [Firefox Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop). This is an object with these properties: - `firstParty` - : `array` of `strings`. Classification flags for the request's first party. - `thirdParty` - : `array` of `strings`. Classification flags for the request or its window hierarchy's third parties. The classification flags include: - `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin that has been found to fingerprint but is not considered to participate in tracking, such as a payment provider. - `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources. - `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request, the `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker. - `any_basic_tracking`: a meta flag that combines any tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`. - `any_strict_tracking`: a meta flag that combines any tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`. - `any_social_tracking`: a meta flag that combines any social tracking flags. **Note** If Firefox Tracking Protection blocks the request an empty object is returned and `error` returns one of these codes: - `NS_ERROR_MALWARE_URI` indicating a malware URI. - `NS_ERROR_PHISHING_URI` indicating a phishing URI. - `NS_ERROR_TRACKING_URI` indicating a tracking URI. - `NS_ERROR_UNWANTED_URI` indicating an unwanted URI. - `NS_ERROR_BLOCKED_URI` indicating a blocked URI. - `NS_ERROR_HARMFUL_URI` indicating a harmful URI. - `NS_ERROR_FINGERPRINTING` indicating a fingerprinting URI. - `NS_ERROR_CRYPTOMINING_URI` indicating a cryptomining URI. - `NS_ERROR_SOCIALTRACKING_URI` indicating a social tracking URI. ## Browser compatibility {{Compat}} ## Examples ```js let target = "<all_urls>"; /* e.g., with no network: "https://developer.mozilla.org/en-US/" NS_ERROR_NET_ON_RESOLVED in Firefox net::ERR_INTERNET_DISCONNECTED in Chrome */ function logError(responseDetails) { console.log(responseDetails.url); console.log(responseDetails.error); } browser.webRequest.onErrorOccurred.addListener(logError, { urls: [target] }); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onErrorOccurred) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/onsendheaders/index.md
--- title: webRequest.onSendHeaders slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onSendHeaders page-type: webextension-api-event browser-compat: webextensions.api.webRequest.onSendHeaders --- {{AddonSidebar}} This event is fired just before sending headers. If your extension or some other extension modified headers in `{{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}}`, you'll see the modified version here. This event is informational only. ## Syntax ```js-nolint browser.webRequest.onSendHeaders.addListener( listener, // function filter, // object extraInfoSpec // optional array of strings ) browser.webRequest.onSendHeaders.removeListener(listener) browser.webRequest.onSendHeaders.hasListener(listener) ``` Events have three functions: - `addListener(listener, filter, extraInfoSpec)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `details` - : `object`. Details about the request. See the [details](#details_2) section for more information. - `filter` - : {{WebExtAPIRef('webRequest.RequestFilter')}}. A filter that restricts the events that is sent to this listener. - `extraInfoSpec` {{optional_inline}} - : `array` of `string`. Extra options for the event. You can only pass one value here: - `"requestHeaders"`: include the request headers in the `details` object passed to the listener ## Additional objects ### details - `cookieStoreId` - : `string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. - `documentUrl` - : `string`. URL of the document in which the resource will be loaded. For example, if the web page at "https\://example.com" contains an image or an iframe, then the `documentUrl` for the image or iframe will be "https\://example.com". For a top-level document, `documentUrl` is undefined. - `frameId` - : `integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab - `incognito` - : `boolean`. Whether the request is from a private browsing window. - `method` - : `string`. Standard HTTP method: for example, "GET" or "POST". - `originUrl` - : `string`. URL of the resource which triggered the request. For example, if "https\://example.com" contains a link, and the user clicks the link, then the `originUrl` for the resulting request is "https\://example.com". The `originUrl` is often but not always the same as the `documentUrl`. For example, if a page contains an iframe, and the iframe contains a link that loads a new document into the iframe, then the `documentUrl` for the resulting request will be the iframe's parent document, but the `originUrl` will be the URL of the document in the iframe that contained the link. - `parentFrameId` - : `integer`. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists. - `proxyInfo` - : `object`. This property is present only if the request is being proxied. It contains the following properties: - `host` - : `string`. The hostname of the proxy server. - `port` - : `integer`. The port number of the proxy server. - `type` - : `string`. The type of proxy server. One of: - "http": HTTP proxy (or SSL CONNECT for HTTPS) - "https": HTTP proxying over TLS connection to proxy - "socks": SOCKS v5 proxy - "socks4": SOCKS v4 proxy - "direct": no proxy - "unknown": unknown proxy - `username` - : `string`. Username for the proxy service. - `proxyDNS` - : `boolean`. True if the proxy will perform domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup. - `failoverTimeout` - : `integer`. Failover timeout in seconds. If the proxy connection fails, the proxy will not be used again for this period. - `requestId` - : `string`. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request. - `requestHeaders` {{optional_inline}} - : {{WebExtAPIRef('webRequest.HttpHeaders')}}. The HTTP request headers that have been sent out with this request. - `tabId` - : `integer`. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. - `thirdParty` - : `boolean`. Indicates whether the request and its content window hierarchy are third party. - `timeStamp` - : `number`. The time when this event fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `type` - : {{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", "stylesheet". - `url` - : `string`. Target of the request. - `urlClassification` - : `object`. The type of tracking associated with the request, if with the request has been classified by [Firefox Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop). This is an object with the following properties: - `firstParty` - : `array` of `strings`. Classification flags for the request's first party. - `thirdParty` - : `array` of `strings`. Classification flags for the request or its window hierarchy's third parties. The classification flags include: - `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin that has been found to fingerprint but is not considered to participate in tracking, such as a payment provider. - `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources. - `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request, the `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker. - `any_basic_tracking`: a meta flag that combines any tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`. - `any_strict_tracking`: a meta flag that combines any tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`. - `any_social_tracking`: a meta flag that combines any social tracking flags. ## Browser compatibility {{Compat}} ## Examples This code logs all cookies that will be sent in making requests to the target [match pattern](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns): ```js // The target match pattern let targetPage = "*://*.google.ca/*"; // Log cookies sent with this request function logCookies(e) { for (const header of e.requestHeaders) { if (header.name === "Cookie") { console.log(header.value); } } } // Listen for onSendHeaders, and pass // "requestHeaders" so we get the headers browser.webRequest.onSendHeaders.addListener( logCookies, { urls: [targetPage] }, ["requestHeaders"], ); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onSendHeaders) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/webrequest
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/webrequest/onauthrequired/index.md
--- title: webRequest.onAuthRequired slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onAuthRequired page-type: webextension-api-event browser-compat: webextensions.api.webRequest.onAuthRequired --- {{AddonSidebar}} Fired when the server sends a `401` or `407` status code and a `WWW-Authenticate` header using the `Basic` scheme (that is, when the server asks the client to provide authentication credentials, such as a username and password). The listener can respond in one of four ways: - Take no action - : The listener can do nothing, just observing the request. If this happens, it does not affect the handling of the request, and the browser asks the user to log in, if appropriate. - Cancel the request - : The listener can cancel the request. If it does this, authentication fails, and the user is not asked to log in. Extensions can cancel requests as follows: - in addListener, pass `"blocking"` in the `extraInfoSpec` parameter - in the listener, return an object with a `cancel` property set to `true` - Provide credentials synchronously - : If credentials are available synchronously, the extension can supply them synchronously. If the extension does this, the browser attempts to log in with the credentials. The listener can provide credentials synchronously as follows: - in addListener, pass `"blocking"` in the `extraInfoSpec` parameter - in the listener, return an object with an `authCredentials` property set to the credentials to supply - Provide credentials asynchronously - : The extension might need to fetch credentials asynchronously. For example, the extension might need to fetch credentials from storage or ask the user. In this case, the listener can supply credentials asynchronously as follows: - in addListener, pass `"blocking"` in the `extraInfoSpec` parameter - in the listener, return a `Promise` that resolves with an object containing an `authCredentials` property, set to the credentials to supply > **Note:** Chrome does not support a Promise as a return value ([Chromium issue 1510405](https://crbug.com/1510405)). For alternatives, see [the return value of the `listener`](#listener). See [Examples](#examples). If your extension provides bad credentials, then the listener is called again. For this reason, take care to avoid entering an infinite loop by repeatedly providing bad credentials. ## Permissions In Firefox and Chrome Manifest V2 extensions, you must add the [`"webRequest"` and `"webRequestBlocking"` API permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) to your `manifest.json`. For Chrome Manifest V3 extensions, the `"webRequestBlocking"` permission is no longer available (except for policy-installed extensions). Instead, the `"webRequest"` and `"webRequestAuthProvider"` permissions enable you to supply credentials asynchronously. > **Note:** Firefox does not support `"webRequestAuthProvider"`, but support is planned. See [bug 1820569](https://bugzilla.mozilla.org/show_bug.cgi?id=1820569). ## Proxy authorization Firefox does not generally fire `webRequest` events for system requests, such as browser or extension upgrades or search engine queries. To enable proxy authorization to work smoothly for system requests, from version 57, Firefox supports an exception to this. If an extension has the `"webRequest"`, `"webRequestBlocking"`, `"proxy"`, and `"<all_urls>"` permissions, then it can use `onAuthRequired` to supply credentials for proxy authorization (but not for normal web authorization). The listener cannot cancel system requests or make any other modifications to any system requests. ## Syntax ```js-nolint browser.webRequest.onAuthRequired.addListener( listener, // function filter, // object extraInfoSpec // optional array of strings ) browser.webRequest.onAuthRequired.removeListener(listener) browser.webRequest.onAuthRequired.hasListener(listener) ``` Events have three functions: - `addListener(listener, filter, extraInfoSpec)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed these arguments: - `details` - : `object`. Details about the request. See the [details](#details_2) section for more information. Returns: {{WebExtAPIRef('webRequest.BlockingResponse')}} or a {{jsxref("Promise")}}. - To handle the request synchronously, include `"blocking"` in the `extraInfoSpec` parameter and return a `BlockingResponse` object with its `cancel` or `authCredentials` properties set. This behavior is the same for Firefox and Chrome. However, synchronous handling is only appropriate for the simplest of extensions. - To handle the request asynchronously: - in Firefox, the `extraInfoSpec` array must include `"blocking"`, and the event handler function can return a Promise that resolves to a `BlockingResponse` object, with its `cancel` or `authCredentials` properties set. This is basically the same as handling the event synchronously. - in Chrome, the `extraInfoSpec` array must include `"asyncBlocking"` (without `"blocking"`). The event handler function is passed a function as a second parameter (called `asyncCallback`) that should be invoked with the `BlockingResponse` result, with its `cancel` or `authCredentials` properties set. - `filter` - : {{WebExtAPIRef('webRequest.RequestFilter')}}. A filter that restricts the events that are sent to this listener. - `extraInfoSpec` {{optional_inline}} - : `array` of `string`. Extra options for the event. You can pass any of the following values: - `"blocking"`: make the request block so you can cancel the request or supply authentication credentials. To handle the request asynchronously in Chrome, use `"asyncBlocking"` instead. - `"responseHeaders"`: include `responseHeaders` in the `details` object passed to the listener ## Additional objects ### details - `challenger` - : `object`. The server requesting authentication. This is an object with the following properties: - `host` - : `string`. The server's [hostname](https://en.wikipedia.org/wiki/Hostname#Internet_hostnames). - `port` - : `integer`. The server's port number. - `cookieStoreId` - : `string`. If the request is from a tab open in a contextual identity, the cookie store ID of the contextual identity. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. - `frameId` - : `integer`. This is `0` if the request occurs in the main frame; a positive value is 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. - `incognito` - : `boolean`. Whether the request is from a private browsing window. - `isProxy` - : `boolean`. `true` for `Proxy-Authenticate`, `false` for `WWW-Authenticate`. > **Note:** `webRequest.onAuthRequired` is only called for HTTP and HTTPS/TLS proxy servers requiring authentication, not for SOCKS proxy servers requiring authentication. - `method` - : `string`. Standard HTTP method (For example, `"GET"` or `"POST"`). - `parentFrameId` - : `integer`. ID of the frame that contains the frame that sent the request. Set to `-1` if no parent frame exists. - `proxyInfo` - : `object`. This property is present only if the request is being proxied. It contains the following properties: - `host` - : `string`. The hostname of the proxy server. - `port` - : `integer`. The port number of the proxy server. - `type` - : `string`. The type of proxy server. One of: - `"http"`: HTTP proxy (or SSL CONNECT for HTTPS) - `"https"`: HTTP proxying over TLS connection to proxy - `"socks"`: SOCKS v5 proxy - `"socks4"`: SOCKS v4 proxy - `"direct"`: no proxy - `"unknown"`: unknown proxy - `username` - : `string`. Username for the proxy service. - `proxyDNS` - : `boolean`. True if the proxy performs domain name resolution based on the hostname supplied, meaning that the client should not do its own DNS lookup. - `failoverTimeout` - : `integer`. Failover timeout in seconds. If the connection fails to connect the proxy server after this number of seconds, the next proxy server in the array returned from [FindProxyForURL()](</en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy#findproxyforurl()_return_value>) is used. - `realm` {{optional_inline}} - : `string`. The authentication [realm](https://datatracker.ietf.org/doc/html/rfc1945#section-11) provided by the server, if there is one. - `requestId` - : `string`. The ID of the request. Request IDs are unique within a browser session, so you can relate different events associated with the same request. - `responseHeaders` {{optional_inline}} - : {{WebExtAPIRef('webRequest.HttpHeaders')}}. The HTTP response headers received with this response. - `scheme` - : `string`. The authentication scheme: `"basic"` or `"digest`". - `statusCode` - : `integer`. Standard HTTP status code returned by the server. - `statusLine` - : `string`. HTTP status line of the response, the `'HTTP/0.9 200 OK'` string for HTTP/0.9 responses (i.e., responses that lack a status line), or an empty string if there are no headers. - `tabId` - : `integer`. ID of the tab where the request takes place. Set to `-1` if the request isn't related to a tab. - `thirdParty` - : `boolean`. Indicates whether the request and its content window hierarchy are third-party. - `timeStamp` - : `number`. The time when this event fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `type` - : {{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, `"image"`, `"script"`, or `"stylesheet"`. - `url` - : `string`. Target of the request. - `urlClassification` - : `object`. The type of tracking associated with the request if the request is classified by [Firefox Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop). This is an object with the following properties: - `firstParty` - : `array` of `strings`. Classification flags for the request's first party. - `thirdParty` - : `array` of `strings`. Classification flags for the request or its window hierarchy's third parties. The classification flags include: - `fingerprinting` and `fingerprinting_content`: indicates the request is involved in fingerprinting. `fingerprinting_content` indicates the request is loaded from an origin found to fingerprint but is not considered to participate in tracking, such as a payment provider. - `cryptomining` and `cryptomining_content`: similar to the fingerprinting category but for cryptomining resources. - `tracking`, `tracking_ad`, `tracking_analytics`, `tracking_social`, and `tracking_content`: indicates the request is involved in tracking. `tracking` is any generic tracking request. The `ad`, `analytics`, `social`, and `content` suffixes identify the type of tracker. - `any_basic_tracking`: a meta flag that combines tracking and fingerprinting flags, excluding `tracking_content` and `fingerprinting_content`. - `any_strict_tracking`: a meta flag that combines tracking and fingerprinting flags, including `tracking_content` and `fingerprinting_content`. - `any_social_tracking`: a meta flag that combines any social tracking flags. ## Examples This code observes authentication requests for the target URL: ```js const target = "https://intranet.company.com/"; function observe(requestDetails) { console.log(`observing: ${requestDetails.requestId}`); } browser.webRequest.onAuthRequired.addListener(observe, { urls: [target] }); ``` This code cancels authentication requests for the target URL: ```js const target = "https://intranet.company.com/"; function cancel(requestDetails) { console.log(`canceling: ${requestDetails.requestId}`); return { cancel: true }; } browser.webRequest.onAuthRequired.addListener(cancel, { urls: [target] }, [ "blocking", ]); ``` This code supplies credentials synchronously. It keeps track of outstanding requests to ensure that it doesn't repeatedly try to submit bad credentials: ```js const target = "https://intranet.company.com/"; const myCredentials = { username: "[email protected]", password: "zDR$ERHGDFy", }; const pendingRequests = []; // A request has completed. // We can stop worrying about it. function completed(requestDetails) { console.log(`completed: ${requestDetails.requestId}`); let index = pendingRequests.indexOf(requestDetails.requestId); if (index > -1) { pendingRequests.splice(index, 1); } } function provideCredentialsSync(requestDetails) { // If we have seen this request before, then // assume our credentials were bad, and give up. if (pendingRequests.includes(requestDetails.requestId)) { console.log(`bad credentials for: ${requestDetails.requestId}`); return { cancel: true }; } pendingRequests.push(requestDetails.requestId); console.log(`providing credentials for: ${requestDetails.requestId}`); return { authCredentials: myCredentials }; } browser.webRequest.onAuthRequired.addListener( provideCredentialsSync, { urls: [target] }, ["blocking"], ); browser.webRequest.onCompleted.addListener(completed, { urls: [target] }); browser.webRequest.onErrorOccurred.addListener(completed, { urls: [target] }); ``` This code supplies credentials asynchronously, fetching them from storage. It also keeps track of outstanding requests to ensure that it doesn't repeatedly try to submit bad credentials: ```js const target = "https://httpbin.org/basic-auth/*"; const pendingRequests = []; /* * A request has completed. We can stop worrying about it. */ function completed(requestDetails) { console.log(`completed: ${requestDetails.requestId}`); let index = pendingRequests.indexOf(requestDetails.requestId); if (index > -1) { pendingRequests.splice(index, 1); } } function provideCredentialsAsync(requestDetails) { // If we have seen this request before, // then assume our credentials were bad, // and give up. if (pendingRequests.includes(requestDetails.requestId)) { console.log(`bad credentials for: ${requestDetails.requestId}`); return { cancel: true }; } else { pendingRequests.push(requestDetails.requestId); console.log(`providing credentials for: ${requestDetails.requestId}`); // we can return a promise that will be resolved // with the stored credentials return browser.storage.local.get(null); } } browser.webRequest.onAuthRequired.addListener( provideCredentialsAsync, { urls: [target] }, ["blocking"], ); browser.webRequest.onCompleted.addListener(completed, { urls: [target] }); browser.webRequest.onErrorOccurred.addListener(completed, { urls: [target] }); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.webRequest`](https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onAuthRequired) API. This documentation is derived from [`web_request.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.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/extension/index.md
--- title: extension slug: Mozilla/Add-ons/WebExtensions/API/extension page-type: webextension-api browser-compat: webextensions.api.extension --- {{AddonSidebar}} Utilities related to your extension. Get URLs to resources packages with your extension. Get the [`Window`](/en-US/docs/Web/API/Window) object for your extension's pages. Get the values for various settings. > **Note:** **The messaging APIs in this module are deprecated** in favor of the equivalent APIs in the [`runtime`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime) module. ## Types - {{WebExtAPIRef("extension.ViewType")}} - : The type of extension view. ## Properties - {{WebExtAPIRef("extension.lastError")}} {{deprecated_inline}} - : Set for the lifetime of a callback if an asynchronous extension API has resulted in an error. If no error has occurred, `lastError` will be {{jsxref("undefined")}}. - {{WebExtAPIRef("extension.inIncognitoContext")}} - : `True` for content scripts running inside incognito tabs, and for extension pages running inside an incognito process. (The latter only applies to extensions with '`split`' `incognito_behavior`.) ## Functions - {{WebExtAPIRef("extension.getBackgroundPage()")}} - : Returns the [`Window`](/en-US/docs/Web/API/Window) object for the background page running inside the current extension. Returns [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) if the extension has no background page. - {{WebExtAPIRef("extension.getExtensionTabs()")}} {{deprecated_inline}} - : Returns an array of the JavaScript [Window](/en-US/docs/Web/API/Window) objects for each of the tabs running inside the current extension. - {{WebExtAPIRef("extension.getURL()")}} {{deprecated_inline}} - : Converts a relative path within an extension install directory to a fully-qualified URL. - {{WebExtAPIRef("extension.getViews()")}} - : Returns an array of the [`Window`](/en-US/docs/Web/API/Window) objects for each of the pages running inside the current extension. - {{WebExtAPIRef("extension.isAllowedIncognitoAccess()")}} - : Retrieves the state of the extension's access to Incognito-mode (as determined by the user-controlled '_Allowed in Incognito_' checkbox). - {{WebExtAPIRef("extension.isAllowedFileSchemeAccess()")}} - : Retrieves the state of the extension's access to the `file://` scheme (as determined by the user-controlled '_Allow access to File URLs_' checkbox). - {{WebExtAPIRef("extension.sendRequest()")}} {{deprecated_inline}} - : Sends a single request to other listeners within the extension. - {{WebExtAPIRef("extension.setUpdateUrlData()")}} - : Sets the value of the ap CGI parameter used in the extension's update URL. This value is ignored for extensions that are hosted in the browser vendor's store. ## Events - {{WebExtAPIRef("extension.onRequest")}} {{deprecated_inline}} - : Fired when a request is sent from either an extension process or a content script. - {{WebExtAPIRef("extension.onRequestExternal")}} {{deprecated_inline}} - : Fired when a request is sent from another extension. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/getbackgroundpage/index.md
--- title: extension.getBackgroundPage() slug: Mozilla/Add-ons/WebExtensions/API/extension/getBackgroundPage page-type: webextension-api-function browser-compat: webextensions.api.extension.getBackgroundPage --- {{AddonSidebar}} Returns the [Window](/en-US/docs/Web/API/Window) of the background page if the background script is running. If the script is not running, null is returned. This a synchronous function. > **Note:** This method cannot be used in Private Browsing mode — it always returns null. Consider using {{WebExtAPIRef("runtime.sendMessage","runtime.sendMessage()")}} or {{WebExtAPIRef("runtime.connect","runtime.connect()")}}. See [Firefox bug 1329304](https://bugzil.la/1329304) for more information. ## Syntax ```js-nolint let page = browser.extension.getBackgroundPage() ``` ### Parameters None. ### Return value `object`. [Window](/en-US/docs/Web/API/Window) of the background page or null. ## Examples Suppose a [background script](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#background_scripts) defines a function `foo()`: ```js // background.js function foo() { console.log("I'm defined in background.js"); } ``` A script running in a [popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#browser_actions_2) can call this function directly like this: ```js // popup.js let page = browser.extension.getBackgroundPage(); page.foo(); // -> "I'm defined in background.js" ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#method-getBackgroundPage) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/inincognitocontext/index.md
--- title: extension.inIncognitoContext slug: Mozilla/Add-ons/WebExtensions/API/extension/inIncognitoContext page-type: webextension-api-property browser-compat: webextensions.api.extension.inIncognitoContext --- {{AddonSidebar}} Boolean value, `true` for content scripts running inside private browsing tabs and for extension pages running inside a private browsing process. ## Syntax ```js-nolint let isPrivate = browser.extension.inIncognitoContext; // true or false ``` ### Value A _boolean_ value indicate if the current script is running in a private tab or process. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#property-inIncognitoContext) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/sendrequest/index.md
--- title: extension.sendRequest() slug: Mozilla/Add-ons/WebExtensions/API/extension/sendRequest page-type: webextension-api-function status: - deprecated browser-compat: webextensions.api.extension.sendRequest --- {{AddonSidebar}}{{Deprecated_Header}} > **Warning:** This method has been deprecated. Use {{WebExtAPIRef("runtime.sendMessage")}} instead. Sends a request to other listeners within the extension. Similar to {{WebExtAPIRef('runtime.connect')}}, but only sends a request with an optional response. The {{WebExtAPIRef('extension.onRequest')}} event fires in each page of the extension. ## Syntax ```js-nolint chrome.extension.sendRequest( extensionId, // optional string request, // any (response) => {/* … */} // optional function ) ``` This API is also available as `browser.extension.sendRequest()` in a [version that returns a promise](/en-US/docs/Mozilla/Add-ons/WebExtensions/API#callbacks_and_promises). ### Parameters - `extensionId` {{optional_inline}} - : `string`. The extension ID of the extension you want to connect to. If omitted, default is your own extension. - `request` - : `any`. - `responseCallback` {{optional_inline}} - : `function`. The function is passed these arguments: - `response` - : `any`. The JSON response object sent by the handler of the request. If an error occurs while connecting to the extension, the callback will be called with no arguments and {{WebExtAPIRef('runtime.lastError')}} will be set to the error message. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#method-sendRequest) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/getextensiontabs/index.md
--- title: extension.getExtensionTabs() slug: Mozilla/Add-ons/WebExtensions/API/extension/getExtensionTabs page-type: webextension-api-function browser-compat: webextensions.api.extension.getExtensionTabs --- {{AddonSidebar}} > **Warning:** This method has been deprecated. Use {{WebExtAPIRef("extension.getViews()")}} instead. Returns an array of the JavaScript [Window](/en-US/docs/Web/API/Window) objects for each of the tabs running inside the current extension. If `windowId` is specified, returns only the Window objects of tabs attached to the specified window. ## Syntax ```js-nolint chrome.extension.getExtensionTabs( windowId // optional integer ) ``` This API is also available as `browser.extension.getExtensionTabs()`. ### Parameters - `windowId` {{optional_inline}} - : `integer`. ### Return value `array` of `object`. Array of global window objects ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#method-getExtensionTabs) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/getviews/index.md
--- title: extension.getViews() slug: Mozilla/Add-ons/WebExtensions/API/extension/getViews page-type: webextension-api-function browser-compat: webextensions.api.extension.getViews --- {{AddonSidebar}} Returns an array of the [Window](/en-US/docs/Web/API/Window) objects for each of the pages running inside the current extension. This includes, for example: - the background page, if one is defined - any popup pages, if defined and loaded - any options pages, if defined and loaded - any browser tabs that host content packaged with the extension In Firefox, if this method is called from a page that is part of a private browsing window, such as a sidebar in a private window or a popup opened from a private window, then its return value will not include the extension's background page. ## Syntax ```js-nolint let windows = browser.extension.getViews( fetchProperties // optional object ) ``` ### Parameters - `fetchProperties` {{optional_inline}} - : An object with the following properties: - `type` {{optional_inline}} - : `string`. An {{WebExtAPIRef('extension.ViewType')}} indicating the type of view to get. If omitted, this function returns all views. - `windowId` {{optional_inline}} - : `integer`. The window to restrict the search to. If omitted, this function returns all views. In Firefox version 92 and earlier, sidebar views are not matched and, therefore, not returned. ### Return value `array` of `object`. Array of [Window](/en-US/docs/Web/API/Window) objects. ## Browser compatibility {{Compat}} ## Examples Get all windows belonging to this extension, and log their URLs: ```js const windows = browser.extension.getViews(); for (const extensionWindow of windows) { console.log(extensionWindow.location.href); } ``` Get only windows in browser tabs hosting content packaged with the extension: ```js const windows = browser.extension.getViews({ type: "tab" }); ``` Get only windows in popups: ```js const windows = browser.extension.getViews({ type: "popup" }); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#method-getViews) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/onrequestexternal/index.md
--- title: extension.onRequestExternal slug: Mozilla/Add-ons/WebExtensions/API/extension/onRequestExternal page-type: webextension-api-event browser-compat: webextensions.api.extension.onRequestExternal --- {{AddonSidebar}} > **Warning:** This is not implemented in Firefox because it has been deprecated since Chrome 33. Please use [runtime.onMessageExternal](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessageExternal) instead. Fired when a request is sent from another extension. ## Syntax ```js-nolint chrome.extension.onRequestExternal.addListener(function( request, // optional any sender, // runtime.MessageSender sendResponse, // function ) { }) chrome.extension.onRequestExternal.removeListener(listener) chrome.extension.onRequestExternal.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` - : `any`. The request sent by the calling script. - `sender` - : {{WebExtAPIRef('runtime.MessageSender')}}. - `sendResponse` - : `function`. Function to call when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#event-onRequestExternal) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/viewtype/index.md
--- title: extension.ViewType slug: Mozilla/Add-ons/WebExtensions/API/extension/ViewType page-type: webextension-api-type browser-compat: webextensions.api.extension.ViewType --- {{AddonSidebar}} The type of extension view. ## Type Values of this type are strings. Possible values are: `"tab"`, `"popup"`, `"sidebar"`. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#type-ViewType) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/onrequest/index.md
--- title: extension.onRequest slug: Mozilla/Add-ons/WebExtensions/API/extension/onRequest page-type: webextension-api-event browser-compat: webextensions.api.extension.onRequest --- {{AddonSidebar}} > **Warning:** This is not implemented in Firefox because it has been deprecated since Chrome 33. Please use [runtime.onMessage](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage) instead. Fired when a request is sent from either an extension process or a content script. ## Syntax ```js-nolint chrome.extension.onRequest.addListener(function( request, // optional any sender, // runtime.MessageSender () => {/* … */} // function ) {/* … */}) chrome.extension.onRequest.removeListener(listener) chrome.extension.onRequest.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` - : `any`. The request sent by the calling script. - `sender` - : {{WebExtAPIRef('runtime.MessageSender')}}. - `sendResponse` - : `function`. Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one `onRequest` listener in the same document, then only one may send a response. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#event-onRequest) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/isallowedincognitoaccess/index.md
--- title: extension.isAllowedIncognitoAccess() slug: Mozilla/Add-ons/WebExtensions/API/extension/isAllowedIncognitoAccess page-type: webextension-api-function browser-compat: webextensions.api.extension.isAllowedIncognitoAccess --- {{AddonSidebar}} Check whether the extension is allowed access to tabs opened in "private browsing" mode. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let isAllowed = browser.extension.isAllowedIncognitoAccess() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a boolean: `true` if the extension is allowed access to private tabs, `false` otherwise. ## Examples ```js function logIsAllowed(answer) { console.log(`Is allowed: ${answer}`); } let isAllowed = browser.extension.isAllowedIncognitoAccess(); isAllowed.then(logIsAllowed); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#method-isAllowedIncognitoAccess) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/isallowedfileschemeaccess/index.md
--- title: extension.isAllowedFileSchemeAccess() slug: Mozilla/Add-ons/WebExtensions/API/extension/isAllowedFileSchemeAccess page-type: webextension-api-function browser-compat: webextensions.api.extension.isAllowedFileSchemeAccess --- {{AddonSidebar}} Returns `true` if the extension can access the "file://" scheme, `false` otherwise. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let isAllowed = browser.extension.isAllowedFileSchemeAccess() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a boolean: `true` if the extension is allowed access to "file://" URLs, `false` otherwise. Firefox will always return `false`. ## Browser compatibility {{Compat}} ## Examples ```js function logIsAllowed(answer) { console.log(`Is allowed: ${answer}`); } let isAllowed = browser.extension.isAllowedFileSchemeAccess(); isAllowed.then(logIsAllowed); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#method-isAllowedFileSchemeAccess) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/setupdateurldata/index.md
--- title: extension.setUpdateUrlData() slug: Mozilla/Add-ons/WebExtensions/API/extension/setUpdateUrlData page-type: webextension-api-function browser-compat: webextensions.api.extension.setUpdateUrlData --- {{AddonSidebar}} Sets parameters for the extension's update URL. This value is ignored for extensions that are hosted in the browser vendor's store. ## Syntax ```js-nolint browser.extension.setUpdateUrlData( data // string ) ``` ### Parameters - `data` - : `string`. ## Browser compatibility {{Compat}} ## Examples {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#method-setUpdateUrlData) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/lasterror/index.md
--- title: extension.lastError slug: Mozilla/Add-ons/WebExtensions/API/extension/lastError page-type: webextension-api-property browser-compat: webextensions.api.extension.lastError --- {{AddonSidebar}} > **Warning:** This function is deprecated, use {{WebExtAPIRef("runtime.lastError")}} instead. An alias for {{WebExtAPIRef("runtime.lastError")}}. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#property-lastError) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/extension
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/extension/geturl/index.md
--- title: extension.getURL() slug: Mozilla/Add-ons/WebExtensions/API/extension/getURL page-type: webextension-api-function status: - deprecated browser-compat: webextensions.api.extension.getURL --- {{AddonSidebar}} > **Warning:** This function is deprecated. Please use [`runtime.getURL`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/getURL). Converts a relative path within an extension's install directory to a fully-qualified URL. ## Syntax ```js-nolint browser.extension.getURL( path // string ) ``` ### Parameters - `path` - : `string`. A path to a resource within an extension expressed relative to its install directory. ### Return value `string`. The fully-qualified URL to the resource. ## Browser compatibility {{Compat}} ## Examples Given a file packaged with the add-on at "beasts/frog.html", get the full URL like this: ```js let fullURL = browser.extension.getURL("beasts/frog.html"); // -> something like: // moz-extension://2c127fa4-62c7-7e4f-90e5-472b45eecfdc/beasts/frog.html ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.extension`](https://developer.chrome.com/docs/extensions/reference/extension/#method-getURL) API. This documentation is derived from [`extension.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/extension.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/find/index.md
--- title: find slug: Mozilla/Add-ons/WebExtensions/API/find page-type: webextension-api browser-compat: webextensions.api.find --- {{AddonSidebar}} Finds text in a web page, and highlights matches. To use this API you need to have the "find" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). ## Functions - {{WebExtAPIRef("find.find()")}} - : Find text in a web page. - {{WebExtAPIRef("find.highlightResults()")}} - : Highlight the last set of matches found. - {{WebExtAPIRef("find.removeHighlighting()")}} - : Remove any highlighting. ## Browser compatibility {{WebExtExamples("h2")}} {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/find
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/find/removehighlighting/index.md
--- title: find.removeHighlighting() slug: Mozilla/Add-ons/WebExtensions/API/find/removeHighlighting page-type: webextension-api-function browser-compat: webextensions.api.find.removeHighlighting --- {{AddonSidebar}} Remove any highlighting of a previous search that was applied by a previous call to {{WebExtAPIRef("find.highlightResults()")}}, or by the browser's native UI. ## Syntax ```js-nolint browser.find.removeHighlighting() ``` ### Parameters None. ### Return value None. ## Browser compatibility {{Compat}} ## Examples ```js browser.find.removeHighlighting(); ```
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/find
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/find/find/index.md
--- title: find.find() slug: Mozilla/Add-ons/WebExtensions/API/find/find page-type: webextension-api-function browser-compat: webextensions.api.find.find --- {{AddonSidebar}} Searches for text in a tab. You can use this function to search normal HTTP(S) web pages. It searches a single tab: you can specify the ID of a particular tab to search, or it will search the active tab by default. It searches all frames in the tab. You can make the search case-sensitive and make it match whole words only. By default, the function just returns the number of matches found. By passing in the `includeRangeData` and `includeRectData` options, you can get more information about the location of the matches in the target tab. This function stores the results internally, so the next time any extension calls {{WebExtAPIRef("find.highlightResults()")}}, then the results of this find call will be highlighted, until the next time someone calls `find()`. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint browser.find.find( queryphrase, // string options // optional object ) ``` ### Parameters - `options` {{optional_inline}} - : `object`. An object specifying additional options. It may take any of the following properties, all optional: - `caseSensitive` - : `boolean`. If `true` the, the search is case-sensitive. Defaults to `false`. - `entireWord` - : `boolean`. Match only entire words: so "Tok" will not be matched inside "Tokyo". Defaults to `false`. - `includeRangeData` - : `boolean`. Include range data in the response, which describe where in the page DOM the match was found. Defaults to `false`. - `includeRectData` - : `boolean`. Include rectangle data in the response, which describes where in the rendered page the match was found. Defaults to `false` - `matchDiacritics` - : `boolean`. If `true`, the search distinguishes between accented letters and their base letters. For example, when set to `true`, searching for "résumé" does not find a match for "resume". Defaults to `false`. - `tabId` - : `integer`. ID of the tab to search. Defaults to the active tab. - `queryphrase` - : `string`. The text to search for. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an object containing up to three properties: - `count` - : `integer`. The number of results found. - `rangeData` {{optional_inline}} - : `array`. If `includeRangeData` was given in the `options` parameter, then this property will be included. It is provided as an array of `RangeData` objects, one for each match. Each `RangeData` object describes where in the DOM tree the match was found. This would enable, for example, an extension to get the text surrounding each match, so as to display context for the matches. The items correspond to the items given in `rectData`, so `rangeData[i]` describes the same match as `rectData[i]`. Each `RangeData` contains the following properties: - `endOffset` - : The ordinal position of the end of the match within its text node. - `endTextNodePos` - : The ordinal position of the text node in which the match ended. - `framePos` - : The index of the frame containing the match. 0 corresponds to the parent window. Note that the order of objects in the `rangeData` array will sequentially line up with the order of frame indexes: for example, `framePos` for the first sequence of `rangeData` objects will be 0, `framePos` for the next sequence will be 1, and so on. - `startOffset` - : The ordinal position of the start of the match within its text node. - `startTextNodePos` - : The ordinal position of the text node in which the match started. - `rectData` {{optional_inline}} - : `array`. If `includeRectData` was given in the `options` parameter, then this property will be included. It is an array of `RectData` objects. It contains client rectangles for all the text matched in the search, relative to the top-left of the viewport. Extensions can use this to provide custom highlighting of the results. Each `RectData` object contains rectangle data for a single match. It has two properties: - `rectsAndTexts` - : An object containing two properties, both arrays: - `rectList`: an array of objects which each have four integer properties: `top`, `left`, `bottom`, `right`. These describe a rectangle relative to the top-left of the viewport. - `textList`: an array of strings, corresponding to the `rectList` array. The entry at `textList[i]` contains the part of the match bounded by the rectangle at `rectList[i]`. For example, consider part of a web page that looks like this: ![Text reading "this domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission." and a "More information" link.](rects-1.png) If you search for "You may", the match needs to be described by two rectangles: ![This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.". The words "you may" are highlighted.](rects-2.png) In this case, in the `RectData` that describes this match, `rectsAndTexts.rectList` and `rectsAndTexts.textList` will each have 2 items. - `textList[0]` will contain "You ", and `rectList[0]` will contain its bounding rectangle. - `textList[1]` will contain "may", and `rectList[1]` will contain _its_ bounding rectangle. - `text` - : The complete text of the match, "You may" in the example above. ## Browser compatibility {{Compat}} ## Examples ### Basic examples Search the active tab for "banana", log the number of matches, and highlight them: ```js function found(results) { console.log(`There were: ${results.count} matches.`); if (results.count > 0) { browser.find.highlightResults(); } } browser.find.find("banana").then(found); ``` Search for "banana" across all tabs (note that this requires the "tabs" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or matching [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions), because it accesses `tab.url`): ```js async function findInAllTabs(allTabs) { for (const tab of allTabs) { const results = await browser.find.find("banana", { tabId: tab.id }); console.log(`In page "${tab.url}": ${results.count} matches.`); } } browser.tabs.query({}).then(findInAllTabs); ``` ### Using rangeData In this example the extension uses `rangeData` to get the context in which the match was found. The context is the complete `textContent` of the node in which the match was found. If the match spanned nodes, the context is the concatenation of the `textContent` of all spanned nodes. Note that for simplicity, this example doesn't handle pages that contain frames. To support this you'd need to split `rangeData` into groups, one per frame, and execute the script in each frame. The background script: ```js // background.js async function getContexts(matches) { // get the active tab ID const activeTabArray = await browser.tabs.query({ active: true, currentWindow: true, }); const tabId = activeTabArray[0].id; // execute the content script in the active tab await browser.tabs.executeScript(tabId, { file: "get-context.js" }); // ask the content script to get the contexts for us const contexts = await browser.tabs.sendMessage(tabId, { ranges: matches.rangeData, }); for (const context of contexts) { console.log(context); } } browser.browserAction.onClicked.addListener((tab) => { browser.find.find("example", { includeRangeData: true }).then(getContexts); }); ``` The content script: ```js /** * Get all the text nodes into a single array */ function getNodes() { const walker = document.createTreeWalker( document, window.NodeFilter.SHOW_TEXT, null, false, ); const nodes = []; while ((node = walker.nextNode())) { nodes.push(node); } return nodes; } /** * Gets all text nodes in the document, then for each match, return the * complete text content of nodes that contained the match. * If a match spanned more than one node, concatenate the textContent * of each node. */ function getContexts(ranges) { const contexts = []; const nodes = getNodes(); for (const range of ranges) { let context = nodes[range.startTextNodePos].textContent; let pos = range.startTextNodePos; while (pos < range.endTextNodePos) { pos++; context += nodes[pos].textContent; } contexts.push(context); } return contexts; } browser.runtime.onMessage.addListener((message, sender, sendResponse) => { sendResponse(getContexts(message.ranges)); }); ``` ### Using rectData In this example the extension uses `rectData` to "redact" the matches, by adding black DIVs over the top of their bounding rectangles: ![Three search results with some texted redacted by black rectangles.](redacted.png) Note that in many ways this is a poor way to redact pages. The background script: ```js // background.js async function redact(matches) { // get the active tab ID const activeTabArray = await browser.tabs.query({ active: true, currentWindow: true, }); const tabId = activeTabArray[0].id; // execute the content script in the active tab await browser.tabs.executeScript(tabId, { file: "redact.js" }); // ask the content script to redact matches for us await browser.tabs.sendMessage(tabId, { rects: matches.rectData }); } browser.browserAction.onClicked.addListener((tab) => { browser.find.find("banana", { includeRectData: true }).then(redact); }); ``` The content script: ```js // redact.js /** * Add a black DIV where the rect is. */ function redactRect(rect) { const redaction = document.createElement("div"); redaction.style.backgroundColor = "black"; redaction.style.position = "absolute"; redaction.style.top = `${rect.top}px`; redaction.style.left = `${rect.left}px`; redaction.style.width = `${rect.right - rect.left}px`; redaction.style.height = `${rect.bottom - rect.top}px`; document.body.appendChild(redaction); } /** * Go through every rect, redacting them. */ function redactAll(rectData) { for (const match of rectData) { for (const rect of match.rectsAndTexts.rectList) { redactRect(rect); } } } browser.runtime.onMessage.addListener((message) => { redactAll(message.rects); }); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/find
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/find/highlightresults/index.md
--- title: find.highlightResults() slug: Mozilla/Add-ons/WebExtensions/API/find/highlightResults page-type: webextension-api-function browser-compat: webextensions.api.find.highlightResults --- {{AddonSidebar}} Highlights the results of a previous call to {{WebExtAPIRef("find.find()")}}. When an extension calls `find()`, the matches are not highlighted automatically, but they are stored by the browser. Call `highlightResults()` to highlight them. Note that the stored results are global across all extensions, so for example, if extension A calls `find("apple")`, then extension B calls `find("banana")`, then if extension A calls `highlightResults()`, the results for "banana" will be highlighted. ## Syntax ```js-nolint browser.find.highlightResults( options // optional object ) ``` ### Parameters - `options` {{optional_inline}} - : `object`. An object specifying additional options. It may take any of the following properties, all optional: - `tabId` - : `integer`. ID of the tab to highlight. Defaults to the active tab. - `rangeIndex` - : `integer`. Index of the range to highlight. Defaults to highlighting all ranges. - `noScroll` - : `boolean`. Don't scroll to highlighted item. Defaults to `true`. ### Return value None. ## Browser compatibility {{Compat}} ## Examples Search the active tab for "banana", log the number of matches, and highlight them: ```js function found(results) { console.log(`There were: ${results.count} matches.`); if (results.count > 0) { browser.find.highlightResults(); } } browser.find.find("banana").then(found); ```
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/search/index.md
--- title: search slug: Mozilla/Add-ons/WebExtensions/API/search page-type: webextension-api browser-compat: webextensions.api.search --- {{AddonSidebar}} Use the search API to retrieve the installed search engines and execute searches. To use this API you need to have the `"search"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). When choosing between `search.query()` and `search.search()`, consider the following: - {{WebExtAPIRef("search.query()")}} is available in most major browsers, making it ideal for use in cross-browser extensions. However, it can only issue searches against the browser's default search engine. - {{WebExtAPIRef("search.search()")}} is available only in Firefox. However, it has the advantage of being able to issue a search against any search engine installed in the browser. ## Functions - {{WebExtAPIRef("search.get()")}} - : Retrieve all search engines. - {{WebExtAPIRef("search.query()")}} - : Search using the browser's default search engine. - {{WebExtAPIRef("search.search()")}} - : Search using a specified search engine. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/search
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/search/get/index.md
--- title: search.get() slug: Mozilla/Add-ons/WebExtensions/API/search/get page-type: webextension-api-function browser-compat: webextensions.api.search.get --- {{AddonSidebar}} Gets an array of all installed search engines. Each search engine returned is identified with a name, which you can pass into {{WebExtAPIRef("search.search()")}} to use that particular engine to make a search. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let gettingEngines = browser.search.get() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an [array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of search engine objects. Each search engine object may contain the following properties: - `name` - : `string`. The search engine's name. - `isDefault` - : `boolean`. `true` if the search engine is the default. Only one search engine can be the default at any given time. - `alias` {{optional_inline}} - : `string`. If a search engine has an alias, the user can search with a particular search engine by entering the alias in address bar before the search term. For example, if the Wikipedia engine has an alias "wk", the user can search Wikipedia for pandas by entering "wk pandas" in the address bar. The alias is sometimes also called a "keyword". - `favIconUrl` {{optional_inline}} - : `string`. The search engine's icon, as a data: URL. ## Browser compatibility {{Compat}} ## Examples Get all installed search engines: ```js function retrieved(results) { console.log(`There were: ${results.length} search engines retrieved.`); for (const searchEngine of results) { console.log(JSON.stringify(searchEngine.name)); } } browser.search.get().then(retrieved); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/search
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/search/search/index.md
--- title: search.search() slug: Mozilla/Add-ons/WebExtensions/API/search/search page-type: webextension-api-function browser-compat: webextensions.api.search.search --- {{AddonSidebar}} Perform a search using the search engine specified or the default search engine if no search engine is specified. The results are displayed in the current tab, a new tab, or a new window according to the `disposition` property or in the tab specified in the `tabId` property. If neither is specified, the results display in a new tab. To use this function, your extension must have the `"search"` [manifest permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). To get the installed search engines, use {{WebExtAPIRef("search.get()")}}. ## Syntax ```js-nolint browser.search.search( searchProperties // object ) ``` ### Parameters - `searchProperties` - : `object`. An object with the following properties: - `disposition` {{optional_inline}} - : `string`. The location where the search results are displayed. Valid values are `CURRENT_TAB`, `NEW_TAB`, and `NEW_WINDOW`. Defaults to `NEW_TAB`. Cannot be specified with `tabId`. - `engine` {{optional_inline}} - : `string`. The name of the search engine. If the search engine name doesn't exist, the function rejects the call with an error. If this property is omitted, the default search engine is used. - `query` - : `string`. The search query. - `tabId` {{optional_inline}} - : `integer`. An optional identifier for the tab you want to execute the search in. If this property is omitted, the search results are displayed in a new tab. Cannot be specified with `disposition`. ### Return value None. ## Examples A search using the default search engine with the results shown in the current tab (default): ```js function search() { browser.search.search({ query: "styracosaurus", }); } browser.browserAction.onClicked.addListener(search); ``` A search using Wikipedia with the results shown in a new window: ```js function search() { browser.search.search({ query: "styracosaurus", engine: "Wikipedia (en)", disposition: "NEW_WINDOW", }); } browser.browserAction.onClicked.addListener(search); ``` A search using Wikipedia with the results shown in the current tab: ```js function search(tab) { browser.search.search({ query: "styracosaurus", engine: "Wikipedia (en)", tabId: tab.id, }); } browser.browserAction.onClicked.addListener(search); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/search
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/search/query/index.md
--- title: search.query() slug: Mozilla/Add-ons/WebExtensions/API/search/query page-type: webextension-api-function browser-compat: webextensions.api.search.query --- {{AddonSidebar}} Perform a search using the browser's default search engine. The results are displayed in the current tab, a new tab, or a new window according to the `disposition` property or in the tab specified in the `tabId` property. If neither is specified, the results display in the current tab. To use this function, your extension must have the `"search"` [manifest permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). ## Syntax ```js-nolint browser.search.query( queryInfo // object ) ``` ### Parameters - `queryInfo` - : `object`. An object with the following properties: - `disposition` {{optional_inline}} - : `string`. The location where the search results are displayed. Valid values are `CURRENT_TAB`, `NEW_TAB`, and `NEW_WINDOW`. Defaults to `CURRENT_TAB`. Cannot be specified with `tabId`. - `tabId` {{optional_inline}} - : `integer`. An optional identifier for the tab you want to execute the search in. If this property is omitted, the search results are displayed in a new tab. Cannot be specified with `disposition`. - `text` - : `string`. The search query. ### Return value None. ## Examples A search with the results shown in the current tab (default): ```js function search() { browser.search.query({ text: "styracosaurus", }); } browser.browserAction.onClicked.addListener(search); ``` A search with the results shown in a new window: ```js function search() { browser.search.query({ text: "styracosaurus", disposition: "NEW_WINDOW", }); } browser.browserAction.onClicked.addListener(search); ``` A search with the results shown in a specific tab: ```js function search(tab) { browser.search.query({ query: "styracosaurus", tabId: tab.id, }); } browser.browserAction.onClicked.addListener(search); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/events/index.md
--- title: events slug: Mozilla/Add-ons/WebExtensions/API/events page-type: webextension-api browser-compat: webextensions.api.events --- {{AddonSidebar}} Common types used by APIs that dispatch events. ## Types - {{WebExtAPIRef("events.Rule")}} - : Description of a declarative rule for handling events. - {{WebExtAPIRef("events.Event")}} - : An object which allows the addition and removal of listeners for a browser event. - {{WebExtAPIRef("events.UrlFilter")}} - : Filters URLs for various criteria. If any of the given criteria match, then the whole filter matches. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.events`](https://developer.chrome.com/docs/extensions/reference/events/) API. This documentation is derived from [`events.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/events.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/events
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/events/rule/index.md
--- title: events.Rule slug: Mozilla/Add-ons/WebExtensions/API/events/Rule page-type: webextension-api-type browser-compat: webextensions.api.events.Rule --- {{AddonSidebar}} Description of a declarative rule for handling events. ## Type Values of this type are objects. They contain the following properties: - `id` {{optional_inline}} - : `string`. Optional identifier that allows referencing this rule. - `tags` {{optional_inline}} - : `array` of `string`. Tags can be used to annotate rules and perform operations on sets of rules. - `conditions` - : `array` of `any`. List of conditions that can trigger the actions. - `actions` - : `array` of `any`. List of actions that are triggered if one of the conditions is fulfilled. - `priority` {{optional_inline}} - : `integer`. Optional priority of this rule. Defaults to 100. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.events`](https://developer.chrome.com/docs/extensions/reference/events/#type-Rule) API. This documentation is derived from [`events.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/events.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/events
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/events/urlfilter/index.md
--- title: events.UrlFilter slug: Mozilla/Add-ons/WebExtensions/API/events/UrlFilter page-type: webextension-api-type browser-compat: webextensions.api.events.UrlFilter --- {{AddonSidebar}} Describes various criteria for filtering URLs. If all of the criteria specified in the filter's properties match the URL, then the filter matches. Filters are often provided to API methods in an [Array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of UrlFilters. For example, [webNavigation](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation) listeners can be added with a filter which is an object with a single `url` property that is an [Array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of UrlFilters, e.g. `{url:[UrlFilter, UrlFilter, …]}`. If any filter within the Array of UrlFilters matches, then it is considered a match for the Array. Effectively, the criteria specified within a single filter are AND'ed together, while all of the individual filters within an Array are OR'ed. All criteria are case sensitive. ## Type Values of this type are objects. They contain the following properties: However, note that these last two patterns will not match the last component of the hostname, because no implicit dot is added at the end of the hostname. So for example, `"org."` will match `https://borg.com` but not `https://example.org`. To match these patterns, use `hostSuffix`. - `hostContains` {{optional_inline}} - : `string`. Matches if the [hostname](/en-US/docs/Web/API/HTMLAnchorElement/hostname) of the URL (without protocol or port – see `schemes` and `ports`) contains the given string. - To test whether a hostname component starts with "foo", use `".foo"`. This matches `www.foobar.com` and `foo.com`, because an implicit dot is added at the beginning of the hostname. - To test whether a hostname component ends with "foo", use `"foo."`. - To test whether a hostname component exactly matches "foo", use `".foo."`. - `hostEquals` {{optional_inline}} - : `string`. Matches if the hostname of the URL is equal to a specified string. - Example: `"www.example.com"` matches `http://www.example.com` and `https://www.example.com/`, but not `http://example.com/`. - `hostPrefix` {{optional_inline}} - : `string`. Matches if the hostname of the URL starts with a specified string. - `hostSuffix` {{optional_inline}} - : `string`. Matches if the hostname of the URL ends with a specified string. - Example: `".example.com"` matches `http://www.example.com/`, but not `http://example.com/`. - Example: `"example.com"` matches `http://www.example.com/`, and `http://fakeexample.com/`. - `pathContains` {{optional_inline}} - : `string`. Matches if the path segment of the URL contains a specified string. - `pathEquals` {{optional_inline}} - : `string`. Matches if the path segment of the URL is equal to a specified string. - `pathPrefix` {{optional_inline}} - : `string`. Matches if the path segment of the URL starts with a specified string. - `pathSuffix` {{optional_inline}} - : `string`. Matches if the path segment of the URL ends with a specified string. - `queryContains` {{optional_inline}} - : `string`. Matches if the query segment of the URL contains a specified string. - `queryEquals` {{optional_inline}} - : `string`. Matches if the query segment of the URL is equal to a specified string. - `queryPrefix` {{optional_inline}} - : `string`. Matches if the query segment of the URL starts with a specified string. - `querySuffix` {{optional_inline}} - : `string`. Matches if the query segment of the URL ends with a specified string. - `urlContains` {{optional_inline}} - : `string`. Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. - `urlEquals` {{optional_inline}} - : `string`. Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. - `urlMatches` {{optional_inline}} - : `string`. Matches if the URL (without fragment identifier) matches a specified [regular expression](/en-US/docs/Web/JavaScript/Guide/Regular_expressions). Port numbers are stripped from the URL if they match the default port number. - For example: `urlMatches: "^[^:]*:(?://)?(?:[^/]*\\.)?mozilla\\.org/.*$"` matches `https://mozilla.org/`, `https://developer.mozilla.org/`, but not `https://developer.fakemozilla.org/`. - `originAndPathMatches` {{optional_inline}} - : `string`. Matches if the URL without query segment and fragment identifier matches a specified [regular expression](/en-US/docs/Web/JavaScript/Guide/Regular_expressions). Port numbers are stripped from the URL if they match the default port number. - `urlPrefix` {{optional_inline}} - : `string`. Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. - Example: `"https://developer"` matches `https://developer.mozilla.org/` and `https://developers.facebook.com/`. - `urlSuffix` {{optional_inline}} - : `string`. Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. Note that an implicit forward slash "/" is added after the host, so `"com/"` matches `https://example.com`, but `"com"` does not. - `schemes` {{optional_inline}} - : `array` of `string`. Matches if the scheme of the URL is equal to any of the schemes specified in the array. Because schemes are always converted to lowercase, this should always be given in lowercase or it will never match. - Example: `["https"]` will match only HTTPS URLs. - `ports` {{optional_inline}} - : `array` of (`integer` or (`array` of `integer`)). An array which may contain integers and arrays of integers. Integers are interpreted as port numbers, while arrays of integers are interpreted as port ranges. Matches if the port of the URL matches any port number or is contained in any ranges. - For example: `[80, 443, [1000, 1200]]` matches all requests on ports 80, 443, and in the range 1000-1200. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.events`](https://developer.chrome.com/docs/extensions/reference/events/#type-UrlFilter) API. This documentation is derived from [`events.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/events.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/events
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/events/event/index.md
--- title: events.Event slug: Mozilla/Add-ons/WebExtensions/API/events/Event page-type: webextension-api-type browser-compat: webextensions.api.events.Event --- {{AddonSidebar}} An object which allows the addition and removal of listeners for a browser event. ## Type Values of this type are objects. ## Methods - {{WebExtAPIRef("events.Event.addListener","events.Event.addListener()")}} - : Registers an event listener to an event. - {{WebExtAPIRef("events.Event.removeListener","events.Event.removeListener()")}} - : Deregisters an event listener from an event. - {{WebExtAPIRef("events.Event.hasListener","events.Event.hasListener()")}} - : Tests registration status of a listener. - {{WebExtAPIRef("events.Event.hasListeners","events.Event.hasListeners()")}} - : Tests whether any listeners are registered to the event. - {{WebExtAPIRef("events.Event.addRules","events.Event.addRules()")}} - : Registers rules to handle events. - {{WebExtAPIRef("events.Event.getRules","events.Event.getRules()")}} - : Returns currently registered rules. - {{WebExtAPIRef("events.Event.removeRules","events.Event.removeRules()")}} - : Unregisters currently registered rules. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.events`](https://developer.chrome.com/docs/extensions/reference/events/#type-Event) API. This documentation is derived from [`events.json`](https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/events.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/userscripts/index.md
--- title: userScripts slug: Mozilla/Add-ons/WebExtensions/API/userScripts page-type: webextension-api browser-compat: webextensions.api.userScripts --- {{AddonSidebar}} Use this API to register user scripts, third-party scripts designed to manipulate webpages or provide new features. Registering a user script instructs the browser to attach the script to pages that match the URL patterns specified during registration. > **Note:** When using Manifest V3 or higher, use {{WebExtAPIRef("scripting.registerContentScripts()")}} to register scripts. This API offers similar capabilities to {{WebExtAPIRef("contentScripts")}} but with features suited to handling third-party scripts: - execution is in an isolated sandbox: each user script is run in an isolated sandbox within the web content processes, preventing accidental or deliberate interference among scripts. - access to the `window` and `document` global values related to the webpage the user script is attached to. - no access to WebExtension APIs or associated permissions granted to the extension: the API script, which inherits the extension's permissions, can provide packaged WebExtension APIs to registered user scripts. An API script is declared in the extension's manifest file using the "user_scripts" manifest key. > **Warning:** This API requires the presence of the [`user_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/user_scripts) key in the manifest.json, even if no API script is specified. For example. `user_scripts: {}`. To use the API, call `{{WebExtAPIRef("userScripts.register","register()")}}` passing in an object defining the scripts to register. The method returns a Promise that is resolved with a `{{WebExtAPIRef("userScripts.RegisteredUserScript","RegisteredUserScript")}}` object. > **Note:** User scripts are unregistered when the related extension page (from which the user scripts were registered) is unloaded, so you should register a user script from an extension page that persists at least as long as you want the user scripts to stay registered. ## Types - {{WebExtAPIRef("userScripts.RegisteredUserScript")}} - : The `object` returned by the {{WebExtAPIRef("userScripts.register","register()")}} method. It represents the registered user scripts and is used to deregister the user scripts. ## Methods - {{WebExtAPIRef("userScripts.register()")}} - : Registers user scripts. ## Events - {{WebExtAPIRef("userScripts.onBeforeScript")}} - : An event available to the API script, registered in[`"user_scripts"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/user_scripts), that execute before a user script executes. Use it to trigger the export of the additional APIs provided by the API script, so they are available to the user script. ## Browser compatibility {{Compat}} ## See also - [Working with `userScripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/userScripts/Working_with_userScripts) - {{WebExtAPIRef("contentScripts","browser.contentScripts")}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts/register/index.md
--- title: userScripts.register() slug: Mozilla/Add-ons/WebExtensions/API/userScripts/register page-type: webextension-api-function browser-compat: webextensions.api.userScripts.register --- {{AddonSidebar}} This method enables user scripts to be registered from an extension's pages (such as the background page). This method is very similar to the {{WebExtAPIRef("contentScripts.register","contentScripts.register()")}} API method (for example, they both return a promise that resolves to an API object with an {{WebExtAPIRef("userScripts.RegisteredUserScript.unregister","unregister()")}} method for unregistering the script). There are, however, differences in the options supported. This is an asynchronous method that returns a {{JSxRef("Promise")}}. ## Syntax ```js-nolint const registeredUserScript = await browser.userScripts.register( userScriptOptions // object ); // … await registeredUserScript.unregister(); ``` ### Parameters - `userScriptOptions` - : `object`. Represents the user scripts to register. It has similar syntax to {{WebExtAPIRef("contentScripts.register","contentScripts.register()")}}. The `UserScriptOptions` object has the following properties: - `scriptMetadata` {{Optional_Inline}} - : A `JSON` object containing arbitrary metadata properties associated with the registered user scripts. However, while arbitrary, the object must be serializable, so it is compatible with [the structured clone algorithm.](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) This metadata is used to pass details from the script to the [`API script`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/user_scripts). For example, providing details of a subset of the APIs that need to be injected by the [`API script`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/user_scripts). The API does not use this metadata, - `allFrames` {{Optional_Inline}} - : Same as `all_frames` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `cookieStoreId` {{optional_inline}} - : An array of cookie store ID strings or a string containing a cookie store ID. Registers the user script in the tabs that belong to the cookie store IDs. This enables scripts to be registered for all default or non-contextual identity tabs, private browsing tabs (if the [extension is enabled in private browsing](https://support.mozilla.org/en-US/kb/extensions-private-browsing)), the tabs of a [contextual identity](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities), or a combination of these. - `excludeGlobs` {{Optional_Inline}} - : Same as `exclude_globs` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `excludeMatches` {{Optional_Inline}} - : Same as `exclude_matches` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `includeGlobs` {{Optional_Inline}} - : Same as `include_globs` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `js` - : An array of objects. Each object has either a property named `file`, which is a URL starting at the extension's manifest.json and pointing to a JavaScript file to register, or a property named `code`, which contains JavaScript code to register. - `matchAboutBlank` {{Optional_Inline}} - : Same as `match_about_blank` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `matches` - : Same as `matches` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. The URL patterns provided in `matches` must be enabled by the host permissions defined in the manifest [`permission`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) property or enabled by the user from the [`optional_permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) list. For example, if matches includes `https://mozilla.org/a` a script is only registered if host permissions include, for example, `https://mozilla.org/*`. If the URL pattern isn't enabled, the call to register fails with the error "Permission denied to register a user script for ORIGIN". - `runAt` {{Optional_Inline}} - : Same as `run_at` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. Unlike content script options, the userScriptOptions object does not have a CSS property. Use {{WebExtAPIRef("contentScripts.register","contentScripts.register()")}} to dynamically register and unregister stylesheets. ### Return value A {{JSxRef("Promise")}} that is fulfilled with a {{WebExtAPIRef("userScripts.RegisteredUserScript","RegisteredUserScript")}} object that is use to unregister the user scripts. > **Note:** User scripts are unregistered when the related extension page (from which the user scripts were registered) is unloaded, so you should register user scripts from an extension page that persists at least as long as you want the user scripts to stay registered. ## Browser compatibility {{Compat}} ## See also - {{WebExtAPIRef("contentScripts.register","contentScripts.register()")}} - {{WebExtAPIRef("userScripts.RegisteredUserScript.unregister","RegisteredUserScript.unregister()")}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts/onbeforescript/index.md
--- title: userScripts.onBeforeScript slug: Mozilla/Add-ons/WebExtensions/API/userScripts/onBeforeScript page-type: webextension-api-event browser-compat: webextensions.api.userScripts.onBeforeScript --- {{AddonSidebar}} The `onBeforeScript` event of the {{WebExtAPIRef("userScripts","browser.userScripts")}} is fired before a user script is executed. It can only be included in the API script, the script registered in [`"user_scripts"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/user_scripts), where it is used to detect that the custom API methods should be exported to the user script. ## Syntax ```js-nolint browser.userScripts.onBeforeScript.addListener(listener) browser.userScripts.onBeforeScript.removeListener(listener) browser.userScripts.onBeforeScript.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: - `script` - : An `object` that represents the user script that matched a web page. Its properties and methods are as follows: - `defineGlobals` - : A method that exports an object containing properties and methods available globally to the user script sandbox. This method must be called synchronously to guarantee that the user script has not executed. - `export` - : A method that converts a value to one that the user script code can access. This method is used in API methods exported to the user script to result or resolve non-primitive values. The exported objects can also provide methods that the user script code can access and call. - `global` - : An `object` that provides access to the sandbox for the user script. - `metadata` - : The `scriptMetadata` property set when the user script was registered using `userScripts.register`. ## Examples An example of how the listener might be used: ```js browser.userScripts.onBeforeScript.addListener((script) => { script; // This is an API object that represents the user script // that is going to be executed. script.metadata; // Access the user script metadata (returns the // value of the scriptMetadata property from // the call to userScripts.register). // Export some global properties into the user script sandbox // (this method has to be called synchronously from the // listener, otherwise the user script may have executed). script.defineGlobals({ aGlobalPropertyAccessibleFromUserScriptCode: "prop value", myCustomAPIMethod(param1, param2) { // Custom methods exported from the API script can use // the WebExtensions APIs available to content scripts. browser.runtime.sendMessage(/* … */); // … return 123; // primitive values can be returned directly // … // Non primitive values have to be exported explicitly // using the export method provided by the script API // object return script.export({ objKey1: { nestedProp: "nestedValue", }, // Explicitly exported objects can also provide methods. objMethod() { /* … */ }, }); }, async myAsyncMethod(param1, param2, param3) { // exported methods can also be declared as async }, }); }); ``` ## Browser compatibility {{Compat}} ## See also - {{WebExtAPIRef("contentScripts")}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts/working_with_userscripts/index.md
--- title: Working with userScripts slug: Mozilla/Add-ons/WebExtensions/API/userScripts/Working_with_userScripts page-type: guide --- {{AddonSidebar}} By implementing userScripts, extension developers can modify how sites look and/or work to better meet user needs. Implement userScripts in your extension using the following steps: 1. Define the script in the extension's manifest using the `"user_scripts"` key. 2. Register the userScript 3. Implement the userScript functions Let's step through the processes using a small sample web extension that illustrates the process. The example is available in the [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub. ## userScripts Manifest A user script is identified by the contents of the [user_scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/user_scripts) key of the extension's manifest. The minimum information for the `user_scripts` key would be: ```json "user_scripts": { "api_script": "customUserScriptAPIs.js" } ``` The "api_script" property indicates the path to the JavaScript file that contains the code for the `userScript`. ## Load the example extension Once you have downloaded the example: Navigate to about:debugging, click on **Load Temporary Add-on…** and double-click on the extension's manifest. The default code included with the example allows you to load a `userScript` which will "eat" the content of pages matching the Hosts entry. Make any changes you want to make before clicking the **Register script** button at the bottom of the panel. In the following image, the extension will "eat" the content of pages whose domain name ends in .org. This is the default behavior for this extension. ![User script example](userscriptexample.png) Nothing will happen until you click the **Register script** button. The button implements the user script according to the settings on this dialog. That means that you can experiment with the behavior of the script without having to implement an extensions yourself. ## Register the userScript Before a userScript can be executed, it must be registered using the `userScripts.register()` method. Here is the code to register the example extension: ```js async function registerScript() { const params = { hosts: stringToArray(hostsInput.value), code: codeInput.value, excludeMatches: stringToArray(excludeMatchesInput.value), includeGlobs: stringToArray(includeGlobsInput.value), excludeGlobs: stringToArray(excludeGlobsInput.value), runAt: runAtInput.value, matchAboutBlank: stringToBool(matchAboutBlankInput.value), allFrames: stringToBool(allFramesInput.value), scriptMetadata: { name: scriptNameInput.value || null }, }; // Store the last submitted values to the extension storage // (so that they can be restored when the popup is opened // the next time). await browser.storage.local.set({ lastSetValues: params, }); try { // Clear the last userScripts.register result. lastResultEl.textContent = ""; await browser.runtime.sendMessage(params); lastResultEl.textContent = "UserScript successfully registered"; // Clear the last userScripts.register error. lastErrorEl.textContent = ""; // Clear the last error stored. await browser.storage.local.remove("lastError"); } catch (e) { // There was an error on registering the userScript, // let's show the error message in the popup and store // the last error into the extension storage. const lastError = `${e}`; // Show the last userScripts.register error. lastErrorEl.textContent = lastError; // Store the last error. await browser.storage.local.set({ lastError }); } } ``` This code first initializes the params object to pass values to the [userScripts.register](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/userScripts/register) method. ## Implement the userScript functions Once the script has been registered, navigate to a page whose domain name ends in .org, and you will see something like this: ![Status message indicating that websites ending in .org have been eaten: "This page has been eaten. {"OldStoredValue:" "website address", "NewStoredValue:" "website address"}"](user_script_in_action.png) ## See also - {{WebExtAPIRef("userScripts")}} - {{WebExtAPIRef("userScripts.register()", "userScripts.register()")}} - {{WebExtAPIRef("userScripts.onBeforeScript")}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts/registereduserscript/index.md
--- title: userScripts.RegisteredUserScript slug: Mozilla/Add-ons/WebExtensions/API/userScripts/RegisteredUserScript page-type: webextension-api-type browser-compat: webextensions.api.userScripts.RegisteredUserScript --- {{AddonSidebar}} A `RegisteredUserScript` object is returned by a call to {{WebExtAPIRef("userScripts.register","userScripts.register()")}} and represents the user scripts registered in that call. The object defines a single method, {{WebExtAPIRef("userScripts.RegisteredUserScript.unregister","unregister()")}}, which is used to unregister the user scripts. > **Note:** If this object is destroyed (for example because it goes out of scope) then the associated scripts will be unregistered automatically, so you should keep a reference to this object for as long as you want the user scripts to stay registered. ## Methods - {{WebExtAPIRef("userScripts.RegisteredUserScript.unregister","unregister()")}} - : Unregisters the user scripts represented by this object. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts/registereduserscript
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts/registereduserscript/unregister/index.md
--- title: RegisteredUserScript.unregister() slug: Mozilla/Add-ons/WebExtensions/API/userScripts/RegisteredUserScript/unregister page-type: webextension-api-function browser-compat: webextensions.api.userScripts.RegisteredUserScript.unregister --- {{AddonSidebar}} The `unregister()` method of the {{WebExtAPIRef("userScripts.RegisteredUserScript","RegisteredUserScript")}} object unregisters the user scripts represented by the object, user scripts that were registered using {{WebExtAPIRef("userScripts.register","userScripts.register()")}}. > **Note:** User Scripts are automatically unregistered when the related extension page (from which the user scripts were registered) is unloaded, so you should register a user script from an extension page that persists at least as long as you want the user scripts to stay registered. ## Syntax ```js-nolint const registeredUserScript = await browser.userScripts.register( userScriptOptions // object ); // … await registeredUserScript.unregister() ``` ### Parameters None. ### Return value A {{JSxRef("Promise")}} that is resolved once the user scripts are unregistered. The promise does not return a value. ## Browser compatibility {{Compat}} ## See also - {{WebExtAPIRef("userScripts.register","userScripts.register()")}} - {{WebExtAPIRef("userScripts.RegisteredUserScript","RegisteredUserScript")}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/userscripts/userscriptoptions/index.md
--- title: UserScripts.UserScriptOptions slug: Mozilla/Add-ons/WebExtensions/API/userScripts/UserScriptOptions page-type: webextension-api-type --- {{AddonSidebar}} The UserScriptOptions object represents the content scripts to register. It has similar syntax to the contentScript options supported by browser.contentScripts.register. The differences are: - it does not support a CSS property (use browser.contentScripts.register to dynamically register/unregister stylesheets) - It does support an optional scriptMetadata property (as a plain JSON object which contains some metadata properties associated to the registered userScripts) The UserScriptOptions object has the following properties: - `allFrames` {{optional_inline}} - : Same as `all_frames` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `excludeGlobs` {{optional_inline}} - : Same as `exclude_globs` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `excludeMatches` {{optional_inline}} - : Same as `exclude_matches` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `includeGlobs` {{optional_inline}} - : Same as `include_globs` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `js` {{optional_inline}} - : An array of objects. Each object has either a property named `file`, which is a URL starting at the extension's manifest.json and pointing to a JavaScript file to register, or a property named `code`, which is some JavaScript code to register. - `matchAboutBlank` {{optional_inline}} - : Same as `match_about_blank` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `matches` - : Same as `matches` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `runAt` {{optional_inline}} - : Same as `run_at` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key. - `scriptMetadata` {{optional_inline}} - : A user script metadata value It has similar syntax to the contentScript options supported by browser.contentScripts.register.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/index.md
--- title: contextualIdentities slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities page-type: webextension-api browser-compat: webextensions.api.contextualIdentities --- {{AddonSidebar}} Work with contextual identities: list, create, remove, and update contextual identities. "Contextual identities", also known as "containers", are a browser feature that lets users assume multiple identities when browsing the web, and maintain some separation between these identities. For example, a user might consider their "work identity" separate from their "personal identity", and not want to share cookies between these two contexts. With the contextual identities feature, each contextual identity has a name, a color, and an icon. New tabs can be assigned to an identity, and the name, icon, and color appears in the address bar. Internally, each identity gets a cookie store that is not shared with other tabs. This cookie store is identified by the `cookieStoreId` in this and other APIs. ![A context menu with "open in new container tab" submenu highlighted. The submenu shows personal, work, banking, and shopping contextual identities.](containers.png)Contextual identities are an experimental feature in Firefox and are only enabled by default in Firefox Nightly. To enable them in other versions of Firefox, set the `privacy.userContext.enabled` preference to `true`. Note that although contextual identities are available in Firefox for Android, there's no UI to work with them in this version of the browser. Before Firefox 57, the `contextualIdentities` API is only available if the contextual identities feature is itself enabled. If an extension tried to use the `contextualIdentities` API without the feature being enabled, then method calls would resolve their promises with `false`. From Firefox 57 onwards, if an extension that uses the `contextualIdentities` API is installed, then the contextual identities feature will be enabled automatically. Note though that it's still possible for the user to disable the feature using the "privacy.userContext.enabled" preference. If this happens, then `contextualIdentities` method calls will reject their promises with an error message. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. Contextual identities are not supported in any other browsers. To use this API you need to include the "contextualIdentities" and "cookies" [permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) in your [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file. ## Types - {{WebExtAPIRef("contextualIdentities.ContextualIdentity")}} - : Contains information about a contextual identity. ## Functions - {{WebExtAPIRef("contextualIdentities.create()")}} - : Creates a new contextual identity. - {{WebExtAPIRef("contextualIdentities.get()")}} - : Retrieves a contextual identity, given its cookie store ID. - {{WebExtAPIRef("contextualIdentities.move()")}} - : Moves one or more contextual identities within the list of contextual identities. - {{WebExtAPIRef("contextualIdentities.query()")}} - : Retrieves all contextual identities, or all contextual identities with a particular name. - {{WebExtAPIRef("contextualIdentities.update()")}} - : Updates properties of an existing contextual identity. - {{WebExtAPIRef("contextualIdentities.remove()")}} - : Deletes a contextual identity. ## Events - {{WebExtAPIRef("contextualIdentities.onCreated")}} - : Fired when a contextual identity is created. - {{WebExtAPIRef("contextualIdentities.onRemoved")}} - : Fired when a contextual identity is removed. - {{WebExtAPIRef("contextualIdentities.onUpdated")}} - : Fired when one or more properties of a contextual identity is updated. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/remove/index.md
--- title: contextualIdentities.remove() slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities/remove page-type: webextension-api-function browser-compat: webextensions.api.contextualIdentities.remove --- {{AddonSidebar}} Removes a contextual identity, given its cookie store ID. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removeContext = browser.contextualIdentities.remove( cookieStoreId // string ) ``` ### Parameters - `cookieStoreId` - : `string`. The ID of the contextual identity's cookie store. Because contextual identities each have their own cookie store, this serves as an identifier for the contextual identity itself. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('contextualIdentities.ContextualIdentity', 'ContextualIdentity')}} that describes the identity that was removed. If the identity could not be found or the contextual identities feature is not enabled, the promise is rejected. ## Browser compatibility {{Compat}} ## Examples This example tries to remove the contextual identity whose ID is "firefox-container-1": ```js function onRemoved(context) { if (!context) { console.error("Context not found"); } else { console.log(`Removed identity: ${context.cookieStoreId}.`); } } function onError(e) { console.error(e); } browser.contextualIdentities .remove("firefox-container-1") .then(onRemoved, onError); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/get/index.md
--- title: contextualIdentities.get() slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities/get page-type: webextension-api-function browser-compat: webextensions.api.contextualIdentities.get --- {{AddonSidebar}} Gets information about a contextual identity, given its cookie store ID. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let getContext = browser.contextualIdentities.get( cookieStoreId // string ) ``` ### Parameters - `cookieStoreId` - : `string`. The ID of this contextual identity's cookie store. Because contextual identities each have their own cookie store, this serves as an identifier for the contextual identity itself. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('contextualIdentities.ContextualIdentity', 'ContextualIdentity')}} that describes the identity. If the identity could not be found or the contextual identities feature is not enabled, the promise is rejected. ## Browser compatibility {{Compat}} ## Examples This example tries to retrieve the contextual identity whose ID is "firefox-container-1": ```js function onGot(context) { if (!context) { console.error("Context not found"); } else { console.log(`Name: ${context.name}`); } } function onError(e) { console.error(e); } browser.contextualIdentities.get("firefox-container-1").then(onGot, onError); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/create/index.md
--- title: contextualIdentities.create() slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities/create page-type: webextension-api-function browser-compat: webextensions.api.contextualIdentities.create --- {{AddonSidebar}} Creates a new contextual identity. Once created, the user will be able to create new tabs belonging to this contextual identity, just as they can with the built-in identities. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let createContext = browser.contextualIdentities.create( details // object ) ``` ### Parameters - `details` - : `object`. An object containing properties for the new contextual identity. This contains the following properties: - `name` - : `string`. The name of the new identity. This will be displayed in the browser's UI, enabling them to open a new tab belonging to the identity. It will also be displayed in the URL bar for tabs belonging to this identity. - `color` - : `string`. The color associated with the new identity. This will be used to highlight tabs belonging to this identity. You can supply any of the following values here: - "blue" - "turquoise" - "green" - "yellow" - "orange" - "red" - "pink" - "purple" - "toolbar" - `icon` - : `string`. The name of an icon to display in the URL bar for tabs belonging to this identity. You can supply any of the following values here: - "fingerprint" - "briefcase" - "dollar" - "cart" - "circle" - "gift" - "vacation" - "food" - "fruit" - "pet" - "tree" - "chill" - "fence" ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('contextualIdentities.ContextualIdentity', 'ContextualIdentity')}} that describes the new identity. If the contextual identities feature is not enabled, the promise is rejected. ## Browser compatibility {{Compat}} ## Examples This example creates a new contextual identity and logs its cookie store ID: ```js function onCreated(context) { console.log(`New identity's ID: ${context.cookieStoreId}.`); } function onError(e) { console.error(e); } browser.contextualIdentities .create({ name: "my-thing", color: "purple", icon: "briefcase", }) .then(onCreated, onError); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/oncreated/index.md
--- title: contextualIdentities.onCreated slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities/onCreated page-type: webextension-api-event browser-compat: webextensions.api.contextualIdentities.onCreated --- {{AddonSidebar}} Fired when a new contextual identity is created. Contextual identities may be created by extensions using the `contextualIdentities` API, or directly by the user, using the browser's user interface. ## Syntax ```js-nolint browser.contextualIdentities.onCreated.addListener(listener) browser.contextualIdentities.onCreated.removeListener(listener) browser.contextualIdentities.onCreated.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed this argument: - `changeInfo` - : `object`. An object that contains a single property, `contextualIdentity`, which is a {{WebExtAPIRef("contextualIdentities.ContextualIdentity")}} object, representing the identity that was created. ## Browser compatibility {{Compat}} ## Examples ```js function handleCreated(changeInfo) { console.log(`Created: ${changeInfo.contextualIdentity.name}`); } browser.contextualIdentities.onCreated.addListener(handleCreated); ``` {{WebExtExamples}} <!-- // 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/contextualidentities
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/update/index.md
--- title: contextualIdentities.update() slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities/update page-type: webextension-api-function browser-compat: webextensions.api.contextualIdentities.update --- {{AddonSidebar}} Updates properties of a contextual identity, given its cookie store ID. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let createContext = browser.contextualIdentities.update( cookieStoreId, // string details // object ) ``` ### Parameters - `cookieStoreId` - : `string`. The ID of this contextual identity's cookie store. Because contextual identities each have their own cookie store, this serves as an identifier for the contextual identity itself. - `details` - : `object`. An object containing new values for the properties that you wish to change. This may contain any of the following properties: - `name` {{optional_inline}} - : `string`. A new name for the identity. This will be displayed in the browser's UI, enabling them to open a new tab in the identity. It will also be displayed in the URL bar for tabs belonging to this identity. - `color` {{optional_inline}} - : `string`. A new color for the identity. This will be used to highlight tabs belonging to this identity. You can supply any of the following values here: - "blue" - "turquoise" - "green" - "yellow" - "orange" - "red" - "pink" - "purple" - "toolbar" - `icon` {{optional_inline}} - : `string`. A new icon for the identity. You can supply any of the following values here: - "fingerprint" - "briefcase" - "dollar" - "cart" - "circle" - "gift" - "vacation" - "food" - "fruit" - "pet" - "tree" - "chill" - "fence" ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('contextualIdentities.ContextualIdentity', 'ContextualIdentity')}} that describes the updated identity. If the identity could not be found or the contextual identities feature is not enabled, the promise is rejected. ## Browser compatibility {{Compat}} ## Examples This example updates the contextual identity whose ID is "firefox-container-1" to have a new name, color, and icon: ```js function onUpdated(context) { console.log(`New identity's name: ${context.name}.`); } function onError(e) { console.error(e); } browser.contextualIdentities .update("firefox-container-1", { name: "my-thing", color: "purple", icon: "briefcase", }) .then(onUpdated, onError); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/contextualidentity/index.md
--- title: contextualIdentities.ContextualIdentity slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities/ContextualIdentity page-type: webextension-api-type browser-compat: webextensions.api.contextualIdentities.ContextualIdentity --- {{AddonSidebar}} The **`contextualIdentities.ContextualIdentity`** type describes a single contextual identity. ## Type Values of this type are objects. They contain the following properties: - `cookieStoreId` - : `string`. The cookie store ID for the identity. Since contextual identities don't share cookie stores, this serves as a unique identifier. - `color` - : `string`. The color for the identity. This will be shown in tabs belonging to this identity. The following values are valid: - "blue" - "turquoise" - "green" - "yellow" - "orange" - "red" - "pink" - "purple" - "toolbar" The value "toolbar" represents a theme-dependent color. Identities with color "toolbar" will be displayed in the same color as text in the toolbar (corresponding to the [theme key](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme#colors) `"toolbar_field_text"`). - `colorCode` - : `string`. A hex code representing the exact color used for the identity. For example: `"#37adff"`. In the special case of the "toolbar" color, `colorCode` is always `"#7c7c7d"`, regardless of the displayed color. - `icon` - : `string`. The name of an icon for the identity. This will be shown in the URL bar for tabs belonging to this identity. The following values are valid: - "fingerprint" - "briefcase" - "dollar" - "cart" - "circle" - "gift" - "vacation" - "food" - "fruit" - "pet" - "tree" - "chill" - "fence" - `iconUrl` - : `string`. A full resource:// URL pointing to the identity's icon. For example: "resource://usercontext-content/fingerprint.svg". - `name` - : `string`. Name of the identity. This will be shown in the URL bar for tabs belonging to this identity. Note that names don't have to be unique. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/onupdated/index.md
--- title: contextualIdentities.onUpdated slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities/onUpdated page-type: webextension-api-event browser-compat: webextensions.api.contextualIdentities.onUpdated --- {{AddonSidebar}} Fired when the properties of a contextual identity, such as its name, icon, or color, are changed. Contextual identities may be updated by extensions using the `contextualIdentities` API, or directly by the user, using the browser's user interface. ## Syntax ```js-nolint browser.contextualIdentities.onUpdated.addListener(listener) browser.contextualIdentities.onUpdated.removeListener(listener) browser.contextualIdentities.onUpdated.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: - `changeInfo` - : `object`. An object that contains a single property, `contextualIdentity`, which is a {{WebExtAPIRef("contextualIdentities.ContextualIdentity")}} object representing the identity whose properties were updated. ## Browser compatibility {{Compat}} ## Examples ```js function handleUpdated(changeInfo) { console.log(`Updated: ${changeInfo.contextualIdentity.name}`); } browser.contextualIdentities.onUpdated.addListener(handleUpdated); ``` {{WebExtExamples}} <!-- // 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/contextualidentities
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/onremoved/index.md
--- title: contextualIdentities.onRemoved slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities/onRemoved page-type: webextension-api-event browser-compat: webextensions.api.contextualIdentities.onRemoved --- {{AddonSidebar}} Fired when a new contextual identity is removed. Contextual identities may be removed by extensions using the `contextualIdentities` API, or directly by the user, using the browser's user interface. ## Syntax ```js-nolint browser.contextualIdentities.onRemoved.addListener(listener) browser.contextualIdentities.onRemoved.removeListener(listener) browser.contextualIdentities.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: - `changeInfo` - : `object`. An object that contains a single property, `contextualIdentity`, which is a {{WebExtAPIRef("contextualIdentities.ContextualIdentity")}} object representing the identity that was removed. ## Browser compatibility {{Compat}} ## Examples ```js function handleRemoved(changeInfo) { console.log(`Removed: ${changeInfo.contextualIdentity.name}`); } browser.contextualIdentities.onRemoved.addListener(handleRemoved); ``` {{WebExtExamples}} <!-- // 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/contextualidentities
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/query/index.md
--- title: contextualIdentities.query() slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities/query page-type: webextension-api-function browser-compat: webextensions.api.contextualIdentities.query --- {{AddonSidebar}} Gets information about all contextual identities, or about those contextual identities that match a given filter argument. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let getContext = browser.contextualIdentities.query( details // object ) ``` ### Parameters - `details` - : `object`. An object that can be used to filter the contextual identities returned. This may contain any of the following properties: - `name` {{optional_inline}} - : `string`. Return only contextual identities with this name. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an array of {{WebExtAPIRef('contextualIdentities.ContextualIdentity', 'ContextualIdentity')}} objects, each describing a single identity. If the contextual identities feature is not enabled, the promise is rejected. ## Browser compatibility {{Compat}} ## Examples Retrieve all contextual identities, and log their names: ```js function onGot(contexts) { for (const context of contexts) { console.log(`Name: ${context.name}`); } } function onError(error) { console.error(error); } browser.contextualIdentities.query({}).then(onGot, onError); ``` Retrieve all contextual identities whose names are "my-thing", and log their names: ```js function onGot(contexts) { for (const context of contexts) { console.log(`Name: ${context.name}`); } } function onError(error) { console.error(error); } browser.contextualIdentities .query({ name: "my-thing", }) .then(onGot, onError); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contextualidentities/move/index.md
--- title: contextualIdentities.move() slug: Mozilla/Add-ons/WebExtensions/API/contextualIdentities/move page-type: webextension-api-function browser-compat: webextensions.api.contextualIdentities.move --- {{AddonSidebar}} Moves one or more contextual identities to a new position within the list of contextual identities. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let moveContainers = browser.contextualIdentities.move( cookieStoreIds, // string or array of string position // integer ) ``` ### Parameters - `cookieStoreIds` - : `string` or `array` of `string`. An ordered list of the contextual identity cookie store IDs to move. - `position` - : `integer`. The position to move `cookieStoreIds` to in the list of contextual identities. Zero-based; `0` indicates the first position. `-1` indicates that the items are moved to the end of the list. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is fulfilled when the contextual identities are reordered. The promise is rejected if the request is for an invalid move or the contextual identities feature is not enabled. ## Examples This example moves the first identity to the end and then back to the start. ```js let identities = await browser.contextualIdentities.query({}); let firstId = identities[0].cookieStoreId; // Moves first identity to the end. await browser.contextualIdentities.move(firstId, -1); // Move identity to the start again. await browser.contextualIdentities.move(firstId, 0); ``` Another way of moving the first identity to the end is by moving all other identities to the start. ```js let identities = await browser.contextualIdentities.query({}); let ids = identities.map((identity) => identity.cookieStoreId); // Create an array without the first item: let otherIds = ids.slice(1); // Move other identities to the start, // effectively putting the first identity at the end. await browser.contextualIdentities.move(otherIds, 0); ``` This example moves the "Personal" identity to before "Work". The example assumes containers with these names to exist. This may not be the case in customized or localized (non-English) Firefox instances. ```js let identities = await browser.contextualIdentities.query({}); // Find the index and ID of the container with the name "Personal". let personalIndex = identities.findIndex((ci) => ci.name === "Personal"); if (personalIndex === -1) { throw new Error("Personal container not found"); } let personalId = identities[personalIndex].cookieStoreId; // Find the index of the container with the name "Work". let workIndex = identities.findIndex((identity) => identity.name === "Work"); if (workIndex === -1) { throw new Error("Work container not found!"); } if (personalIndex < workIndex) { // When the Personal identity moves, all following // identities shift to the left by one. To place // the Personal identity before the Work identity, // we should therefore subtract one. workIndex--; } await browser.contextualIdentities.move(personalId, workIndex); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/index.md
--- title: tabs slug: Mozilla/Add-ons/WebExtensions/API/tabs page-type: webextension-api browser-compat: webextensions.api.tabs --- {{AddonSidebar}} Interact with the browser's tab system. > **Note:** When using Manifest V3 or higher, the methods to execute scripts, insert CSS, and remove CSS are provided by the {{WebExtAPIRef("scripting")}} API through the {{WebExtAPIRef("scripting.executeScript()")}}, {{WebExtAPIRef("scripting.insertCSS()")}} and {{WebExtAPIRef("scripting.removeCSS()")}} methods. You can use this API to get a list of opened tabs, filtered by various criteria, and to open, update, move, reload, and remove tabs. You can't directly access the content hosted by tabs using this API, but you can insert JavaScript and CSS into tabs using the {{WebExtAPIRef("tabs.executeScript()")}} or {{WebExtAPIRef("tabs.insertCSS()")}} APIs. You can use most of this API without any special permission. However: - To access `Tab.url`, `Tab.title`, and `Tab.favIconUrl` (or to filter by these properties via {{WebExtAPIRef("tabs.query()")}}), you need to have the `"tabs"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions), or have [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) that match `Tab.url`. - Access to these properties by host permissions is supported since Firefox 86 and Chrome 50. In Firefox 85 and earlier, the "tabs" permission was required instead. - To use {{WebExtAPIRef("tabs.executeScript()")}} or {{WebExtAPIRef("tabs.insertCSS()")}}, you must have the [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the tab Alternatively, you can get these permissions temporarily, only for the currently active tab and only in response to an explicit user action, by asking for the [`"activeTab"` permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission). Many tab operations use a Tab `id`. Tab `id`s are guaranteed to be unique to a single tab only within a browser session. If the browser is restarted, then it can and will reuse tab `id`s. To associate information with a tab across browser restarts, use {{WebExtAPIRef("sessions.setTabValue()")}}. ## Types - {{WebExtAPIRef("tabs.MutedInfoReason")}} - : Specifies the reason a tab was muted or unmuted. - {{WebExtAPIRef("tabs.MutedInfo")}} - : This object contains a boolean indicating whether the tab is muted, and the reason for the last state change. - {{WebExtAPIRef("tabs.PageSettings")}} - : Used to control how a tab is rendered as a PDF by the [`tabs.saveAsPDF()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/saveAsPDF) method. - {{WebExtAPIRef("tabs.Tab")}} - : This type contains information about a tab. - {{WebExtAPIRef("tabs.TabStatus")}} - : Indicates whether the tab has finished loading. - {{WebExtAPIRef("tabs.WindowType")}} - : The type of window that hosts this tab. - {{WebExtAPIRef("tabs.ZoomSettingsMode")}} - : Defines whether zoom changes are handled by the browser, by the extension, or are disabled. - {{WebExtAPIRef("tabs.ZoomSettingsScope")}} - : Defines whether zoom changes will persist for the page's origin, or only take effect in this tab. - {{WebExtAPIRef("tabs.ZoomSettings")}} - : Defines zoom settings {{WebExtAPIRef("tabs.ZoomSettingsMode", "mode")}}, {{WebExtAPIRef("tabs.ZoomSettingsScope", "scope")}}, and default zoom factor. ## Properties - {{WebExtAPIRef("tabs.TAB_ID_NONE")}} - : A special ID value given to tabs that are not browser tabs (for example, tabs in devtools windows). ## Functions - {{WebExtAPIRef("tabs.captureTab()")}} - : Creates a data URL encoding an image of the visible area of the given tab. - {{WebExtAPIRef("tabs.captureVisibleTab()")}} - : Creates a data URL encoding an image of the visible area of the currently active tab in the specified window. - {{WebExtAPIRef("tabs.connect()")}} - : Sets up a messaging connection between the extension's background scripts (or other privileged scripts, such as popup scripts or options page scripts) and any [content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) running in the specified tab. - {{WebExtAPIRef("tabs.create()")}} - : Creates a new tab. - {{WebExtAPIRef("tabs.detectLanguage()")}} - : Detects the primary language of the content in a tab. - {{WebExtAPIRef("tabs.discard()")}} - : Discards one or more tabs. - {{WebExtAPIRef("tabs.duplicate()")}} - : Duplicates a tab. - {{WebExtAPIRef("tabs.executeScript()")}} (Manifest V2 only) - : Injects JavaScript code into a page. - {{WebExtAPIRef("tabs.get()")}} - : Retrieves details about the specified tab. - {{WebExtAPIRef("tabs.getAllInWindow()")}} {{deprecated_inline}} - : Gets details about all tabs in the specified window. - {{WebExtAPIRef("tabs.getCurrent()")}} - : Gets information about the tab that this script is running in, as a [`tabs.Tab`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/Tab) object. - {{WebExtAPIRef("tabs.getSelected()")}} {{deprecated_inline}} - : Gets the tab that is selected in the specified window. **Deprecated: use [`tabs.query({active: true})`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query) instead.** - {{WebExtAPIRef("tabs.getZoom()")}} - : Gets the current zoom factor of the specified tab. - {{WebExtAPIRef("tabs.getZoomSettings()")}} - : Gets the current zoom settings for the specified tab. - {{WebExtAPIRef("tabs.goForward()")}} - : Go forward to the next page, if one is available. - {{WebExtAPIRef("tabs.goBack()")}} - : Go back to the previous page, if one is available. - {{WebExtAPIRef("tabs.hide()")}} {{experimental_inline}} - : Hides one or more tabs. - {{WebExtAPIRef("tabs.highlight()")}} - : Highlights one or more tabs. - {{WebExtAPIRef("tabs.insertCSS()")}} (Manifest V2 only) - : Injects CSS into a page. - {{WebExtAPIRef("tabs.move()")}} - : Moves one or more tabs to a new position in the same window or to a different window. - {{WebExtApiRef("tabs.moveInSuccession()")}} - : Modifies the succession relationship for a group of tabs. - {{WebExtAPIRef("tabs.print()")}} - : Prints the contents of the active tab. - {{WebExtAPIRef("tabs.printPreview()")}} - : Opens print preview for the active tab. - {{WebExtAPIRef("tabs.query()")}} - : Gets all tabs that have the specified properties, or all tabs if no properties are specified. - {{WebExtAPIRef("tabs.reload()")}} - : Reload a tab, optionally bypassing the local web cache. - {{WebExtAPIRef("tabs.remove()")}} - : Closes one or more tabs. - {{WebExtAPIRef("tabs.removeCSS()")}} (Manifest V2 only) - : Removes from a page CSS which was previously injected by calling {{WebExtAPIRef("tabs.insertCSS()")}}. - {{WebExtAPIRef("tabs.saveAsPDF()")}} - : Saves the current page as a PDF. - {{WebExtAPIRef("tabs.sendMessage()")}} - : Sends a single message to the content script(s) in the specified tab. - {{WebExtAPIRef("tabs.sendRequest()")}} {{deprecated_inline}} - : Sends a single request to the content script(s) in the specified tab. **Deprecated**: use {{WebExtAPIRef("tabs.sendMessage()")}} instead. - {{WebExtAPIRef("tabs.setZoom()")}} - : Zooms the specified tab. - {{WebExtAPIRef("tabs.setZoomSettings()")}} - : Sets the zoom settings for the specified tab. - {{WebExtAPIRef("tabs.show()")}} {{experimental_inline}} - : Shows one or more tabs that have been {{WebExtAPIRef("tabs.hide()", "hidden")}}. - {{WebExtAPIRef("tabs.toggleReaderMode()")}} - : Toggles Reader mode for the specified tab. - {{WebExtAPIRef("tabs.update()")}} - : Navigate the tab to a new URL, or modify other properties of the tab. - {{WebExtAPIRef("tabs.warmup()")}} - : Prepare the tab to make a potential following switch faster. ## Events - {{WebExtAPIRef("tabs.onActivated")}} - : Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired. - {{WebExtAPIRef("tabs.onActiveChanged")}} {{deprecated_inline}} - : Fires when the selected tab in a window changes. **Deprecated:** use {{WebExtAPIRef("tabs.onActivated")}} instead. - {{WebExtAPIRef("tabs.onAttached")}} - : Fired when a tab is attached to a window, for example because it was moved between windows. - {{WebExtAPIRef("tabs.onCreated")}} - : Fired when a tab is created. Note that the tab's URL may not be set at the time this event fired. - {{WebExtAPIRef("tabs.onDetached")}} - : Fired when a tab is detached from a window, for example because it is being moved between windows. - {{WebExtAPIRef("tabs.onHighlightChanged")}} {{deprecated_inline}} - : Fired when the highlighted or selected tabs in a window change. **Deprecated:** use {{WebExtAPIRef("tabs.onHighlighted")}} instead. - {{WebExtAPIRef("tabs.onHighlighted")}} - : Fired when the highlighted or selected tabs in a window change. - {{WebExtAPIRef("tabs.onMoved")}} - : Fired when a tab is moved within a window. - {{WebExtAPIRef("tabs.onRemoved")}} - : Fired when a tab is closed. - {{WebExtAPIRef("tabs.onReplaced")}} - : Fired when a tab is replaced with another tab due to prerendering. - {{WebExtAPIRef("tabs.onSelectionChanged")}} {{deprecated_inline}} - : Fires when the selected tab in a window changes. **Deprecated:** use {{WebExtAPIRef("tabs.onActivated")}} instead. - {{WebExtAPIRef("tabs.onUpdated")}} - : Fired when a tab is updated. - {{WebExtAPIRef("tabs.onZoomChange")}} - : Fired when a tab is zoomed. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/discard/index.md
--- title: tabs.discard() slug: Mozilla/Add-ons/WebExtensions/API/tabs/discard page-type: webextension-api-function browser-compat: webextensions.api.tabs.discard --- {{AddonSidebar}} Discards one or more tabs. Some browsers automatically "discard" unused tabs to free memory. Discarded tabs stay visible in the tabstrip. The browser remembers the tab's state and restores it when the user selects the tab. The details of when tabs are and what is discarded are browser-specific. You can control whether the browser or this API discards a tab by setting its `autoDiscardable` property to `false` in {{WebExtAPIRef("tabs.update")}}. This setting prevents the browser from discarding the tab. The tab can then only be discarded with this API. It's not possible to discard the active tab or a tab whose document contains a [`beforeunload`](/en-US/docs/Web/API/Window/beforeunload_event) listener that would display a prompt. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let discarding = browser.tabs.discard( tabIds // integer or integer array ) ``` ### Parameters - `tabIds` - : `integer` or `array` of `integer`. The IDs of the tab or tabs to discard. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when all the specified tabs have been discarded. If any error occurs (for example, invalid tab IDs), the promise will be rejected with an error message. If the ID of the active tab is passed in, it will not be discarded, but the promise will be fulfilled and any other tabs passed in will be discarded. ## Examples Discard a single tab: ```js function onDiscarded() { console.log(`Discarded`); } function onError(error) { console.log(`Error: ${error}`); } let discarding = browser.tabs.discard(2); discarding.then(onDiscarded, onError); ``` Discard multiple tabs: ```js function onDiscarded() { console.log(`Discarded`); } function onError(error) { console.log(`Error: ${error}`); } let discarding = browser.tabs.discard([15, 14, 1]); discarding.then(onDiscarded, onError); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-discard) 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/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/windowtype/index.md
--- title: tabs.WindowType slug: Mozilla/Add-ons/WebExtensions/API/tabs/WindowType page-type: webextension-api-type browser-compat: webextensions.api.tabs.WindowType --- {{AddonSidebar}} The type of window that hosts this tab. ## Type Values of this type are strings. Possible values are: - **"normal"** - **"popup"** - **"panel"** - **"devtools"** ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#type-WindowType) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/connect/index.md
--- title: tabs.connect() slug: Mozilla/Add-ons/WebExtensions/API/tabs/connect page-type: webextension-api-function browser-compat: webextensions.api.tabs.connect --- {{AddonSidebar}} Call this function to set up a connection between the extension's background scripts (or other privileged scripts, such as popup scripts or options page scripts) and any [content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) that belong to this extension and are running in the specified tab. This function returns a {{WebExtAPIRef("runtime.Port")}} object. When this is called, the {{WebExtAPIRef('runtime.onConnect')}} event will be fired in any content script belonging to this extension that are running in the specified tab. The event listener will be passed another {{WebExtAPIRef("runtime.Port")}} object. The two sides can then use the `Port` objects to exchange messages. For more details, see [connection-based messaging](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#connection-based_messaging). You can message without creating a connection, for advice on choosing between the options, see [Choosing between one-off messages and connection-based messaging](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#choosing_between_one-off_messages_and_connection-based_messaging). ## Syntax ```js-nolint browser.tabs.connect( tabId, // integer connectInfo // optional object ) ``` ### Parameters - `tabId` - : `integer`. ID of the tab whose content scripts we want to connect to. - `connectInfo` {{optional_inline}} - : An object with the following properties: - `name` {{optional_inline}} - : `string`. Will be passed into {{WebExtAPIRef("runtime.onConnect")}} event listeners in content scripts belonging to this extension and running in the specified tab. - `frameId` {{optional_inline}} - : `integer`. Open a port to a specific frame identified by `frameId` instead of all frames in the tab. ### Return value {{WebExtAPIRef('runtime.Port')}}. A port that can be used to communicate with the content scripts running in the specified tab. ## Examples In this example a background script listens for a click on a [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#browser_actions_2), then connects to the currently active tab, then sends a message using the `Port` that's returned from `connect()`: ```js function connectToTab(tabs) { if (tabs.length > 0) { let examplePort = browser.tabs.connect(tabs[0].id, { name: "tabs-connect-example", }); examplePort.postMessage({ greeting: "Hi from background script" }); } } function onError(error) { console.log(`Error: ${error}`); } browser.browserAction.onClicked.addListener(() => { let gettingActive = browser.tabs.query({ currentWindow: true, active: true, }); gettingActive.then(connectToTab, onError); }); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-connect) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/moveinsuccession/index.md
--- title: tabs.moveInSuccession() slug: Mozilla/Add-ons/WebExtensions/API/tabs/moveInSuccession page-type: webextension-api-function browser-compat: webextensions.api.tabs.moveInSuccession --- {{AddonSidebar}} Modifies the succession relationship for a group of tabs. Using the {{WebExtAPIRef('tabs')}} API, a tab can be assigned a _successor_ tab in the same window. If tab B is the successor of tab A, and tab A is closed while it is the active tab, tab B will be activated next. If tab A doesn't have a successor, then the browser is free to determine which tab to activate next. If tab B is the successor of tab A, then tab A is called a _predecessor_ of tab B. A tab can have at most one successor, but it can have any number of predecessors. A tab cannot take itself or a tab in a different window as a successor. All tabs start out with no successor; tabs only get a successor if assigned one by a WebExtension. However, the browser must not orphan a tab in a succession relationship with other tabs, if possible: if tab B is the successor of tab A, and tab C is the successor of tab B, and B is closed (or moved to another window), then tab A will take tab C as its successor. Preventing C from being orphaned in this way is called _moving a tab_ (B) _from its line of succession_. `tabs.moveInSuccession()` takes an array of tab IDs, and moves all of those tabs from their lines of succession. It then makes each tab the successor of the previous tab in the array, forming a chain. It can optionally set the successor of the last tab in the chain to an anchor tab, which is _not_ moved from its line of succession. Additional options can control whether the tab chain is "prepended" or "appended" to the anchor tab, and whether the operation acts like a linked-list insert. While the successor tab can be assigned with {{WebExtAPIRef('tabs.update()')}}, it is often desirable to use `tabs.moveInSuccession()` to change successors, even if only a single tab is having its successor assigned. The difference is that `browser.tabs.moveInSuccession([a], b)` moves tab `a` from its line of succession, so any predecessors of `a` will adopt `a`'s previous successor; whereas if `browser.tabs.update(a, {successorTabId: b})` is used instead, tab `a` may continue to be the successor of other tabs, which could be unexpected. Another advantage of `tabs.moveInSuccession()` is that all of the succession changes happen atomically, without having to worry about races between calls to {{WebExtAPIRef('tabs.update()')}} and {{WebExtAPIRef('tabs.get()')}} and other operations like the user closing a tab. ## Syntax ```js-nolint browser.tabs.moveInSuccession([1, 3, 5, 7, 2, 9], 4, {insert:true}) ``` ### Parameters - `tabIds` - : `array` of `integer`. An array of tab `ID`s. The order of the elements in the array defines the relationship of the tabs. Any invalid tab `ID`s, or tab `ID`s corresponding to tabs not in the same window as `tabId` (or the first tab in the array, if `tabId` is omitted), will be ignored—they will keep their current successors and predecessors. - `tabId` {{optional_inline}} - : `integer`. The `ID` of the tab that will be the successor of the last tab in the `tabIds` array. If this `ID` is invalid or {{WebExtAPIRef('tabs.TAB_ID_NONE')}}, the last tab will not have a successor. Defaults to {{WebExtAPIRef('tabs.TAB_ID_NONE')}}. - `options` {{optional_inline}} - : `object`. - `append` {{optional_inline}} - : `boolean`. Determines whether to move the tabs in `tabIds` before or after `tabId` in the succession. If `false`, the tabs are moved before `tabId`, if `true`, the tabs are moved after `tabId`. Defaults to `false`. - `insert` {{optional_inline}} - : `boolean`. Determines whether to link up the current predecessors or successor (depending on `options.append`) of `tabId` to the other side of the chain after it is prepended or appended. If true, one of the following happens: if `options.append` is `false`, the first tab in the array is set as the successor of any current predecessors of `tabId`; if `options.append` is `true`, the current successor of tabId is set as the successor of the last tab in the array. Defaults to `false`. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onattached/index.md
--- title: tabs.onAttached slug: Mozilla/Add-ons/WebExtensions/API/tabs/onAttached page-type: webextension-api-event browser-compat: webextensions.api.tabs.onAttached --- {{AddonSidebar}} Fired when a tab is attached to a window, for example because it was moved between windows. ## Syntax ```js-nolint browser.tabs.onAttached.addListener(listener) browser.tabs.onAttached.removeListener(listener) browser.tabs.onAttached.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed these arguments: - `tabId` - : `integer`. ID of the tab that was attached to a new window. - `attachInfo` - : `object`. ID of the new window, and index of the tab within it. See the [attachInfo](#attachinfo_2) section for more details. ## Additional objects ### attachInfo - `newWindowId` - : `integer`. ID of the new window. - `newPosition` - : `integer`. Index position that the tab has in the new window. ## Examples Listen for attach events, and log the info: ```js function handleAttached(tabId, attachInfo) { console.log(`Tab: ${tabId} attached`); console.log(`New window: ${attachInfo.newWindowId}`); console.log(`New index: ${attachInfo.newPosition}`); } browser.tabs.onAttached.addListener(handleAttached); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onAttached) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/detectlanguage/index.md
--- title: tabs.detectLanguage() slug: Mozilla/Add-ons/WebExtensions/API/tabs/detectLanguage page-type: webextension-api-function browser-compat: webextensions.api.tabs.detectLanguage --- {{AddonSidebar}} Detects the primary language of the content in a tab, using the [Compact Language Detector](https://github.com/CLD2Owners/cld2) (CLD). This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let detecting = browser.tabs.detectLanguage( tabId, // optional integer callback // optional function ) ``` ### Parameters - `tabId` {{optional_inline}} - : `integer`. Defaults to the active tab of the current window. - `callback` {{optional_inline}} - : `function`. Currently, if a `tabId` is specified, this method uses this callback to return the results instead of returning a promise. The callback receives as its only input parameter a string containing the detected language code such as `en` or `fr`. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a string representing an ISO language code such as `en` or `fr`. For a complete list of languages supported by this method, see [kLanguageInfoTable](https://src.chromium.org/viewvc/chrome/trunk/src/third_party/cld/languages/internal/languages.cc#l23). For an unknown language, `"und"` will be returned (but see [bug 1288263](https://bugzil.la/1288263)). If any error occurs the promise will be rejected with an error message. ## Examples Detect and log the language of the active tab when the user clicks a browser action: ```js function onLanguageDetected(lang) { console.log(`Language is: ${lang}`); } function onError(error) { console.log(`Error: ${error}`); } browser.browserAction.onClicked.addListener(() => { browser.tabs.detectLanguage().then(onLanguageDetected, onError); }); ``` Detect and log the language of every open tab when the user clicks a browser action (note that this example requires the "tabs" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions)): ```js function onLanguageDetected(url, lang) { console.log(`Language in ${url} is: ${lang}`); } function onError(error) { console.log(`Error: ${error}`); } function detectLanguages(tabs) { for (const tab of tabs) { browser.tabs .detectLanguage(tab.id) .then((lang) => onLanguageDetected(tab.url, lang), onError); } } browser.browserAction.onClicked.addListener(() => { browser.tabs.query({}).then(detectLanguages, onError); }); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-detectLanguage) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/remove/index.md
--- title: tabs.remove() slug: Mozilla/Add-ons/WebExtensions/API/tabs/remove page-type: webextension-api-function browser-compat: webextensions.api.tabs.remove --- {{AddonSidebar}} Closes one or more tabs. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.tabs.remove( tabIds // integer or integer array ) ``` ### Parameters - `tabIds` - : `integer` or `array` of `integer` The ids of the tab or tabs to close. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when all the specified tabs have been removed or their `beforeunload` prompts have been handled. If any error occurs, the promise will be rejected with an error message. ## Examples Close a single tab: ```js function onRemoved() { console.log(`Removed`); } function onError(error) { console.log(`Error: ${error}`); } let removing = browser.tabs.remove(2); removing.then(onRemoved, onError); ``` Close multiple tabs: ```js function onRemoved() { console.log(`Removed`); } function onError(error) { console.log(`Error: ${error}`); } let removing = browser.tabs.remove([15, 14, 1]); removing.then(onRemoved, onError); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-remove) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onselectionchanged/index.md
--- title: tabs.onSelectionChanged slug: Mozilla/Add-ons/WebExtensions/API/tabs/onSelectionChanged page-type: webextension-api-event status: - deprecated browser-compat: webextensions.api.tabs.onSelectionChanged --- {{AddonSidebar}} > **Warning:** This event is deprecated. Use {{WebExtAPIRef("tabs.onActivated")}} instead. Fires when the selected tab in a window changes. ## Syntax ```js-nolint browser.tabs.onSelectionChanged.addListener(listener) browser.tabs.onSelectionChanged.removeListener(listener) browser.tabs.onSelectionChanged.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed these arguments: - `tabId` - : `integer`. The ID of the tab that has become active. - `selectInfo` - : `object`. See the [selectInfo](#selectinfo_2) section for more details. ## Additional objects ### selectInfo - `windowId` - : `integer`. The ID of the window the selected tab changed in. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onSelectionChanged) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/get/index.md
--- title: tabs.get() slug: Mozilla/Add-ons/WebExtensions/API/tabs/get page-type: webextension-api-function browser-compat: webextensions.api.tabs.get --- {{AddonSidebar}} Given a tab ID, get the tab's details as a {{WebExtAPIRef("tabs.Tab")}} object. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let getting = browser.tabs.get( tabId // integer ) ``` ### Parameters - `tabId` - : `integer`. ID of the tab to get. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('tabs.Tab')}} object containing information about the tab. If the tab could not be found or some other error occurs, the promise will be rejected with an error message. ## Examples Get information about a tab when it is activated: ```js async function logListener(info) { try { let tabInfo = await browser.tabs.get(info.tabId); console.log(tabInfo); } catch (error) { console.error(error); } } browser.tabs.onActivated.addListener(logListener); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-get) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/create/index.md
--- title: tabs.create() slug: Mozilla/Add-ons/WebExtensions/API/tabs/create page-type: webextension-api-function browser-compat: webextensions.api.tabs.create --- {{AddonSidebar}} Creates a new tab. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let creating = browser.tabs.create( createProperties // object ) ``` ### Parameters - `createProperties` - : `object`. Properties to give the new tab. To learn more about these properties, see the {{WebExtAPIRef("tabs.Tab")}} documentation. - `active` {{optional_inline}} - : `boolean`. Whether the tab should become the active tab in the window. If `false`, it has no effect. Does not affect whether the window is focused (see {{WebExtAPIRef('windows.update')}}). Defaults to `true`. - `cookieStoreId` {{optional_inline}} - : `string`. Use this to create a tab whose cookie store ID is `cookieStoreId`. This option is only available if the extension has the `"cookies"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. - `discarded` {{optional_inline}} - : `boolean`. Whether the tab is created and made visible in the tab bar without any content loaded into memory, a state known as discarded. The tab's content is loaded when the tab is activated. - `index` {{optional_inline}} - : `integer`. The position the tab should take in the window. The provided value will be clamped to between zero and the number of tabs in the window. - `muted` {{optional_inline}} - : `boolean`. Whether the tab should be muted. Defaults to `false`. - `openerTabId` {{optional_inline}} - : `integer`. The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as the newly created tab. - `openInReaderMode` {{optional_inline}} - : `boolean`. If `true`, open this tab in [Reader Mode](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/toggleReaderMode). Defaults to `false`. - `pinned` {{optional_inline}} - : `boolean`. Whether the tab should be pinned. Defaults to `false`. - `selected` {{optional_inline}} - : `boolean`. Whether the tab should become the selected tab in the window. Defaults to `true`. > **Warning:** This property is deprecated, and is not supported in Firefox. Use `active` instead. - `title` {{optional_inline}} - : `string`. The title of the tab. Allowed only if the tab is created with `discarded` set to `true`. - `url` {{optional_inline}} - : `string`. The URL to navigate the tab to initially. Defaults to the New Tab Page. Fully-qualified URLs must include a scheme (for example, 'http\://www\.google.com' not 'www\.google.com'). For security reasons, in Firefox, this may not be a privileged URL. So passing any of the following URLs will fail: - chrome: URLs - javascript: URLs - data: URLs - file: URLs (i.e., files on the filesystem. However, to use a file packaged inside the extension, see below) - privileged about: URLs (for example, `about:config`, `about:addons`, `about:debugging`). Non-privileged URLs (e.g., `about:blank`) are allowed. - The New Tab page (`about:newtab`) can be opened if no value for URL is provided. To load a page that's packaged with your extension, specify an absolute URL starting at the extension's manifest.json file. For example: '/path/to/my-page.html'. If you omit the leading '/', the URL is treated as a relative URL, and different browsers may construct different absolute URLs. - `windowId` {{optional_inline}} - : `integer`. The window to create the new tab in. Defaults to the current window. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('tabs.Tab')}} object containing details about the created tab. If the tab could not be created (for example, because `url` used a privileged scheme) the promise will be rejected with an error message. The promise returned by `browser.tabs.create()` resolves as soon as the tab has been created. The tab may still be loading. To detect when the tab has finished loading, listen to the {{WebExtAPIRef('tabs.onUpdated')}} or the {{WebExtAPIRef('webNavigation.onCompleted')}} event before calling `tabs.create`. ## Examples Open "https\://example.org" in a new tab: ```js function onCreated(tab) { console.log(`Created new tab: ${tab.id}`); } function onError(error) { console.log(`Error: ${error}`); } browser.browserAction.onClicked.addListener(() => { let creating = browser.tabs.create({ url: "https://example.org", }); creating.then(onCreated, onError); }); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-create) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/tabstatus/index.md
--- title: tabs.TabStatus slug: Mozilla/Add-ons/WebExtensions/API/tabs/TabStatus page-type: webextension-api-type browser-compat: webextensions.api.tabs.TabStatus --- {{AddonSidebar}} Indicates whether the tab has finished loading. ## Type Values of this type are strings. Possible values are: `"loading"` and `"complete"`. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#type-TabStatus) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/onactivechanged/index.md
--- title: tabs.onActiveChanged slug: Mozilla/Add-ons/WebExtensions/API/tabs/onActiveChanged page-type: webextension-api-event status: - deprecated browser-compat: webextensions.api.tabs.onActiveChanged --- {{AddonSidebar}} > **Warning:** This event is deprecated. Use {{WebExtAPIRef("tabs.onActivated")}} instead. Fires when the selected tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to {{WebExtAPIRef('tabs.onUpdated')}} events to be notified when a URL is set. ## Syntax ```js-nolint browser.tabs.onActiveChanged.addListener(listener) browser.tabs.onActiveChanged.removeListener(listener) browser.tabs.onActiveChanged.hasListener(listener) ``` Events have three functions: - `addListener(listener)` - : Adds a listener to this event. - `removeListener(listener)` - : Stop listening to this event. The `listener` argument is the listener to remove. - `hasListener(listener)` - : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise. ## addListener syntax ### Parameters - `listener` - : The function called when this event occurs. The function is passed these arguments: - `tabId` - : `integer`. The ID of the tab that has become active. - `selectInfo` - : `object`. See the [selectInfo](#selectinfo_2) section for more details. ## Additional objects ### selectInfo - `windowId` - : `integer`. The ID of the window containing the selected tab. ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#event-onActiveChanged) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/sendrequest/index.md
--- title: tabs.sendRequest() slug: Mozilla/Add-ons/WebExtensions/API/tabs/sendRequest page-type: webextension-api-function status: - deprecated browser-compat: webextensions.api.tabs.sendRequest --- {{AddonSidebar}} > **Warning:** This method has been deprecated. Use {{WebExtAPIRef("tabs.sendMessage()")}} instead. Sends a single request to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The {{WebExtAPIRef('extension.onRequest')}} event is fired in each content script running in the specified tab for the current extension. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let sending = browser.tabs.sendRequest( tabId, // integer request // any ) ``` ### Parameters - `tabId` - : `integer`. - `request` - : `any`. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with the JSON response object sent by the handler of the message in the content script, or with no arguments if the content script did not send a response. If an error occurs while connecting to the specified tab or any other error occurs, the promise will be rejected with an error message. ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-sendRequest) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/tabs/capturevisibletab/index.md
--- title: tabs.captureVisibleTab() slug: Mozilla/Add-ons/WebExtensions/API/tabs/captureVisibleTab page-type: webextension-api-function browser-compat: webextensions.api.tabs.captureVisibleTab --- {{AddonSidebar}} Creates a data URL encoding the image of an area of the currently active tab in the specified window. You must have the `<all_urls>` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) to use this method. (Alternately, Chrome allows use of this method with the `activeTab` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) and a qualifying user gesture). This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let capturing = browser.tabs.captureVisibleTab( windowId, // optional integer options // optional extensionTypes.ImageDetails ) ``` ### Parameters - `windowId` {{optional_inline}} - : `integer`. The target window. Defaults to the current window. - `options` {{optional_inline}} - : {{WebExtAPIRef('extensionTypes.ImageDetails')}}. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a data URL which encodes the captured image. May be assigned to the 'src' property of an HTML Image element for display. If any error occurs the promise will be rejected with an error message. ## Examples Capture an image of the active tab in the current window, with default settings: ```js function onCaptured(imageUri) { console.log(imageUri); } function onError(error) { console.log(`Error: ${error}`); } browser.browserAction.onClicked.addListener(() => { let capturing = browser.tabs.captureVisibleTab(); capturing.then(onCaptured, onError); }); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.tabs`](https://developer.chrome.com/docs/extensions/reference/tabs/#method-captureVisibleTab) API. This documentation is derived from [`tabs.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0