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/browseraction
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browseraction/imagedatatype/index.md
--- title: browserAction.ImageDataType slug: Mozilla/Add-ons/WebExtensions/API/browserAction/ImageDataType page-type: webextension-api-type browser-compat: webextensions.api.browserAction.ImageDataType --- {{AddonSidebar}} Pixel data for an image. Must be an [`ImageData`](/en-US/docs/Web/API/ImageData) object (for example, from a {{htmlelement("canvas")}} element). ## Type An [`ImageData`](/en-US/docs/Web/API/ImageData) object. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.browserAction`](https://developer.chrome.com/docs/extensions/reference/browserAction/#type-ImageDataType) API. This documentation is derived from [`browser_action.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/browser_action.json) in the Chromium code. <!-- // Copyright 2015 The Chromium Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -->
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/index.md
--- title: browserSettings slug: Mozilla/Add-ons/WebExtensions/API/browserSettings page-type: webextension-api browser-compat: webextensions.api.browserSettings --- {{AddonSidebar}} Enables an extension to modify certain global browser settings. Each property of this API is a {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object, providing the ability to modify a particular setting. Because these are global settings, it's possible for extensions to conflict. See the documentation for [`BrowserSetting.set()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting/set) for details of how conflicts are handled. To use this API you need to have the "browserSettings" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). ## Properties - {{WebExtAPIRef("browserSettings.allowPopupsForUserEvents")}} - : Determines whether code running in web pages can display popups in response to user events. - {{WebExtAPIRef("browserSettings.cacheEnabled")}} - : Determines whether the browser cache is enabled or not. - {{WebExtAPIRef("browserSettings.closeTabsByDoubleClick")}} - : Determines whether the selected tab can be closed with a double click. - {{WebExtAPIRef("browserSettings.colorManagement")}} - : Determines various settings for color management. - {{WebExtAPIRef("browserSettings.contextMenuShowEvent")}} - : Determines the mouse event that triggers a context menu popup. - {{WebExtAPIRef("browserSettings.ftpProtocolEnabled")}} - : Determines whether the FTP protocol is enabled. - {{WebExtAPIRef("browserSettings.homepageOverride")}} - : Read the value of the browser's home page. - {{WebExtAPIRef("browserSettings.imageAnimationBehavior")}} - : Determines how the browser treats animated images. - {{WebExtAPIRef("browserSettings.newTabPageOverride")}} - : Reads the value of the browser's new tab page. - {{WebExtAPIRef("browserSettings.newTabPosition")}} - : Controls the position of newly opened tabs relative to already open tabs. - {{WebExtAPIRef("browserSettings.openBookmarksInNewTabs")}} - : Determines whether bookmarks are opened in the current tab or a new tab. - {{WebExtAPIRef("browserSettings.openSearchResultsInNewTabs")}} - : Determines whether search results are opened in the current tab or a new tab. - {{WebExtAPIRef("browserSettings.openUrlbarResultsInNewTabs")}} - : Determines whether address bar autocomplete suggestions are opened in the current tab or a new tab. - {{WebExtAPIRef("browserSettings.overrideContentColorScheme")}} - : Controls whether to override the browser theme (light or dark) when setting pages' preferred color scheme. - {{WebExtAPIRef("browserSettings.overrideDocumentColors")}} - : Controls whether the user-chosen colors override the page's colors. - {{WebExtAPIRef("browserSettings.tlsVersionRestrictionConfig")}} - : Read the highest and lowest versions of TLS supported by the browser. - {{WebExtAPIRef("browserSettings.useDocumentFonts")}} - : Controls whether the browser will use the fonts specified by a web page or use only built-in fonts. - {{WebExtAPIRef("browserSettings.webNotificationsDisabled")}} - : Prevents websites from showing notifications using the [`Notification`](/en-US/docs/Web/API/Notification) Web API. - {{WebExtAPIRef("browserSettings.zoomFullPage")}} - : Controls whether zoom is applied to the entire page or to text only. - {{WebExtAPIRef("browserSettings.zoomSiteSpecific")}} - : Controls whether page zoom is applied on a per-site or per-tab basis. If {{WebExtAPIRef("privacy.websites")}}`.resistFingerprinting` is true, this setting has no effect and zoom is applied on a per-tab basis. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/webnotificationsdisabled/index.md
--- title: browserSettings.webNotificationsDisabled slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/webNotificationsDisabled page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.webNotificationsDisabled --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object that can be used to prevent websites from showing notifications using the [`Notifications`](/en-US/docs/Web/API/Notifications_API) Web API. The `Notifications` API is used to display desktop notifications to the user. There are three levels of permission for notifications: _allow_, _deny_, and _prompt_. Users can set this permission for every site. If the user has not set a permission for a particular site, then the browser will fall back to a global permission, which defaults to _prompt_. Setting `browserSettings.webNotificationsDisabled` to `true` switches the global permission to _deny_. Note that this won't affect sites for which the user has set a per-site preference. For example, if the user sets <https://example.org> to _allow_, and an extension then sets `browserSettings.webNotificationsDisabled` to `true`, then pages under [https://example.org](https://example.org) will still be allowed to show notifications. Setting `browserSettings.webNotificationsDisabled` to `false` switches the global default back to its default value. Note that this setting has no effect on notifications created by extensions using the [`notifications`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications) API. ## Browser compatibility {{Compat}} ## Examples Toggle the setting: ```js async function toggleWebNotifications() { let current = await browser.browserSettings.webNotificationsDisabled.get({}); console.log(`Current value: ${current.value}`); browser.browserSettings.webNotificationsDisabled.set({ value: !current.value, }); } browser.browserAction.onClicked.addListener(() => { toggleWebNotifications(); }); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/closetabsbydoubleclick/index.md
--- title: browserSettings.closeTabsByDoubleClick slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/closeTabsByDoubleClick page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.closeTabsByDoubleClick --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object that can be used to enable or disable the user's ability to close a tab using double-click. The underlying value is a boolean. By default, closeTabsByDoubleClick is false. The setting can be changed by the user in about:config. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/ftpprotocolenabled/index.md
--- title: browserSettings.ftpProtocolEnabled slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/ftpProtocolEnabled page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.ftpProtocolEnabled --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object that determines whether the FTP protocol is enabled in the browser. The underlying value is a boolean. > **Note:** From Firefox version 88 this setting is read-only. ## Browser compatibility {{Compat}} ## Examples Toggle the setting: ```js function toggleAllowFtp() { function toggle(current) { console.log(`Current value: ${current.value}`); browser.browserSettings.ftpProtocolEnabled.set({ value: !current.value }); } browser.browserSettings.ftpProtocolEnabled.get({}).then(toggle); } browser.browserAction.onClicked.addListener(() => { toggleAllowFtp(); }); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/imageanimationbehavior/index.md
--- title: browserSettings.imageAnimationBehavior slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/imageAnimationBehavior page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.imageAnimationBehavior --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object that can be used to change the way the browser handles animated images, such as GIFs. The underlying value is a string that can take one of three values: - "normal": the default. Play animated images as normal. - "none": don't animate images at all. - "once": play the animation once. ## Browser compatibility {{Compat}} ## Examples Disable animated images: ```js browser.browserSettings.imageAnimationBehavior.set({ value: "none" }); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/contextmenushowevent/index.md
--- title: browserSettings.contextMenuShowEvent slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/contextMenuShowEvent page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.contextMenuShowEvent --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object which determines whether the browser's context menu is shown on the mouseup event or on the mousedown event. Its underlying value is a string that may be either "mouseup" or "mousedown". The default value is "mouseup" on Windows, and "mousedown" on macOS and Linux. Assigning to it on Windows has no effect - the setting is only designed to allow the context menu to be opened on mouseup instead of mousedown, not the inverse. ## Browser compatibility {{Compat}} ## Examples Set the setting to "mouseup": ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.contextMenuShowEvent .set({ value: "mouseup" }) .then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/cacheenabled/index.md
--- title: browserSettings.cacheEnabled slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/cacheEnabled page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.cacheEnabled --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object that can be used to globally enable or disable the browser cache. The underlying value is a boolean. ## Browser compatibility {{Compat}} ## Examples Getting the current value of this setting: ```js function logResult(result) { console.log(`Current value: ${result.value}`); console.log(`Current level of control: ${result.levelOfControl}`); } browser.browserSettings.cacheEnabled.get({}).then(logResult); ``` Disabling the browser cache: ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.cacheEnabled.set({ value: false }).then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/homepageoverride/index.md
--- title: browserSettings.homepageOverride slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/homepageOverride page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.homepageOverride --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object that can be used to get a string representing the URL currently set as the browser's homepage. Note that this is a read-only setting. To change the homepage, see [chrome_settings_overrides](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_settings_overrides). ## Browser compatibility {{Compat}} ## Examples Get the current value of the homepage URL: ```js browser.browserSettings.homepageOverride.get({}).then((result) => { console.log(result.value); }); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/usedocumentfonts/index.md
--- title: browserSettings.useDocumentFonts slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/useDocumentFonts page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.useDocumentFonts --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object whose underlying value is a boolean. By default, of course, web pages can specify the fonts they want using CSS properties like [`font-family`](/en-US/docs/Web/CSS/font-family). This setting enables an extension to instruct Firefox to ignore the fonts specified by the page, and only use system fonts. Its underlying value is a boolean: - `true`: use the fonts specified by the web page. This is the default. - `false`: use the system fonts. ## Browser compatibility {{Compat}} ## Examples Set the setting to `false`: ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.useDocumentFonts.set({ value: false }).then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/openbookmarksinnewtabs/index.md
--- title: browserSettings.openBookmarksInNewTabs slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/openBookmarksInNewTabs page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.openBookmarksInNewTabs --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object whose underlying value is a boolean. If set to `true`, then when the user selects a bookmark, it will be opened in a new tab. If set to `false` (the default) bookmarks are opened in the current tab. ## Browser compatibility {{Compat}} ## Examples Set the setting to `true`: ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.openBookmarksInNewTabs .set({ value: true }) .then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/overridecontentcolorscheme/index.md
--- title: browserSettings.overrideContentColorScheme slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/overrideContentColorScheme page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.overrideContentColorScheme --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object whose underlying value is a string. Firefox enables users to choose a theme for the browser UI. These themes apply either a light or dark theme to webpages. Using the `layout.css.prefers-color-scheme.content-override` preference, users can override the theme and choose to render webpages in a light or dark theme or follow the device's theme. This browser setting exposes that preference. This object takes these values: - "light": Applies a light theme to webpages. - "dark": Applies a dark theme to webpages. - "system": Applies a light or dark theme to webpages based on the device's theme. - "browser": Applies a light or dark theme to webpages based on the browser's theme. ## Browser compatibility {{Compat}} ## Examples This example overrides the setting to use the dark theme for webpages: ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.overrideContentColorScheme .set({ value: "dark" }) .then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/openurlbarresultsinnewtabs/index.md
--- title: browserSettings.openUrlbarResultsInNewTabs slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/openUrlbarResultsInNewTabs page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.openUrlbarResultsInNewTabs --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object whose underlying value is a boolean. When the user focuses the address bar and starts typing, the browser offers autocomplete suggestions: a dropdown list of web pages based on the user's incomplete input and their browsing history. If set to `true`, then when the user selects one of these items, the item is opened in a new tab. If set to `false` (the default) the item is opened in the current tab. ## Browser compatibility {{Compat}} ## Examples Set the setting to `true`: ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.openUrlbarResultsInNewTabs .set({ value: true }) .then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/opensearchresultsinnewtabs/index.md
--- title: browserSettings.openSearchResultsInNewTabs slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/openSearchResultsInNewTabs page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.openSearchResultsInNewTabs --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object whose underlying value is a boolean. If set to `true`, then when the user selects a term in the browser's search box, the search results are displayed in a new tab. If set to `false` (the default) the search results are shown in the current tab. Note that this does not affect the behavior when selecting items from the omnibox/awesomebar,only the dedicated search box. ## Browser compatibility {{Compat}} ## Examples Set the setting to `true`: ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.openSearchResultsInNewTabs .set({ value: true }) .then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/zoomfullpage/index.md
--- title: browserSettings.zoomFullPage slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/zoomFullPage page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.zoomFullPage --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object whose underlying value is a boolean. By default zoom applies to all the content of a web page. Using the [Zoom Text Only setting](https://support.mozilla.org/en-US/kb/font-size-and-zoom-increase-size-of-web-pages#w_how-to-only-change-the-size-of-the-text/en-US/docs/) users can choose to zoom only the text on a page. This settings enables web extensions to control this setting and determine whether zoom is applied to the entire page or to text only. The settings are: - `true`: zoom applies to all the content of a web page (default). - `false`: zoom applies to web page text only. ## Browser compatibility {{Compat}} ## Examples Set the setting to `false`: ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.zoomFullPage.set({ value: false }).then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/colormanagement/index.md
--- title: browserSettings.colorManagement slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/colorManagement page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.colorManagement --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object used to query and set the browser's color management features. By default, Firefox applies color management to tagged media and defaults to sRGB for untagged media. This behavior means that some untagged media, such as that used in animation and movie production, may have undesired color corrections made to it. Use these settings to prevent that. The object has these properties: - `mode` - : A string that represents the mode used for color management. Valid values are `off`, `full`, and `tagged_only`. - `useNativeSRGB` - : A boolean representing whether or not built-in sRGB color management is used. - `useWebRenderCompositor` - : A boolean representing whether or not the WebRender compositor is used. ## Browser compatibility {{Compat}} ## Examples Set color mode to "full": ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.colorManagement.mode .set({ value: "full" }) .then(logResult); ``` Get the native sRGB color management color mode: ```js function logResult(result) { console.log(`Current useNativeSRGB value: ${result.value}`); } browser.browserSettings.colorManagement.useNativeSRGB.get({}).then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/newtabposition/index.md
--- title: browserSettings.newTabPosition slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/newTabPosition page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.newTabPosition --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object that can be used to control the position of newly opened tabs relative to already open tabs. The underlying value is a string that can take one of three values: - "afterCurrent": Open all new tabs next to the current tab. - "relatedAfterCurrent": The default. Open new tabs next to the current tab if they are related to the current tab (for example, if they were opened via a link in the current tab). Otherwise, open new tabs at the end of the tabstrip. - "atEnd": Open all tabs at the end of the tabstrip. ## Browser compatibility {{Compat}} ## Examples This code sets the value to "afterCurrent" and then logs the new value: ```js async function setAfterCurrent() { let result = await browser.browserSettings.newTabPosition.set({ value: "afterCurrent", }); console.log(`Result: ${result}`); let newValue = await browser.browserSettings.newTabPosition.get({}); console.log(`New value: ${newValue.value}`); } ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/zoomsitespecific/index.md
--- title: browserSettings.zoomSiteSpecific slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/zoomSiteSpecific page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.zoomSiteSpecific --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object whose underlying value is a boolean. This property sets the [configuration setting](https://support.mozilla.org/en-US/kb/about-config-editor-firefox) `browser.zoom.siteSpecific`, which controls how zoom settings are applied to sites and tabs. If `browser.zoom.siteSpecific` is true, zoom operations apply to all pages from the same site so that: - when a page loads, if there is a zoom level for that site it is applied to the page otherwise the global default zoom level is applied. - when the zoom level for a page changes, the zoom levels of other pages from the site in other tabs are also changed. If `browser.zoom.siteSpecific` is set false, zoom operations apply to the active tab only so that: - when a new tab opens, the global default zoom level is applied. - when the zoom level in a tab changes, it persists across page loads and does not affect the zoom level in any other tab. When Firefox is installed, `browser.zoom.siteSpecific` is true. If [`privacy.websites`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/privacy/websites)`.resistFingerprinting` is true, this setting has no effect and zoom is set on a per-tab basis. ## Browser compatibility {{Compat}} ## Examples Set the setting to `false`: ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.zoomSiteSpecific.set({ value: false }).then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/overridedocumentcolors/index.md
--- title: browserSettings.overrideDocumentColors slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/overrideDocumentColors page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.overrideDocumentColors --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object whose underlying value is a string. Firefox enables the user to set their own colors for document backgrounds and text. By default these values are only applied when a high-contrast theme is selected (a high-contrast theme is a feature of some operating system UIs that increases the contrast for improved accessibility). However, users can also choose to apply these colors always or never. This browser setting exposes that preference. Its underlying value is a string that may take any one of the following values: - "high-contrast-only": Apply the user's choices only when a high-contrast theme is selected. This is the default. - "never": Never apply the user's choices. - "always": Always apply the user's choices. ## Browser compatibility {{Compat}} ## Examples Set the setting to "always": ```js function logResult(result) { console.log(`Setting was modified: ${result}`); } browser.browserSettings.overrideDocumentColors .set({ value: "always" }) .then(logResult); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/newtabpageoverride/index.md
--- title: browserSettings.newTabPageOverride slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/newTabPageOverride page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.newTabPageOverride --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object that can be used to get a string representing the URL for the "new tab" page: that is, the page that's loaded when the user opens a new empty tab. Note that this is a read-only setting. ## Browser compatibility {{Compat}} ## Examples Get the current value of the new tab URL: ```js browser.browserSettings.newTabPageOverride.get({}).then((result) => { console.log(result.value); }); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/tlsversionrestrictionconfig/index.md
--- title: browserSettings.tlsVersionRestrictionConfig slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/tlsVersionRestrictionConfig page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.tlsVersionRestrictionConfig --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object used to read the highest and lowest versions of TLS supported by the browser. The object has these properties: - `minimum` - : The lowest TLS version supported by the browser. Valid values are `TLSv1`, `TLSv1.1`, `TLSv1.2`, `TLSv1.3`, and `unknown`. - `maximum` - : The highest TLS version supported by the browser. Valid values are `TLSv1`, `TLSv1.1`, `TLSv1.2`, `TLSv1.3`, and `unknown`. This is a read-only setting. ## Browser compatibility {{Compat}} ## Examples Get the highest TLS version supported by the browser: ```js browser.browserSettings.tlsVersionRestrictionConfig.maximum .get({}) .then((result) => { console.log(`Highest TLS version supported: ${result}`); }); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsersettings/allowpopupsforuserevents/index.md
--- title: browserSettings.allowPopupsForUserEvents slug: Mozilla/Add-ons/WebExtensions/API/browserSettings/allowPopupsForUserEvents page-type: webextension-api-property browser-compat: webextensions.api.browserSettings.allowPopupsForUserEvents --- {{AddonSidebar}} A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object that can be used to enable or disable the ability of web pages to open popups in response to user actions. The underlying value is a boolean. By default, browsers allow web pages to open popups in response to a particular set of events: for example, [click](/en-US/docs/Web/API/Element/click_event), [mouseup](/en-US/docs/Web/API/Element/mouseup_event), [submit](/en-US/docs/Web/API/HTMLFormElement/submit_event). If `allowPopupsForUserEvents` is set to `false`, no user events will be able to open popups. If it is set to `true`, the default set of events will be allowed to open popups. For example, suppose a web page has code like this: ```js window.addEventListener("click", (e) => { window.open("https://example.com", "myPopup", "height=400,width=400"); }); ``` By default, this will open a popup window. If your extension sets `allowPopupsForUserEvents` to `false`, then it will not open a popup, and the user will be informed that the popup was blocked. ## Browser compatibility {{Compat}} ## Examples Toggle the setting: ```js function toggleAllowPopup() { function toggle(current) { console.log(`Current value: ${current.value}`); browser.browserSettings.allowPopupsForUserEvents.set({ value: !current.value, }); } browser.browserSettings.allowPopupsForUserEvents.get({}).then(toggle); } browser.browserAction.onClicked.addListener(() => { toggleAllowPopup(); }); ``` {{WebExtExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms/index.md
--- title: alarms slug: Mozilla/Add-ons/WebExtensions/API/alarms page-type: webextension-api browser-compat: webextensions.api.alarms --- {{AddonSidebar}} Schedule code to run at a specific time in the future. This is like [`setTimeout()`](/en-US/docs/Web/API/setTimeout) and [`setInterval()`](/en-US/docs/Web/API/setInterval), except that those functions don't work with background pages that are loaded on demand. Alarms do not persist across browser sessions. They are created globally across all contexts of a single extension. E.g. alarm created in background script will fire [`onAlarm`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/alarms/onAlarm) event in background script, options page, popup page and extension tabs (and vice versa). Alarms API is not available in [`Content scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#webextension_apis). To use this API you need to have the "alarms" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). ## Types - {{WebExtAPIRef("alarms.Alarm")}} - : Information about a particular alarm. ## Methods - {{WebExtAPIRef("alarms.clear()")}} - : Clear a specific alarm, given its name. - {{WebExtAPIRef("alarms.clearAll()")}} - : Clear all scheduled alarms. - {{WebExtAPIRef("alarms.create()")}} - : Create a new alarm. - {{WebExtAPIRef("alarms.get()")}} - : Retrieves a specific alarm, given its name. - {{WebExtAPIRef("alarms.getAll()")}} - : Retrieve all scheduled alarms. ## Events - {{WebExtAPIRef("alarms.onAlarm")}} - : Fired when an alarm goes off. {{WebExtExamples("h2")}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.alarms`](https://developer.chrome.com/docs/extensions/reference/alarms/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms/onalarm/index.md
--- title: alarms.onAlarm slug: Mozilla/Add-ons/WebExtensions/API/alarms/onAlarm page-type: webextension-api-event browser-compat: webextensions.api.alarms.onAlarm --- {{AddonSidebar}} Fired when any alarm set by the extension goes off. ## Syntax ```js-nolint browser.alarms.onAlarm.addListener(listener) browser.alarms.onAlarm.removeListener(listener) browser.alarms.onAlarm.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: - `alarm` - : {{WebExtAPIRef('alarms.Alarm')}}. The alarm that fired. Use `Alarm.name` to figure out which alarm fired. ## Examples Handle an alarm going off: ```js function handleAlarm(alarmInfo) { console.log(`on alarm: ${alarmInfo.name}`); } browser.alarms.onAlarm.addListener(handleAlarm); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.alarms`](https://developer.chrome.com/docs/extensions/reference/alarms/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms/get/index.md
--- title: alarms.get() slug: Mozilla/Add-ons/WebExtensions/API/alarms/get page-type: webextension-api-function browser-compat: webextensions.api.alarms.get --- {{AddonSidebar}} Gets an alarm, given its name. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let getAlarm = browser.alarms.get( name // optional string ) ``` ### Parameters - `name` {{optional_inline}} - : `string`. The name of the alarm to get. If you don't supply this, the empty string "" will be used. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an `{{WebExtAPIRef('alarms.Alarm', "Alarm")}}` object. This represents the alarm whose name matches `name`. If no alarms match, this will be `undefined`. ## Examples ```js function gotAlarm(alarm) { if (alarm) { console.log(alarm.name); } } let getAlarm = browser.alarms.get("my-periodic-alarm"); getAlarm.then(gotAlarm); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.alarms`](https://developer.chrome.com/docs/extensions/reference/alarms/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms/create/index.md
--- title: alarms.create() slug: Mozilla/Add-ons/WebExtensions/API/alarms/create page-type: webextension-api-function browser-compat: webextensions.api.alarms.create --- {{AddonSidebar}} Creates a new alarm for the current browser session. An alarm may fire once or multiple times. An alarm is cleared after it fires for the last time. ## Syntax ```js-nolint browser.alarms.create( name, // optional string alarmInfo // optional object ) ``` ### Parameters - `name` {{optional_inline}} - : `string`. A name for the alarm. Defaults to the empty string. This can be used to refer to a particular alarm in {{WebExtAPIRef('alarms.get()')}} and {{WebExtAPIRef('alarms.clear()')}}. It will also be available in {{WebExtAPIRef('alarms.onAlarm')}} as the `name` property of the {{WebExtAPIRef('alarms.Alarm')}} object passed into the listener function. Alarm names are unique within the scope of a single extension. If an alarm with an identical name exists, the existing alarm will be cleared and the alarm being created will replace it. - `alarmInfo` {{optional_inline}} - : `object`. You can use this to specify when the alarm will initially fire, either as an absolute value (`when`), or as a delay from the time the alarm is set (`delayInMinutes`). To make the alarm recur, specify `periodInMinutes`. On Chrome, unless the extension is loaded unpackaged, alarms it creates are not allowed to fire more than once per minute. If an extension tries to set `delayInMinutes` to a value < 1, or `when` to a value < 1 minute in the future, then the alarm will fire after 1 minute. If an extension tries to set `periodInMinutes` to a value < 1, then the alarm will fire every minute. The `alarmInfo` object may contain the following properties: - `when` {{optional_inline}} - : `double`. The time the alarm will fire first, given as [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). To get the number of milliseconds between the epoch and the current time, use [`Date.now()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now). If you specify `when`, don't specify `delayInMinutes`. - `delayInMinutes` {{optional_inline}} - : `double`. The time the alarm will fire first, given as minutes from the time the alarm is set. If you specify `delayInMinutes`, don't specify `when`. - `periodInMinutes` {{optional_inline}} - : `double`. If this is specified, the alarm will fire again every `periodInMinutes` after its initial firing. If you specify this value you may omit both `when` and `delayInMinutes`, and the alarm will then fire initially after `periodInMinutes`. If `periodInMinutes` is not specified, the alarm will only fire once. ## Examples Create a one-time delay-based alarm with "" for the name: ```js const delayInMinutes = 5; browser.alarms.create({ delayInMinutes, }); ``` Create a periodic delay-based alarm named "my-periodic-alarm": ```js const delayInMinutes = 5; const periodInMinutes = 2; browser.alarms.create("my-periodic-alarm", { delayInMinutes, periodInMinutes, }); ``` Create a periodic absolute alarm named "my-periodic-alarm": ```js const when = 1545696000; const periodInMinutes = 2; browser.alarms.create("my-periodic-alarm", { when, periodInMinutes, }); ``` ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.alarms`](https://developer.chrome.com/docs/extensions/reference/alarms/) 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/alarms
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms/clearall/index.md
--- title: alarms.clearAll() slug: Mozilla/Add-ons/WebExtensions/API/alarms/clearAll page-type: webextension-api-function browser-compat: webextensions.api.alarms.clearAll --- {{AddonSidebar}} Cancels all active alarms. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let clearAlarms = browser.alarms.clearAll() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a boolean. This will be `true` if any alarms were cleared, `false` otherwise. Note that Chrome always passes `true` here. ## Examples ```js function onClearedAll(wasCleared) { console.log(wasCleared); // true/false } let clearAlarms = browser.alarms.clearAll(); clearAlarms.then(onClearedAll); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.alarms`](https://developer.chrome.com/docs/extensions/reference/alarms/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms/alarm/index.md
--- title: alarms.Alarm slug: Mozilla/Add-ons/WebExtensions/API/alarms/Alarm page-type: webextension-api-type browser-compat: webextensions.api.alarms.Alarm --- {{AddonSidebar}} Information about a single alarm. This object is returned from {{WebExtAPIRef('alarms.get()')}} and {{WebExtAPIRef('alarms.getAll()')}}, and is passed into the {{WebExtAPIRef('alarms.onAlarm')}} listener. ## Type Values of this type are objects. They contain the following properties: - `name` - : `string`. Name of this alarm. This is the name that was passed into the {{WebExtAPIRef('alarms.create()')}} call that created this alarm. - `scheduledTime` - : `double`. Time at which the alarm is scheduled to fire next, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time). - `periodInMinutes` {{optional_inline}} - : `double`. If this is not `null`, then the alarm is periodic, and this represents its period in minutes. ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.alarms`](https://developer.chrome.com/docs/extensions/reference/alarms/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms/clear/index.md
--- title: alarms.clear() slug: Mozilla/Add-ons/WebExtensions/API/alarms/clear page-type: webextension-api-function browser-compat: webextensions.api.alarms.clear --- {{AddonSidebar}} Cancels an alarm, given its name. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let clearAlarm = browser.alarms.clear( name // string ) ``` ### Parameters - `name` {{optional_inline}} - : `string`. The name of the alarm to clear. If you don't supply this, the empty string "" will be used. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a boolean. This will be `true` if the alarm was cleared, `false` otherwise. ## Examples ```js function onCleared(wasCleared) { console.log(wasCleared); // true/false } let clearAlarm = browser.alarms.clear("my-periodic-alarm"); clearAlarm.then(onCleared); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.alarms`](https://developer.chrome.com/docs/extensions/reference/alarms/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/alarms/getall/index.md
--- title: alarms.getAll() slug: Mozilla/Add-ons/WebExtensions/API/alarms/getAll page-type: webextension-api-function browser-compat: webextensions.api.alarms.getAll --- {{AddonSidebar}} Gets all active alarms for the extension. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let getAlarms = browser.alarms.getAll() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an array of [`Alarm`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/alarms/Alarm) objects. Each of these represents an active alarm that belongs to the extension. If no alarms are active, the array will be empty. ## Examples ```js function gotAll(alarms) { for (const alarm of alarms) { console.log(alarm.name); } } browser.alarms.getAll().then(gotAll); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.alarms`](https://developer.chrome.com/docs/extensions/reference/alarms/) API.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/index.md
--- title: browsingData slug: Mozilla/Add-ons/WebExtensions/API/browsingData page-type: webextension-api browser-compat: webextensions.api.browsingData --- {{AddonSidebar}} Enables extensions to clear the data that is accumulated while the user is browsing. In the `browsingData` API, browsing data is divided into types: - browser cache - cookies - downloads - history - local storage - plugin data - saved form data - saved passwords You can use the {{WebExtAPIRef("browsingData.remove()")}} function to remove any combination of these types. There are also dedicated functions to remove each particular type of data, such as {{WebExtAPIRef("browsingData.removePasswords()", "removePasswords()")}}, {{WebExtAPIRef("browsingData.removeHistory()", "removeHistory()")}} and so on. All the `browsingData.remove[X]()` functions take a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which you can use to control two further aspects of data removal: - how far back in time to remove data - whether to remove data only from normal web pages, or also from hosted web apps and add-ons. Note that this option is not yet supported in Firefox. Finally, this API gives you a {{WebExtAPIRef("browsingData.settings()")}} function that gives you the current value of the settings for the browser's built-in "Clear History" feature. To use this API you must have the "browsingData" [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions). ## Types - {{WebExtAPIRef("browsingData.DataTypeSet")}} - : Object used to specify the type of data to remove: for example, history, downloads, passwords, and so on. - {{WebExtAPIRef("browsingData.RemovalOptions")}} - : Object used to specify how far back in time to remove data, and whether to remove data added through normal web browsing, by hosted apps, or by add-ons. ## Methods - {{WebExtAPIRef("browsingData.remove()")}} - : Removes browsing data for the data types specified. - {{WebExtAPIRef("browsingData.removeCache()")}} - : Clears the browser's cache. - {{WebExtAPIRef("browsingData.removeCookies()")}} - : Removes cookies. - {{WebExtAPIRef("browsingData.removeDownloads()")}} - : Removes the list of downloaded files. - {{WebExtAPIRef("browsingData.removeFormData()")}} - : Clears saved form data. - {{WebExtAPIRef("browsingData.removeHistory()")}} - : Clears the browser's history. - {{WebExtAPIRef("browsingData.removeLocalStorage()")}} - : Clears any [local storage](/en-US/docs/Web/API/Window/localStorage) created by websites. - {{WebExtAPIRef("browsingData.removePasswords()")}} - : Clears saved passwords. - {{WebExtAPIRef("browsingData.removePluginData()")}} - : Clears data associated with plugins. - {{WebExtAPIRef("browsingData.settings()")}} - : Gets the current value of settings in the browser's "Clear History" feature. ## Browser compatibility {{Compat}} {{WebExtExamples("h2")}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/removehistory/index.md
--- title: browsingData.removeHistory() slug: Mozilla/Add-ons/WebExtensions/API/browsingData/removeHistory page-type: webextension-api-function browser-compat: webextensions.api.browsingData.removeHistory --- {{AddonSidebar}} Clears the record of web pages that the user has visited (browsing history). You can use the `removalOptions` parameter, which is a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, to: - clear only records of web pages visited after a given time - control whether to clear only records of normal web pages or to clear records of hosted apps and extensions as well. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.browsingData.removeHistory( removalOptions // RemovalOptions object ) ``` ### Parameters - `removalOptions` - : `object`. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which may be used to clear only records of web pages visited after a given time, and whether to clear only records of normal web pages or to clear records of hosted apps and extensions as well. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message. ## Examples Remove records of pages visited in the last week: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } function weekInMilliseconds() { return 1000 * 60 * 60 * 24 * 7; } let oneWeekAgo = new Date().getTime() - weekInMilliseconds(); browser.browsingData .removeHistory({ since: oneWeekAgo }) .then(onRemoved, onError); ``` Remove all records of visited pages: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } browser.browsingData.removeHistory({}).then(onRemoved, onError); ``` ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/removelocalstorage/index.md
--- title: browsingData.removeLocalStorage() slug: Mozilla/Add-ons/WebExtensions/API/browsingData/removeLocalStorage page-type: webextension-api-function browser-compat: webextensions.api.browsingData.removeLocalStorage --- {{AddonSidebar}} Clears any [local storage](/en-US/docs/Web/API/Window/localStorage) created by websites. You can use the `removalOptions` parameter, which is a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, to: - clear only local storage objects created after a given time - control whether to clear only local storage objects created by normal web pages or to clear objects created by hosted apps and extensions as well. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.browsingData.removeLocalStorage( removalOptions // RemovalOptions object ) ``` ### Parameters - `removalOptions` - : `object`. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which may be used to clear only local storage objects created by normal web pages or to clear objects created by hosted apps and extensions as well. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message. ## Examples Remove all local storage: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } browser.browsingData.removeLocalStorage({}).then(onRemoved, onError); ``` ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/remove/index.md
--- title: browsingData.remove() slug: Mozilla/Add-ons/WebExtensions/API/browsingData/remove page-type: webextension-api-function browser-compat: webextensions.api.browsingData.remove --- {{AddonSidebar}} Removes the specified browsing data. The browsing data to be removed is specified in the `dataTypes` option, which is a {{WebExtAPIRef("browsingData.DataTypeSet")}} object. You can use the `removalOptions` option, which is a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, to control how far back in time to remove data and whether to remove data only from normal web pages or to remove data from hosted apps and extensions as well. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.browsingData.remove( removalOptions, // RemovalOptions object dataTypes // DataTypeSet object ) ``` ### Parameters - `removalOptions` - : `object`. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which may be used to control how far back in time to remove data, and whether to remove data from hosted web apps and extensions, or just normal web pages. - `dataTypes` - : `object`. A {{WebExtAPIRef("browsingData.DataTypeSet")}} object, describing the types of data to remove (e.g. history, downloads, …). ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message. ## Examples Remove download history and browsing history for the last week: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } function weekInMilliseconds() { return 1000 * 60 * 60 * 24 * 7; } let oneWeekAgo = new Date().getTime() - weekInMilliseconds(); browser.browsingData .remove({ since: oneWeekAgo }, { downloads: true, history: true }) .then(onRemoved, onError); ``` Remove all download and browsing history: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } browser.browsingData .remove({}, { downloads: true, history: true }) .then(onRemoved, onError); ``` {{WebExtExamples}} ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/removecache/index.md
--- title: browsingData.removeCache() slug: Mozilla/Add-ons/WebExtensions/API/browsingData/removeCache page-type: webextension-api-function browser-compat: webextensions.api.browsingData.removeCache --- {{AddonSidebar}} Clears the browser's cache. Note that although this function can take a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, it will be ignored. The entire cache is always cleared when using this function. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.browsingData.removeCache( removalOptions // RemovalOptions object ) ``` ### Parameters - `removalOptions` {{optional_inline}} - : `object`. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object. This parameter has no effect. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message. ## Examples Clear the browser cache: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } browser.browsingData.removeCache({}).then(onRemoved, onError); ``` ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/settings/index.md
--- title: browsingData.settings() slug: Mozilla/Add-ons/WebExtensions/API/browsingData/settings page-type: webextension-api-property browser-compat: webextensions.api.browsingData.settings --- {{AddonSidebar}} Browsers have a built-in "Clear History" feature, which enables the user to clear various types of browsing data. This has a UI that enables the user to select what type of data to remove (e.g. history, downloads, …) and how far back in time to remove data. This function returns the current value of these settings. Note that not all data types will always be removable through the UI, and some UI options may map to more than one data type. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let getSettings = browser.browsingData.settings() ``` ### Parameters None. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an object containing the settings information. This object has three properties: - `options` - : `{{WebExtAPIRef("browsingData.RemovalOptions")}}`. A `RemovalOptions` object describing the removal options currently selected. - `dataToRemove` - : `{{WebExtAPIRef("browsingData.DataTypeSet")}}`. This will contain a property for every data type that can be toggled in the browser's UI. Each property will have a value of `true` if that type is selected for removal and `false` otherwise. - `dataRemovalPermitted` - : `{{WebExtAPIRef("browsingData.DataTypeSet")}}`. This will contain a property for every data type that can be toggled in the browser's UI. Each will have a value of `true` if the administrator of the device has allowed the user to remove that type, and `false` otherwise. If any error occurs, the promise will be rejected with an error message. ## Browser compatibility {{Compat}} ## Examples Log current settings: ```js function onGotSettings(settings) { console.log(settings.options); console.log(settings.dataToRemove); console.log(settings.dataRemovalPermitted); } function onError(error) { console.error(error); } browser.browsingData.settings().then(onGotSettings, onError); ``` {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/datatypeset/index.md
--- title: browsingData.DataTypeSet slug: Mozilla/Add-ons/WebExtensions/API/browsingData/DataTypeSet page-type: webextension-api-type browser-compat: webextensions.api.browsingData.DataTypeSet --- {{AddonSidebar}} The **`browsingData.DataTypeSet`** type describes a set of data types. It contains a number of boolean properties. The name of each property is the name of a particular type of browsing data: "downloads", "history" and so on. All properties are optional. This type is used: - in {{WebExtAPIRef("browsingData.remove()")}} to describe which data types to remove - in {{WebExtAPIRef("browsingData.settings()")}} to describe which data types are currently selected in the browser's "Clear History" feature. ## Type Values of this type are objects. They contain the following properties: - `cache` {{optional_inline}} - : `boolean`. The browser's cache. - `cookies` {{optional_inline}} - : `boolean`. Cookies acquired while browsing. - `downloads` {{optional_inline}} - : `boolean`. The user's download history. - `fileSystems` {{optional_inline}} - : `boolean`. Website's file systems. - `formData` {{optional_inline}} - : `boolean`. Saved form data, for autocomplete. - `history` {{optional_inline}} - : `boolean`. The user's browsing history. - `indexedDB` {{optional_inline}} - : `boolean`. IndexedDB data. - `localStorage` {{optional_inline}} - : `boolean`. Local storage data. - `passwords` {{optional_inline}} - : `boolean`. Saved passwords, for autocomplete. - `pluginData` {{optional_inline}} - : `boolean`. Stored data associated with plugins. - `serverBoundCertificates` {{optional_inline}} - : `boolean`. Stored server-bound certificates. - `serviceWorkers` {{optional_inline}} - : `boolean`. Data cached by service workers. ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/removeplugindata/index.md
--- title: browsingData.removePluginData() slug: Mozilla/Add-ons/WebExtensions/API/browsingData/removePluginData page-type: webextension-api-function browser-compat: webextensions.api.browsingData.removePluginData --- {{AddonSidebar}} Clears data stored by browser plugins. You can use the `removalOptions` parameter, which is a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, to: - clear only plugin data stored after a given time - control whether to clear only data stored by plugins running in normal web pages or to clear data stored by plugins running in hosted apps and extensions as well. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.browsingData.removePluginData( removalOptions // RemovalOptions object ) ``` ### Parameters - `removalOptions` - : `object`. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which may be used to clear only plugin data stored after a given time, and whether to clear only data stored by plugins running in normal web pages or to clear data stored by plugins running in hosted apps and extensions as well. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message. ## Examples Remove data stored by plugins in the last week: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } function weekInMilliseconds() { return 1000 * 60 * 60 * 24 * 7; } let oneWeekAgo = new Date().getTime() - weekInMilliseconds(); browser.browsingData .removePluginData({ since: oneWeekAgo }) .then(onRemoved, onError); ``` Remove all data stored by plugins: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } browser.browsingData.removePluginData({}).then(onRemoved, onError); ``` ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/removedownloads/index.md
--- title: browsingData.removeDownloads() slug: Mozilla/Add-ons/WebExtensions/API/browsingData/removeDownloads page-type: webextension-api-function browser-compat: webextensions.api.browsingData.removeDownloads --- {{AddonSidebar}} Clears the browser's download history. Note that this does not delete the downloaded objects themselves, only records of downloads in the browser's history. You can use the `removalOptions` parameter, which is a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, to: - clear records of items downloaded after a given time - control whether to clear only records of items downloaded from normal web pages or to clear records from hosted apps and extensions as well. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.browsingData.removeDownloads( removalOptions // RemovalOptions object ) ``` ### Parameters - `removalOptions` - : `object`. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which may be used to clear only records created after a given time, and whether to clear only records of items downloaded from normal web pages or to clear records from hosted apps and extensions as well. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message. ## Examples Remove records of objects downloaded in the last week: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } function weekInMilliseconds() { return 1000 * 60 * 60 * 24 * 7; } let oneWeekAgo = new Date().getTime() - weekInMilliseconds(); browser.browsingData .removeDownloads({ since: oneWeekAgo }) .then(onRemoved, onError); ``` Remove all records of downloaded objects: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } browser.browsingData.removeDownloads({}).then(onRemoved, onError); ``` ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/removecookies/index.md
--- title: browsingData.removeCookies() slug: Mozilla/Add-ons/WebExtensions/API/browsingData/removeCookies page-type: webextension-api-function browser-compat: webextensions.api.browsingData.removeCookies --- {{AddonSidebar}} Clears the browser's cookies. You can use the `removalOptions` parameter, which is a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, to: - clear only cookies created after a given time - control whether to clear cookies only set from normal web pages or to clear cookies set from hosted apps and extensions as well. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.browsingData.removeCookies( removalOptions // RemovalOptions object ) ``` ### Parameters - `removalOptions` - : `object`. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which may be used to clear only cookies created after a given time, and whether to clear cookies only set from normal web pages or to clear cookies set from hosted apps and extensions as well. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message. ## Examples Remove cookies created in the last week: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } function weekInMilliseconds() { return 1000 * 60 * 60 * 24 * 7; } let oneWeekAgo = new Date().getTime() - weekInMilliseconds(); browser.browsingData .removeCookies({ since: oneWeekAgo }) .then(onRemoved, onError); ``` Remove all cookies: > **Warning:** Using the API to remove all cookies will, simultaneously, clear all local storage objects (including those of other extensions). > > If you want to clear all cookies without disrupting local storage facilities, use [browser.cookies](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies) to loop through and remove the contents of all cookie stores. ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } browser.browsingData.removeCookies({}).then(onRemoved, onError); ``` ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/removeformdata/index.md
--- title: browsingData.removeFormData() slug: Mozilla/Add-ons/WebExtensions/API/browsingData/removeFormData page-type: webextension-api-function browser-compat: webextensions.api.browsingData.removeFormData --- {{AddonSidebar}} Clears data that the browser has saved for autofilling forms. You can use the `removalOptions` parameter, which is a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, to: - clear only form data entered after a given time - control whether to clear only form data entered in normal web pages or to clear data entered in hosted apps and extensions as well. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.browsingData.removeFormData( removalOptions // RemovalOptions object ) ``` ### Parameters - `removalOptions` - : `object`. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which may be used to clear only form data entered after a given time, and whether to clear only form data entered in normal web pages or to clear data entered in hosted apps and extensions as well. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message. ## Examples Remove form data saved in the last week: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } function weekInMilliseconds() { return 1000 * 60 * 60 * 24 * 7; } let oneWeekAgo = new Date().getTime() - weekInMilliseconds(); browser.browsingData .removeFormData({ since: oneWeekAgo }) .then(onRemoved, onError); ``` Remove all saved form data: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } browser.browsingData.removeFormData({}).then(onRemoved, onError); ``` ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/removaloptions/index.md
--- title: browsingData.RemovalOptions slug: Mozilla/Add-ons/WebExtensions/API/browsingData/RemovalOptions page-type: webextension-api-type browser-compat: webextensions.api.browsingData.RemovalOptions --- {{AddonSidebar}} The **`browsingData.RemovalOptions`** type contains options to control certain aspects of browsing data removal. ## Type Values of this type are objects. They contain the following properties: - `cookieStoreId` {{optional_inline}} - : `string`. This property only applies to cookies and indexedDB items. The removal is limited to items belonging to a specific [cookie store](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/CookieStore) as specified by the ID. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information. > **Note:** On Firefox Nightly removal of localStorage items by `cookieStoreId` is also supported. - `hostnames` {{optional_inline}} - : `Array` of `string`. This property applies to cookie, indexedDB, local storage, and service worker registration items. Remove only cookie, indexedDB, local storage, and service worker registration items associated with these hostnames. You must pass in just a hostname here, without protocol (for example, "google.com" not "https\://google.com"). You can use the [`URL`](/en-US/docs/Web/API/URL) interface to parse a raw URL and retrieve the hostname. Items associated with subdomains of a given hostname are _not_ removed: you must explicitly list subdomains. - `originTypes` {{optional_inline}} - : `object`. Used to control whether to remove data only from normal web pages, or also from hosted web apps and extensions. If this option is omitted, only data from normal web pages ("`unprotectedWeb`") is removed. Before removing data from web apps or extensions, be very careful to ensure that this is really what the user wants. This object may contain any of the following properties: - `unprotectedWeb` {{optional_inline}} - : `boolean`. If present and `true`, remove data from normal web pages. - `protectedWeb` {{optional_inline}} - : `boolean`. If present and `true`, remove data from websites that have been installed as hosted apps. - `extension` {{optional_inline}} - : `boolean`. If present and `true`, remove data from extensions. - `since` {{optional_inline}} - : `number`. How far back in time to remove data, given in [milliseconds since the UNIX epoch](https://en.wikipedia.org/wiki/Unix_time). Note that when removing the browser cache, the entire cache is always removed and this option is ignored. If the `since` property is omitted, it defaults to 0, which means "forever". ## Browser compatibility {{Compat}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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/browsingdata
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/browsingdata/removepasswords/index.md
--- title: browsingData.removePasswords() slug: Mozilla/Add-ons/WebExtensions/API/browsingData/removePasswords page-type: webextension-api-function browser-compat: webextensions.api.browsingData.removePasswords --- {{AddonSidebar}} Clears saved passwords. You can use the `removalOptions` parameter, which is a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, to: - clear only passwords that were saved after a given time - control whether to clear passwords that were saved on normal web pages or to clear passwords that were saved on hosted apps and extensions as well. This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). ## Syntax ```js-nolint let removing = browser.browsingData.removePasswords( removalOptions // RemovalOptions object ) ``` ### Parameters - `removalOptions` - : `object`. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which may be used to clear only passwords that were saved after a given time, and whether to clear passwords that were saved on normal web pages or to clear passwords that were saved on hosted apps and extensions as well. ### Return value A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message. ## Examples Remove passwords saved in the last week: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } function weekInMilliseconds() { return 1000 * 60 * 60 * 24 * 7; } let oneWeekAgo = new Date().getTime() - weekInMilliseconds(); browser.browsingData .removePasswords({ since: oneWeekAgo }) .then(onRemoved, onError); ``` Remove all saved passwords: ```js function onRemoved() { console.log("removed"); } function onError(error) { console.error(error); } browser.browsingData.removePasswords({}).then(onRemoved, onError); ``` ## Browser compatibility {{Compat}} {{WebExtExamples}} > **Note:** This API is based on Chromium's [`chrome.browsingData`](https://developer.chrome.com/docs/extensions/reference/browsingData/) 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
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/intercept_http_requests/index.md
--- title: Intercept HTTP requests slug: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests page-type: guide --- {{AddonSidebar}} To intercept HTTP requests, use the {{WebExtAPIRef("webRequest")}} API. This API enables you to add listeners for various stages of making an HTTP request. In the listeners, you can: - Get access to request headers and bodies and response headers. - Cancel and redirect requests. - Modify request and response headers. This article looks at three different uses for the `webRequest` module: - Logging request URLs as they are made. - Redirecting requests. - Modifying request headers. ## Logging request URLs To see how you can use `webRequest` to log requests, create a new directory called "requests". In that directory, create a file called "manifest.json" and add: ```json { "description": "Demonstrating webRequests", "manifest_version": 2, "name": "webRequest-demo", "version": "1.0", "permissions": ["webRequest", "<all_urls>"], "background": { "scripts": ["background.js"] } } ``` Next, create a file called "background.js" and add: ```js function logURL(requestDetails) { console.log(`Loading: ${requestDetails.url}`); } browser.webRequest.onBeforeRequest.addListener(logURL, { urls: ["<all_urls>"], }); ``` You use {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} to call the `logURL()` function just before starting the request. The `logURL()` function grabs the URL of the request from the event object and logs it to the browser console. The `{urls: ["<all_urls>"]}` [pattern](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) means you intercept HTTP requests to all URLs. To test it: - [Install the extension](https://extensionworkshop.com/documentation/develop/temporary-installation-in-firefox/) - Open the [Browser Console](https://firefox-source-docs.mozilla.org/devtools-user/browser_console/) (use <kbd>Ctrl + Shift + J</kbd>) - Enable _Show Content Messages_ in the menu: ![Browser console menu: Show Content Messages](browser_console_show_content_messages.png) - Open some web pages. In the Browser Console, you should see the URLs for any resources the browser requests. For example, this screenshot shows the URLs from loading a Wikipedia page: ![Browser console menu: URLs from extension](browser_console_url_from_extension.png) <!-- {{EmbedYouTube("X3rMgkRkB1Q")}} --> ## Redirecting requests Now use `webRequest` to redirect HTTP requests. First, replace "manifest.json" with this: ```json { "description": "Demonstrating webRequests", "manifest_version": 2, "name": "webRequest-demo", "version": "1.0", "permissions": [ "webRequest", "webRequestBlocking", "https://developer.mozilla.org/" ], "background": { "scripts": ["background.js"] } } ``` The changes here: - Add the `webRequestBlocking` [`permission`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). This extra permission is needed when an extension wants to modify a request. - Replace the `<all_urls>` permission with individual [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions), as this is good practice to minimize the number of requested permissions. Next, replace "background.js" with this: ```js let pattern = "https://developer.mozilla.org/*"; const targetUrl = "https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_second_WebExtension/frog.jpg"; function redirect(requestDetails) { console.log(`Redirecting: ${requestDetails.url}`); if (requestDetails.url === targetUrl) { return; } return { redirectUrl: targetUrl, }; } browser.webRequest.onBeforeRequest.addListener( redirect, { urls: [pattern], types: ["image"] }, ["blocking"], ); ``` Again, you use the {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} event listener to run a function just before each request is made. This function replaces the `redirectUrl` with the target URL specified in the function. In this case, the frog image from the [your second extension tutorial](/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_second_WebExtension). This time you are not intercepting every request: the `{urls:[pattern], types:["image"]}` option specifies that you only intercept requests (1) to URLs residing under "https\://developer.mozilla.org/" and (2) for image resources. See {{WebExtAPIRef("webRequest.RequestFilter")}} for more on this. Also, note that you're passing an option called `"blocking"`: you must pass this whenever you want to modify the request. It makes the listener function block the network request, so the browser waits for the listener to return before continuing. See the {{WebExtAPIRef("webRequest.onBeforeRequest")}} documentation for more on `"blocking"`. To test it out, open a page on MDN that contains images (for example, [the page listing extension user interface components](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface)), [reload the extension](https://extensionworkshop.com/documentation/develop/temporary-installation-in-firefox/#reloading_a_temporary_add-on), and then reload the MDN page. You see something like this: ![Images on a page replaced with a frog image](beastify_by_redirect.png) ## Modifying request headers Finally, use `webRequest` to modify request headers. In this example, you change the "User-Agent" header so the browser identifies itself as Opera 12.16, but only when visiting pages under "https\://useragentstring.com/". Update the "manifest.json" to include `https://useragentstring.com/` like this: ```json { "description": "Demonstrating webRequests", "manifest_version": 2, "name": "webRequest-demo", "version": "1.0", "permissions": [ "webRequest", "webRequestBlocking", "https://useragentstring.com/" ], "background": { "scripts": ["background.js"] } } ``` Replace "background.js" with code like this: ```js let targetPage = "https://useragentstring.com/*"; let ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16"; function rewriteUserAgentHeader(e) { e.requestHeaders.forEach((header) => { if (header.name.toLowerCase() === "user-agent") { header.value = ua; } }); return { requestHeaders: e.requestHeaders }; } browser.webRequest.onBeforeSendHeaders.addListener( rewriteUserAgentHeader, { urls: [targetPage] }, ["blocking", "requestHeaders"], ); ``` You use the {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} event listener to run a function just before the request headers are sent. The listener function is called only for requests to URLs matching the `targetPage` [pattern](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns). Also, note that you again pass `"blocking"` as an option. You also pass `"requestHeaders"`, meaning the listener is passed an array containing the request headers you expect to send. See {{WebExtAPIRef("webRequest.onBeforeSendHeaders")}} for more information on these options. The listener function looks for the "User-Agent" header in the array of request headers, replaces its value with the value of the `ua` variable, and returns the modified array. This modified array is sent to the server. To test it out, open [useragentstring.com](https://useragentstring.com/) and check that it identifies the browser as Firefox. Then reload the extension, reload [useragentstring.com](https://useragentstring.com/), and see that Firefox is now identified as Opera. ![useragentstring.com showing details of the modified user agent string](modified_request_header.png) ## Learn more To learn about all the things you can do with the `webRequest` API, see its [reference documentation](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest).
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/index.md
--- title: User interface slug: Mozilla/Add-ons/WebExtensions/user_interface page-type: guide --- {{AddonSidebar}} Extensions that use WebExtension APIs are provided with several user interface options so that their functionality can be made available to the user. A summary of those options is provided below, with a more detailed introduction to each user interface option in this section. > **Note:** For advice on using these UI components to create a great user experience in your extension, please see the [User experience best practices](https://extensionworkshop.com/documentation/develop/user-experience-best-practices/) article. <table class="standard-table"> <thead> <tr> <th scope="col">UI option</th> <th scope="col">Description</th> <th scope="col">Example</th> </tr> </thead> <tbody> <tr> <td> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button" >Toolbar button</a > (browser action) </td> <td> A button on the browser toolbar that dispatches an event to the extension when clicked. By default, the button is visible in all tabs. </td> <td> <img alt="Example showing a toolbar button (browser action)." src="browser-action.png" /> </td> </tr> <tr> <td> Toolbar button with a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups" >popup</a > </td> <td> A popup on a button in the browser toolbar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction. </td> <td> <img alt="Example of the pop-up on a toolbar button" src="popup-shadow.png" /> </td> </tr> <tr> <td> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions" >Address bar button</a > (page action) </td> <td> A button on the browser address bar that dispatches an event to the extension when clicked. By default, the button is hidden in all tabs. </td> <td> <img alt="Example showing an address bar button (page action) " src="address_bar_button.png" /> </td> </tr> <tr> <td> Address bar button with a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups" >popup</a > </td> <td> A popup on a button in the browser address bar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction. </td> <td> <img alt="Example of a popup on the address bar button" src="page_action_popup.png" /> </td> </tr> <tr> <td> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items" >Context menu item</a > </td> <td> Menu items, checkboxes, and radio buttons on one or more of the browser's context menus. Also, menus can be structured by adding separators. When menu items are clicked, an event is dispatched to the extension. </td> <td> <img alt="Example of content menu items added by a WebExtension, from the context-menu-demo example" src="context_menu_example.png" /> </td> </tr> <tr> <td> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars" >Sidebar</a > </td> <td> <p> An HTML document displayed next to a web page, with the option for unique content per page. The sidebar is opened when the extension is installed, then obeys the user's sidebar visibility selection. User interaction within the sidebar is handled by its HTML document. </p> </td> <td><img alt="Example of a sidebar" src="bookmarks-sidebar.png" /></td> </tr> <tr> <td> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages" >Options page</a > </td> <td> A page that enables you to define preferences for your extension that your users can change. The user can access this page from the browser's add-ons manager. </td> <td> <img alt="Example showing the options page content added in the favorite colors example." src="options_page.png" /> </td> </tr> <tr> <td> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages" >Extension page</a > </td> <td> Use web pages included in your extension to provide forms, help, or any other content required, within windows or tabs. </td> <td> <img alt="Example of a simple bundled page displayed as a detached panel." src="bundled_page_as_panel_small.png" /> </td> </tr> <tr> <td> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Notifications" >Notification</a > </td> <td> Transient notifications displayed to the user through the underlying operating system's notifications mechanism. Dispatches an event to the extension when the user clicks a notification, or when a notification closes (either automatically or at the user's request). </td> <td> <img alt="Example of an extension triggered system notification" src="notify-shadowed.png" /> </td> </tr> <tr> <td> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Omnibox" >Address bar suggestion</a > </td> <td> Offer custom address bar suggestions when the user enters a keyword. </td> <td> <img alt="Example showing the result of the firefox_code_search WebExtension&#x27;s customization of the address bar suggestions." src="omnibox_example_small.png" /> </td> </tr> <tr> <td> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels" >Developer tools panel</a > </td> <td> A tab with an associated HTML document that displays in the browser's developer tools. </td> <td> <img alt="Example showing the result of the firefox_code_search WebExtension&#x27;s customization of the address bar suggestions." src="developer_panel_tab.png" /> </td> </tr> </tbody> </table> The following how-to guides provide step-by-step guidance to creating some of these user interface options: - [Accessibility guidelines](https://extensionworkshop.com/documentation/develop/build-an-accessible-extension/) - [Add a button to the toolbar](/en-US/docs/Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar) - [Browser styles](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles) - [Extending the developer tools](/en-US/docs/Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools) - [Implement a settings page](/en-US/docs/Mozilla/Add-ons/WebExtensions/Implement_a_settings_page)
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/omnibox/index.md
--- title: Address bar suggestions slug: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox page-type: guide --- {{AddonSidebar}} Using the {{WebExtAPIRef("omnibox")}} API, extensions can customize the suggestions offered in the browser address bar's drop-down when the user enters a keyword. ![Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.](omnibox_example_small.png) This enables your extension to, for example, search a library of free ebooks or, as in the example above, a repository of code examples. ## Specifying the omnibox customization You tell your extension that it is going to customize the address bar suggestions by including the [omnibox](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/omnibox) key and definition of the trigger keyword in its [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file: ```json "omnibox": { "keyword" : "cs" } ``` In the extension's background JavaScript file, using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, you can optionally define the first suggestion to be displayed in the address bar drop-down. Use this to provide a hint on how to use the feature: ```js browser.omnibox.setDefaultSuggestion({ description: `Search the Firefox codebase (e.g. "hello world" | "path:omnibox.js onInputChanged")`, }); ``` You can then add the code to provide the customized content by listening for {{WebExtAPIRef("omnibox.onInputStarted")}}, which is dispatched when the user has typed the keyword and a space, and {{WebExtAPIRef("omnibox.onInputChanged")}}, which is dispatched whenever the user updates the address bar entry. You can then populate the suggestions, in this case building a [search of mozilla-central](https://searchfox.org/mozilla-central) using the term entered by the user: ```js browser.omnibox.onInputChanged.addListener((text, addSuggestions) => { let headers = new Headers({ Accept: "application/json" }); let init = { method: "GET", headers }; let url = buildSearchURL(text); let request = new Request(url, init); fetch(request).then(createSuggestionsFromResponse).then(addSuggestions); }); ``` If the extension set a default suggestion using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, then this will appear first in the drop-down. The extension can then listen for the user clicking one of the suggestions, using {{WebExtAPIRef("omnibox.onInputEntered")}}. If the default suggestion is clicked the user's custom term is returned, otherwise the suggestion's string is returned. This also passes information on the user's browser preferences for handling new links. In the code below the user's custom term is used to create a search, otherwise the suggested URL is opened: ```js browser.omnibox.onInputEntered.addListener((text, disposition) => { let url = text; if (!text.startsWith(SOURCE_URL)) { // Update the URL if the user clicks on the default suggestion. url = `${SEARCH_URL}?q=${text}`; } switch (disposition) { case "currentTab": browser.tabs.update({ url }); break; case "newForegroundTab": browser.tabs.create({ url }); break; case "newBackgroundTab": browser.tabs.create({ url, active: false }); break; } }); ``` ## Examples The [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [firefox-code-search](https://github.com/mdn/webextensions-examples/tree/main/firefox-code-search) example which customizes the search bar.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/sidebars/index.md
--- title: Sidebars slug: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars page-type: guide --- {{AddonSidebar}} A sidebar is a pane that is displayed at the side of the browser window, next to the web page. This page describes sidebars, specifying them, designing them, and examples of use. The browser provides a UI that enables the user to select a sidebar to display. For example, Firefox has the "View" > "Sidebar" menu. Each browser window can display its own sidebar, which is displayed on every tab in the window. The browser may include a number of built-in sidebars. For example, Firefox includes a sidebar for interacting with bookmarks: ![Annotator sidebar with a box allowing the user to take notes about the page.](bookmarks-sidebar.png) Using the [`sidebar_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action) manifest.json key, an extension can add its own sidebar to the browser. It will be listed alongside the built-in sidebars, and the user will be able to open it using the same mechanism as for the built-in sidebars. Like a browser action popup, the sidebar's contents are specified as an HTML document. When the user opens the sidebar, the sidebar's document is loaded into every open browser window. Each window gets its own instance of the document. When new windows are opened, they get their own sidebar documents as well. A document for a particular tab can be set using the {{WebExtAPIRef("sidebarAction.setPanel()")}} function. A sidebar can figure out which window it belongs to using the {{WebExtAPIRef("windows.getCurrent()")}} API: ```js // sidebar.js browser.windows.getCurrent({ populate: true }).then((windowInfo) => { myWindowId = windowInfo.id; }); ``` This is useful if a sidebar wants to display different content for different windows. For an example of this, see the ["annotate-page" example](https://github.com/mdn/webextensions-examples/tree/main/annotate-page). Sidebar documents get access to the same set of privileged JavaScript APIs that the extension's background and popup scripts get. They can get direct access to the background page (unless the sidebar belongs to an incognito mode window) using {{WebExtAPIRef("runtime.getBackgroundPage()")}}, and can interact with content scripts or native applications using messaging APIs like {{WebExtAPIRef("tabs.sendMessage()")}} and {{WebExtAPIRef("runtime.sendNativeMessage()")}}. Sidebar documents are unloaded when their browser window is closed or when the user closes the sidebar. This means that unlike background pages, sidebar documents don't stay loaded all the time, but unlike browser action popups, they stay loaded while the user interacts with web pages. When an extension that defines a sidebar is first installed, its sidebar will be opened automatically. This is intended to help the user understand that the extension includes a sidebar. Note that it's not possible for an extension to open sidebars programmatically: sidebars can only be opened by the user. ## Specifying sidebars To specify a sidebar, define the default document with the [`sidebar_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action) manifest.json key, alongside a default title and icon: ```json "sidebar_action": { "default_title": "My sidebar", "default_panel": "sidebar.html", "default_icon": "sidebar_icon.png" } ``` The title, panel, and icon can be changed programmatically using the {{WebExtAPIRef("sidebarAction")}} API. Title and icon are shown to the user in any UI provided by the browser to list sidebars, such as the "View > Sidebar" menu in Firefox. ## Sidebar design For details on how to design a sidebar's web page to match the style of Firefox, see the [Acorn Design System](https://acorn.firefox.com/latest/) documentation. ## Example The [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [annotate-page](https://github.com/mdn/webextensions-examples/tree/main/annotate-page) example which implements a sidebar.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/extension_pages/index.md
--- title: Extension pages slug: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages page-type: guide --- {{AddonSidebar}} You can include HTML pages in your extension to provide forms, help, or any other content your extension needs. ![Example of a simple bundled page displayed as a detached panel.](bundled_page_as_panel_small.png) These pages also get access to the same privileged JavaScript APIs that are available to your extension's background scripts. However, they are in their own tab, with their own JavaScript event queue, their own globals, etc. Think of the background page as a "hidden extension page". ## Specifying extension pages You can include HTML files—and associated CSS or JavaScript files—in your extension. The files can be included in the root or organized within meaningful sub-folders. ```plain /my-extension /manifest.json /my-page.html /my-page.js ``` ## Displaying extension pages There are two options for displaying extension pages: {{WebExtAPIRef("windows.create()")}} and {{WebExtAPIRef("tabs.create()")}}. Using `windows.create()`, for example, you can open an HTML page into a detached panel (a window without the normal browser UI of address bar, bookmark bar, and alike) to create a dialog-like user experience: ```js let createData = { type: "detached_panel", url: "my-page.html", width: 250, height: 100, }; let creating = browser.windows.create(createData); ``` When the window is no longer needed, it can be closed programmatically. For example, after the user clicks a button, you may pass the current window's id to {{WebExtAPIRef("windows.remove()")}}: ```js document.getElementById("closeme").addEventListener("click", () => { let winId = browser.windows.WINDOW_ID_CURRENT; let removing = browser.windows.remove(winId); }); ``` ## Extension pages and history By default, pages you open in this way will be stored in the user's history, just like normal web pages. If you don't want to have this behavior, use {{WebExtAPIRef("history.deleteUrl()")}} to remove the browser's record: ```js function onVisited(historyItem) { if (historyItem.url === browser.extension.getURL(myPage)) { browser.history.deleteUrl({ url: historyItem.url }); } } browser.history.onVisited.addListener(onVisited); ``` To use the history API, you must request the "`history`" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) in your [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file. ## Web page design For details on how to design your web page's to match the style of Firefox, see the [Acorn Design System](https://acorn.firefox.com/latest/). ## Examples The [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [window-manipulator](https://github.com/mdn/webextensions-examples/tree/main/window-manipulator) example, which implements several of the options for creating windows.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/options_pages/index.md
--- title: Options page slug: Mozilla/Add-ons/WebExtensions/user_interface/Options_pages page-type: guide --- {{AddonSidebar}} An Options page enables you to define preferences for your extension that your users can change. Users can access the options page for an extension from the browser's add-ons manager: {{EmbedYouTube("eODy24csH5M")}} The way users access the page, and the way it's integrated into the browser's user interface, will vary from one browser to another. You can open the page programmatically by calling [`runtime.openOptionsPage()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/openOptionsPage). Options pages have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of [`eval()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). See [Content Security Policy](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy) for more details. ## Specifying the options page To create an options page, write an HTML file defining the page. This page can include CSS and JavaScript files, like a normal web page. This page, from the [favourite-color](https://github.com/mdn/webextensions-examples/tree/main/favourite-colour) example, includes a JavaScript file: ```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> </head> <body> <form> <label for="color">Favorite color</label> <input type="text" id="color" name="color" /> <button type="submit">Save</button> </form> <script src="options.js"></script> </body> </html> ``` JavaScript running in the page can use all the [WebExtension APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/API) that the add-on has [permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) for. In particular, you can use the [`storage`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage) API to persist preferences. Package the page's files in your extension. You also need to include the [`options_ui`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui) key in your manifest.json file, giving it the URL to the page. ```json "options_ui": { "page": "options.html" }, ``` See the [`options_ui`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui) page for **sharing options** between your options page and background or content scripts. ## Options content design For details on how to design your options content to match the style of Firefox, see the [Acorn Design System](https://acorn.firefox.com/latest/). ## Examples The [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [favourite-color](https://github.com/mdn/webextensions-examples/tree/main/favourite-colour) example which implements options page features.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.md
--- title: Context menu items slug: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items page-type: guide --- {{AddonSidebar}} This user interface option adds one or more items to a browser context menu. This is the menu available when a user right-clicks on a web page. Tabs and bookmarks can also have context menus, available through the {{WebExtAPIRef("menus")}} API. ![Example of content menu items added by a WebExtension, from the context-menu-demo example](context_menu_example.png) You use this option to expose features relevant to specific browser or web page contexts. For example, you can show features to open a graphic editor when the user clicks on an image or offer a feature to save page content when part of a page is selected. You can add plain menu items, checkbox items, radio button groups, and separators to menus. Once a context menu item has been added using {{WebExtAPIRef("menus.create")}} it's displayed in all browser tabs, but you can hide it by removing it with {{WebExtAPIRef("menus.remove")}}. The full list of supported contexts is available at {{WebExtAPIRef("menus.ContextType")}} and includes contexts outside of a web page, such as bookmark items in the browser UI. For example, the "[Open bookmark in Container Tab](https://github.com/Rob--W/bookmark-container-tab)" extension adds a menu item that allows the user to open a bookmark URL in a new container tab. ![A context menu with "open in new container tab" submenu highlighted. The submenu shows personal, work, banking, shopping, and Facebook contextual identities. There is an option at the top of the submenu to select no container.](extension_context_menu.png) You can also override the context menus displayed in extension pages, such as custom sidebars and popups, to use either the tab or bookmark context menus instead of the default context menu, with {{WebExtAPIRef("menus.overrideContext")}}. This is a helpful method when your extension provides a custom presentation of tabs or bookmarks. The menu automatically includes menu items for any other extensions that have defined tab or bookmark context menu items. You can choose whether to include the default context menu items. Hiding the default items gives the extension complete control over the items displayed in the rendered native context menu, as shown in the image below for the Tree Style Tab extension. ![A tab context menu displayed for a tab item in the sidebar of the Tree Style Tab extension. The menu shows custom tab actions, a menu item for the extension, and a menu item for the Simple Tab Group extension.](custom_sidebar_tab_menu.png) ## Specifying context menu items You manage context menu items programmatically, using the {{WebExtAPIRef("contextMenus")}} API. However, you need to request the `contextMenus` permission in your manifest.json to be able to take advantage of the API. ```json "permissions": ["contextMenus"] ``` You can then add (and update or delete) the context menu items in your extension's background script. To create a menu item you specify an id, its title, and the context menus it should appear on: ```js browser.contextMenus.create( { id: "log-selection", title: browser.i18n.getMessage("contextMenuItemSelectionLogger"), contexts: ["selection"], }, onCreated, ); ``` Your extension then listens for clicks on the menu items. The passed information about the item clicked, the context where the click happened, and details of the tab where the click took place can then be used to invoke the appropriate extension functionality. ```js browser.contextMenus.onClicked.addListener((info, tab) => { switch (info.menuItemId) { case "log-selection": console.log(info.selectionText); break; // … } }); ``` ## Icons For details on how to create icons to use with your context menu, see [Iconography](https://acorn.firefox.com/latest/styles/iconography-q7JqGl5H) in the [Acorn Design System](https://acorn.firefox.com/latest/) documentation. ## Examples The [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub contains two examples of extensions that implement context menu items: - [menu-demo](https://github.com/mdn/webextensions-examples/tree/main/menu-demo) adds several items to the browser's context menu. - [context-menu-copy-link-with-types](https://github.com/mdn/webextensions-examples/tree/main/context-menu-copy-link-with-types) adds a context menu item to links that copies the link URL to the clipboard, as plain text and rich HTML.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.md
--- title: devtools panels slug: Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels page-type: guide --- {{AddonSidebar}} > **Note:** This feature is available since Firefox 54. When an extension provides tools that are of use to developers, it's possible to add a UI for them to the browser's developer tools as a new panel. ![Simple example showing the addition of "My panel" to the Developer Tools tabs.](developer_panel_tab.png) ## Specifying a developer tools panel A developer tools panel is added using the [`devtools.panels`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/panels) API, which in turn needs to be run from a special devtools page. Add the devtools page by including the [`devtools_page`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page) key in extension's [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) and provide the location of the page's HTML file in the extension: ```json "devtools_page": "devtools-page.html" ``` From the devtools page, call a script that will add the devtools panel: ```html <body> <script src="devtools.js"></script> </body> ``` In the script, create the devtools panel by specifying the panel's title, icon, and HTML file that provides the panel's content: ```js function handleShown() { console.log("panel is being shown"); } function handleHidden() { console.log("panel is being hidden"); } browser.devtools.panels .create( "My Panel", // title "icons/star.png", // icon "devtools/panel/panel.html", // content ) .then((newPanel) => { newPanel.onShown.addListener(handleShown); newPanel.onHidden.addListener(handleHidden); }); ``` The extension can now run code in the inspected window using [`devtools.inspectedWindow.eval()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/inspectedWindow/eval) or by injecting a content script via the background script by passing a message. You can find more details on how to do this in [Extending the developer tools.](/en-US/docs/Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools) ## Developer panel design For details on how to design your developer panel's web page to match the style of Firefox, see the [Acorn Design System](https://acorn.firefox.com/latest/) documentation. ## Icons For details on how to create icons to use with your developer tools panel, see [Iconography](https://acorn.firefox.com/latest/styles/iconography-q7JqGl5H) in the [Acorn Design System](https://acorn.firefox.com/latest/) documentation. ## Examples The [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [devtools-panels](https://github.com/mdn/webextensions-examples/tree/main/devtools-panels) example which implements a devtools panel.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/popups/index.md
--- title: Popups slug: Mozilla/Add-ons/WebExtensions/user_interface/Popups page-type: guide --- {{AddonSidebar}} A popup is a dialog that's associated with a [toolbar button](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button) or [address bar button](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions). This page describes popups in general, specifying them, debugging, resizing, and designing them, as well as examples of use. ![Page action pop-up example with three options: kittens, puppies, and reset.](page_action_popup.png) When the user clicks the button, the popup is shown. When the user clicks anywhere outside the popup, the popup is closed. The popup can be closed programmatically by calling [`window.close()`](/en-US/docs/Web/API/Window/close) from a script running in the popup. However, you can't open the popup programmatically from an extension's JavaScript; it can be opened only in response to a user action. You can define a keyboard shortcut that opens the popup using the `"_execute_browser_action"` and `"_execute_page_action"` shortcuts in Manifest V2 and `"_execute_action"`and, where supported, `"_execute_page_action"` shortcuts in Manifest V3. See the documentation for the special shortcuts in manifest.json key [`commands`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/commands#special_shortcuts). ## Specifying a popup The popup is specified as an HTML file, which can include CSS and JavaScript files, as a normal web page does. Unlike a normal page, though, the JavaScript can use all the [WebExtension APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/API) that the extension has [permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) for. The popup's document is loaded every time the popup is shown, and unloaded every time the popup is closed. The HTML file is included in the extension and specified as part of the [`browser_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) or [`page_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action) key by `"default_popup"` in the manifest.json: ```json "browser_action": { "default_icon": "icons/beasts-32.png", "default_title": "Beastify", "default_popup": "popup/choose_beast.html" } ``` Popups have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of [`eval()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). See [Content Security Policy](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy) for more details on this. ## Debugging popups You can debug a popup's markup and JavaScript using the Add-on Debugger, but you'll need to turn on the Disable popup auto-hide feature to prevent popups from hiding when you click outside them. [Read about debugging popups](https://extensionworkshop.com/documentation/develop/debugging/#debugging_popups). ## Popup resizing Popups resize automatically to fit their content. The algorithm for this may differ from one browser to another. In Firefox, the size is calculated just before the popup is shown, and at most 10 times per second after DOM mutations. For strict mode documents, the size is calculated based on the layout size of the [`<body>`](/en-US/docs/Web/HTML/Element/body) element. For quirks mode, it's the [`<html>`](/en-US/docs/Web/HTML/Element/html) element. Firefox calculates the preferred width of the contents of that element, reflows it to that width, and then resizes so there's no vertical scrolling. It will grow to a size of **800x600 pixels** at most if that fits on the user's screen. (Prior to Firefox 60 [it was only 680px](https://bugzil.la/1434177).) If the user [moves the extension's button to the menu](https://support.mozilla.org/en-US/kb/customize-firefox-controls-buttons-and-toolbars#w_customize-the-menu-or-the-toolbar) or it appears in the toolbar overflow, then the popup appears inside the menu's panel and is given a fixed width. When setting the popup `width` in CSS, you should set the it in the [`<body>`](/en-US/docs/Web/HTML/Element/body) and not in the `:root`. In Firefox Android 57, the popup is shown as a normal page in a new tab. ## Popup design For details on how to design your popup's web page to match the style of Firefox, see the [Acorn Design System](https://acorn.firefox.com/latest/). ## Examples The [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [beastify](https://github.com/mdn/webextensions-examples/tree/main/beastify) example, which implements a browser action with a popup.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/browser_styles/index.md
--- title: Browser styles slug: Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles page-type: guide browser-compat: - webextensions.manifest.action - webextensions.manifest.browser_action - webextensions.manifest.page_action - webextensions.manifest.sidebar_action - webextensions.manifest.options_ui --- {{AddonSidebar}} Your extension can include user interface elements - browser and page action [popups](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups), [sidebars](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars), and [options pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages) - that are specified by: 1. creating an HTML file defining the structure of the UI element. 2. adding a manifest.json key ([`action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/action), [`browser_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action), [`page_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action), [`sidebar_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action), or [`options_ui`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui)) pointing to that HTML file. You can style these elements to match the browser's style. The manifest.json keys include an optional property to help with this: `browser_style`. If this is included and set to `true`, your document gets one or more extra stylesheets that help make it look consistent with the browser's UI and with other extensions that use the `browser_style` property. > **Note:** > Support for `browser_style` in Manifest V3 is deprecated. Starting from Firefox 115, the default value of `options_ui.browser_style` and `sidebar_action.browser_style` changes from `true` to `false`. In Firefox 118, `"browser_style": true` will no longer be supported in Manifest V3 extensions. > If your Manifest V3 extension depends on the `"browser_style": true` styles, follow the [Manifest V3 migration guide for `browser_style`](#manifest_v3_migration). > See ([Firefox bug 1827910](https://bugzil.la/1827910)) for more information. > If you want to apply the Firefox style to your extension, see the [Firefox Style Guide](https://acorn.firefox.com/latest/). When considering whether to use `browser_style: true`, test your extension with various themes (built-in or from AMO) to ensure that the extension UI behaves the way you expect it to. > **Warning:** When `browser_style: true` is included in your web extension's manifest, text selection in your extension's UI is disabled except in input controls. If this causes a problem, include `browser_style:false` instead. > **Note:** **Google Chrome** and **Opera** use `chrome_style` instead of `browser_style` in Manifest V2. So for cross-browser extensions you need to add both keys. `chrome_style` is not available in Manifest V3. In Firefox, the stylesheet can be seen at `chrome://browser/content/extension.css`. The extra stylesheet at `chrome://browser/content/extension-mac.css` is also included on macOS. Most styles are automatically applied, but some elements require you to add the non-standard `browser-style` class to get their styling, as detailed in the table below: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Element</th> <th scope="col">Example</th> </tr> </thead> <tbody> <tr> <td> <code ><a href="/en-US/docs/Web/HTML/Element/button">&#x3C;button></a></code > </td> <td> <pre class="brush: html"> &#x3C;button class="browser-style">Click me&#x3C;/button></pre > </td> </tr> <tr> <td> <p> <code ><a href="/en-US/docs/Web/HTML/Element/select" >&#x3C;select></a ></code > </p> </td> <td> <pre class="brush: html"> &#x3C;select class="browser-style" name="select"> &#x3C;option value="value1">Value 1&#x3C;/option> &#x3C;option value="value2" selected>Value 2&#x3C;/option> &#x3C;option value="value3">Value 3&#x3C;/option> &#x3C;/select></pre > </td> </tr> <tr> <td> <code ><a href="/en-US/docs/Web/HTML/Element/textarea" >&#x3C;textarea></a ></code > </td> <td> <pre class="brush: html"> &#x3C;textarea class="browser-style">Write here&#x3C;/textarea></pre > </td> </tr> <tr> <td> Parent of an <code ><a href="/en-US/docs/Web/HTML/Element/input">&#x3C;input></a></code > </td> <td> <pre class="brush: html"> &#x3C;div class="browser-style"> &#x3C;input type="radio" id="op1" name="choices" value="op1"/> &#x3C;label for="op1">Option 1&#x3C;/label> &#x3C;input type="radio" id="op2" name="choices" value="op2"/> &#x3C;label for="op2">Option 2&#x3C;/label> &#x3C;/div></pre > </td> </tr> </tbody> </table> ## Manifest V3 migration As `browser_style` is a deprecated in Manifest V3 you may want to remove support when you migrate your Manifest V2 extensions. Using `options_ui`, as an example, you would you take these steps to remove support for `browser_style`: - Set `options_ui/browser_style` to `false`. - Does the appearance of your extensions UI change? - If the appearance doesn't change, remove the key. - If the appearance changes, experiment to determine what dependency exist and add the relevant properties in the extension's stylesheet. The styles are most likely to cause layout changes are `box-sizing:`, `border-box`, and `display: flex`. If you cannot identify the dependencies, include the content of [extension.css](https://hg.mozilla.org/mozilla-central/raw-file/a445f1762c895000bcdabd9d95697522359d41ed/browser/components/extensions/extension.css) with the extension and delete all parts that aren't relevant, usually the `body` and `body *` blocks as most extensions don't use the `browser-style` class. ## Firefox panel components (legacy) > **Note:** This feature is non-standard and only works in Firefox. The `chrome://browser/content/extension.css` stylesheet also contains the styles for the legacy Firefox panel components (navigation components). The [legacy Firefox Style Guide](https://firefoxux.github.io/StyleGuide/#/navigation) documents proper usage. <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Element</th> <th scope="col">Example</th> </tr> </thead> <tbody> <tr> <td>Header</td> <td> <pre class="brush: html"> &#x3C;header class="panel-section panel-section-header"> &#x3C;div class="icon-section-header">&#x3C;img src="image.svg"/>&#x3C;/div> &#x3C;div class="text-section-header">Header&#x3C;/div> &#x3C;/header></pre > </td> </tr> <tr> <td>Footer</td> <td> <pre class="brush: html"> &#x3C;footer class="panel-section panel-section-footer"> &#x3C;button class="panel-section-footer-button">Cancel&#x3C;/button> &#x3C;div class="panel-section-footer-separator">&#x3C;/div> &#x3C;button class="panel-section-footer-button default">Confirm&#x3C;/button> &#x3C;/footer></pre > </td> </tr> <tr> <td>Tabs</td> <td> <pre class="brush: html"> &#x3C;div class="panel-section panel-section-tabs"> &#x3C;button class="panel-section-tabs-button selected">Tab&#x3C;/button> &#x3C;div class="panel-section-tabs-separator">&#x3C;/div> &#x3C;button class="panel-section-tabs-button">Tab&#x3C;/button> &#x3C;div class="panel-section-tabs-separator">&#x3C;/div> &#x3C;button class="panel-section-tabs-button">Tab&#x3C;/button> &#x3C;/div></pre > </td> </tr> <tr> <td>Form</td> <td> <pre class="brush: html"> &#x3C;div class="panel-section panel-section-formElements"> &#x3C;div class="panel-formElements-item"> &#x3C;label for="name01">Label:&#x3C;/label> &#x3C;input type="text" value="Name" id="name01" /> &#x3C;/div> &#x3C;div class="panel-formElements-item"> &#x3C;label for="picker01">Label:&#x3C;/label> &#x3C;select id="picker01"> &#x3C;option value="value1" selected="true">Dropdown&#x3C;/option> &#x3C;option value="value2">List Item&#x3C;/option> &#x3C;option value="value3">List Item&#x3C;/option> &#x3C;/select> &#x3C;/div> &#x3C;div class="panel-formElements-item"> &#x3C;label for="placeholder01">Label:&#x3C;/label> &#x3C;input type="text" placeholder="Placeholder" id="placeholder01" /> &#x3C;button name="expander" class="expander">&#x3C;/button> &#x3C;/div> &#x3C;/div></pre > </td> </tr> <tr> <td>Menu</td> <td> <pre class="brush: html"> &#x3C;div class="panel-section panel-section-list"> &#x3C;div class="panel-list-item"> &#x3C;div class="icon">&#x3C;/div> &#x3C;div class="text">List Item&#x3C;/div> &#x3C;div class="text-shortcut">Ctrl-L&#x3C;/div> &#x3C;/div> &#x3C;div class="panel-list-item"> &#x3C;div class="icon">&#x3C;/div> &#x3C;div class="text">List Item&#x3C;/div> &#x3C;div class="text-shortcut">&#x3C;/div> &#x3C;/div> &#x3C;div class="panel-section-separator">&#x3C;/div> &#x3C;div class="panel-list-item disabled"> &#x3C;div class="icon">&#x3C;/div> &#x3C;div class="text">Disabled List Item&#x3C;/div> &#x3C;div class="text-shortcut">&#x3C;/div> &#x3C;/div> &#x3C;div class="panel-section-separator">&#x3C;/div> &#x3C;div class="panel-list-item"> &#x3C;div class="icon">&#x3C;/div> &#x3C;div class="text">List Item&#x3C;/div> &#x3C;div class="text-shortcut">&#x3C;/div> &#x3C;/div> &#x3C;div class="panel-list-item"> &#x3C;div class="icon">&#x3C;/div> &#x3C;div class="text">List Item&#x3C;/div> &#x3C;div class="text-shortcut">&#x3C;/div> &#x3C;/div> &#x3C;/div></pre > </td> </tr> </tbody> </table> ### Example #### HTML ```html <header class="panel-section panel-section-header"> <div class="icon-section-header"><!-- An image goes here. --></div> <div class="text-section-header">Header</div> </header> <div class="panel-section panel-section-list"> <div class="panel-list-item"> <div class="icon"></div> <div class="text">List Item</div> <div class="text-shortcut">Ctrl-L</div> </div> <div class="panel-list-item"> <div class="icon"></div> <div class="text">List Item</div> <div class="text-shortcut"></div> </div> <div class="panel-section-separator"></div> <div class="panel-list-item disabled"> <div class="icon"></div> <div class="text">Disabled List Item</div> <div class="text-shortcut"></div> </div> <div class="panel-section-separator"></div> <div class="panel-list-item"> <div class="icon"></div> <div class="text">List Item</div> <div class="text-shortcut"></div> </div> <div class="panel-list-item"> <div class="icon"></div> <div class="text">List Item</div> <div class="text-shortcut"></div> </div> </div> <footer class="panel-section panel-section-footer"> <button class="panel-section-footer-button">Cancel</button> <div class="panel-section-footer-separator"></div> <button class="panel-section-footer-button default">Confirm</button> </footer> ``` ```css hidden /* Global */ html, body { background: white; box-sizing: border-box; color: #222426; cursor: default; display: flex; flex-direction: column; font: caption; margin: 0; padding: 0; -moz-user-select: none; } body * { box-sizing: border-box; text-align: start; } button.panel-section-footer-button, button.panel-section-tabs-button { color: inherit; background-color: unset; font: inherit; text-shadow: inherit; appearance: none; border: none; } /* Panel Section */ .panel-section { display: flex; flex-direction: row; } .panel-section-separator { background-color: rgba(0, 0, 0, 0.15); min-height: 1px; } /* Panel Section - Header */ .panel-section-header { border-bottom: 1px solid rgba(0, 0, 0, 0.15); padding: 16px; } .panel-section-header > .icon-section-header { background-position: center center; background-repeat: no-repeat; height: 32px; margin-right: 16px; position: relative; width: 32px; } .panel-section-header > .text-section-header { align-self: center; font-size: 1.385em; font-weight: lighter; } /* Panel Section - List */ .panel-section-list { flex-direction: column; padding: 4px 0; } .panel-list-item { align-items: center; display: flex; flex-direction: row; height: 24px; padding: 0 16px; } .panel-list-item:not(.disabled):hover { background-color: rgba(0, 0, 0, 0.06); border-bottom: 1px solid rgba(0, 0, 0, 0.1); border-top: 1px solid rgba(0, 0, 0, 0.1); } .panel-list-item:not(.disabled):hover:active { background-color: rgba(0, 0, 0, 0.1); } .panel-list-item.disabled { color: #999; } .panel-list-item > .icon { flex-grow: 0; flex-shrink: 0; } .panel-list-item > .text { flex-grow: 10; } .panel-list-item > .text-shortcut { color: #808080; font-family: "Lucida Grande", caption; font-size: 0.847em; justify-content: flex-end; } .panel-section-list .panel-section-separator { margin: 4px 0; } /* Panel Section - Footer */ .panel-section-footer { background-color: rgba(0, 0, 0, 0.06); border-top: 1px solid rgba(0, 0, 0, 0.15); color: #1a1a1a; display: flex; flex-direction: row; height: 41px; margin-top: -1px; padding: 0; } .panel-section-footer-button { flex: 1 1 auto; height: 100%; margin: 0 -1px; padding: 12px; text-align: center; } .panel-section-footer-button > .text-shortcut { color: #808080; font-family: "Lucida Grande", caption; font-size: 0.847em; } .panel-section-footer-button:hover { background-color: rgba(0, 0, 0, 0.06); } .panel-section-footer-button:hover:active { background-color: rgba(0, 0, 0, 0.1); } .panel-section-footer-button.default { background-color: #0996f8; box-shadow: 0 1px 0 #0670cc inset; color: #fff; } .panel-section-footer-button.default:hover { background-color: #0670cc; box-shadow: 0 1px 0 #005bab inset; } .panel-section-footer-button.default:hover:active { background-color: #005bab; box-shadow: 0 1px 0 #004480 inset; } .panel-section-footer-separator { background-color: rgba(0, 0, 0, 0.1); width: 1px; z-index: 99; } ``` ```css hidden /* Example specific – not part of chrome://browser/content/extension.css */ body { background: #fcfcfc; background-clip: padding-box; border: 1px solid rgba(24, 26, 27, 0.2); box-shadow: 0 3px 5px rgba(24, 26, 27, 0.1), 0 0 7px rgba(24, 26, 27, 0.1); box-sizing: content-box; margin: 2em auto 0.5em; width: 384px; } html { min-height: 100vh; } html > body { margin: auto; } .icon-section-header { background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgdmlld0JveD0iMCAwIDMyIDMyIj48Y2lyY2xlIGZpbGw9IiMzNjM5NTkiIGN4PSIxNSIgY3k9IjE1IiByPSIxNSIvPjwvc3ZnPg=="); } ``` #### Result {{EmbedLiveSample("Example","640","360")}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/page_actions/index.md
--- title: Address bar button slug: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions page-type: guide --- {{AddonSidebar}} Commonly referred to as a [page action](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction) button, this user interface option is a button added to the browser address bar. Users click the button to interact with extensions. ![Page action button is an icon of a dog paw print](address_bar_button.png) ## Page actions and browser actions The address bar button (or page action) is similar to the toolbar button (or browser action). The differences are: - **The button's location:** - The page action is displayed inside the browser address bar. - The browser action is displayed outside the address bar, in the browser toolbar. - **The button's visibility:** - The page action is hidden by default (although this default can be changed via the `show_matches` and `hide_matches` [manifest key](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action) properties), and you call [`pageAction.show()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction/show) and [`pageAction.hide()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction/hide) to show or hide it in specific tabs. - The browser action is always displayed. Use a page action when the action relates to the current page. Use a browser action when the action relates to the browser as a whole or to many pages. For example: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="row">Type</th> <th scope="col">Bookmarks action</th> <th scope="col">Content action</th> <th scope="col">Tabs operation</th> </tr> </thead> <tbody> <tr> <th scope="row">page action</th> <td>Bookmark this page</td> <td>Reddit enhancement</td> <td>Send tab</td> </tr> <tr> <th scope="row">browser action</th> <td>Show all bookmarks</td> <td>Enable ad-blocking</td> <td>Sync all open tabs</td> </tr> </tbody> </table> ## Specifying the page action You define the page action's properties using the [`page_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action) key in manifest.json: ```json "page_action": { "default_icon": { "19": "button/geo-19.png", "38": "button/geo-38.png" }, "default_title": "Whereami?" } ``` The only mandatory key is `default_icon`. There are two ways to specify a page action: with or without a [popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups). - **Without a popup:** When the user clicks the button, an event is dispatched to the extension, which the extension listens for using [`pageAction.onClicked`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction/onClicked): ```js browser.pageAction.onClicked.addListener(handleClick); ``` - **With a popup:** the `click` event is not dispatched. Instead, the popup appears when the user clicks the button. The user then interacts with the popup. When the user clicks outside of the popup, it closes automatically. See the [Popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups) article for more details on creating and managing popups. Note that your extension can have just one page action. You can change any of the page action properties programmatically using the [`pageAction`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction) API. ## Icons For details on how to create icons to use with your page action, see [Iconography](https://acorn.firefox.com/latest/styles/iconography-q7JqGl5H) in the [Acorn Design System](https://acorn.firefox.com/latest/) documentation. ## Examples The [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [chill-out](https://github.com/mdn/webextensions-examples/tree/main/chill-out) example which implements a page action without a popup.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/toolbar_button/index.md
--- title: Toolbar button slug: Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button page-type: guide --- {{AddonSidebar}} Commonly referred to as a [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction), this user interface option is a button added to the browser toolbar. Users click the button to interact with your extension. ![A custom browser action icon it the browser tool bar that looks like paw print.](toolbar_button.png) The toolbar button (browser action) is very like the address bar button (page action). For the differences, and guidance on when to use what, see [Page actions and browser actions](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions#page_actions_and_browser_actions). ## Specifying the browser action You define the browser action's properties using the [`"browser_action"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) key in manifest.json: ```json "browser_action": { "default_icon": { "19": "button/geo-19.png", "38": "button/geo-38.png" }, "default_title": "Whereami?" } ``` There are no mandatory properties for this key. If you don't specify `"default_icon"` the extension icon is used, and the default web extension puzzle pace icon is used if the extension doesn't specify an icon. If `"default_title"` isn't specified, the extension name is used. There are two ways to specify a browser action: with or without a [popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups). If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using [`browserAction.onClicked`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction/onClicked): ```js browser.browserAction.onClicked.addListener(handleClick); ``` If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user can interact with the popup, which closes automatically when the user clicks outside it. See the [Popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups) article for more details on creating and managing popups. Note that your extension can have only one browser action. You can change many of the browser action properties programmatically using the [`browserAction`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction) API. ## Icons For details on how to create icons to use with your browser action, see [Iconography](https://acorn.firefox.com/latest/styles/iconography-q7JqGl5H) in the [Acorn Design System](https://acorn.firefox.com/latest/) documentation. ## Examples The [`webextensions-examples`](https://github.com/mdn/webextensions-examples) repository on GitHub contains two examples of extensions that implement browser actions: - [bookmark-it](https://github.com/mdn/webextensions-examples/tree/main/bookmark-it) uses a browser action without a popup - [beastify](https://github.com/mdn/webextensions-examples/tree/main/beastify) uses a browser action with a popup
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/notifications/index.md
--- title: Notifications slug: Mozilla/Add-ons/WebExtensions/user_interface/Notifications page-type: guide --- {{AddonSidebar}} Notifications allow you to communicate information about your extension or its content using the underlying operating system's notification service. ![Click notification in the top right corner of the browser window.](notify-shadowed.png) Notifications can include a call to action for the user, and your add-on can listen for the user clicking the notification or the notification closing. ## Specifying notifications You manage notifications programmatically, using the {{WebExtAPIRef("notifications")}} API. To use this API you must request the `notifications` permission in your manifest.json: ```json "permissions": ["notifications"] ``` You then use {{WebExtAPIRef("notifications.create")}} to create your notifications, as in this example from [notify-link-clicks-i18n:](https://github.com/mdn/webextensions-examples/tree/main/notify-link-clicks-i18n) ```js const title = browser.i18n.getMessage("notificationTitle"); const content = browser.i18n.getMessage("notificationContent", message.url); browser.notifications.create({ type: "basic", iconUrl: browser.extension.getURL("icons/link-48.png"), title, message: content, }); ``` This code creates a notification with an icon, title, and message. If the notification includes a call to action, you can listen for the user clicking the notification to call the function to handle the action: ```js browser.notifications.onClicked.addListener(handleClick); ``` If you are issuing calls to action through notifications, you will also want to define the optional notification `id`, so you can figure out which call to action the user has selected. ## Icons For details on how to create icons to use with your notification, see [Iconography](https://acorn.firefox.com/latest/styles/iconography-q7JqGl5H) in the [Acorn Design System](https://acorn.firefox.com/latest/) documentation. ## Examples The [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [notify-link-clicks-i18n](https://github.com/mdn/webextensions-examples/tree/main/notify-link-clicks-i18n) example which implements notifications.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/native_manifests/index.md
--- title: Native manifests slug: Mozilla/Add-ons/WebExtensions/Native_manifests page-type: guide --- {{AddonSidebar}} Native manifests are specially formatted JSON files that are provisioned on the user's computer by some means outside the extension installation process. For example, a native manifest might be provisioned by a device administrator or by a native application installer. There are three different types of native manifest: <table class="standard-table"> <tbody> <tr> <td> <a href="#native_messaging_manifests">Native messaging manifests</a> </td> <td> Enable a feature called <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging" >native messaging</a >, in which an extension can communicate with a native app installed on the device. </td> </tr> <tr> <td> <a href="#managed_storage_manifests">Managed storage manifests</a> </td> <td> Define read-only data that an extension can access using the {{WebExtAPIRef("storage.managed")}} API. </td> </tr> <tr> <td><a href="#pkcs_11_manifests">PKCS #11 manifests</a></td> <td> Enable an extension to use the {{WebExtAPIRef("pkcs11")}} API to enumerate PKCS #11 security modules and install them in Firefox. </td> </tr> </tbody> </table> For all native manifests, you need to arrange things so the browser can find the manifest. The section on [manifest location](#manifest_location) describes these rules. ## Native messaging manifests The native messaging manifest contains a single JSON object with the following properties: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>name</code></td> <td>String</td> <td> <p>Name of the native application.</p> <p> This must match the name passed into {{WebExtAPIRef("runtime.connectNative()")}} or {{WebExtAPIRef("runtime.sendNativeMessage()")}} by the extension. </p> <p> On MacOS and Linux, it must also match the native messaging manifest's filename (excluding the <code>.json</code> extension). </p> <p> On Windows, it must match the name of the registry key you create, that contains the location of the native messaging manifest. </p> <p> The name must match the following regular expression: <code>"^\w+(\.\w+)*$"</code>. This means that it may only contain (lowercase or uppercase) alphanumeric characters, underscores, and dots. It may not start or end with a dot, and a dot cannot be followed by another dot. </p> </td> </tr> <tr> <td><code>description</code></td> <td>String</td> <td>Description of the native application.</td> </tr> <tr> <td><code>path</code></td> <td>String</td> <td> <p>Path to the native application.</p> <p> On Windows, this may be relative to the manifest itself. On MacOS and Linux it must be absolute. </p> </td> </tr> <tr> <td><code>type</code></td> <td>String</td> <td> <p>Describes the method used to connect the extension with the app.</p> <p> Currently, only one value can be given here, <code>"stdio"</code>, which indicates that messages are received by the app using standard input (<code>stdin</code>) and sent using standard output (<code>stdout</code>). </p> </td> </tr> <tr> <td><code>allowed_extensions</code></td> <td>Array of String</td> <td> <p> An array of <a href="https://extensionworkshop.com/documentation/develop/extensions-and-the-add-on-id/" >Add-on ID</a > values. Each value represents an extension which is allowed to communicate with this native application. </p> <p> Note that this means you will probably want to include the <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings" >browser_specific_settings</a ></code > key in your extension's <code>manifest.json</code> file, so you can set an explicit ID during development. </p> </td> </tr> </tbody> </table> For example, here's a manifest for the `ping_pong` native application: ```json { "name": "ping_pong", "description": "Example host for native messaging", "path": "/path/to/native-messaging/app/ping_pong.py", "type": "stdio", "allowed_extensions": ["[email protected]"] } ``` This allows the extension whose ID is `[email protected]` to connect, by passing the name `ping_pong` into the relevant {{WebExtAPIRef("runtime")}} API function. The application itself is at `/path/to/native-messaging/app/ping_pong.py`. ## Managed storage manifests The managed storage manifest contains a single JSON object with the following properties: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>name</code></td> <td>String</td> <td> <p> The ID of the extension that can access this storage, given as the ID you've specified in the extension's <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings" >browser_specific_settings</a ></code > key. </p> </td> </tr> <tr> <td><code>description</code></td> <td>String</td> <td>Human-readable description, ignored by Firefox.</td> </tr> <tr> <td><code>type</code></td> <td>String</td> <td> <p>This must be <code>"storage"</code>.</p> </td> </tr> <tr> <td><code>data</code></td> <td>Object</td> <td> <p> A JSON object that may contain any valid JSON values, including strings, numbers, booleans, arrays, or objects. This will become the data in the <code>browser.storage.managed</code> storage area. </p> </td> </tr> </tbody> </table> For example: ```json { "name": "[email protected]", "description": "ignored", "type": "storage", "data": { "color": "management thinks it should be blue!" } } ``` Given this JSON manifest, the `[email protected]` extension could access the data using code like this: ```js let storageItem = browser.storage.managed.get("color"); storageItem.then((res) => { console.log(`Managed color is: ${res.color}`); }); ``` ## PKCS #11 manifests The PKCS #11 manifest is a file containing a JSON object with the following properties: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>name</code></td> <td>String</td> <td> <p>Name of the PKCS #11 module.</p> <p>This must match the name used in the <code>pkcs11</code> API.</p> <p> On MacOS and Linux, it must also match the manifest's filename (excluding the extension). </p> <p> On Windows, it must match the name of the registry key you create, which contains the location of the manifest. </p> <p> The name must match the following regular expression: <code>"^\w+(\.\w+)*$"</code>. This means that it may only contain lowercase alphanumeric characters, underscores and dots. It may not start or end with a dot, and a dot cannot be followed by another dot. </p> </td> </tr> <tr> <td><code>description</code></td> <td>String</td> <td> <p>Description of the module.</p> <p> This is used to set the friendly name for the module in the browser's UI (for example, the "Security Devices" dialog in Firefox). </p> </td> </tr> <tr> <td><code>path</code></td> <td>String</td> <td> <p>Path to the module.</p> <p> On Windows, this may be relative to the manifest itself. On MacOS and Linux it must be absolute. </p> </td> </tr> <tr> <td><code>type</code></td> <td>String</td> <td>This must be <code>"pkcs11"</code>.</td> </tr> <tr> <td><code>allowed_extensions</code></td> <td>Array of String</td> <td> <p> An array of <a href="https://extensionworkshop.com/documentation/develop/extensions-and-the-add-on-id/" >Add-on ID</a > values. Each value represents an extension which is allowed to interact with the module. </p> <div class="notecard note"> <p> <strong>Note:</strong> This means you will probably want to include the <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings" >browser_specific_settings</a ></code > key in your extension's <code>manifest.json</code> file, so you can set an explicit ID during development. </p> </div> </td> </tr> </tbody> </table> For example: ```json { "name": "my_module", "description": "My test module", "type": "pkcs11", "path": "/path/to/libpkcs11testmodule.dylib", "allowed_extensions": ["[email protected]"] } ``` Given this JSON manifest, saved as `my_module.json`, the `[email protected]` extension could install the security module at `/path/to/libpkcs11testmodule.dylib` using code like this: ```js browser.pkcs11.installModule("my_module"); ``` ## Manifest location On Linux and macOS, you need to store the manifest in a particular place. On Windows, you need to create a registry key that points to the manifest's location. The detailed rules are the same for all the manifest types, except that the penultimate component of the path identifies the type of manifest. The examples below show the form for each of the three different types. In all the examples, `<name>` is the value of the `name` property in the manifest. ### Windows For global visibility, create a registry key with the following name: ```plain HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\NativeMessagingHosts\<name> ``` ```plain HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\ManagedStorage\<name> ``` ```plain HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\PKCS11Modules\<name> ``` The key should have a single default value, which is the path to the manifest. > **Warning:** As of Firefox 64, the 32-bit registry view [Wow6432Node](https://en.wikipedia.org/wiki/WoW64#Registry_and_file_system) will be checked first for these keys, followed by the "native" registry view. Use whichever is appropriate for your application. > > **For Firefox 63 and older:** This key should _not_ be created under [Wow6432Node](https://en.wikipedia.org/wiki/WoW64#Registry_and_file_system), even if the app is 32-bit. Previous versions of the browser will always look for the key under the "native" view of the registry, not the 32-bit emulation. To ensure that the key is created in the "native" view, you can pass the `KEY_WOW64_64KEY` or `KEY_WOW64_32KEY` flags into `RegCreateKeyEx`. See [Accessing an Alternate Registry View](https://docs.microsoft.com/windows/win32/winprog64/accessing-an-alternate-registry-view). For per-user visibility, create a registry key with the following name: ```plain HKEY_CURRENT_USER\SOFTWARE\Mozilla\NativeMessagingHosts\<name> ``` ```plain HKEY_CURRENT_USER\SOFTWARE\Mozilla\ManagedStorage\<name> ``` ```plain HKEY_CURRENT_USER\SOFTWARE\Mozilla\PKCS11Modules\<name> ``` The key should have a single default value, which is the path to the manifest. ### macOS For global visibility, store the manifest in: ```plain /Library/Application Support/Mozilla/NativeMessagingHosts/<name>.json ``` ```plain /Library/Application Support/Mozilla/ManagedStorage/<name>.json ``` ```plain /Library/Application Support/Mozilla/PKCS11Modules/<name>.json ``` For per-user visibility, store the manifest in: ```plain ~/Library/Application Support/Mozilla/NativeMessagingHosts/<name>.json ``` ```plain ~/Library/Application Support/Mozilla/ManagedStorage/<name>.json ``` ```plain ~/Library/Application Support/Mozilla/PKCS11Modules/<name>.json ``` ### Linux For global visibility, store the manifest in either: ```plain /usr/lib/mozilla/native-messaging-hosts/<name>.json ``` ```plain /usr/lib/mozilla/managed-storage/<name>.json ``` ```plain /usr/lib/mozilla/pkcs11-modules/<name>.json ``` or: ```plain /usr/lib64/mozilla/native-messaging-hosts/<name>.json ``` ```plain /usr/lib64/mozilla/managed-storage/<name>.json ``` ```plain /usr/lib64/mozilla/pkcs11-modules/<name>.json ``` For per-user visibility, store the manifest in: ```plain ~/.mozilla/native-messaging-hosts/<name>.json ``` ```plain ~/.mozilla/managed-storage/<name>.json ``` ```plain ~/.mozilla/pkcs11-modules/<name>.json ```
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/working_with_the_tabs_api/index.md
--- title: Work with the Tabs API slug: Mozilla/Add-ons/WebExtensions/Working_with_the_Tabs_API page-type: guide --- {{AddonSidebar}} Tabs let a user open several web pages in their browser window and then switch between those web pages. With the Tabs API, you can work with and manipulate these tabs to create utilities that provide users with new ways to work with tabs or to deliver the features of your extension. In this how-to article we'll look at: - Permissions needed to use the Tabs API. - Discovering more about tabs and their properties using {{WebExtAPIRef("tabs.query")}}. - Creating, duplicating, moving, updating, reloading, and removing tabs. - Manipulating a tab's zoom level. - Manipulating a tab's CSS. We then conclude by looking at some other, miscellaneous features offered by the API. > **Note:** There are some Tab API features covered elsewhere. These are the methods you can use to manipulate tab content with scripts ({{WebExtAPIRef("tabs.connect")}}, {{WebExtAPIRef("tabs.sendMessage")}}, and {{WebExtAPIRef("tabs.executeScript")}}). If you want more information on these methods, see the Concepts article [Content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) and the how-to guide [Modify a web page](/en-US/docs/Mozilla/Add-ons/WebExtensions/Modify_a_web_page). ## Permissions and the Tabs API For the majority of the Tabs API functions you don't need any permissions; however, there are some exceptions: - `"tabs"` permission is needed to access the `Tab.url`, `Tab.title`, and `Tab.favIconUrl` properties of the Tab object. In Firefox, you also need `"tabs"` to perform a [query](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query) by URL. - [Host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) is needed for {{WebExtAPIRef("tabs.executeScript()")}} or {{WebExtAPIRef("tabs.insertCSS()")}}. The following is how you might request `"tabs"` permission in your extension's manifest.json file: ```json "permissions": [ "<all_urls>", "tabs" ], ``` This request gives you use of all Tabs API feature on all website your user visits. There is also an alternative approach for requesting permissions to use {{WebExtAPIRef("tabs.executeScript()")}} or {{WebExtAPIRef("tabs.insertCSS()")}} where you don't need host permission, in the form of [`"activeTab"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission). This permission provides the same rights as `"tabs"` with `<all_urls>`, but with two restrictions: - the user must interact with the extension through its browser or page action, context menu, or shortcut key. - it only grants permission within the active tab. The benefit of this approach is the user won't get a permissions warning saying your extension can "Access your data for all websites". This is because `<all_urls>` permission gives an extension the ability to execute scripts in any tab, any time it likes, whereas [`"activeTab"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission) is limited to allowing the extension to perform a user requested action in the current tab. ## Discovering more about tabs and their properties There will be occasions when you want to get a list of all the tabs in all the browser windows. Other times you might want to find a subset of tabs that match some specific criteria, such as those opened from a specific tab or displaying pages from a particular domain. And once you have your list of tabs, you'll probably want to know more about their properties. This is where {{WebExtAPIRef("tabs.query()")}} comes in. Used alone to get all tabs or taking the `queryInfo` object—to specify query criteria such as whether the tab is active, in the current window, or one or more of 17 criteria—{{WebExtAPIRef("tabs.query()")}} returns an array of {{WebExtAPIRef("tabs.Tab")}} objects containing information about the tabs. Where you want information about the current tab only, you can get a {{WebExtAPIRef("tabs.Tab")}} object for that tab using {{WebExtAPIRef("tabs.getCurrent()")}}. If you have a tab's ID, you can get its {{WebExtAPIRef("tabs.Tab")}} object using {{WebExtAPIRef("tabs.get()")}}. ### How to example To see how {{WebExtAPIRef("tabs.query()")}} and {{WebExtAPIRef("tabs.Tab")}} are used, let's walk through how the [tabs-tabs-tabs](https://github.com/mdn/webextensions-examples/tree/main/tabs-tabs-tabs) example adds the list of "switch to tabs" to its toolbar button popup. ![The tabs toolbar menu showing the switch to tap area](switch_to_tab.png) - manifest.json - : Here is the [`manifest.json`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/manifest.json): ```json { "browser_action": { "default_title": "Tabs, tabs, tabs", "default_popup": "tabs.html" }, "description": "A list of methods you can perform on a tab.", "homepage_url": "https://github.com/mdn/webextensions-examples/tree/main/tabs-tabs-tabs", "manifest_version": 2, "name": "Tabs, tabs, tabs", "permissions": ["tabs"], "version": "1.0" } ``` > **Note:** > > - **`tabs.html` is defined as the `default_popup` in `browser_action`.** It is displayed whenever the user clicks the extension's toolbar icon. > - **Permissions includes tabs.** This is needed to support the tab list feature, as the extension reads the title of the tabs for display in the popup. - tabs.html - : `tabs.html` defines the content of the extension's popup: ```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="tabs.css" /> </head> <body> <div class="panel"> <div class="panel-section panel-section-header"> <div class="text-section-header">Tabs-tabs-tabs</div> </div> <a href="#" id="tabs-move-beginning"> Move active tab to the beginning of the window </a> <br /> <!-- Define the other menu items --> <div class="switch-tabs"> <p>Switch to tab</p> <div id="tabs-list"></div> </div> </div> <script src="tabs.js"></script> </body> </html> ``` This does the following: 1. The menu items are declared. 2. An empty `div` with the ID `tabs-list` is declared to contain the list of tabs. 3. `tabs.js` is called. - tabs.js - : In [`tabs.js`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/tabs.js), we'll see how the list of tabs is built and added to the popup. #### Creating the popup First, an event handler is added to execute `listTabs()` when `tabs.html` is loaded: ```js document.addEventListener("DOMContentLoaded", listTabs); ``` The first thing that `listTabs()` does is to call `getCurrentWindowTabs()`. This is where {{WebExtAPIRef("tabs.query()")}} is used to get a {{WebExtAPIRef("tabs.Tab")}} object for the tabs in the current window: ```js function getCurrentWindowTabs() { return browser.tabs.query({ currentWindow: true }); } ``` Now, `listTabs()` is ready to create the content for the popup. To start with: 1. Grab the `<div id="tabs-list">` element. 2. Create a document fragment (into which the list will be built). 3. Set counters. 4. Clear the content of the `<div id="tabs-list">` element. ```js function listTabs() { getCurrentWindowTabs().then((tabs) => { const tabsList = document.getElementById('tabs-list'); const currentTabs = document.createDocumentFragment(); const limit = 5; let counter = 0; tabsList.textContent = ''; ``` Next, we'll create the links for each tab: 1. Loops through the first 5 items from the {{WebExtAPIRef("tabs.Tab")}} object. 2. For each item, add a hyperlink to the document fragment. - The link's label—that is, its text—is set using the tab's `title` (or the `id`, if it has no `title`). - The link's address is set using the tab's `id`. ```js for (const tab of tabs) { if (!tab.active && counter <= limit) { const tabLink = document.createElement("a"); tabLink.textContent = tab.title || tab.id; tabLink.setAttribute("href", tab.id); tabLink.classList.add("switch-tabs"); currentTabs.appendChild(tabLink); } counter += 1; } ``` Finally, the document fragment is written to the `<div id="tabs-list">` element: ```js tabsList.appendChild(currentTabs); }); } ``` #### Working with the active tab Another related example feature is the "Alert active tab" info option that dumps all the {{WebExtAPIRef("tabs.Tab")}} object properties for the active tab into an alert: ```js else if (e.target.id === "tabs-alertinfo") { callOnActiveTab((tab) => { let props = ""; for (const item in tab) { props += `${ item } = ${ tab[item] } \n`; } alert(props); }); } ``` Where `callOnActiveTab()` finds the active tab object by looping through the {{WebExtAPIRef("tabs.Tab")}} objects looking for the item with active set: ```js document.addEventListener("click", (e) => { function callOnActiveTab(callback) { getCurrentWindowTabs().then((tabs) => { for (const tab of tabs) { if (tab.active) { callback(tab, tabs); } } }); } } ``` ## Creating, duplicating, moving, updating, reloading, and removing tabs Having gathered information about the tabs you'll most likely want to do something with them—either to offer users features for manipulating and managing tabs or to implement functionality in your extension. The following functions are available: - create a new tab ({{WebExtAPIRef("tabs.create()")}}). - duplicate a tab ({{WebExtAPIRef("tabs.duplicate()")}}). - remove a tab ({{WebExtAPIRef("tabs.remove()")}}). - move a tab ({{WebExtAPIRef("tabs.move()")}}). - update the tab's URL—effectively browse to a new page—({{WebExtAPIRef("tabs.update()")}}). - reload the tab's page ({{WebExtAPIRef("tabs.reload()")}}). > **Note:** These functions all require the ID (or IDs) of the tab they are manipulating: > > - {{WebExtAPIRef("tabs.duplicate()")}} > - {{WebExtAPIRef("tabs.remove()")}} > - {{WebExtAPIRef("tabs.move()")}} > > Whereas the following functions will act on the active tab (if no tab `id` is provided): > > - {{WebExtAPIRef("tabs.update()")}} > - {{WebExtAPIRef("tabs.reload()")}} ### How to example The [tabs-tabs-tabs](https://github.com/mdn/webextensions-examples/tree/main/tabs-tabs-tabs) example exercises all of these features except for updating a tab's URL The way in which these APIs are used is similar, so we'll look at one of the more involved implementations, that of the "Move active tab to the beginning of the window list" option. But first, here is a demonstration of the feature in action: {{EmbedYouTube("-lJRzTIvhxo")}} - manifest.json - : None of the functions require a permission to operate, so there are no features in the [manifest.json](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/manifest.json) file that need to be highlighted. - tabs.html - : [`tabs.html`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/tabs.html) defines the "menu" displayed in the popup, which includes the "Move active tab to the beginning of the window list" option, with a series of `<a>` tags grouped by a visual separator. Each menu item is given an `id`, which is used in `tabs.js` to determine which menu item is being requested. ```html <a href="#" id="tabs-move-beginning"> Move active tab to the beginning of the window </a> <br /> <a href="#" id="tabs-move-end">Move active tab to the end of the window</a> <br /> <div class="panel-section-separator"></div> <a href="#" id="tabs-duplicate">Duplicate active tab</a><br /> <a href="#" id="tabs-reload">Reload active tab</a><br /> <a href="#" id="tabs-alertinfo">Alert active tab info</a><br /> ``` - tabs.js - : To implement the "menu" defined in `tabs.html`, [`tabs.js`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/tabs.js) includes a listener for clicks in `tabs.html`: ```js document.addEventListener("click", (e) => { function callOnActiveTab(callback) { getCurrentWindowTabs().then((tabs) => { for (const tab of tabs) { if (tab.active) { callback(tab, tabs); } } }); } }); ``` A series of `if` statements then look to match the `id` of the item clicked. This code snippet is for the "Move active tab to the beginning of the window list" option: ```js if (e.target.id === "tabs-move-beginning") { callOnActiveTab((tab, tabs) => { let index = 0; if (!tab.pinned) { index = firstUnpinnedTab(tabs); } console.log(`moving ${tab.id} to ${index}`); browser.tabs.move([tab.id], { index }); }); } ``` It's worth noting the use of `console.log()`. This enables you to output information to the [debugger](https://extensionworkshop.com/documentation/develop/debugging/) console, which can be useful when resolving issues found during development. ![Example of the console.log output, from the move tabs feature, in the debugging console](console.png) The move code first calls `callOnActiveTab()` which in turn calls `getCurrentWindowTabs()` to get a {{WebExtAPIRef("tabs.Tab")}} object containing the active window's tabs. It then loops through the object to find and return the active tab object: ```js function callOnActiveTab(callback) { getCurrentWindowTabs().then((tabs) => { for (const tab of tabs) { if (tab.active) { callback(tab, tabs); } } }); } ``` #### Pinned tabs A feature of tabs is that the user can _pin_ tabs in a window. Pinned tabs are placed at the start of the tab list and cannot be moved. This means that the earliest position a tab can move to is the first position after any pinned tabs. So, `firstUnpinnedTab()` is called to find the position of the first unpinned tab by looping through the `tabs` object: ```js function firstUnpinnedTab(tabs) { for (const tab of tabs) { if (!tab.pinned) { return tab.index; } } } ``` We now have everything needed to move the tab: the active tab object from which we can get the tab `id` and the position the tab is to be moved to. So, we can implement the move: ```js browser.tabs.move([tab.id], { index }); ``` The remaining functions to duplicate, reload, create, and remove tabs are implemented similarly. ## Manipulating a tab's zoom level The next set of functions enable you to get ({{WebExtAPIRef("tabs.getZoom")}}) and set ({{WebExtAPIRef("tabs.setZoom")}}) the zoom level within a tab. You can also retrieve the zoom settings ({{WebExtAPIRef("tabs.getZoomSettings")}}) but, at the time of writing, the ability to set the settings ({{WebExtAPIRef("tabs.setZoomSettings")}}) wasn't available in Firefox. The level of zoom can be between 30% and 500% (represented as decimals `0.3` to `5`). In Firefox the default zoom settings are: - **default zoom level:** 100%. - **zoom mode:** automatic (so the browser manages how zoom levels are set). - **scope of zoom changes:** `"per-origin"`, meaning that when you visit a site again, it takes the zoom level set in your last visit. ### How to example The [tabs-tabs-tabs](https://github.com/mdn/webextensions-examples/tree/main/tabs-tabs-tabs) example includes three demonstrations of the zoom feature: zoom in, zoom out, and reset zoom. Here is the feature in action: {{EmbedYouTube("RFr3oYBCg28")}} Let's take a look at how the zoom in is implemented. - manifest.json - : None of the zoom functions require permissions, so there are no features in the [manifest.json](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/manifest.json) file that need to be highlighted. - tabs.html - : We have already discussed how the [`tabs.html`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/tabs.html) defines the options for this extension, nothing new or unique is done to provide the zoom options. - tabs.js - : [`tabs.js`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/tabs.js) starts by defining several constants used in the zoom code: ```js const ZOOM_INCREMENT = 0.2; const MAX_ZOOM = 5; const MIN_ZOOM = 0.3; const DEFAULT_ZOOM = 1; ``` It then uses the same listener we discussed earlier so it can act on clicks in `tabs.html`. For the zoom in feature, this runs: ```js else if (e.target.id === "tabs-add-zoom") { callOnActiveTab((tab) => { browser.tabs.getZoom(tab.id).then((zoomFactor) => { //the maximum zoomFactor is 5, it can't go higher if (zoomFactor >= MAX_ZOOM) { alert("Tab zoom factor is already at max!"); } else { let newZoomFactor = zoomFactor + ZOOM_INCREMENT; //if the newZoomFactor is set to higher than the max accepted //it won't change, and will never alert that it's at maximum newZoomFactor = newZoomFactor > MAX_ZOOM ? MAX_ZOOM : newZoomFactor; browser.tabs.setZoom(tab.id, newZoomFactor); } }); }); } ``` This code uses `callOnActiveTab()` to get the details of the active tab, then {{WebExtAPIRef("tabs.getZoom")}} gets the tab's current zoom factor. The current zoom is compared to the defined maximum (`MAX_ZOOM`) and an alert issued if the tab is already at the maximum zoom. Otherwise, the zoom level is incremented but limited to the maximum zoom, then the zoom is set with {{WebExtAPIRef("tabs.getZoom")}}. ## Manipulating a tab's CSS Another significant capability offered by the Tabs API is the ability to manipulate the CSS within a tab—add new CSS to a tab ({{WebExtAPIRef("tabs.insertCSS()")}}) or remove CSS from a tab ({{WebExtAPIRef("tabs.removeCSS()")}}). This can be useful, for example, if you want to highlight certain page elements or change the default layout of the page. ### How to example The [apply-css](https://github.com/mdn/webextensions-examples/tree/main/apply-css) example uses these features to add a red border to the web page in the active tab. Here is the feature in action: {{EmbedYouTube("bcK-GT2Dyhs")}} Let's walk through how it's set up. - manifest.json - : The [`manifest.json`](https://github.com/mdn/webextensions-examples/blob/main/apply-css/manifest.json) requests permissions required to use the CSS features. You need either: - `"tabs"` permission and [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions); or, - `"activeTab"` permission. The latter is the most useful, as it allows an extension to use {{WebExtAPIRef("tabs.insertCSS()")}} and {{WebExtAPIRef("tabs.removeCSS()")}} in the active tab when run from the extension's browser or page action, context menu, or a shortcut. ```json { "description": "Adds a page action to toggle applying CSS to pages.", "manifest_version": 2, "name": "apply-css", "version": "1.0", "homepage_url": "https://github.com/mdn/webextensions-examples/tree/main/apply-css", "background": { "scripts": ["background.js"] }, "page_action": { "default_icon": "icons/off.svg" }, "permissions": ["activeTab", "tabs"] } ``` You will note that `"tabs"` permission is requested in addition to `"activeTab"`. This additional permission is needed to enable the extension's script to access the tab's URL, the importance of which we'll see in a moment. The other main features in the manifest.json file are the definition of: - **a background script**, which starts running as soon as the extension is loaded. - **a "page action"**, which defines an icon to be added to the browser's address bar. - background.js - : On startup, [`background.js`](https://github.com/mdn/webextensions-examples/blob/main/apply-css/background.js) sets some constants to define the CSS to be applied, titles for the "page action", and a list of protocols the extension will work in: ```js const CSS = "body { border: 20px solid red; }"; const TITLE_APPLY = "Apply CSS"; const TITLE_REMOVE = "Remove CSS"; const APPLICABLE_PROTOCOLS = ["http:", "https:"]; ``` When first loaded, the extension uses {{WebExtAPIRef("tabs.query()")}} to get a list of all the tabs in the current browser window. It then loops through the tabs calling `initializePageAction()`. ```js browser.tabs.query({}).then((tabs) => { for (const tab of tabs) { initializePageAction(tab); } }); ``` `initializePageAction` uses `protocolIsApplicable()` to determine whether the active tab's URL is one the CSS can be applied to: ```js function protocolIsApplicable(url) { const anchor = document.createElement("a"); anchor.href = url; return APPLICABLE_PROTOCOLS.includes(anchor.protocol); } ``` Then, if the example can act on the tab, `initializePageAction()` sets the tab's `pageAction` (navigation bar) icon and title to use the "off" versions before making the `pageAction` visible: ```js function initializePageAction(tab) { if (protocolIsApplicable(tab.url)) { browser.pageAction.setIcon({ tabId: tab.id, path: "icons/off.svg" }); browser.pageAction.setTitle({ tabId: tab.id, title: TITLE_APPLY }); browser.pageAction.show(tab.id); } } ``` Next, a listener on `pageAction.onClicked` waits for the `pageAction` icon to be clicked, and calls `toggleCSS` when it is. ```js browser.pageAction.onClicked.addListener(toggleCSS); ``` `toggleCSS()` gets the title of the `pageAction` and then takes the action described: - **For "Apply CSS":** - toggles the `pageAction` icon and title to the "remove" versions. - applies the CSS using {{WebExtAPIRef("tabs.insertCSS()")}}. - **For "Remove CSS":** - toggles the `pageAction` icon and title to the "apply" versions. - removes the CSS using {{WebExtAPIRef("tabs.removeCSS()")}}. ```js function toggleCSS(tab) { function gotTitle(title) { if (title === TITLE_APPLY) { browser.pageAction.setIcon({ tabId: tab.id, path: "icons/on.svg" }); browser.pageAction.setTitle({ tabId: tab.id, title: TITLE_REMOVE }); browser.tabs.insertCSS({ code: CSS }); } else { browser.pageAction.setIcon({ tabId: tab.id, path: "icons/off.svg" }); browser.pageAction.setTitle({ tabId: tab.id, title: TITLE_APPLY }); browser.tabs.removeCSS({ code: CSS }); } } browser.pageAction.getTitle({ tabId: tab.id }).then(gotTitle); } ``` Finally, to ensure that the `pageAction` is valid after each update to the tab, a listener on {{WebExtAPIRef("tabs.onUpdated")}} calls `initializePageAction()` each time the tab is updated to check that the tab is still using a protocol to which the CSS can be applied. ```js browser.tabs.onUpdated.addListener((id, changeInfo, tab) => { initializePageAction(tab); }); ``` ## Some other interesting abilities There are a couple of other Tabs API features that don't fit into one of the earlier sections: - Capture the visible tab content with {{WebExtAPIRef("tabs.captureVisibleTab")}}. - Detect the primary language of the content in a tab using {{WebExtAPIRef("tabs.detectLanguage")}}. This could be used, for example, to match the language in your extension's UI with that of the page it's running in. ## Learn more If you want to learn more about the Tabs API, check out: - [Tabs API reference](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs) - [Example extensions](/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples) (many of which use the Tabs API)
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/match_patterns/index.md
--- title: Match patterns slug: Mozilla/Add-ons/WebExtensions/Match_patterns page-type: guide browser-compat: webextensions.match_patterns.scheme --- {{AddonSidebar}} Match patterns are a way to specify groups of URLs: a match pattern matches a specific set of URLs. They are used in WebExtensions APIs in a few places, most notably to specify which documents to load [content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) into, and to specify which URLs to add [`webRequest`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest) listeners to. APIs that use match patterns usually accept a list of match patterns, and will perform the appropriate action if the URL matches any of the patterns. See, for example, the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key in manifest.json. ## Match pattern structure > **Note:** Some browsers don't support certain schemes. > Check the [Browser compatibility table](#browser_compatibility) for details. All match patterns are specified as strings. Apart from the special [`<all_urls>`](#all_urls) pattern, match patterns consist of three parts: _scheme_, _host_, and _path_. The scheme and host are separated by `://`. ```plain <scheme>://<host><path> ``` ### scheme The _scheme_ component may take one of two forms: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Form</th> <th scope="col">Matches</th> </tr> </thead> <tbody> <tr> <td><code>*</code></td> <td> Only "http" and "https" and in some browsers also <a href="/en-US/docs/Web/API/WebSockets_API">"ws" and "wss"</a>. </td> </tr> <tr> <td> One of <code>http</code>, <code>https</code>, <code>ws</code>, <code>wss</code>, <code>ftp</code>, <code>data</code>, <code>file</code>, or <code>(chrome-)extension</code>. </td> <td>Only the given scheme.</td> </tr> </tbody> </table> ### host The _host_ component may take one of three forms: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Form</th> <th scope="col">Matches</th> </tr> </thead> <tbody> <tr> <td><code>*</code></td> <td>Any host.</td> </tr> <tr> <td><code>*.</code> followed by part of the hostname.</td> <td>The given host and any of its subdomains.</td> </tr> <tr> <td>A complete hostname, without wildcards.</td> <td>Only the given host.</td> </tr> </tbody> </table> _host_ must not include a port number. _host_ is optional only if the _scheme_ is "file". Note that the wildcard may only appear at the start. ### path The _path_ component must begin with a `/`. After that, it may subsequently contain any combination of the `*` wildcard and any of the characters that are allowed in URL paths or query strings. Unlike _host_, the _path_ component may contain the `*` wildcard in the middle or at the end, and the `*` wildcard may appear more than once. The value for the _path_ matches against the string which is the URL path plus the [URL query string](https://en.wikipedia.org/wiki/Query_string). This includes the `?` between the two, if the query string is present in the URL. For example, if you want to match URLs on any domain where the URL path ends with `foo.bar`, then you need to use an array of Match Patterns like `['*://*/*foo.bar', '*://*/*foo.bar?*']`. The `?*` is needed, rather than just `bar*`, in order to anchor the ending `*` as applying to the URL query string and not some portion of the URL path. Neither the [URL fragment identifier](https://en.wikipedia.org/wiki/Fragment_identifier), nor the `#` which precedes it, are considered as part of the _path_. > **Note:** The path pattern string should not include a port number. Adding a port, as in: `http://localhost:1234/*` causes the match pattern to be ignored. However, `http://localhost:1234` will match with `http://localhost/*`. ### \<all_urls> The special value `<all_urls>` matches all URLs under any of the supported schemes: that is "http", "https", "ws", "wss", "ftp", "data", and "file". ## Examples <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Pattern</th> <th scope="col">Example matches</th> <th scope="col">Example non-matches</th> </tr> </thead> <tbody> <tr> <td> <p><code>&#x3C;all_urls></code></p> <p>Match all URLs.</p> </td> <td> <p><code>http://example.org/</code></p> <p><code>https://a.org/some/path/</code></p> <p><code>ws://sockets.somewhere.org/</code></p> <p><code>wss://ws.example.com/stuff/</code></p> <p><code>ftp://files.somewhere.org/</code></p> </td> <td> <p><code>resource://a/b/c/</code><br />(unsupported scheme)</p> <p> <code>ftps://files.somewhere.org/</code><br />(unsupported scheme) </p> </td> </tr> <tr> <td> <p><code>*://*/*</code></p> <p>Match all HTTP, HTTPS and WebSocket URLs.</p> </td> <td> <p><code>http://example.org/</code></p> <p><code>https://a.org/some/path/</code></p> <p><code>ws://sockets.somewhere.org/</code></p> <p><code>wss://ws.example.com/stuff/</code></p> </td> <td> <p><code>ftp://ftp.example.org/</code><br />(unmatched scheme)</p> <p><code>file:///a/</code><br />(unmatched scheme)</p> </td> </tr> <tr> <td> <p><code>*://*.mozilla.org/*</code></p> <p> Match all HTTP, HTTPS and WebSocket URLs that are hosted at "mozilla.org" or one of its subdomains. </p> </td> <td> <p><code>http://mozilla.org/</code></p> <p><code>https://mozilla.org/</code></p> <p><code>http://a.mozilla.org/</code></p> <p><code>http://a.b.mozilla.org/</code></p> <p><code>https://b.mozilla.org/path/</code></p> <p><code>ws://ws.mozilla.org/</code></p> <p><code>wss://secure.mozilla.org/something</code></p> </td> <td> <p><code>ftp://mozilla.org/</code><br />(unmatched scheme)</p> <p><code>http://mozilla.com/</code><br />(unmatched host)</p> <p><code>http://firefox.org/</code><br />(unmatched host)</p> </td> </tr> <tr> <td> <p><code>*://mozilla.org/</code></p> <p> Match all HTTP, HTTPS and WebSocket URLs that are hosted at exactly "mozilla.org/". </p> </td> <td> <p><code>http://mozilla.org/</code></p> <p><code>https://mozilla.org/</code></p> <p><code>ws://mozilla.org/</code></p> <p><code>wss://mozilla.org/</code></p> </td> <td> <p><code>ftp://mozilla.org/</code><br />(unmatched scheme)</p> <p><code>http://a.mozilla.org/</code><br />(unmatched host)</p> <p><code>http://mozilla.org/a</code><br />(unmatched path)</p> </td> </tr> <tr> <td> <p><code>ftp://mozilla.org/</code></p> <p>Match only "ftp://mozilla.org/".</p> </td> <td><code>ftp://mozilla.org</code></td> <td> <p><code>http://mozilla.org/</code><br />(unmatched scheme)</p> <p><code>ftp://sub.mozilla.org/</code><br />(unmatched host)</p> <p><code>ftp://mozilla.org/path</code><br />(unmatched path)</p> </td> </tr> <tr> <td> <p><code>https://*/path</code></p> <p>Match HTTPS URLs on any host, whose path is "path".</p> </td> <td> <p><code>https://mozilla.org/path</code></p> <p><code>https://a.mozilla.org/path</code></p> <p><code>https://something.com/path</code></p> </td> <td> <p><code>http://mozilla.org/path</code><br />(unmatched scheme)</p> <p><code>https://mozilla.org/path/</code><br />(unmatched path)</p> <p><code>https://mozilla.org/a</code><br />(unmatched path)</p> <p><code>https://mozilla.org/</code><br />(unmatched path)</p> <p> <code>https://mozilla.org/path?foo=1</code><br />(unmatched path due to URL query string) </p> </td> </tr> <tr> <td> <p><code>https://*/path/</code></p> <p> Match HTTPS URLs on any host, whose path is "path/" and which has no URL query string. </p> </td> <td> <p><code>https://mozilla.org/path/</code></p> <p><code>https://a.mozilla.org/path/</code></p> <p><code>https://something.com/path</code>/</p> </td> <td> <p><code>http://mozilla.org/path/</code><br />(unmatched scheme)</p> <p><code>https://mozilla.org/path</code><br />(unmatched path)</p> <p><code>https://mozilla.org/a</code><br />(unmatched path)</p> <p><code>https://mozilla.org/</code><br />(unmatched path)</p> <p> <code>https://mozilla.org/path/?foo=1</code ><br />(unmatched path due to URL query string) </p> </td> </tr> <tr> <td> <p><code>https://mozilla.org/*</code></p> <p> Match HTTPS URLs only at "mozilla.org", with any URL path and URL query string. </p> </td> <td> <p><code>https://mozilla.org/</code></p> <p><code>https://mozilla.org/path</code></p> <p><code>https://mozilla.org/another</code></p> <p><code>https://mozilla.org/path/to/doc</code></p> <p><code>https://mozilla.org/path/to/doc?foo=1</code></p> </td> <td> <p><code>http://mozilla.org/path</code><br />(unmatched scheme)</p> <p><code>https://mozilla.com/path</code><br />(unmatched host)</p> </td> </tr> <tr> <td> <p><code>https://mozilla.org/a/b/c/</code></p> <p>Match only this URL, or this URL with any URL fragment.</p> </td> <td> <p><code>https://mozilla.org/a/b/c/</code></p> <p><code>https://mozilla.org/a/b/c/#section1</code></p> </td> <td>Anything else.</td> </tr> <tr> <td> <p><code>https://mozilla.org/*/b/*/</code></p> <p> Match HTTPS URLs hosted on "mozilla.org", whose path contains a component "b" somewhere in the middle. Will match URLs with query strings, if the string ends in a <code>/</code>. </p> </td> <td> <p><code>https://mozilla.org/a/b/c/</code></p> <p><code>https://mozilla.org/d/b/f/</code></p> <p><code>https://mozilla.org/a/b/c/d/</code></p> <p><code>https://mozilla.org/a/b/c/d/#section1</code></p> <p><code>https://mozilla.org/a/b/c/d/?foo=/</code></p> <p> <code >https://mozilla.org/a?foo=21314&#x26;bar=/b/&#x26;extra=c/</code > </p> </td> <td> <p><code>https://mozilla.org/b/*/</code><br />(unmatched path)</p> <p><code>https://mozilla.org/a/b/</code><br />(unmatched path)</p> <p> <code>https://mozilla.org/a/b/c/d/?foo=bar</code><br />(unmatched path due to URL query string) </p> </td> </tr> <tr> <td> <p><code>file:///blah/*</code></p> <p>Match any FILE URL whose path begins with "blah".</p> </td> <td> <p><code>file:///blah/</code></p> <p><code>file:///blah/bleh</code></p> </td> <td><code>file:///bleh/</code><br />(unmatched path)</td> </tr> </tbody> </table> ### Invalid match patterns <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Invalid pattern</th> <th scope="col">Reason</th> </tr> </thead> <tbody> <tr> <td><code>resource://path/</code></td> <td>Unsupported scheme.</td> </tr> <tr> <td><code>https://mozilla.org</code></td> <td>No path.</td> </tr> <tr> <td><code>https://mozilla.*.org/</code></td> <td>"*" in host must be at the start.</td> </tr> <tr> <td><code>https://*zilla.org/</code></td> <td>"*" in host must be the only character or be followed by ".".</td> </tr> <tr> <td><code>http*://mozilla.org/</code></td> <td>"*" in scheme must be the only character.</td> </tr> <tr> <td><code>https://mozilla.org:80/</code></td> <td>Host must not include a port number.</td> </tr> <tr> <td><code>*://*</code></td> <td>Empty path: this should be "<code>*://*/*</code>".</td> </tr> <tr> <td><code>file://*</code></td> <td>Empty path: this should be "<code>file:///*</code>".</td> </tr> </tbody> </table> ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/working_with_files/index.md
--- title: Work with files slug: Mozilla/Add-ons/WebExtensions/Working_with_files page-type: guide --- {{AddonSidebar}} Your browser extension may need to work with files to deliver its full functionality. This article looks at the five mechanisms you have for handling files: - Downloading files to the user's selected download folder. - Opening files using a file picker on a web page. - Opening files using drag and drop onto a web page. - Storing files or blobs locally with IndexedDB using the idb-file-storage library. - Passing files to a native application on the user's computer. For each of these mechanisms, we introduce their use with references to the relevant API documentation, guides, and any examples that show how to use the API. ## Download files using the downloads API This mechanism enables you to get a file from your website (or any location you can define as a URL) to the user's computer. The key method is {{WebExtAPIRef("downloads.download()")}}, which in its simplest form accepts a URL and downloads the file from that URL to the user's default downloads folder: ```js browser.downloads.download({ url: "https://example.org/image.png" }); ``` You can let the user download to a location of their choice by specifying the `saveAs` parameter. > **Note:** Using [URL.createObjectURL()](/en-US/docs/Web/API/URL/createObjectURL_static) you can also download files and blobs defined in your JavaScript, which can include local content retrieved from IndexedDB. The downloads API also provides features to cancel, pause, resume, erase, and remove downloads; search for downloaded files in the download manager; show downloaded files in the computer's file manager; and open a file in an associated application. To use this API, you need to have the `"downloads"` [API permission](/en-US/docs/Web/API/Permissions#api_permissions) specified in your [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file. Example: [Latest download](https://github.com/mdn/webextensions-examples/tree/main/latest-download) API reference: [downloads API](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads) ## Open files in an extension using a file picker If you want to work with a file from the user's computer one option is to let the user select a file using the computer's file browser. Either create a new page or inject code into an existing page to use the `file` type of the HTML `input` element to offer the user a file picker. Once the user has picked a file or files, the script associated with the page can access the content of the file using the [DOM File API](/en-US/docs/Web/API/File), in the same way a web application does. Example: [Imagify](https://github.com/mdn/webextensions-examples/tree/main/imagify) Guide: [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications) API references: [HTML input element](/en-US/docs/Web/HTML/Element/input/file) | [DOM File API](/en-US/docs/Web/API/File) > **Note:** If you want to access or process all the files in a selected folder, you can do so using `<input type="file" webkitdirectory="true"/>` to select the folder and return all the files it contains. ## Open files in an extension using drag and drop The Web Drag and Drop API offers an alternative to using a file picker. To use this method, establish a 'drop zone' that fits with your UI, then add listeners for the [`dragenter`](/en-US/docs/Web/API/HTMLElement/dragenter_event), [`dragover`](/en-US/docs/Web/API/HTMLElement/dragover_event), and [`drop`](/en-US/docs/Web/API/HTMLElement/drop_event) events to the element. In the handler for the drop event, your code can access any file dropped by the user from the object offered by the `dataTransfer` property using [`DataTransfer.files`](/en-US/docs/Web/API/DataTransfer/files). Your code can then access and manipulate the files using the [DOM File API](/en-US/docs/Web/API/File). Example: [Imagify](https://github.com/mdn/webextensions-examples/tree/main/imagify) Guides: [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications) | [File drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop) API references: [DOM File API](/en-US/docs/Web/API/File) ## Store files data locally using the IndexedDB file storage library If your extension needs to save files locally, the [idb-file-storage library](https://www.npmjs.com/package/idb-file-storage) provides a simple Promise-based wrapper to the [IndexedDB API](/en-US/docs/Web/API/IndexedDB_API) to aid the storage and retrieval of files and blobs. The key features of the library are: - [getFileStorage](https://rpl.github.io/idb-file-storage/function/index.html#static-function-getFileStorage) - : Returns an `IDBFileStorage` instance, creating the named storage if it does not exist. - [IDBFileStorage](https://rpl.github.io/idb-file-storage/class/src/idb-file-storage.js~IDBFileStorage.html) - : Provides the methods to save and retrieve files, such as: - list to obtain an optionally filtered list of file in the database. - put to add a file or blob to the database. - get to retrieve a file or blob from the database. - remove to delete a file or blob from the database. The [Store Collected Images](https://github.com/mdn/webextensions-examples/tree/main/store-collected-images/webextension-plain) example illustrates how to use most of these features. The Store Collected Images example lets users add images to a collection using an option on the image context menu. Selected images are collected in a popup and can be saved to a named collection. A toolbar button ({{WebExtAPIRef("browserAction")}}) opens a navigate collection page, on which the user can view and delete saved images, with a filter option to narrow choices. [See the example in action](https://www.youtube.com/watch?v=t6aVqMMe2Rc&ab_channel=LucaGreco). The workings of the library can be understood by viewing [image-store.js](https://github.com/mdn/webextensions-examples/blob/main/store-collected-images/webextension-plain/utils/image-store.js) in /utils/: ### Creating the store and saving the images ```js async function saveCollectedBlobs(collectionName, collectedBlobs) { const storedImages = await getFileStorage({ name: "stored-images" }); for (const item of collectedBlobs) { await storedImages.put(`${collectionName}/${item.uuid}`, item.blob); } } ``` `saveCollectedBlobs` is called when the user clicks save in the popup and has provided a name for the image collection. First, `getFileStorage` creates, if it does not exist already, or retrieves the IndexedDB database `"stored-images"` to the object `storedImages`. `storedImages.put()` then adds each collected image to the database, under the collection name, using the blob's unique id (the file name). If the image being stored has the same name as one already in the database, it is overwritten. If you want to avoid this, query the database first using `imagesStore.list()` with a filter for the file name; and, if the list returns a file, add a suitable suffix to the name of the new image to store a separate item. ### Retrieving stored images for display ```js export async function loadStoredImages(filter) { const imagesStore = await getFileStorage({ name: "stored-images" }); let listOptions = filter ? { includes: filter } : undefined; const imagesList = await imagesStore.list(listOptions); let storedImages = []; for (const storedName of imagesList) { const blob = await imagesStore.get(storedName); storedImages.push({ storedName, blobUrl: URL.createObjectURL(blob) }); } return storedImages; } ``` `loadStoredImages()` is called when the user clicks view or reload in the navigate collection page. `getFileStorage()` opens the `"stored-images"` database, then `imagesStore.list()` gets a filtered list of the stored images. This list is then used to retrieve images with `imagesStore.get()` and build a list to return to the UI. Note the use of [`URL.createObjectURL(blob)`](/en-US/docs/Web/API/URL/createObjectURL_static) to create a URL that references the image blob. This URL is then used in the UI ([navigate-collection.js](https://github.com/mdn/webextensions-examples/blob/main/store-collected-images/webextension-plain/navigate-collection.js)) to display the image. ### Delete collected images ```js async function removeStoredImages(storedImages) { const imagesStore = await getFileStorage({ name: "stored-images" }); for (const storedImage of storedImages) { URL.revokeObjectURL(storedImage.blobUrl); await imagesStore.remove(storedImage.storedName); } } ``` `removeStoredImages()` is called when the user clicks delete in the navigate collection page. Again, `getFileStorage()` opens the `"stored-images"` database then `imagesStore.remove()` removes each image from the filtered list of images. Note the use of [`URL.revokeObjectURL()`](/en-US/docs/Web/API/URL/revokeObjectURL_static) to explicitly revoke the blob URL. This enables the garbage collector to free the memory allocated to the URL. If this is not done, the memory will not get returned until the page on which it was created is closed. If the URL was created in an extension's background page, this is not unloaded until the extension is disabled, uninstalled, or reloaded, so holding this memory unnecessarily could affect browser performance. If the URL is created in an extension's page (new tab, popup, or sidebar) the memory is released when the page is closed, but it is still a good practice to revoke the URL when it is no longer needed. Once the blob URL has been revoked, any attempt to load it will result in an error. For example, if the blob URL was used as the `SRC` attribute of an `IMG` tag, the image will not load and will not be visible. It is therefore good practice to remove any revoked blob URLs from generated HTML elements when the blob URL is revoked. Example: [Store Collected Images](https://github.com/mdn/webextensions-examples/tree/main/store-collected-images/webextension-plain) API References: [idb-file-storage library](https://rpl.github.io/idb-file-storage/) > **Note:** You can also use the full Web [IndexedDB API](/en-US/docs/Web/API/IndexedDB_API) to store data from your extension. This can be useful where you need to store data that isn't handled well by the simple key/value pairs offered by the DOM [Storage API](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage). ## Process files in a local app Where you have a native app or want to deliver additional native features for file processing, use native messaging to pass a file to a native app for processing. You have two options: - Connection-based messaging - : Here you trigger the process with `runtime.connectNative()`, which returns a [`runtime.Port`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/Port) object. You can then pass a JSON message to the native application using the `postMessage()` function of `Port`. Using the `onMessage.addListener()` function of `Port` you can listen for messages from the native application. The native application is opened if it is not running when `runtime.connectNative()` is called and the application remains running until the extension calls `Port.disconnect()` or the page that connected to it is closed. - Connectionless messaging - : Here you use `runtime.sendNativeMessage()` to send a JSON message to a new, temporary instance of the native application. The browser closes the native application after receiving any message back from the native application. To add the file or blob you want the native application to process use [`JSON.stringify()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). To use this method the extension must request the `"nativeMessaging"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or [optional permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) in its `manifest.json` file. Where optional permission is used, remember to check that permission has being granted and where necessary request permission from the user with the {{WebExtAPIRef("permissions")}} API. Reciprocally, the native application must grant permission for the extension by including its ID in the `"allowed_extensions"` field of the app manifest. Example: [Native Messaging](https://github.com/mdn/webextensions-examples/tree/main/native-messaging) (illustrates simple messaging only) Guides: [Native messaging](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging) API references: [runtime API](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime)
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/firefox_workflow_overview/index.md
--- title: Firefox workflow overview slug: Mozilla/Add-ons/WebExtensions/Firefox_workflow_overview page-type: guide --- {{AddonSidebar}} <table> <tbody> <tr> <td> <img alt="Firefox workflow prepare step graphic" src="firefox_workflow_prepare.png" /> </td> <td> <img alt="Firefox workflow code step graphic" src="firefox_workflow_code.png" /> </td> <td> <img alt="Firefox workflow publish step graphic" src="firefox_workflow_publish.png" /> </td> <td> <img alt="Firefox workflow enhance step graphic" src="firefox_workflow_enhance.png" /> </td> <td> <img alt="Firefox workflow retire step graphic" src="firefox_workflow_retire.png" /> </td> </tr> <tr> <td> <ul> <li>Choose a Firefox version for web extension development</li> <li>Choose your IDE or code editor</li> <li> <a href="https://extensionworkshop.com/documentation/develop/getting-started-with-web-ext/" >Install web-ext</a > </li> <li> Get familiar with the <a href="/en-US/docs/Mozilla/Add-ons/AMO/Policy" >add-on policies and developer agreement</a > </li> </ul> </td> <td> <ul> <li> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension" >Code your extension</a > </li> <li> Run your extension with<a href="https://extensionworkshop.com/documentation/develop/getting-started-with-web-ext/#testing_out_an_extension" > web-ext run</a > or <a href="https://extensionworkshop.com/documentation/develop/temporary-installation-in-firefox/" >about: debugging</a >) </li> <li> <a href="https://extensionworkshop.com/documentation/develop/testing-persistent-and-restart-features/" >Test persistent and restart features</a > </li> <li> Debug with the<a href="/en-US/docs/Tools/Browser_Toolbox"> Addon Debugging Window</a > </li> </ul> </td> <td> <ul> <li> Package your extension with<a href="https://extensionworkshop.com/documentation/develop/getting-started-with-web-ext/#packaging_your_extension" > web-ext build</a > </li> <li> Create an <a href="https://addons.mozilla.org">addons.mozilla.org</a> account </li> <li> <a href="https://extensionworkshop.com/documentation/publish/submitting-an-add-on/" >Submit your extension</a > </li> <li> <a href="https://extensionworkshop.com/documentation/publish/source-code-submission/" >Submit your source code</a > (if required) </li> <li> <a href="https://extensionworkshop.com/documentation/develop/create-an-appealing-listing/" >Create an appealing listing</a > </li> </ul> </td> <td> <ul> <li>Responded to Mozilla extension review</li> <li>Promote your extension</li> <li> <a href="https://extensionworkshop.com/documentation/publish/recommended-extensions/" >Nominate your extension to be featured</a > </li> <li>Update and improve your extension</li> </ul> </td> <td> <ul> <li> <a href="https://extensionworkshop.com/documentation/manage/retiring-your-extension/" >Retire your extension</a > </li> </ul> </td> </tr> </tbody> </table> \* Or distribute your extension for [sideloading](https://extensionworkshop.com/documentation/publish/distribute-sideloading/), [desktop apps](https://extensionworkshop.com/documentation/publish/distribute-for-desktop-apps/), or [in an enterprise](https://extensionworkshop.com/documentation/enterprise/). **Have an extension you want to bring to Firefox?** We provide advice, guidelines, and tools to help making make porting straightforward. To get started, visit [Porting a Google Chrome extension](https://extensionworkshop.com/documentation/develop/porting-a-google-chrome-extension/).
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/chrome_incompatibilities/index.md
--- title: Chrome incompatibilities slug: Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities page-type: guide --- {{AddonSidebar}} The WebExtension APIs aim to provide compatibility across all the main browsers, so extensions should run on any browser with minimal changes. However, there are significant differences between Chrome (and Chromium-based browsers), Firefox, and Safari. In particular: - Support for WebExtension APIs differs across browsers. See [Browser support for JavaScript APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs) for details. - Support for `manifest.json` keys differs across browsers. See the ["Browser compatibility" section](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json#browser_compatibility) on the [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) page for more details. - Extension API namespace: - **In Firefox and Safari:** Extension APIs are accessed under the `browser` namespace. The `chrome` namespace is also supported for compatibility with Chrome. - **In Chrome:** Extension APIs are accessed under the `chrome` namespace. (cf. [Chrome bug 798169](https://crbug.com/798169)) - Asynchronous APIs: - **In Firefox and Safari:** Asynchronous APIs are implemented using promises. - **In Chrome:** In Manifest V2, asynchronous APIs are implemented using callbacks. In Manifest V3, support is provided for [promises](https://developer.chrome.com/docs/extensions/mv3/intro/mv3-overview/#promises) on most appropriate methods. (cf. [Chrome bug 328932](https://crbug.com/328932)) Callbacks are supported in Manifest V3 for backward compatibility. The rest of this page details these and other incompatibilities. ## JavaScript APIs ### chrome.\* and browser.\* namespace - **In Firefox and Safari:** The APIs are accessed using the `browser` namespace. ```js browser.browserAction.setIcon({ path: "path/to/icon.png" }); ``` - **In Chrome:** The APIs are accessed using the `chrome` namespace. ```js chrome.browserAction.setIcon({ path: "path/to/icon.png" }); ``` ### Callbacks and promises - **In Firefox and Safari (all versions), and Chrome (starting from Manifest Version 3):** Asynchronous APIs use [promises](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to return values. ```js function logCookie(c) { console.log(c); } function logError(e) { console.error(e); } let setCookie = browser.cookies.set({ url: "https://developer.mozilla.org/", }); setCookie.then(logCookie, logError); ``` - **In Chrome:** In Manifest V2, asynchronous APIs use callbacks to return values and {{WebExtAPIRef("runtime.lastError")}} to communicate errors. In Manifest V3, callbacks are supported for backward compatibility, along with support for [promises](https://developer.chrome.com/docs/extensions/mv3/intro/mv3-overview/#promises) on most appropriate methods. ```js function logCookie(c) { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError); } else { console.log(c); } } chrome.cookies.set({ url: "https://developer.mozilla.org/" }, logCookie); ``` ### Firefox supports both the chrome and browser namespaces As a porting aid, the Firefox implementation of WebExtensions supports `chrome` using callbacks and `browser` using promises. This means that many Chrome extensions work in Firefox without changes. > **Note:** The `browser` namespace is supported by Firefox and Safari. Chrome does not offer the `browser` namespace, until [Chrome bug 798169](https://crbug.com/798169) is resolved. If you choose to write your extension to use `browser` and promises, Firefox provides a polyfill that should enable it to run in Chrome: <https://github.com/mozilla/webextension-polyfill>. ### Partially supported APIs The [Browser support for JavaScript APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs) page includes compatibility tables for all APIs that have any support in Firefox. Where there are caveats regarding support for an API method, property, type, or event, this is indicated in these tables with an asterisk "\*". Selecting the asterisk expands the table to display a note explaining the caveat. The tables are generated from compatibility data stored as [JSON files in GitHub](https://github.com/mdn/browser-compat-data). The rest of this section describes the main compatibility issues you may need to consider when building a cross-browser extension. Also, remember to check the browser compatibility tables, as they may contain additional compatibility information. #### Notifications API For `notifications.create()`, with `type "basic"`: - **In Firefox**: `iconUrl` is optional. - **In Chrome**: `iconUrl` is required. When the user clicks on a notification: - **In Firefox**: The notification is cleared immediately. - **In Chrome**: This is not the case. If you call `notifications.create()` more than once in rapid succession: - **In Firefox**: The notifications may not display. Waiting to make subsequent calls within the `notifications.create()` callback function is not a sufficient delay to prevent this. #### Proxy API Firefox and Chrome include a Proxy API. However, the design of these two APIs is incompatible. - **In Firefox**: Proxies are set using the [proxy.settings](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy/settings) property or [proxy.onRequest](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy/onRequest) to provide [ProxyInfo](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy/ProxyInfo) dynamically. See [proxy](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy) for more information on the API. - **In Chrome**: Proxy settings are defined in a [`proxy.ProxyConfig`](https://developer.chrome.com/docs/extensions/reference/proxy/#type-ProxyConfig) object. Depending on Chrome's proxy settings, the settings may contain [`proxy.ProxyRules`](https://developer.chrome.com/docs/extensions/reference/proxy/#type-ProxyRules) or a [`proxy.PacScript`](https://developer.chrome.com/docs/extensions/reference/proxy/#type-PacScript). Proxies are set using the [proxy.settings](https://developer.chrome.com/docs/extensions/reference/proxy/#property-settings) property. See [chrome.proxy](https://developer.chrome.com/docs/extensions/reference/proxy/) for more information on the API. #### Tabs API When using `tabs.executeScript()` or `tabs.insertCSS()`: - **In Firefox**: Relative URLs passed are resolved relative to the current page URL. - **In Chrome**: Relative URLs are resolved relative to the extension's base URL. To work cross-browser, you can specify the path as an absolute URL, starting at the extension's root, like this: ```plain /path/to/script.js ``` When calling `tabs.remove()`: - **In Firefox**: The `tabs.remove()` promise is fulfilled after the `beforeunload` event. - **In Chrome**: The callback does not wait for `beforeunload`. #### WebRequest API - **In Firefox:** - Requests can be redirected only if their original URL uses the `http:` or `https:` scheme. - The `activeTab` permission does not allow for intercepting network requests in the current tab. (See [bug 1617479](https://bugzil.la/1617479)) - Events are not fired for system requests (for example, extension upgrades or search bar suggestions). - **From Firefox 57 onwards:** Firefox makes an exception for extensions that need to intercept {{WebExtAPIRef("webRequest.onAuthRequired")}} for proxy authorization. See the documentation for {{WebExtAPIRef("webRequest.onAuthRequired")}}. - 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 with the URL of the extension page. > **Note:** _Any_ website may link or redirect to that URL, and extensions should treat any input (POST data, for example) as if it came from an untrusted source, as a normal web page should. - Some of the `browser.webRequest.*` APIs allow for returning Promises that resolves `webRequest.BlockingResponse` asynchronously. - **In Chrome:** Only `webRequest.onAuthRequired` supports asynchronous `webRequest.BlockingResponse` by supplying `'asyncBlocking'`, through a callback instead of a Promise. #### Windows API - **In Firefox:** `onFocusChanged` of the {{WebExtAPIRef("windows")}} API triggers multiple times for a focus change. ### Unsupported APIs #### DeclarativeContent API - **In Firefox:** Chrome's [declarativeContent](https://developer.chrome.com/docs/extensions/reference/declarativeContent/) API [is not implemented](https://bugzil.la/1435864). In addition, Firefox [will not support](https://bugzil.la/1323433#c16) the `declarativeContent.RequestContentScript` API (which is rarely used and is unavailable in stable releases of Chrome). ### Miscellaneous incompatibilities #### URLs in CSS - **In Firefox:** URLs in injected CSS files are resolved relative to _the CSS file_. - **In Chrome:** URLs in injected CSS files are resolved relative to _the page they are injected into_. #### Support for dialogs in background pages - **In Firefox:** [`alert()`](/en-US/docs/Web/API/Window/alert), [`confirm()`](/en-US/docs/Web/API/Window/confirm), and [`prompt()`](/en-US/docs/Web/API/Window/prompt) are not supported in background pages. #### web_accessible_resources - **In Firefox:** Resources are assigned a random {{Glossary("UUID")}} that changes for every instance of Firefox: `moz-extension://«random-UUID»/«path»`. This randomness can prevent you from doing things, such as adding your extension's URL to another domain's CSP policy. - **In Chrome:** When a resource is listed in `web_accessible_resources`, it is accessible as `chrome-extension://«your-extension-id»/«path»`. The extension ID is fixed for an extension. #### Manifest "key" property - **In Firefox:** As Firefox uses random UUIDs for `web_accessible_resources`, this property is unsupported. Firefox extensions can fix their extension ID through the `browser_specific_settings.gecko.id` manifest key (see [browser_specific_settings.gecko](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings#firefox_gecko_properties)). - **In Chrome:** When working with an unpacked extension, the manifest may include a [`"key"` property](https://developer.chrome.com/docs/extensions/mv3/manifest/key/) to pin the extension ID across different machines. This is mainly useful when working with `web_accessible_resources`. #### Content script HTTP(S) requests - **In Firefox:** When a content script makes an HTTP(S) request, you _must_ provide absolute URLs. - **In Chrome:** When a content script makes a request (for example, using [`fetch()`](/en-US/docs/Web/API/Fetch_API/Using_Fetch)) to a relative URL (like `/api`), it is sent to `https://example.com/api`. #### Content script environment - **In Firefox:** The global scope of the [content script environment](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#content_script_environment) is not strictly equal to `window` ([Firefox bug 1208775](https://bugzil.la/1208775)). More specifically, the global scope (`globalThis`) is composed of standard JavaScript features as usual, plus `window` as the prototype of the global scope. Most DOM APIs are inherited from the page through `window`, through [Xray vision](/en-US/docs/Mozilla/Add-ons/WebExtensions/Sharing_objects_with_page_scripts#xray_vision_in_firefox) to shield the content script from modifications by the web page. A content script may encounter JavaScript objects from its global scope or Xray-wrapped versions from the web page. - **In Chrome:** The global scope is `window`, and the available DOM APIs are generally independent of the web page (other than sharing the underlying DOM). Content scripts cannot directly access JavaScript objects from the web page. #### Executing code in a web page from content script - **In Firefox:** {{jsxref("Global_Objects/eval", "eval")}} runs code in the context of the content script and `window.eval` runs code in the context of the page. See [Using `eval` in content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#using_eval_in_content_scripts). - **In Chrome:** {{jsxref("Global_Objects/eval", "eval")}} and `window.eval` always runs code in the context of the content script, not in the context of the page. #### Sharing variables between content scripts - **In Firefox:** You cannot share variables between content scripts by assigning them to `this.{variableName}` in one script and then attempting to access them using `window.{variableName}` in another. This is a limitation created by the sandbox environment in Firefox. This limitation may be removed; see [Firefox bug 1208775](https://bugzil.la/1208775). #### Content script lifecycle during navigation - **In Firefox:** Content scripts remain injected in a web page after the user has navigated away. However, window object properties are destroyed. For example, if a content script sets `window.prop1 = "prop"` and the user then navigates away and returns to the page `window.prop1` is undefined. This issue is tracked in [Firefox bug 1525400](https://bugzil.la/1525400). To mimic the behavior of Chrome, listen for the [pageshow](/en-US/docs/Web/API/Window/pageshow_event) and [pagehide](/en-US/docs/Web/API/Window/pagehide_event) events. Then simulate the injection or destruction of the content script. - **In Chrome:** Content scripts are destroyed when the user navigates away from a web page. If the user clicks the back button to return to the page through history, the content script is injected into the web page. #### "per-tab" zoom behavior - **In Firefox:** The zoom level persists across page loads and navigation within the tab. - **In Chrome:** Zoom changes are reset on navigation; navigating a tab always loads pages with their per-origin zoom factors. See {{WebExtAPIRef("tabs.ZoomSettingsScope")}}. ## manifest.json keys The main [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) page includes a table describing browser support for `manifest.json` keys. Where there are caveats around support for a given key, this is indicated in the table with an asterisk "\*". Selecting the asterisk expands the table to display a note explaining the caveat. The tables are generated from compatibility data stored as [JSON files in GitHub](https://github.com/mdn/browser-compat-data). ## Native messaging ### Connection-based messaging arguments **On Linux and Mac:** Chrome passes one argument to the native app, which is the origin of the extension that started it, in the form of `chrome-extension://«extensionID/»` (trailing slash required). This enables the app to identify the extension. **On Windows:** Chrome passes two arguments: 1. The origin of the extension 2. A handle to the Chrome native window that started the app ### allowed_extensions - **In Firefox:** The manifest key is called `allowed_extensions`. - **In Chrome:** The manifest key is called `allowed_origins`. ### App manifest location - **In Chrome:** The app manifest is expected in a different place. See [Native messaging host location](https://developer.chrome.com/docs/apps/nativeMessaging/#native-messaging-host-location) in the Chrome docs. ### App persistence - **In Firefox:** When a native messaging connection is closed, Firefox kills the subprocesses if they do not break away. On Windows, the browser puts the native application's process into a [Job object](<https://msdn.microsoft.com/library/windows/desktop/ms684161(v=vs.85).aspx>) and kills the job. Suppose the native application launches other processes and wants them to remain open after the native application is killed. In that case, the native application must use `CreateProcess`, instead of `ShellExecute`, to launch the additional process with the [`CREATE_BREAKAWAY_FROM_JOB`](<https://msdn.microsoft.com/library/windows/desktop/ms684863(v=vs.85).aspx>) flag. ## Data cloning algorithm Some extension APIs allow an extension to send data from one part of the extension to another, such as {{WebExtAPIRef("runtime.sendMessage()")}}, {{WebExtAPIRef("tabs.sendMessage()")}}, {{WebExtAPIRef("runtime.onMessage")}}, the `postMessage()` method of {{WebExtAPIRef("runtime.port")}}, and {{WebExtAPIRef("tabs.executeScript()")}}. - **In Firefox:** The [Structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) is used. - **In Chrome:** The [JSON serialization algorithm](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description) is used. It may switch to structured cloning in the future ([issue 248548](https://crbug.com/248548)). The Structured clone algorithm supports more types than the JSON serialization algorithm. A notable exception are (DOM) objects with a `toJSON` method. DOM objects are not cloneable nor JSON-serializable by default, but with a `toJSON()` method, these can be JSON-serialized (but still not cloned with the structured cloning algorithm). Examples of JSON-serializable objects that are not structured cloneable include instances of {{domxref("URL")}} and {{domxref("PerformanceEntry")}}. Extensions that rely on the `toJSON()` method of the JSON serialization algorithm can use {{jsxref("JSON.stringify()")}} followed by {{jsxref("JSON.parse()")}} to ensure that a message can be exchanged because a parsed JSON value is always structurally cloneable.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/your_second_webextension/index.md
--- title: Your second extension slug: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension page-type: guide --- {{AddonSidebar}} If you've been through the [Your first extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension) article, you've already got an idea of how to write an extension. In this article, you'll write a slightly more complex extension that demonstrates a few more of the APIs. The extension adds a new button to the Firefox toolbar. When the user clicks the button, we display a popup enabling them to choose an animal. Once they choose an animal, we'll replace the current page's content with a picture of the chosen animal. To implement this, we will: - **define a [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button), which is a button attached to the Firefox toolbar**. For the button we'll supply: - an icon, called "beasts-32.png" - a popup to open when the button is pressed. The popup will include HTML, CSS, and JavaScript. - **define an icon for the extension**, called "beasts-48.png". This will be shown in the Add-ons Manager. - **write a content script, "beastify.js" that will be injected into web pages**. This is the code that will actually modify the pages. - **package some images of the animals, to replace images in the web page**. We'll make the images "web accessible resources" so the web page can refer to them. You could visualize the overall structure of the extension like this: ![The manifest.json file includes icons, browser actions, including popups, and web accessible resources. The choose beast JavaScript popup resource calls in the beastify script.](untitled-1.png) It's a simple extension, but shows many of the basic concepts of the WebExtensions API: - adding a button to the toolbar - defining a popup panel using HTML, CSS, and JavaScript - injecting content scripts into web pages - communicating between content scripts and the rest of the extension - packaging resources with your extension that can be used by web pages You can find [complete source code for the extension on GitHub](https://github.com/mdn/webextensions-examples/tree/main/beastify). ## Writing the extension Create a new directory and navigate to it: ```bash mkdir beastify cd beastify ``` ### manifest.json Now create a new file called "manifest.json", and give it the following contents: ```json { "manifest_version": 2, "name": "Beastify", "version": "1.0", "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify", "homepage_url": "https://github.com/mdn/webextensions-examples/tree/main/beastify", "icons": { "48": "icons/beasts-48.png" }, "permissions": ["activeTab"], "browser_action": { "default_icon": "icons/beasts-32.png", "default_title": "Beastify", "default_popup": "popup/choose_beast.html" }, "web_accessible_resources": [ "beasts/frog.jpg", "beasts/turtle.jpg", "beasts/snake.jpg" ] } ``` - The first three keys: [`manifest_version`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version), [`name`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name), and [`version`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version), are mandatory and contain basic metadata for the extension. - [`description`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/description) and [`homepage_url`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/homepage_url) are optional, but recommended: they provide useful information about the extension. - [`icons`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons) is optional, but recommended: it allows you to specify an icon for the extension, that will be shown in the Add-ons Manager. - [`permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) lists permissions the extension needs. We're just asking for the [`activeTab` permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission) here. - [`browser_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) specifies the toolbar button. We're supplying three pieces of information here: - `default_icon` is mandatory, and points to the icon for the button - `default_title` is optional, and will be shown in a tooltip - `default_popup` is used if you want a popup to be shown when the user clicks the button. We do, so we've included this key and made it point to an HTML file included with the extension. - [`web_accessible_resources`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources) lists files that we want to make accessible to web pages. Since the extension replaces the content in the page with images we've packaged with the extension, we need to make these images accessible to the page. Note that all paths given are relative to manifest.json itself. ### The icon The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager (you can open this by visiting the URL "about:addons"). Our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-48.png". Create the "icons" directory and save an icon there named "beasts-48.png". You could use [the one from our example](https://raw.githubusercontent.com/mdn/webextensions-examples/main/beastify/icons/beasts-48.png), which is taken from the [Aha-Soft's Free Retina iconset](http://www.aha-soft.com/free-icons/free-retina-icon-set/), and used under the terms of its license. If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the `96` property of the `icons` object in manifest.json: ```json "icons": { "48": "icons/beasts-48.png", "96": "icons/beasts-96.png" } ``` ### The toolbar button The toolbar button also needs an icon, and our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-32.png". Save an icon named "beasts-32.png" in the "icons" directory. You could use [the one from our example](https://raw.githubusercontent.com/mdn/webextensions-examples/main/beastify/icons/beasts-32.png), which is taken from the [IconBeast Lite icon set](http://www.iconbeast.com/free/) and used under the terms of its [license](http://www.iconbeast.com/faq/). If you don't supply a popup, then a click event is dispatched to your extension when the user clicks the button. If you do supply a popup, the click event is not dispatched, but instead, the popup is opened. We want a popup, so let's create that next. ### The popup The function of the popup is to enable the user to choose one of three beasts. Create a new directory called "popup" under the extension root. This is where we'll keep the code for the popup. The popup will consist of three files: - **`choose_beast.html`** defines the content of the panel - **`choose_beast.css`** styles the content - **`choose_beast.js`** handles the user's choice by running a content script in the active tab ```bash mkdir popup cd popup touch choose_beast.html choose_beast.css choose_beast.js ``` #### choose_beast.html The HTML file looks like this: ```html <!doctype html> <html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="choose_beast.css" /> </head> <body> <div id="popup-content"> <button>Frog</button> <button>Turtle</button> <button>Snake</button> <button type="reset">Reset</button> </div> <div id="error-content" class="hidden"> <p>Can't beastify this web page.</p> <p>Try a different page.</p> </div> <script src="choose_beast.js"></script> </body> </html> ``` We have a [`<div>`](/en-US/docs/Web/HTML/Element/div) element with an ID of `"popup-content"` that contains a button for each animal choice and a reset button. We have another `<div>` with an ID of `"error-content"` and a class `"hidden"`. We'll use that in case there's a problem initializing the popup. Note that we include the CSS and JS files from this file, just like a web page. #### choose_beast.css The CSS fixes the size of the popup, ensures that the three choices fill the space, and gives them some basic styling. It also hides elements with `class="hidden"`: this means that our `<div id="error-content"...` element will be hidden by default. ```css html, body { width: 100px; } .hidden { display: none; } button { border: none; width: 100%; margin: 3% auto; padding: 4px; text-align: center; font-size: 1.5em; cursor: pointer; background-color: #e5f2f2; } button:hover { background-color: #cff2f2; } button[type="reset"] { background-color: #fbfbc9; } button[type="reset"]:hover { background-color: #eaea9d; } ``` #### choose_beast.js Here's the JavaScript for the popup: ```js /** * CSS to hide everything on the page, * except for elements that have the "beastify-image" class. */ const hidePage = `body > :not(.beastify-image) { display: none; }`; /** * Listen for clicks on the buttons, and send the appropriate message to * the content script in the page. */ function listenForClicks() { document.addEventListener("click", (e) => { /** * Given the name of a beast, get the URL to the corresponding image. */ function beastNameToURL(beastName) { switch (beastName) { case "Frog": return browser.runtime.getURL("beasts/frog.jpg"); case "Snake": return browser.runtime.getURL("beasts/snake.jpg"); case "Turtle": return browser.runtime.getURL("beasts/turtle.jpg"); } } /** * Insert the page-hiding CSS into the active tab, * then get the beast URL and * send a "beastify" message to the content script in the active tab. */ function beastify(tabs) { browser.tabs.insertCSS({ code: hidePage }).then(() => { const url = beastNameToURL(e.target.textContent); browser.tabs.sendMessage(tabs[0].id, { command: "beastify", beastURL: url, }); }); } /** * Remove the page-hiding CSS from the active tab, * send a "reset" message to the content script in the active tab. */ function reset(tabs) { browser.tabs.removeCSS({ code: hidePage }).then(() => { browser.tabs.sendMessage(tabs[0].id, { command: "reset", }); }); } /** * Just log the error to the console. */ function reportError(error) { console.error(`Could not beastify: ${error}`); } /** * Get the active tab, * then call "beastify()" or "reset()" as appropriate. */ if (e.target.tagName !== "BUTTON" || !e.target.closest("#popup-content")) { // Ignore when click is not on a button within <div id="popup-content">. return; } if (e.target.type === "reset") { browser.tabs .query({ active: true, currentWindow: true }) .then(reset) .catch(reportError); } else { browser.tabs .query({ active: true, currentWindow: true }) .then(beastify) .catch(reportError); } }); } /** * There was an error executing the script. * Display the popup's error message, and hide the normal UI. */ function reportExecuteScriptError(error) { document.querySelector("#popup-content").classList.add("hidden"); document.querySelector("#error-content").classList.remove("hidden"); console.error(`Failed to execute beastify content script: ${error.message}`); } /** * When the popup loads, inject a content script into the active tab, * and add a click handler. * If we couldn't inject the script, handle the error. */ browser.tabs .executeScript({ file: "/content_scripts/beastify.js" }) .then(listenForClicks) .catch(reportExecuteScriptError); ``` The place to start here is line 99. The popup script executes a content script in the active tab as soon as the popup is loaded, using the [`browser.tabs.executeScript()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript) API. If executing the content script is successful, then the content script will stay loaded in the page until the tab is closed or the user navigates to a different page. A common reason the `browser.tabs.executeScript()` call might fail is that you can't execute content scripts in all pages. For example, you can't execute them in privileged browser pages like about:debugging, and you can't execute them on pages in the [addons.mozilla.org](https://addons.mozilla.org/) domain. If it does fail, `reportExecuteScriptError()` will hide the `<div id="popup-content">` element, show the `<div id="error-content"...` element, and log an error to the [console](https://extensionworkshop.com/documentation/develop/debugging/). If executing the content script is successful, we call `listenForClicks()`. This listens for clicks on the popup. - If the click was not on a button in the popup, we ignore it and do nothing. - If the click was on a button with `type="reset"`, then we call `reset()`. - If the click was on any other button (i.e. the beast buttons), then we call `beastify()`. The `beastify()` function does three things: - map the button clicked to a URL pointing to an image of a particular beast - hide the page's whole content by injecting some CSS, using the [`browser.tabs.insertCSS()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/insertCSS) API - send a "beastify" message to the content script using the [`browser.tabs.sendMessage()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/sendMessage) API, asking it to beastify the page, and passing it the URL to the beast image. The `reset()` function essentially undoes a beastify: - remove the CSS we added, using the [`browser.tabs.removeCSS()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/removeCSS) API - send a "reset" message to the content script asking it to reset the page. ### The content script Create a new directory, under the extension root, called "content_scripts" and create a new file in it called "beastify.js", with the following contents: ```js (() => { /** * Check and set a global guard variable. * If this content script is injected into the same page again, * it will do nothing next time. */ if (window.hasRun) { return; } window.hasRun = true; /** * Given a URL to a beast image, remove all existing beasts, then * create and style an IMG node pointing to * that image, then insert the node into the document. */ function insertBeast(beastURL) { removeExistingBeasts(); const beastImage = document.createElement("img"); beastImage.setAttribute("src", beastURL); beastImage.style.height = "100vh"; beastImage.className = "beastify-image"; document.body.appendChild(beastImage); } /** * Remove every beast from the page. */ function removeExistingBeasts() { const existingBeasts = document.querySelectorAll(".beastify-image"); for (const beast of existingBeasts) { beast.remove(); } } /** * Listen for messages from the background script. * Call "insertBeast()" or "removeExistingBeasts()". */ browser.runtime.onMessage.addListener((message) => { if (message.command === "beastify") { insertBeast(message.beastURL); } else if (message.command === "reset") { removeExistingBeasts(); } }); })(); ``` The first thing the content script does is to check for a global variable `window.hasRun`: if it's set the script returns early, otherwise it sets `window.hasRun` and continues. The reason we do this is that every time the user opens the popup, the popup executes a content script in the active tab, so we could have multiple instances of the script running in a single tab. If this happens, we need to make sure that only the first instance is actually going to do anything. After that, the place to start is line 40, where the content script listens for messages from the popup, using the [`browser.runtime.onMessage`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage) API. We saw above that the popup script can send two different sorts of messages: "beastify" and "reset". - if the message is "beastify", we expect it to contain a URL pointing to a beast image. We remove any beasts that might have been added by previous "beastify" calls, then construct and append an [`<img>`](/en-US/docs/Web/HTML/Element/img) element whose `src` attribute is set to the beast URL. - if the message is "reset", we just remove any beasts that might have been added. ### The beasts Finally, we need to include the images of the beasts. Create a new directory called "beasts", and add the three images in that directory, with the appropriate names. You can get the images from [the GitHub repository](https://github.com/mdn/webextensions-examples/tree/main/beastify/beasts), or from here: ![A brown frog.](frog.jpg) ![An emerald tree boa with white stripes.](snake.jpg) ![A red-eared slider turtle.](turtle.jpg) ## Testing it out First, double check that you have the right files in the right places: ```plain beastify/ beasts/ frog.jpg snake.jpg turtle.jpg content_scripts/ beastify.js icons/ beasts-32.png beasts-48.png popup/ choose_beast.css choose_beast.html choose_beast.js manifest.json ``` Now load the extension as a temporary add-on. Open "about:debugging" in Firefox, click "Load Temporary Add-on", and select your **manifest.json** file. You should then see the extension's icon appear in the Firefox toolbar: ![The beastify icon in the Firefox toolbar](beastify_icon.png) Open a web page, click the icon, select a beast, and see the web page change: ![A page replaced with the image of a turtle](beastify_page.png) ## Developing from the command line You can automate the temporary installation step by using the [web-ext](https://extensionworkshop.com/documentation/develop/getting-started-with-web-ext/) tool. Try this: ```bash cd beastify web-ext run ``` ## What's next? Now that you've created a more advanced WebExtension for Firefox: - [read about the anatomy of an extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension) - [explore the extension examples](/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples) - [find out what you need to develop, test, and publish your extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_next) - [take your learning further](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_next#continue_your_learning_experience).
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/modify_a_web_page/index.md
--- title: Modify a web page slug: Mozilla/Add-ons/WebExtensions/Modify_a_web_page page-type: guide --- {{AddonSidebar}} One of the most common use cases for an extension is to modify a web page. For example, an extension might want to change the style applied to a page, hide particular DOM nodes, or inject extra DOM nodes into the page. There are two ways to do this with WebExtensions APIs: - **Declaratively**: Define a pattern that matches a set of URLs, and load a set of scripts into pages whose URL matches that pattern. - **Programmatically**: Using a JavaScript API, load a script into the page hosted by a particular tab. Either way, these scripts are called _content scripts_, and are different from the other scripts that make up an extension: - They only get access to a small subset of the WebExtension APIs. - They get direct access to the web page in which they are loaded. - They communicate with the rest of the extension using a messaging API. In this article we'll look at both methods of loading a script. ## Modifying pages that match a URL pattern First of all, create a new directory called "modify-page". In that directory, create a file called "manifest.json", with the following contents: ```json { "manifest_version": 2, "name": "modify-page", "version": "1.0", "content_scripts": [ { "matches": ["https://developer.mozilla.org/*"], "js": ["page-eater.js"] } ] } ``` The [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key is how you load scripts into pages that match URL patterns. In this case, `content_scripts` instructs the browser to load a script called "page-eater.js" into all pages under [https://developer.mozilla.org/](/). > **Note:** Since the `"js"` property of `content_scripts` is an array, you can use it to inject more than one script into matching pages. If you do this the pages share the same scope, just like multiple scripts loaded by a page, and they are loaded in the order that they are listed in the array. > **Note:** The `content_scripts` key also has a `"css"` property that you can use to inject CSS stylesheets. Next, create a file called "page-eater.js" inside the "modify-page" directory, and give it the following contents: ```js document.body.textContent = ""; let header = document.createElement("h1"); header.textContent = "This page has been eaten"; document.body.appendChild(header); ``` Now [install the extension](https://extensionworkshop.com/documentation/develop/temporary-installation-in-firefox/), and visit [https://developer.mozilla.org/](/). The page should look like this: ![developer.mozilla.org page "eaten" by the script](eaten_page.png) ## Modifying pages programmatically What if you still want to eat pages, but only when the user asks you to? Let's update this example so we inject the content script when the user clicks a context menu item. First, update "manifest.json" so it has the following contents: ```json { "manifest_version": 2, "name": "modify-page", "version": "1.0", "permissions": ["activeTab", "contextMenus"], "background": { "scripts": ["background.js"] } } ``` Here, we've removed the `content_scripts` key, and added two new keys: - [`permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions): To inject scripts into pages we need permissions for the page we're modifying. The [`activeTab` permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission) is a way to get this temporarily for the currently active tab. We also need the `contextMenus` permission to be able to add context menu items. - [`background`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/background): We're using this to load a persistent ["background script"](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#background_scripts) called `background.js`, in which we'll set up the context menu and inject the content script. Let's create this file. Create a new file called `background.js` in the `modify-page` directory, and give it the following contents: ```js browser.contextMenus.create({ id: "eat-page", title: "Eat this page", }); browser.contextMenus.onClicked.addListener((info, tab) => { if (info.menuItemId === "eat-page") { browser.tabs.executeScript({ file: "page-eater.js", }); } }); ``` In this script we're creating a [context menu item](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/create), giving it a specific id and title (the text to be displayed in the context menu). Then we set up an event listener so that when the user clicks a context menu item, we check to see if it is our `eat-page` item. If it is, we inject "page-eater.js" into the current tab using the [`tabs.executeScript()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript) API. This API optionally takes a tab ID as an argument: we've omitted the tab ID, which means that the script is injected into the currently active tab. At this point the extension should look like this: ```plain modify-page/ background.js manifest.json page-eater.js ``` Now [reload the extension](https://extensionworkshop.com/documentation/develop/temporary-installation-in-firefox/#reloading_a_temporary_add-on), open a page (any page, this time) activate the context menu, and select "Eat this page": ![Option to eat a page on the context menu](eat_from_menu.png) ## Messaging Content scripts and background scripts can't directly access each other's state. However, they can communicate by sending messages. One end sets up a message listener, and the other end can then send it a message. The following table summarizes the APIs involved on each side: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="row"></th> <th scope="col">In content script</th> <th scope="col">In background script</th> </tr> <tr> <th scope="row">Send a message</th> <td> <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime#sendmessage()" >browser.runtime.sendMessage()</a ></code > </td> <td> <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/sendMessage" >browser.tabs.sendMessage()</a ></code > </td> </tr> <tr> <th scope="row">Receive a message</th> <td> <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage" >browser.runtime.onMessage</a ></code > </td> <td> <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime#onmessage" >browser.runtime.onMessage</a ></code > </td> </tr> </thead> </table> > **Note:** In addition to this method of communication, which sends one-off messages, you can also use a [connection-based approach to exchange messages](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#connection-based_messaging). 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). Let's update our example to show how to send a message from the background script. First, edit `background.js` so that it has these contents: ```js browser.contextMenus.create({ id: "eat-page", title: "Eat this page", }); function messageTab(tabs) { browser.tabs.sendMessage(tabs[0].id, { replacement: "Message from the extension!", }); } function onExecuted(result) { let querying = browser.tabs.query({ active: true, currentWindow: true, }); querying.then(messageTab); } browser.contextMenus.onClicked.addListener((info, tab) => { if (info.menuItemId === "eat-page") { let executing = browser.tabs.executeScript({ file: "page-eater.js", }); executing.then(onExecuted); } }); ``` Now, after injecting `page-eater.js`, we use [`tabs.query()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query) to get the currently active tab, and then use [`tabs.sendMessage()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/sendMessage) to send a message to the content scripts loaded into that tab. The message has the payload `{replacement: "Message from the extension!"}`. Next, update `page-eater.js` like this: ```js function eatPageReceiver(request, sender, sendResponse) { document.body.textContent = ""; let header = document.createElement("h1"); header.textContent = request.replacement; document.body.appendChild(header); } browser.runtime.onMessage.addListener(eatPageReceiver); ``` Now, instead of just eating the page right away, the content script listens for a message using [`runtime.onMessage`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage). When a message arrives, the content script runs essentially the same code as before, except that the replacement text is taken from `request.replacement`. Since [`tabs.executeScript()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript) is an asynchronous function, and to ensure we send message only after listener has been added in `page-eater.js`, we use `onExecuted()` which will be called after `page-eater.js` executed. > **Note:** Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>J</kbd> (or <kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>J</kbd> on macOS) OR `web-ext run --bc` to open [Browser Console](https://firefox-source-docs.mozilla.org/devtools-user/browser_console/index.html) to view `console.log` in background script. > > Alternatively, use [Add-on Debugger](/en-US/docs/Mozilla/Add-ons/Add-on_Debugger) which allows you set breakpoint. There is currently no way to [start Add-on Debugger directly from web-ext](https://github.com/mozilla/web-ext/issues/759). If we want send messages back from the content script to the background page, we would use [`runtime.sendMessage()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/sendMessage) instead of [`tabs.sendMessage()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/sendMessage), e.g.: ```js browser.runtime.sendMessage({ title: "from page-eater.js", }); ``` > **Note:** These examples all inject JavaScript; you can also inject CSS programmatically using the [`tabs.insertCSS()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/insertCSS) function. ## Learn more - [Content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) guide - [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) manifest key - [`permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) manifest key - [`tabs.executeScript()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript) - [`tabs.insertCSS()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/insertCSS) - [`tabs.sendMessage()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/sendMessage) - [`runtime.sendMessage()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/sendMessage) - [`runtime.onMessage`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage) - Examples using `content_scripts`: - [borderify](https://github.com/mdn/webextensions-examples/tree/main/borderify) - [emoji-substitution](https://github.com/mdn/webextensions-examples/tree/main/emoji-substitution) - [notify-link-clicks-i18n](https://github.com/mdn/webextensions-examples/tree/main/notify-link-clicks-i18n) - [page-to-extension-messaging](https://github.com/mdn/webextensions-examples/tree/main/page-to-extension-messaging) - Examples using `tabs.executeScript()`: - [beastify](https://github.com/mdn/webextensions-examples/tree/main/beastify) - [context-menu-copy-link-with-types](https://github.com/mdn/webextensions-examples/tree/main/context-menu-copy-link-with-types)
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/sharing_objects_with_page_scripts/index.md
--- title: Share objects with page scripts slug: Mozilla/Add-ons/WebExtensions/Sharing_objects_with_page_scripts page-type: guide --- {{AddonSidebar}} > **Note:** The techniques described in this section are only available in Firefox, and only from Firefox 49 onwards. > **Warning:** As an extension developer you should consider that scripts running in arbitrary web pages are hostile code whose aim is to steal the user's personal information, damage their computer, or attack them in some other way. > > The isolation between content scripts and scripts loaded by web pages is intended to make it more difficult for hostile web pages to do this. > > Since the techniques described in this section break down that isolation, they are inherently dangerous and should be used with great care. As the [content scripts guide notes](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#dom_access), content scripts don't see changes made to the DOM by scripts loaded by web pages. This means that, for example, if a web page loads a library like jQuery, content scripts won't be able to use it, and have to load their own copy. Conversely, scripts loaded by web pages can't see changes made by content scripts. However, Firefox provides some APIs that enable content scripts to: - access JavaScript objects created by page scripts - expose their own JavaScript objects to page scripts. ## Xray vision in Firefox In Firefox, part of the isolation between content scripts and page scripts is implemented using a feature called "Xray vision". When a script in a more-privileged scope accesses an object that's defined in a less-privileged scope it sees only the "native version" of the object. Any [expando](/en-US/docs/Glossary/Expando) properties are invisible, and if any properties of the object have been redefined, it sees the original implementation, not the redefined version. The purpose of this feature is to make it harder for the less-privileged script to confuse the more-privileged script by redefining the native properties of objects. So, for example, when a content script accesses the page's [window](/en-US/docs/Web/API/Window), it won't see any properties the page script added to the window, and if the page script has redefined any existing properties of the window, the content script will see the original version. ## Accessing page script objects from content scripts In Firefox, DOM objects in content scripts get an extra property `wrappedJSObject`. This is an "unwrapped" version of the object, which includes any changes made to that object by any page scripts. Let's take a simple example. Suppose a web page loads a script: ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> </head> <body> <script src="main.js"></script> </body> </html> ``` The script adds an expando property to the global `window`: ```js // main.js let foo = "I'm defined in a page script!"; ``` Xray vision means that if a content script tries to access `foo`, it will be undefined: ```js // content-script.js console.log(window.foo); // undefined ``` In Firefox, content scripts can use `window.wrappedJSObject` to see the expando property: ```js // content-script.js console.log(window.wrappedJSObject.foo); // "I'm defined in a page script!" ``` Note that once you do this, you can no longer rely on any of this object's properties or functions being, or doing, what you expect. Any of them, even setters and getters, could have been redefined by untrusted code. Also note that unwrapping is transitive: when you use `wrappedJSObject`, any properties of the unwrapped object are themselves unwrapped (and therefore unreliable). So it's good practice, once you've got the object you need, to rewrap it, which you can do like this: ```js XPCNativeWrapper(window.wrappedJSObject.foo); ``` See the document on [Xray vision](https://firefox-source-docs.mozilla.org/dom/scriptSecurity/xray_vision.html) for much more detail on this. ## Sharing content script objects with page scripts Firefox also provides APIs enabling content scripts to make objects available to page scripts. There are several approaches here: - [`exportFunction()`](#exportfunction): export a function to page scripts. - [`cloneInto()`](#cloneinto): export an object to page scripts. - constructors from the page context ### exportFunction Given a function defined in the content script, `exportFunction()` exports it to the page script's scope, so the page script can call it. For example, let's consider an extension which has a background script like this: ```js /* Execute content script in the active tab. */ function loadContentScript() { browser.tabs.executeScript({ file: "/content_scripts/export.js", }); } /* Add loadContentScript() as a listener to clicks on the browser action. */ browser.browserAction.onClicked.addListener(loadContentScript); /* Show a notification when we get messages from the content script. */ browser.runtime.onMessage.addListener((message) => { browser.notifications.create({ type: "basic", title: "Message from the page", message: message.content, }); }); ``` This does two things: - execute a content script in the current tab, when the user clicks a browser action - listen for messages from the content script, and display a [notification](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications) when the message arrives. The content script looks like this: ```js /* Define a function in the content script's scope, then export it into the page script's scope. */ function notify(message) { browser.runtime.sendMessage({ content: `Function call: ${message}` }); } exportFunction(notify, window, { defineAs: "notify" }); ``` This defines a function `notify()`, which just sends its argument to the background script. It then exports the function to the page script's scope. Now the page script can call this function: ```js window.notify("Message from the page script!"); ``` ### cloneInto Given an object defined in the content script, this creates a clone of the object in the page script's scope, thereby making the clone accessible to page scripts. By default, this uses the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) to clone the object, meaning that functions in the object are not included in the clone. To include functions, pass the `cloneFunctions` option. For example, here's a content script that defines an object that contains a function, then clones it into the page script's scope: ```js /* Create an object that contains functions in the content script's scope, then clone it into the page script's scope. Because the object contains functions, the cloneInto call must include the `cloneFunctions` option. */ let messenger = { notify(message) { browser.runtime.sendMessage({ content: `Object method call: ${message}`, }); }, }; window.wrappedJSObject.messenger = cloneInto(messenger, window, { cloneFunctions: true, }); ``` Now page scripts see a new property on the window, `messenger`, which has a function `notify()`: ```js window.messenger.notify("Message from the page script!"); ``` ### Constructors from the page context On the xrayed window object pristine constructors for some built-in JavaScript objects such as `Object`, `Function` or `Proxy` and various DOM classes are available. `XMLHttpRequest` does not behave in this way, see the [XHR and fetch](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#xhr_and_fetch) section for details. They will create instances belonging to the page global's object hierarchy and then return an xray wrapper. Since objects created this way already belong to the page and not the content script passing them back to the page will not require additional cloning or exporting. ```js /* JavaScript built-ins */ const objA = new Object(); const objB = new window.Object(); console.log( objA instanceof Object, // true objB instanceof Object, // false objA instanceof window.Object, // false objB instanceof window.Object, // true "wrappedJSObject" in objB, // true; xrayed ); objA.foo = "foo"; objB.foo = "foo"; // xray wrappers for plain JavaScript objects pass through property assignments objB.wrappedJSObject.bar = "bar"; // unwrapping before assignment does not rely on this special behavior window.wrappedJSObject.objA = objA; window.wrappedJSObject.objB = objB; // automatically unwraps when passed to page context window.eval(` console.log(objA instanceof Object); // false console.log(objB instanceof Object); // true try { console.log(objA.foo); } catch (error) { console.log(error); // Error: permission denied } try { objA.baz = "baz"; } catch (error) { console.log(error); // Error: permission denied } console.log(objB.foo, objB.bar); // "foo", "bar" objB.baz = "baz"; `); /* other APIs */ const ev = new Event("click"); console.log( ev instanceof Event, // true ev instanceof window.Event, // true; Event constructor is actually inherited from the xrayed window "wrappedJSObject" in ev, // true; is an xrayed object ); ev.propA = "propA"; // xray wrappers for native objects do not pass through assignments ev.propB = "wrapper"; // define property on xray wrapper ev.wrappedJSObject.propB = "unwrapped"; // define same property on page object Reflect.defineProperty( // privileged reflection can operate on less privileged objects ev.wrappedJSObject, "propC", { get: exportFunction(() => { // getters must be exported like regular functions return "propC"; }, window), }, ); window.eval(` document.addEventListener("click", (e) => { console.log(e instanceof Event, e.propA, e.propB, e.propC); }); `); document.dispatchEvent(ev); // true, undefined, "unwrapped", "propC" ``` ### Promise cloning A Promise cannot be cloned directly using `cloneInto`, as Promise is not supported by the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). However, the desired result can be achieved using `window.Promise` instead of `Promise`, and then cloning the resolution value like this: ```js const promise = new window.Promise((resolve) => { // if just a primitive, then cloneInto is not needed: // resolve("string is a primitive"); // if not a primitive, such as an object, then the value must be cloned const result = { exampleKey: "exampleValue" }; resolve(cloneInto(result, window)); }); // now the promise can be passed to the web page ```
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/native_messaging/index.md
--- title: Native messaging slug: Mozilla/Add-ons/WebExtensions/Native_messaging page-type: guide --- {{AddonSidebar}} **Native messaging** enables an extension to exchange messages with a native application, installed on the user's computer. The native messaging serves the extensions without additional accesses over the web. Password managers: The native application manages, stores, and encrypts passwords. Then the native application communicates with the extension to populate web forms. Native messaging also enables extensions to access resources that are not accessible through WebExtension APIs (e.g., particular hardware). The native application is not installed or managed by the browser. The native application is installed, using the underlying operating system's installation machinery. Create a JSON file called the "host manifest" or "app manifest". Install the JSON file in a defined location. The app manifest file will describe how the browser can connect to the native application. The extension must request the `"nativeMessaging"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or [optional permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) in the `manifest.json` file. Also, the native application must grant permission for the extension by including the ID in the `"allowed_extensions"` field of the app manifest. After installing, the extension can exchange JSON messages with the native application. Use a set of functions in the {{WebExtAPIRef("runtime")}} API. On the native app side, messages are received using standard input (`stdin`) and sent using standard output (`stdout`). ![Application flow: the native app JSON file resides on the users computer, providing resource information to the native application. The read and write functions of the native application interact with the browser extension's runtime events.](native-messaging.png) Support for native messaging in extensions is mostly compatible with Chrome, with two main differences: - The app manifest lists `allowed_extensions` as an array of app IDs, while Chrome lists `allowed_origins`, as an array of `"chrome-extension"` URLs. - The app manifest is stored in a different location [compared to Chrome](https://developer.chrome.com/docs/apps/nativeMessaging/#native-messaging-host-location). There's a complete example in the ["`native-messaging`" directory](https://github.com/mdn/webextensions-examples/tree/main/native-messaging) of the `"webextensions-examples"` repository on GitHub. Most example code in this article is taken from that example. ## Setup ### Extension manifest Extension communicating with a native application: - Set the `"nativeMessaging"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or [optional permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) in the [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file. - Specify your add-on ID explicitly. Use the [`browser_specific_settings`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) manifest key. (The app's manifest will identify the set of extensions that allow connecting to the IDs). Example `manifest.json` file: ```json { "description": "Native messaging example add-on", "manifest_version": 2, "name": "Native messaging example", "version": "1.0", "icons": { "48": "icons/message.svg" }, "browser_specific_settings": { "gecko": { "id": "[email protected]", "strict_min_version": "50.0" } }, "background": { "scripts": ["background.js"] }, "browser_action": { "default_icon": "icons/message.svg" }, "permissions": ["nativeMessaging"] } ``` > **Note:** Chrome does not support the [browser_specific_settings](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) key. You will need to use another manifest without this key to install an equivalent WebExtension on Chrome. See [Chrome incompatibilities below](#chrome_incompatibilities). > **Note:** When using optional permission, check that permission has been granted and, where necessary, request permission from the user with the {{WebExtAPIRef("permissions")}} API before communicating with the native application. ### App manifest The app manifest describes to the browser how it can connect to the native application. The app manifest file must be installed along with the native application. The browser reads and validates app manifest files, but it does not install or manage them. The security model for when and how these files are installed and updated is much more like that for native applications than that for extensions using WebExtension APIs. For details of native app manifest syntax and location, see [Native manifests](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_manifests). For example, here's a manifest for the `"ping_pong"` native application: ```json { "name": "ping_pong", "description": "Example host for native messaging", "path": "/path/to/native-messaging/app/ping_pong.py", "type": "stdio", "allowed_extensions": ["[email protected]"] } ``` This allows the extension whose ID is `"[email protected]"` to connect, by passing the name `"ping_pong"` into the relevant {{WebExtAPIRef("runtime")}} API function. The application itself is at `"/path/to/native-messaging/app/ping_pong.py"`. > **Note:** Chrome identifies allowed extensions with another key: `allowed_origins`, using the ID of the WebExtension. Refer to [Chrome documentation for more details](https://developer.chrome.com/docs/apps/nativeMessaging/#native-messaging-host) and see [Chrome incompatibilities below](#chrome_incompatibilities). ### Windows setup As an example, you can also refer to [the readme on the native messaging extension on GitHub](https://github.com/SphinxKnight/webextensions-examples/tree/master/native-messaging#windows-setup). If you want to check your local setup after having forked this repository on a Windows machine, you may run `check_config_win.py` to troubleshoot some issues. #### App manifest In the example above, the native application is a Python script. It can be difficult to get Windows to run Python scripts reliably in this way, so an alternative is to provide a `.bat` file, and link to that from the application's manifest: ```json { "name": "ping_pong", "description": "Example host for native messaging", "path": "c:\\path\\to\\native-messaging\\app\\ping_pong_win.bat", "type": "stdio", "allowed_extensions": ["[email protected]"] } ``` (See note above about [Chrome compatibility](#chrome_incompatibilities) regarding the `allowed_extensions` key and its counterpart in Chrome). The batch file then invokes the Python script: ```bash @echo off python -u "c:\\path\\to\\native-messaging\\app\\ping_pong.py" ``` #### Registry The browser finds the extension based on registry keys which are located in a specific location. You need to add them either programmatically with your final application or manually if you are using the example from GitHub. For more details, refer to [Manifest location](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_manifests#manifest_location). Following with the `ping_pong` example, if using Firefox (see [this page for Chrome](https://developer.chrome.com/docs/apps/nativeMessaging/#native-messaging-host-location)), two registry entries should be created for the messaging to work: - `HKEY_CURRENT_USER\Software\Mozilla\NativeMessagingHosts\ping_pong` - The default value for this key should be the path to the _application_ manifest: ex. `C:\Users\<myusername>\webextensions-examples\native-messaging\app\ping_pong.json` - `HKEY_LOCAL_MACHINE\Software\Mozilla\NativeMessagingHosts\ping_pong` - Idem, the default value for this key should be the path to the application manifest. > **Note:** If you base your work on the example located on GitHub, please read [this part of the readme](https://github.com/SphinxKnight/webextensions-examples/tree/master/native-messaging#windows-setup) and check the output of `check_config_win.py` before installing the WebExtension on your browser. ## Exchanging messages Given the above setup, an extension can exchange JSON messages with a native application. ### Extension side Native messaging cannot directly be used in content scripts. You must [do it indirectly via background scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#communicating_with_background_scripts). There are two patterns to use here: **connection-based messaging** and **connectionless messaging**. #### Connection-based messaging With this pattern you call {{WebExtAPIRef("runtime.connectNative()")}}, passing the name of the application (the value of the `"name"` property in the app's manifest). This launches the application if it is not already running and returns a {{WebExtAPIRef("runtime.Port")}} object to the extension. Two arguments are passed to the native app when it starts: - The complete path to the app manifest. - (new in Firefox 55) the ID (as given in the [browser_specific_settings](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) `manifest.json` key) of the add-on that started it. > **Note:** Chrome handles the passed arguments differently: > > - On Linux and Mac, Chrome passes _one_ argument: the origin of the extension that started it (in the form `chrome-extension://[extensionID]`). This enables the app to identify the extension. > - On Windows, Chrome passes _two_ arguments: the first is the origin of the extension, and the second is a handle to the Chrome native window that started the app. The application stays running until the extension calls `Port.disconnect()` or the page that connected to it is closed. To send messages using `Port`, call its `postMessage()` function, passing the JSON message to send. To listen for messages using `Port`, add the listener using its `onMessage.addListener()` function. Here's an example background script that establishes a connection with the `"ping_pong"` app, listens for messages from it, then sends it a `"ping"` message whenever the user clicks the browser action: ```js /* On startup, connect to the "ping_pong" app. */ let port = browser.runtime.connectNative("ping_pong"); /* Listen for messages from the app. */ port.onMessage.addListener((response) => { console.log(`Received: ${response}`); }); /* On a click on the browser action, send the app a message. */ browser.browserAction.onClicked.addListener(() => { console.log("Sending: ping"); port.postMessage("ping"); }); ``` #### Connectionless messaging With this pattern you call {{WebExtAPIRef("runtime.sendNativeMessage()")}}, passing it: - the name of the application - the JSON message to send - optionally, a callback. A new instance of the app is created for each message. The app passes two arguments when starting: - the complete path to the app manifest - (new in Firefox 55) the ID (as given in the [browser_specific_settings](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) manifest.json key) of the add-on that started it. The first message sent by the app is treated as a response to the `sendNativeMessage()` call, and will be passed into the callback. Here's the example above, rewritten to use `runtime.sendNativeMessage()`: ```js function onResponse(response) { console.log(`Received ${response}`); } function onError(error) { console.log(`Error: ${error}`); } /* On a click on the browser action, send the app a message. */ browser.browserAction.onClicked.addListener(() => { console.log("Sending: ping"); let sending = browser.runtime.sendNativeMessage("ping_pong", "ping"); sending.then(onResponse, onError); }); ``` ### App side On the application side, you use standard input to receive messages and standard output to send them. Each message is serialized using JSON, UTF-8 encoded and is preceded with an unsigned 32-bit value containing the message length in native byte order. The maximum size of a single message from the application is 1 MB. The maximum size of a message sent to the application is 4 GB. You can quickly get started sending and receiving messages with this NodeJS code, `nm_nodejs.mjs`: ```js #!/usr/bin/env -S /full/path/to/node import fs from "node:fs/promises"; async function getMessage() { const header = new Uint32Array(1); await readFullAsync(1, header); const message = await readFullAsync(header[0]); return message; } async function readFullAsync(length, buffer = new Uint8Array(65536)) { const data = []; while (data.length < length) { const input = await fs.open("/dev/stdin"); const { bytesRead } = await input.read({ buffer }); await input.close(); if (bytesRead === 0) { break; } data.push(...buffer.subarray(0, bytesRead)); } return new Uint8Array(data); } async function sendMessage(message) { const header = new Uint32Array([message.length]); const stdout = await fs.open(`/proc/${process.pid}/fd/1`, "w"); await stdout.write(header); await stdout.write(message); await stdout.close(); } while (true) { try { const message = await getMessage(); await sendMessage(message); } catch (e) { console.error(e); process.exit(1); } } ``` Here's another example written in Python. It listens for messages from the extension. Note that the file has to be executable on Linux. If the message is `"ping"`, then it responds with a message `"pong"`. This is the Python 2 version: ```python #!/usr/bin/env -S python2 -u # Note that running python with the `-u` flag is required on Windows, # in order to ensure that stdin and stdout are opened in binary, rather # than text, mode. import json import sys import struct # Read a message from stdin and decode it. def get_message(): raw_length = sys.stdin.read(4) if not raw_length: sys.exit(0) message_length = struct.unpack('=I', raw_length)[0] message = sys.stdin.read(message_length) return json.loads(message) # Encode a message for transmission, given its content. def encode_message(message_content): # https://docs.python.org/3/library/json.html#basic-usage # To get the most compact JSON representation, you should specify # (',', ':') to eliminate whitespace. # We want the most compact representation because the browser rejects # messages that exceed 1 MB. encoded_content = json.dumps(message_content, separators=(',', ':')) encoded_length = struct.pack('=I', len(encoded_content)) return {'length': encoded_length, 'content': encoded_content} # Send an encoded message to stdout. def send_message(encoded_message): sys.stdout.write(encoded_message['length']) sys.stdout.write(encoded_message['content']) sys.stdout.flush() while True: message = get_message() if message == "ping": send_message(encode_message("pong")) ``` In Python 3, the received binary data must be decoded into a string. The content to be sent back to the addon must be encoded into binary data using a struct: ```python #!/usr/bin/env -S python3 -u # Note that running python with the `-u` flag is required on Windows, # in order to ensure that stdin and stdout are opened in binary, rather # than text, mode. import sys import json import struct # Read a message from stdin and decode it. def getMessage(): rawLength = sys.stdin.buffer.read(4) if len(rawLength) == 0: sys.exit(0) messageLength = struct.unpack('@I', rawLength)[0] message = sys.stdin.buffer.read(messageLength).decode('utf-8') return json.loads(message) # Encode a message for transmission, # given its content. def encodeMessage(messageContent): # https://docs.python.org/3/library/json.html#basic-usage # To get the most compact JSON representation, you should specify # (',', ':') to eliminate whitespace. # We want the most compact representation because the browser rejects # messages that exceed 1 MB. encodedContent = json.dumps(messageContent, separators=(',', ':')).encode('utf-8') encodedLength = struct.pack('@I', len(encodedContent)) return {'length': encodedLength, 'content': encodedContent} # Send an encoded message to stdout def sendMessage(encodedMessage): sys.stdout.buffer.write(encodedMessage['length']) sys.stdout.buffer.write(encodedMessage['content']) sys.stdout.buffer.flush() while True: receivedMessage = getMessage() if receivedMessage == "ping": sendMessage(encodeMessage("pong")) ``` ## Closing the native app If you connected to the native application using `runtime.connectNative()`, then it stays running until the extension calls `Port.disconnect()` or the page that connected to it is closed. If you started the native application by sending `runtime.sendNativeMessage()`, then it is closed after it has received the message and sent a response. To close the native application: - On \*nix systems like macOS and Linux, the browser sends `SIGTERM` to the native application, then `SIGKILL` after the application has had a chance to exit gracefully. These signals propagate to any subprocesses unless they break away into a new process group. - On Windows, the browser puts the native application's process into a [Job object](<https://msdn.microsoft.com/library/windows/desktop/ms684161(v=vs.85).aspx>) and kills the job. If the native application launches additional processes and wants them to remain open after the native application is killed, then the native application must launch the additional process with the [`CREATE_BREAKAWAY_FROM_JOB`](<https://msdn.microsoft.com/library/windows/desktop/ms684863(v=vs.85).aspx>) flag, such as by using `CreateProcess`. ## Troubleshooting If something goes wrong, check the [browser console](https://extensionworkshop.com/documentation/develop/debugging/#viewing_log_output). If the native application sends any output to stderr, the browser will redirect it to the browser console. So if you've got as far as launching the native application, you will see any error messages it emits. If you haven't managed to run the application, you should see an error message giving you a clue about the problem. ```plain "No such native application <name>" ``` - Check that the name passed to `runtime.connectNative()` matches the name in the app manifest - macOS/Linux: check that name of the app manifest is `<name>.json`. - macOS/Linux: check the native application's manifest file location as mentioned [here](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_manifests#mac_os_x). - Windows: check that the registry key is in the correct place, and that its name matches the name in the app manifest. - Windows: check that the path given in the registry key points to the app manifest. ```plain "Error: Invalid application <name>" ``` - Check that the application's name contains no invalid characters. ```plain "'python' is not recognized as an internal or external command, ..." ``` - Windows: if your application is a Python script, check that you have Python installed and have your path set up for it. ```plain "File at path <path> does not exist, or is not executable" ``` - If you see this, then the app manifest has been found successfully. - Check that the "path" in the app's manifest is correct. - Windows: check that you've escaped the path separators (`"c:\\path\\to\\file"`). - Check that the app is at the location pointed to by the `"path"` property in the app's manifest. - Check that the app is executable. ```plain "This extension does not have permission to use native application <name>" ``` - Check that the `"allowed_extensions"` key in the app manifest contains the add-on's ID. ```plain "TypeError: browser.runtime.connectNative is not a function" ``` - Check that the extension has the `"nativeMessaging"` permission. ```plain "[object Object] NativeMessaging.jsm:218" ``` - There was a problem starting the application. ## Chrome incompatibilities There are a number of differences between browsers that affect native messaging in web extensions, including the arguments passed to the native app, location of the manifest file, etc. These differences are discussed in [Chrome incompatibilities > Native messaging](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#native_messaging).
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/your_first_webextension/index.md
--- title: Your first extension slug: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension page-type: guide --- {{AddonSidebar}} > **Note:** If you're familiar with the basic concepts of browser extensions, skip this section to [see how extension files are put together](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension). Then, use the [reference documentation](/en-US/docs/Mozilla/Add-ons/WebExtensions#reference) to start building your extension. Visit [Firefox Extension Workshop](https://extensionworkshop.com/?utm_source=developer.mozilla.org&utm_medium=documentation&utm_campaign=your-first-extension) to learn more about the workflow for testing, publishing, and extensions for Firefox. This article walks through creating an extension for Firefox, from start to finish. The extension adds a red border to any pages loaded from "`mozilla.org`" or any of its subdomains. The source code for this example is on GitHub: <https://github.com/mdn/webextensions-examples/tree/main/borderify>. ## Writing the extension In a suitable location, such as in the `Documents` directory, create a new directory called `borderify` and navigate to it. You can do this using your computer's file explorer or [command line terminal](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line). Understanding how to use the command line terminal is a handy skill, as it helps with your more advanced extension development. Using the terminal, you create the directory like this: ```bash mkdir borderify cd borderify ``` ### manifest.json Using a suitable [text editor](/en-US/docs/Learn/Common_questions/Tools_and_setup/Available_text_editors), create a new file called "manifest.json" directly under the "borderify" directory. Give it the following contents: ```json { "manifest_version": 2, "name": "Borderify", "version": "1.0", "description": "Adds a red border to all webpages matching mozilla.org.", "icons": { "48": "icons/border-48.png" }, "content_scripts": [ { "matches": ["*://*.mozilla.org/*"], "js": ["borderify.js"] } ] } ``` - The first three keys: [`manifest_version`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version), [`name`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name), and [`version`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version), are mandatory and contain basic metadata for the extension. - [`description`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/description) is optional, but recommended: it's displayed in the Add-ons Manager. - [`icons`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons) is optional, but recommended: it allows you to specify an icon for the extension, that will be shown in the Add-ons Manager. The most interesting key here is [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts), which tells Firefox to load a script into Web pages whose URL matches a specific pattern. In this case, we're asking Firefox to load a script called "borderify.js" into all HTTP or HTTPS pages served from "mozilla.org" or any of its subdomains. - [Learn more about content scripts.](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) - [Learn more about match patterns](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns). > **Warning:** [In some situations you need to specify an ID for your extension](https://extensionworkshop.com/documentation/develop/extensions-and-the-add-on-id/#when_do_you_need_an_add-on_id). If you do need to specify an add-on ID, include the [`browser_specific_settings`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) key in `manifest.json` and set its `gecko.id` property: > > ```json > "browser_specific_settings": { > "gecko": { > "id": "[email protected]" > } > } > ``` ### icons/border-48.png The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager. Our manifest.json promised that we would have an icon at "icons/border-48.png". Create the "icons" directory directly under the "borderify" directory. Save an icon there named "border-48.png". You could use [the one from our example](https://raw.githubusercontent.com/mdn/webextensions-examples/main/borderify/icons/border-48.png), which is taken from the Google Material Design iconset, and is used under the terms of the [Creative Commons Attribution-ShareAlike](https://creativecommons.org/licenses/by-sa/3.0/) license. If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the `96` property of the `icons` object in manifest.json: ```json "icons": { "48": "icons/border-48.png", "96": "icons/border-96.png" } ``` Alternatively, you could supply an SVG file here, and it will be scaled correctly. (Though: if you're using SVG and your icon includes text, you may want to use your SVG editor's "convert to path" tool to flatten the text, so that it scales with a consistent size/position.) - [Learn more about specifying icons.](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons) ### borderify.js Finally, create a file called "borderify.js" directly under the "borderify" directory. Give it this content: ```js document.body.style.border = "5px solid red"; ``` This script will be loaded into the pages that match the pattern given in the `content_scripts` manifest.json key. The script has direct access to the document, just like scripts loaded by the page itself. - [Learn more about content scripts.](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) ## Trying it out First, double check that you have the right files in the right places: ```plain borderify/ icons/ border-48.png borderify.js manifest.json ``` ### Installing In Firefox: Open the [about:debugging](https://firefox-source-docs.mozilla.org/devtools-user/about_colon_debugging/index.html) page, click the This Firefox option, click the Load Temporary Add-on button, then select any file in your extension's directory. The extension now installs, and remains installed until you restart Firefox. Alternatively, you can run the extension from the command line using the [web-ext](https://extensionworkshop.com/documentation/develop/getting-started-with-web-ext/) tool. ### Testing > **Note:** By default [extensions don't work in private browsing](https://support.mozilla.org/en-US/kb/extensions-private-browsing). If you want to test this extension in private browsing open "`about:addons`", click on the extension, and select the Allow radio button for Run in Private Windows. Now visit a page under "`https://www.mozilla.org/en-US/`", and you should see the red border round the page. ![Border displayed on mozilla.org](border_on_mozilla_org.png) > **Note:** Don't try it on "`addons.mozilla.org`", though! Content scripts are currently blocked on that domain. Try experimenting a bit. Edit the content script to change the color of the border, or do something else to the page content. Save the content script, then reload the extension's files by clicking the Reload button in "`about:debugging`". You can see the changes right away. - [Learn more about loading extensions](https://extensionworkshop.com/documentation/develop/temporary-installation-in-firefox/) ## Packaging and publishing For other people to use your extension, you need to package it and submit it to Mozilla for signing. To learn more about that, see ["Publishing your extension"](https://extensionworkshop.com/documentation/publish/package-your-extension/). ## What's next? Now you've had an introduction to the process of developing a WebExtension for Firefox: - [write a more complex extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_second_WebExtension) - [read more about the anatomy of an extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension) - [explore the extension examples](/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples) - [find out what you need to develop, test, and publish your extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_next) - [take your learning further](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_next#continue_your_learning_experience).
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/work_with_contextual_identities/index.md
--- title: Work with contextual identities slug: Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities page-type: guide --- {{AddonSidebar}} Many people need or want to interact with the web using multiple personas. They may have accounts for web-based work and personal email. They might sign out of their social media accounts before accessing online shopping, to ensure that any tracking scripts on the shopping sites can't pick up their social media activity. Users often use a standard and private browser window or two different browsers to address these requirements. To address this need, Firefox includes a feature known as contextual identities, container tabs, or account containers. This feature enables the creation of a cookie container (store) for each of the identities the user wants to use in their browser. Tabs can be associated with one of these identities, keeping cookies separate from those of other identities in the browser. The practical upshot of this is that, for example, a user could have a personal and work identity. They can then, for example, use the personal identity in one tab, where they sign into their personal web mail, and the work identity in another tab, where they sign into their work web mail. For more background on this feature, see: - [Put your multiple online personalities in Firefox Multi-Account Containers](https://blog.mozilla.org/en/products/firefox/introducing-firefox-multi-account-containers/) - [Security/Contextual Identity Project/Containers](https://wiki.mozilla.org/Security/Contextual_Identity_Project/Containers) - [Firefox support article on containers](https://support.mozilla.org/en-US/kb/containers?redirectlocale=en-US&as=u&redirectslug=containers-experiment&utm_source=inproduct) ## APIs for working with contextual identities Depending on the nature of your extension, you may want to manage contextual identities, associate objects your extension manipulates with contextual identities, or both. ### Managing contextual identities To manage contextual identities, you use the {{WebExtAPIRef("contextualIdentities")}} API. This API enables you to add, query, update, and delete contextual identities. When you create a contextual identity, it is given a unique `cookieStoreId`. You use this ID to work with entities related to the contextual identity. ### Using `cookieStoreId` Several extension APIs include the `cookieStoreId` in objects to enable extensions to associate these objects with specific contextual identities. - {{WebExtAPIRef("browsingData.removeCookies()")}} and {{WebExtAPIRef("browsingData.removeLocalStorage()")}} where you use {{WebExtAPIRef("browsingData.removalOptions")}} to set the cookie store items are removed from. - {{WebExtAPIRef("contentscripts.register")}} enables you to register a content script restricted to documents associated with one or more `cookieStoreIds`. - {{WebExtAPIRef("downloads")}} where you can associate a download with a cookie store. - {{WebExtAPIRef("proxy")}} where the details passed into the {{WebExtAPIRef("proxy.onRequest")}} listener identify the cookie store associated with the request. - {{WebExtAPIRef("tabs")}} where you can {{WebExtAPIRef("tabs.create","create")}} a tab in a container tab, {{WebExtAPIRef("tabs.tab","get")}} the `cookieStoreId` for a tab, and {{WebExtAPIRef("tabs.query","query")}} tabs based on their associated cookie store. - {{WebExtAPIRef("userscripts.register")}} enables you to register a content script restricted to documents associated with one or more `cookieStoreIds`. - {{WebExtAPIRef("webrequest")}} where all the events return the `cookieStoreId` of the request. - {{WebExtAPIRef("windows.create")}} where you can specify the cookie store for the tabs added to a window when it's created. ## Permissions To use the {{WebExtAPIRef("contextualIdentities")}} API, you must include the "contextualIdentities" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) in your [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file. If an API enables cookies to be modified, you need the "cookies" permission. For example, using `cookieStoreId` in {{WebExtAPIRef("tabs.query")}} does not require the "cookies" API, as reading the property doesn't affect the cookies in the containers. However, using {{WebExtAPIRef("tabs.create")}} requires the permission because the opened tab can read and modify cookies in a container. ## Example walkthrough The example extension [contextual-identities](https://github.com/mdn/webextensions-examples/tree/main/contextual-identities) provides a toolbar button with a popup that lists the identities in the browser. For each identity, the extension provides options to create a tab using its cookies container or remove all of its tabs. Here is a short video of the extension in action: {{EmbedYouTube("SgLCS7_ppas")}} ### manifest.json The main features of the [manifest.json](https://github.com/mdn/webextensions-examples/blob/main/contextual-identities/manifest.json) file are: - the permissions request: ```json "permissions": [ "contextualIdentities", "cookies" ], ``` - specification of the toolbar button (browserAction) that provides access to the extension's features: ```json "browser_action": { "default_title": "Contextual Identities", "default_popup": "context.html", "default_icon": { "128": "identity.svg" } ``` ## context.html A popup on the toolbar button provides the extension's user interface. [context.html](https://github.com/mdn/webextensions-examples/blob/main/contextual-identities/context.html) implements this popup, but it's just a shell into which the context.js script writes the list of contextual identities and their related options. ```html <body> <div class="panel"> <div id="identity-list"></div> </div> <script src="context.js"></script> </body> ``` ## context.js All the extension's features are implemented through [context.js](https://github.com/mdn/webextensions-examples/blob/main/contextual-identities/context.js), which is invoked whenever the toolbar popup is displayed. The script first gets the 'identity-list' `<div>` from context.html. ```js let div = document.getElementById("identity-list"); ``` It then checks whether the contextual identities feature is turned on in the browser. If it's not on, information on how to activate it is added to the popup. ```js if (browser.contextualIdentities === undefined) { div.innerText = 'browser.contextualIdentities not available. Check that the privacy.userContext.enabled pref is set to true, and reload the add-on.'; } else { ``` Firefox installs with the contextual identity feature turned off. It's turned on when an extension using the `contextualIdentities` API is installed. However, the user can turn the feature off using an option on the preferences page (about:preferences), hence the need for the check. The script now uses {{WebExtAPIRef("contextualIdentities.query.")}} to determine whether any contextual identities are defined in the browser. If there are none, a message is added to the popup and the script stops. ```js browser.contextualIdentities.query({}) .then((identities) => { if (!identities.length) { div.innerText = 'No identities returned from the API.'; return; } ``` If there are contextual identities present—Firefox comes with four default identities—the script loops through each one adding its name, styled in its chosen color, to the `<div>` element. The function `createOptions()` then adds the options to "create" or "close all" to the `<div>` before it's added to the popup. ```js for (const identity of identities) { const row = document.createElement('div'); const span = document.createElement('span'); span.className = 'identity'; span.innerText = identity.name; span.style = `color: ${identity.color}`; console.log(identity); row.appendChild(span); createOptions(row, identity); div.appendChild(row); } }); } function createOptions(node, identity) { for (const option of ['Create', 'Close All']) { const a = document.createElement('a'); a.href = '#'; a.innerText = option; a.dataset.action = option.toLowerCase().replace(' ', '-'); a.dataset.identity = identity.cookieStoreId; a.addEventListener('click', eventHandler); node.appendChild(a); } } ``` The script now waits for the user to select an option in the popup. ```js function eventHandler(event) { ``` If the user clicks the option to create a tab for an identity, one is opened using {{WebExtAPIRef("tabs.create")}} by passing the identity's cookie store ID. ```js if (event.target.dataset.action === "create") { browser.tabs.create({ url: "about:blank", cookieStoreId: event.target.dataset.identity, }); } ``` If the user selects the option to close all tabs for the identity, the script performs a {{WebExtAPIRef("tabs.query")}} to get all the tabs using the identity's cookie store. The script then passes this list of tabs to {{WebExtAPIRef("tabs.remove")}}. ```js if (event.target.dataset.action === 'close-all') { browser.tabs.query({ cookieStoreId: event.target.dataset.identity }).then((tabs) => { browser.tabs.remove(tabs.map((i) => i.id)); }); } event.preventDefault(); } ``` ## Learn more If you want to learn more about the contextualIdentities API, check out: - [contextualIdentities API reference](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/contextualIdentities). - [Multi-Account Containers](https://github.com/mozilla/multi-account-containers/#readme) extension source code. This is code for the [Firefox Multi-Account Containers](https://addons.mozilla.org/en-US/firefox/addon/multi-account-containers/) extension. This extension provides users with enhanced functionality for contextual identities, such as the ability to long-click the new tab button and then select the identity to use in the new tab. It showcases contextual identities' capabilities and is well worth a look.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/examples/index.md
--- title: Example extensions slug: Mozilla/Add-ons/WebExtensions/Examples page-type: guide --- {{AddonSidebar}} To illustrate how to use the WebExtension APIs, we maintain a repository of example extensions at <https://github.com/mdn/webextensions-examples>. This article describes how to run these examples and lists the examples along with the WebExtension APIs they demonstrate. These examples work in Firefox Nightly: most work in earlier versions of Firefox, but check the [strict_min_version](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) key in the extension's manifest.json to make sure. > **Warning:** Some examples work only on specific domains or pages. Details of any restrictions are provided in each example's readme file. None of the examples work in private browsing windows by default, see [Extensions in Private Browsing](https://support.mozilla.org/en-US/kb/extensions-private-browsing#w_enabling-or-disabling-extensions-in-private-windows) for details. To try these examples, clone the repository, then install and run the extension using one of these options: - use the [Load Temporary Add-on](https://extensionworkshop.com/documentation/develop/temporary-installation-in-firefox/) feature and open the extension from its source folder. - install [`web-ext`](https://extensionworkshop.com/documentation/develop/getting-started-with-web-ext/), open the extension's source folder at the command line, and use `web-ext run`. The extension stays loaded until you restart Firefox. > **Warning:** Please do not submit these WebExtension examples to addons.mozilla.org (AMO); you do not have to sign the add-on WebExtension examples to run them. If you want to contribute to the repository, [send us a pull request.](https://github.com/mdn/webextensions-examples/blob/main/CONTRIBUTING.md) {{WebExtAllExamples}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/index.md
--- title: manifest.json slug: Mozilla/Add-ons/WebExtensions/manifest.json page-type: landing-page browser-compat: webextensions.manifest --- {{AddonSidebar}} > **Note:** This article describes manifest.json for web extensions. If you are looking for information about the manifest.json in PWAs, check out the [Web App Manifest](/en-US/docs/Web/Manifest) article. The `manifest.json` file is the only file that every extension using WebExtension APIs must contain. Using `manifest.json`, you specify basic metadata about your extension such as the name and version, and can also specify aspects of your extension's functionality (such as background scripts, content scripts, and browser actions). It is a [JSON](/en-US/docs/Glossary/JSON)-formatted file, with one exception: it is allowed to contain "`//`"-style comments. ## List of manifest.json keys These are the `manifest.json` keys; these keys are available in Manifest V2 and above unless otherwise noted: - [action](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/action) (Manifest V3 and above) - [author](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/author) - [background](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/background) - [browser_action](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) (Manifest V2 only) - [browser_specific_settings](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) - [chrome_settings_overrides](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_settings_overrides) - [chrome_url_overrides](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_url_overrides) - [commands](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/commands) - [content_scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) - [content_security_policy](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy) - [declarative_net_request](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request) - [default_locale](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/default_locale) - [description](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/description) - [developer](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/developer) - [devtools_page](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page) - [dictionaries](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/dictionaries) - [externally_connectable](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/externally_connectable) - [homepage_url](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/homepage_url) - [host_permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/host_permissions) (Manifest V3 and above) - [icons](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons) - [incognito](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/incognito) - [manifest_version](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version) - [name](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name) - [offline_enabled](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/offline_enabled) - [omnibox](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/omnibox) - [optional_permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) - [options_page](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_page) - [options_ui](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui) - [page_action](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action) (Manifest V2 only in Chrome) - [permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) - [protocol_handlers](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/protocol_handlers) - [short_name](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/short_name) - [sidebar_action](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action) - [storage](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/storage) - [theme](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme) - [theme_experiment](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme_experiment) - [user_scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/user_scripts) (Manifest V2 only) - [version](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version) - [version_name](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version_name) - [web_accessible_resources](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources) ### Notes about manifest.json keys - `"manifest_version"`, `"version"`, and `"name"` are the only mandatory keys. - `"default_locale"` must be present if the "`_locales`" directory is present, and must be absent otherwise. - `"browser_specific_settings"` is not supported in Google Chrome. ### Accessing manifest.json keys at runtime You can access your extension's manifest from the extension's JavaScript using the {{WebExtAPIRef("runtime.getManifest()")}} function: ```js browser.runtime.getManifest().version; ``` ## Example The block below shows the basic syntax for some common manifest keys. > **Note:** This is not intended to be used as a copy-paste-ready example. Selecting the keys you'll need depends on the extension you are developing. For complete example extensions, see [Example extensions](/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples). ```json { "browser_specific_settings": { "gecko": { "id": "[email protected]", "strict_min_version": "42.0" } }, "background": { "scripts": ["jquery.js", "my-background.js"] }, "browser_action": { "default_icon": { "19": "button/geo-19.png", "38": "button/geo-38.png" }, "default_title": "Whereami?", "default_popup": "popup/geo.html" }, "commands": { "toggle-feature": { "suggested_key": { "default": "Ctrl+Shift+Y", "linux": "Ctrl+Shift+U" }, "description": "Send a 'toggle-feature' event" } }, "content_security_policy": "script-src 'self' https://example.com; object-src 'self'", "content_scripts": [ { "exclude_matches": ["*://developer.mozilla.org/*"], "matches": ["*://*.mozilla.org/*"], "js": ["borderify.js"] } ], "default_locale": "en", "description": "…", "icons": { "48": "icon.png", "96": "[email protected]" }, "manifest_version": 2, "name": "…", "page_action": { "default_icon": { "19": "button/geo-19.png", "38": "button/geo-38.png" }, "default_title": "Whereami?", "default_popup": "popup/geo.html" }, "permissions": ["webNavigation"], "version": "0.1", "user_scripts": { "api_script": "apiscript.js" }, "web_accessible_resources": ["images/my-image.png"] } ``` ## Browser compatibility For a full overview of all manifest keys and their sub-keys, see the [full manifest.json browser compatibility table](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_compatibility_for_manifest.json). {{Compat}} ## See also {{WebExtAPIRef("permissions")}} JavaScript API
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/omnibox/index.md
--- title: omnibox slug: Mozilla/Add-ons/WebExtensions/manifest.json/omnibox page-type: webextension-manifest-key browser-compat: webextensions.manifest.omnibox --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "omnibox": { "keyword": "mdn" }</pre > </td> </tr> </tbody> </table> Use the `omnibox` key to define an omnibox keyword for your extension. When the user types this keyword into the browser's address bar, followed by a space, then any subsequent characters will be sent to the extension using the [`omnibox`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/omnibox) API. The extension will then be able to populate the address bar's drop-down suggestions list with its own suggestions. If two or more extensions define the same keyword, then the extension that was installed last gets to control the keyword. Any previously installed extensions that defined the same keyword will no longer be able to use the `omnibox` API. ## Example ```json "omnibox": { "keyword": "mdn" } ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/name/index.md
--- title: name slug: Mozilla/Add-ons/WebExtensions/manifest.json/name page-type: webextension-manifest-key browser-compat: webextensions.manifest.name --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>String</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>Yes</td> </tr> <tr> <th scope="row">Example</th> <td><pre class="brush: json">"name": "My Extension"</pre></td> </tr> </tbody> </table> Name of the extension. This is used to identify the extension in the browser's user interface and on sites like addons.mozilla.org. It's good practice to keep the name short enough to display in the UI. Google Chrome and Microsoft Edge restrict the name length to 45 characters. This is a [localizable property](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json). ## Example ```json "name": "My Extension" ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/developer/index.md
--- title: developer slug: Mozilla/Add-ons/WebExtensions/manifest.json/developer page-type: webextension-manifest-key browser-compat: webextensions.manifest.developer --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "developer": { "name": "Walt Whitman", "url": "https://en.wikipedia.org/wiki/Walt_Whitman" }</pre > </td> </tr> </tbody> </table> The name of the extension's developer and their homepage URL, intended for display in the browser's user interface. The object, and both of its properties, are optional. The "name" and "url" properties, if present, will override the [author](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/author) and [homepage_url](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/homepage_url) keys, respectively. This object only allows for a single developer name and URL to be specified. This is a [localizable property](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json). ## Example ```json "developer": { "name": "Walt Whitman", "url": "https://en.wikipedia.org/wiki/Walt_Whitman" } ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/manifest_version/index.md
--- title: manifest_version slug: Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version page-type: webextension-manifest-key browser-compat: webextensions.manifest.manifest_version --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Number</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>Yes</td> </tr> <tr> <th scope="row">Example</th> <td><pre class="brush: json">"manifest_version": 3</pre></td> </tr> </tbody> </table> This key specifies the version of manifest.json used by this extension. ## Example ```json "manifest_version": 3 ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/protocol_handlers/index.md
--- title: protocol_handlers slug: Mozilla/Add-ons/WebExtensions/manifest.json/protocol_handlers page-type: webextension-manifest-key browser-compat: webextensions.manifest.protocol_handlers --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Array</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "protocol_handlers": [ { "protocol": "ircs", "name": "IRC Mozilla Extension", "uriTemplate": "https://irccloud.mozilla.com/#!/%s" } ]</pre > </td> </tr> </tbody> </table> Use this key to register one or more web-based protocol handlers. A protocol handler is an application that knows how to handle particular types of links: for example, a mail client is a protocol handler for "mailto:" links. When the user clicks a "mailto:" link, the browser opens the application selected as the handler for the "mailto:" protocol (or offers them a choice of handlers, depending on their settings). > **Note:** By default, extensions do not run in private browsing windows. As protocol handlers are part of the extension, they don't work in private browsing windows by default. Whether an extension can access private browsing windows and its protocol handlers become active is under user control. For details, see [Extensions in Private Browsing](https://support.mozilla.org/en-US/kb/extensions-private-browsing). Your extension can check whether it can access private browsing windows using {{WebExtAPIRef("extension.isAllowedIncognitoAccess")}}. With this key, you can register a website as a handler for a particular protocol. The syntax and semantics of this key is very much like the [`Navigator.registerProtocolHandler()`](/en-US/docs/Web/API/Navigator/registerProtocolHandler) function, except that with `registerProtocolHandler()` a website can only register itself as a handler. Each protocol handler has three properties, all mandatory: - `protocol` - : A string defining the protocol. This must be either: - one of the following: "bitcoin", "dat", "dweb", "ftp", "geo", "gopher", "im", "ipfs", "ipns", "irc", "ircs", "magnet", "mailto", "matrix", "mms", "news", "nntp", "sip", "sms", "smsto", "ssb", "ssh", "tel", "urn", "webcal", "wtai", "xmpp". - a string consisting of a custom name prefixed with "web+" or "ext+". For example: "web+foo" or "ext+foo". The custom name must consist only of lower-case {{Glossary("ASCII")}} characters. It's recommended that extensions use the "ext+" form. - `name` - : A string representing the name of the protocol handler. This will be displayed to the user when they are being asked if they want this handler to open the link. - `uriTemplate` - : A string representing the URL of the handler. This string must include "%s" as a placeholder: this will be replaced with the escaped URL of the document to be handled. This URL might be a true URL, or it could be a phone number, email address, or so forth. This is a [localizable property](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json). ## Example ```json "protocol_handlers": [ { "protocol": "magnet", "name": "Magnet Extension", "uriTemplate": "https://example.com/#!/%s" } ] ``` If the protocol is not in the allowed list then it has to start with 'ext+' ```json "protocol_handlers": [ { "protocol": "ext+foo", "name": "Foo Extension", "uriTemplate": "https://example.com/#!/%s" } ] ``` Handlers can also be [extension pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages). ```json "protocol_handlers": [ { "protocol": "magnet", "name": "Magnet Extension", "uriTemplate": "/example.xhtml#!/%s" } ] ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/options_ui/index.md
--- title: options_ui slug: Mozilla/Add-ons/WebExtensions/manifest.json/options_ui page-type: webextension-manifest-key browser-compat: webextensions.manifest.options_ui --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json;"> "options_ui": { "page": "options/options.html" }</pre > </td> </tr> </tbody> </table> Use the `options_ui` key to define an [options page](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages) for your extension. The options page contains settings for the extension. The user can access it from the browser's add-ons manager, and you can open it from within your extension using {{WebExtAPIRef("runtime.openOptionsPage()")}}. You specify `options_ui` as a path to an HTML file packaged with your extension. The HTML file can include CSS and JavaScript files, just like a normal web page. Unlike a normal page, though, the JavaScript can use all the [WebExtension APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/API) that the extension has [permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) for. However, it runs in a different scope than your background scripts. If you want to **share** data or functions between the JavaScript on your **options page** and your **background script(s)**, you can do so directly by obtaining a reference to the [Window](/en-US/docs/Web/API/Window) of your background scripts by using {{WebExtAPIRef("extension.getBackgroundPage()")}}, or a reference to the {{domxref("Window")}} of any of the pages running within your extension with {{WebExtAPIRef("extension.getViews()")}}. Alternately, you can communicate between the JavaScript for your options page and your background script(s) using {{WebExtAPIRef("runtime.sendMessage()")}}, {{WebExtAPIRef("runtime.onMessage")}}, or {{WebExtAPIRef("runtime.connect()")}}. The latter (or {{WebExtAPIRef("runtime.Port")}} equivalents) can also be used to share options between your [background script(s)](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#background_scripts) and your **[content script(s).](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts)** In general, you will want to store options changed on option pages using the {{WebExtAPIRef("storage", "storage API", "", "true")}} to either {{WebExtAPIRef("storage.sync")}} (if you want the settings synchronized across all instances of that browser that the user is logged into), or {{WebExtAPIRef("storage.local")}} (if the settings are local to the current machine/profile). If you do so and your [background script(s)](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#background_scripts) (or [content script(s)](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts)) need to know about the change, your script(s) might choose to add a listener to {{WebExtAPIRef("storage.onChanged")}}. ## Syntax The `options_ui` key is an object with the following contents: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td> <code> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles"> browser_style </a> </code> <br />{{optional_inline}} <br />{{deprecated_inline}} in Manifest V3. </td> <td><code>Boolean</code></td> <td> <p>Optional, defaulting to:</p> <ul> <li><code>true</code> in Manifest V2 and prior to Firefox 115 in Manifest V3.</li> <li><code>false</code> in Manifest V3 from Firefox 115.</li> </ul> <div class="notecard warning"> <p> Do not set <code>browser_style</code> to true: its not support in Manifest V3 from Firefox 118. See <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles#manifest_v3_migration">Manifest V3 migration for <code>browser_style</code></a>. </p> </div> <p> In Firefox, the stylesheet can be seen at <code>chrome://browser/content/extension.css</code> or <code>chrome://browser/content/extension-mac.css</code> on macOS. When setting dimensions, be aware that this stylesheet sets <code>box-sizing: border-box</code> (see <a href="/en-US/docs/Web/CSS/box-sizing">box-sizing</a>). </p> </td> </tr> <tr> <td><code>open_in_tab</code><br />{{optional_inline}}</td> <td><code>Boolean</code></td> <td> <p>Defaults to <code>false</code>.</p> <p> If <code>true</code>, the options page will open in a normal browser tab, rather than being integrated into the browser's add-ons manager. </p> </td> </tr> <tr> <td><code>page</code></td> <td><code>String</code></td> <td> <p>Mandatory.</p> <p> The path to an HTML file containing the specification of your options page. </p> <p> The path is relative to the location of <code>manifest.json</code> itself. </p> </td> </tr> </tbody> </table> ## Example ```json "options_ui": { "page": "options/options.html" } ``` ## Browser compatibility {{Compat}} ## See also - [`options_page`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_page) {{deprecated_inline}} - [Browser styles](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles) - [Options pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages)
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/host_permissions/index.md
--- title: host_permissions slug: Mozilla/Add-ons/WebExtensions/manifest.json/host_permissions page-type: webextension-manifest-key browser-compat: webextensions.manifest.host_permissions --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Array</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>3 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json;"> "host_permissions": [ "*://developer.mozilla.org/*", "*://*.example.org/*" ]</pre > </td> </tr> </tbody> </table> Use the `host_permissions` key to request access for the APIs in your extension that read or modify host data, such as {{WebExtAPIRef("cookies")}}, {{WebExtAPIRef("webRequest")}}, and {{WebExtAPIRef("tabs")}}. This key is an array of strings, and each string is a request for a permission. ### Requested permissions and user prompts Most browsers treat `host_permission` as optional. If you request permissions using this key, users _may_ get prompted to grant those permissions during installation. As of June 2023, Safari, Firefox, and some Chromium-based browsers don't prompt the user during installation. Users can also grant or revoke host permissions on an ad hoc basis. For example, in Firefox, users can do this using the [extensions panel](https://blog.mozilla.org/addons/2022/11/17/unified-extensions-button-and-how-to-handle-permissions-in-manifest-v3/). Your extension can check whether it has all the required permissions immediately after installation using {{WebExtAPIRef("permissions.contains")}}. If it doesn't have the necessary permissions, it can request them using {{WebExtAPIRef("permissions.request")}}. Providing an onboarding step to explain why some permissions are necessary before requesting them might also be helpful. As the request to grant host permissions may impact users' willingness to install your extension, requesting host permissions is worth careful consideration. For example, you want to avoid requesting unnecessary host permissions and may want to provide information about why you are requesting host permissions in your extension's store description. The article [Request the right permissions](https://extensionworkshop.com/documentation/develop/request-the-right-permissions/) provides more information on the issues you should consider. For information on how to test and preview permission requests, see [Test permission requests](https://extensionworkshop.com/documentation/develop/test-permission-requests/) on the Extension Workshop site. ### Format Host permissions are specified as [match patterns](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns), and each pattern identifies a group of URLs for which the extension is requesting extra privileges. For example, a host permission could be `"*://developer.mozilla.org/*"`. The extra privileges include: - [XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest) and [fetch](/en-US/docs/Web/API/Fetch_API) access to those origins without cross-origin restrictions (though not for requests from content scripts, as was the case in Manifest V2). - the ability to read tab-specific metadata without the "tabs" permission, such as the `url`, `title`, and `favIconUrl` properties of {{WebExtAPIRef("tabs.Tab")}} objects. - the ability to inject scripts programmatically (using {{webextAPIref("tabs/executeScript", "tabs.executeScript()")}}) into pages served from those origins. - the ability to receive events from the {{webextAPIref("webrequest")}} API for these hosts. - the ability to access cookies for that host using the {{webextAPIref("cookies")}} API, as long as the `"cookies"` API permission is also included. - bypassing tracking protection for extension pages where a host is specified as a full domain or with wildcards. In Firefox extensions get host permissions for their origin, which is of the form: ```url moz-extension://60a20a9b-1ad4-af49-9b6c-c64c98c37920/ ``` where `60a20a9b-1ad4-af49-9b6c-c64c98c37920` is the extension's internal ID. The extension can get this URL programmatically by calling {{webextAPIref("extension/getURL", "extension.getURL()")}}: ```js browser.extension.getURL(""); // moz-extension://60a20a9b-1ad4-af49-9b6c-c64c98c37920/ ``` ## Example ```json "host_permissions": ["*://developer.mozilla.org/*"] ``` Request privileged access to pages under `developer.mozilla.org`. ## Example extensions <!-- Ideally we'd use the WebExtExamples template, but examples are not categorized by manifest keys yet - https://github.com/mdn/webextensions-examples/issues/524 --> - [dnr-redirect-url](https://github.com/mdn/webextensions-examples/tree/main/dnr-redirect-url) ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/content_security_policy/index.md
--- title: content_security_policy slug: Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy page-type: webextension-manifest-key browser-compat: webextensions.manifest.content_security_policy --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>String</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> Manifest V2: <pre class="brush: json"> "content_security_policy": "default-src 'self'"</pre> Manifest V3: <pre class="brush: json"> "content_security_policy": { "extension_pages": "default-src 'self'" }</pre> </td> </tr> </tbody> </table> Extensions have a content security policy (CSP) applied to them by default. The default policy restricts the sources from which extensions can load code (such as [\<script>](/en-US/docs/Web/HTML/Element/script) resources) and disallows potentially unsafe practices such as the use of [`eval()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). See [Default content security policy](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy#default_content_security_policy) to learn more about the implications of this. You can use the `"content_security_policy"` manifest key to loosen or tighten the default policy. This key is specified in the same way as the Content-Security-Policy HTTP header. See [Using Content Security Policy](/en-US/docs/Web/HTTP/CSP) for a general description of CSP syntax. For example, you can use this key to: - Restrict permitted sources for other types of content, such as images and stylesheets, using the appropriate [policy directive](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy). - Allow the extension to take advantage of [WebAssembly](/en-US/docs/WebAssembly) by including the `'wasm-unsafe-eval'` source in the `script-src` directive. - Loosen the default {{CSP("script-src")}} policies (Manifest V2 only): - Allow the extension to load scripts from outside its package by supplying their URL in the {{CSP("script-src")}} directive. - Allow the extension to execute inline scripts by [supplying the hash of the script in the `script-src` directive](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_inline_script). - Allow the extension to use `eval()` and similar features by including `'unsafe-eval'` in the {{CSP("script-src")}} directive. There are restrictions on the policy you can specify with this manifest key: - The {{CSP("script-src")}} directive must include at least the `'self'` keyword and may only contain secure sources. The set of permitted secure sources differs between Manifest V2 and Manifest V3. - The policy may include {{CSP("default-src")}} alone (without {{CSP("script-src")}}) if its sources meet the requirement for the {{CSP("script-src")}} directive. - The {{CSP("object-src")}} keyword may be required, see [object-src directive](#object-src_directive) for details. - Directives that reference code – {{CSP("script-src")}}, {{CSP("script-src-elem")}}, {{CSP("worker-src")}}, and {{CSP("default-src")}} (if used as a fallback) – share the same secure source requirement. There are no restrictions on CSP directives that cover non-script content, such as {{CSP("img-src")}}. In Manifest V3, all CSP sources that refer to external or non-static content are forbidden. The only permitted values are `'none'`, `'self'`, and `'wasm-unsafe-eval'`. In Manifest V2, a source for a script directive is considered secure if it meets these criteria: - Wildcard hosts are not permitted, such as `"script-src 'self' *"`. - Remote sources must use `https:` schemes. - Remote sources must not use wildcards for any domains in the [public suffix list](https://publicsuffix.org/list/) (so "\*.co.uk" and "\*.blogspot.com" are not allowed, although "\*.foo.blogspot.com" is permitted). - All sources must specify a host. - The only permitted schemes for sources are `blob:`, `filesystem:`, `moz-extension:`, `https:`, and `wss:`. - The only permitted [keywords](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/default-src#sources) are: `'none'`, `'self'`, `'unsafe-eval'`, and `'wasm-unsafe-eval'`. ## object-src directive The `{{CSP("object-src")}}` directive may be required in some browsers that support obsolete [plugins](/en-US/docs/Glossary/Plugin) and should be set to a secure source such as `'none'` if needed. This may be necessary for browsers up until 2022. - In Firefox, `"object-src"` it optional from Firefox 106. In earlier versions, if `"object-src"` isn't specified, `"content_security_policy"` is ignored and the default CSP used. - In Chrome, `"object-src"` is required. If it's missing or deemed insecure, the default (`"object-src 'self'"`) is used and a warning message logged. - In Safari, there is no requirement for `"object-src"`. See W3C WebExtensions Community Group [issue 204](https://github.com/w3c/webextensions/issues/204), Remove object-src from the CSP, for more information. ## Manifest V2 syntax In Manifest V2, there is one content security policy specified against the key like this: ```json "content_security_policy": "default-src 'self'" ``` ## Manifest V3 syntax In Manifest V3, the `content_security_policy` key is an object that may have any of these properties, all optional: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>extension_pages</code></td> <td><code>String</code></td> <td> The content security policy used for extension pages. The <code>script-src</code> and <code>worker-src</code> directives may only have these values: <ul> <li><code>'self'</code></li> <li><code>'none'</code></li> <li><code>'wasm-unsafe-eval'</code></li> </ul> </td> </tr> <tr> <td><code>sandbox</code></td> <td><code>String</code></td> <td> The content security policy used for sandboxed extension pages. </td> </tr> </tbody> </table> ## Examples ### Valid examples > **Note:** Valid examples demonstrate the correct use of keys in CSP. > However, extensions with 'unsafe-eval', remote script, blob, or remote sources in their CSP are not allowed for Firefox extensions per the [add-on policies](https://extensionworkshop.com/documentation/publish/add-on-policies/) and due to significant security issues. > **Note:** Some examples include the `{{CSP("object-src")}}` directive, which provides backward compatibility for older browser versions. See [object-src directive](#object-src_directive) for more details. Require that all types of content should be packaged with the extension: - Manifest V2 ```json "content_security_policy": "default-src 'self'" ``` - Manifest V3 ```json "content_security_policy": { "extension_pages": "default-src 'self'" } ``` Allow remote scripts from "https://example.com": - Manifest V2 ```json "content_security_policy": "script-src 'self' https://example.com; object-src 'self'" ``` - Manifest V3 does not allow remote URLs in `script-src` of `extension_pages`. Allow remote scripts from any subdomain of "jquery.com": - Manifest V2 ```json "content_security_policy": "script-src 'self' https://*.jquery.com; object-src 'self'" ``` - Manifest V3 does not allow remote URLs in `script-src` of `extension_pages`. Allow [`eval()` and friends](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy#eval%28%29_and_friends): - Manifest V2 ```json "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self';" ``` - Manifest V3 does not allow `'unsafe-eval'` in `script-src`. Allow the inline script: `"<script>alert('Hello, world.');</script>"`: - Manifest V2 ```json "content_security_policy": "script-src 'self' 'sha256-qznLcsROx4GACP2dm0UCKCzCG+HiZ1guq6ZZDob/Tng='; object-src 'self'" ``` - Manifest V3 does not allow CSP hashes in `script-src` of `extension_pages`. Keep the rest of the policy, but also require that images should be packaged with the extension: - Manifest V2 ```json "content_security_policy": "script-src 'self'; object-src 'self'; img-src 'self'" ``` - Manifest V3 ```json "content_security_policy": { "extension_pages": "script-src 'self'; img-src 'self'" } ``` Enable the use of [WebAssembly](/en-US/docs/WebAssembly): - Manifest V2 For backward compatibility, Manifest V2 extensions in Firefox can use WebAssembly without the use of `'wasm-unsafe-eval'`. However, this behavior isn't guaranteed. See [Firefox bug 1770909](https://bugzil.la/1770909). Extensions using WebAssembly are therefore encouraged to declare `'wasm-unsafe-eval'` in their CSP. See [WebAssembly](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy#webassembly) on the Content Security Policy page for more information. ```json "content_security_policy": "script-src 'self' 'wasm-unsafe-eval'" ``` - Manifest V3 ```json "content_security_policy": { "extension_pages": "script-src 'self' 'wasm-unsafe-eval'" } ``` ### Invalid examples Policy that omits the `"object-src"` directive: ```json example-bad "content_security_policy": "script-src 'self' https://*.jquery.com;" ``` However, this is only invalid in browsers that support obsolete [plugins](/en-US/docs/Glossary/Plugin). See [object-src directive](#object-src_directive) for more details.. Policy that omits the `"self"` keyword in the `"script-src"` directive: ```json example-bad "content_security_policy": "script-src https://*.jquery.com; object-src 'self'" ``` Scheme for a remote source is not `https`: ```json example-bad "content_security_policy": "script-src 'self' http://code.jquery.com; object-src 'self'" ``` Wildcard is used with a generic domain: ```json example-bad "content_security_policy": "script-src 'self' https://*.blogspot.com; object-src 'self'" ``` Source specifies a scheme but no host: ```json example-bad "content_security_policy": "script-src 'self' https:; object-src 'self'" ``` Directive includes the unsupported keyword `'unsafe-inline'`: ```json example-bad "content_security_policy": "script-src 'self' 'unsafe-inline'; object-src 'self'" ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/theme_experiment/index.md
--- title: theme_experiment slug: Mozilla/Add-ons/WebExtensions/manifest.json/theme_experiment page-type: webextension-manifest-key browser-compat: webextensions.manifest.theme_experiment --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "theme_experiment": { "stylesheet": "style.css", "colors": { "popup_affordance": "--arrowpanel-dimmed" }, "images": { "theme_toolbar": "--toolbar-bgimage" }, "properties": { "toolbar_image_alignment": "--toolbar-bgalignment" } }</pre > </td> </tr> </tbody> </table> This key enables the definition of experimental [`theme`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme) key properties for the Firefox interface. These experiments are a precursor to proposing new theme features for inclusion in Firefox. Experimentation is done by: - creating a stylesheet that defines mappings between internal CSS selectors for Firefox UI elements and arbitrary CSS variables. The CSS variables are then mapped in the `colors`, `images`, and `properties` objects to new `theme` key properties. - (without a stylesheet) using `colors`, `images`, and `properties` to map internal Firefox CSS selectors, such as `--arrowpanel-dimmed` to new `theme` key properties. This option limits experimentation to UI components that are associated with an inbuilt CSS variable. To discover the CSS selectors for Firefox UI elements or internal Firefox CSS variables use the [browser toolbox](https://firefox-source-docs.mozilla.org/devtools-user/browser_toolbox/index.html). > **Note:** This key is only available for use in Firefox Developer Edition and Firefox Nightly channels and requires the `extensions.experiments.enabled` preference to be enabled. In Firefox 73 and earlier, the `extensions.legacy.enabled` had to be used instead. > **Warning:** This feature is experimental and could be subject to change. ## Syntax The theme_experiment key is an object that takes the following properties: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>stylesheet</code></td> <td><code>String</code></td> <td> <p>Optional</p> <p> Name of a stylesheet providing mapping of Firefox UI element CSS selectors to CSS variables. </p> </td> </tr> <tr> <td><code>images</code></td> <td><code>Object</code></td> <td> <p>Optional</p> <p> Mappings of CSS variables (as defined in Firefox or by the stylesheet defined in <code>stylesheet</code>) to <code>images</code> property names for use in the <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme" >theme</a ></code > key. </p> </td> </tr> <tr> <td><code>colors</code></td> <td><code>Object</code></td> <td> <p>Optional</p> <p> Mappings of CSS variables (as defined in Firefox or by the stylesheet defined in <code>stylesheet</code>) to <code>colors</code> property names for use in the <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme" >theme</a ></code > key. </p> </td> </tr> <tr> <td><code>properties</code></td> <td><code>Object</code></td> <td> <p>Optional</p> <p> Mappings of CSS variables (as defined in Firefox or by the stylesheet defined in <code>stylesheet</code>) to <code>properties</code> property names for use in the <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme" >theme</a ></code > key. </p> </td> </tr> </tbody> </table> ## Examples This example uses a stylesheet named `style.css` to provide the ability to set a color for the browser reload button in the [`theme`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme) key. The stylesheet defines: ```css #reload-button { fill: var(--reload-button-color); } ``` where `#reload-button` is the Firefox internal CSS selector for the reload button and `--reload-button-color` is an arbitrary name. In the `manifest.json` file, `--reload-button-color` is then mapped to the name to be used in the `colors` property of `theme`: ```json "theme_experiment": { "stylesheet": "style.css", "colors": { "reload_button": "--reload-button-color" } } ``` The argument `reload_button` is used in the same way as any other `theme` property: ```json "theme": { "colors": { "reload_button": "orange" } } ``` This has the effect of making the reload icon orange. ![Outcome of a theme experiment, showing the reload button colored orange.](theme_experiment.png) This property can also be used in `browser.theme.update()`. `images` and `properties` work in a similar way to `colors`. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/version_name/index.md
--- title: version_name slug: Mozilla/Add-ons/WebExtensions/manifest.json/version_name page-type: webextension-manifest-key browser-compat: webextensions.manifest.version_name --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>String</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td><pre class="brush: json">"version_name": "0.1 beta"</pre></td> </tr> </tbody> </table> In addition to the [version](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version) field, which is used for update purposes, [version_name](https://developer.chrome.com/docs/extensions/mv3/manifest/version/) can be set to a descriptive version string and will be used for display purposes if present. If no **version_name** is present, the **version** field will be used for display purposes as well. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/user_scripts/index.md
--- title: user_scripts slug: Mozilla/Add-ons/WebExtensions/manifest.json/user_scripts page-type: webextension-manifest-key browser-compat: webextensions.manifest.user_scripts --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "user_scripts": { "api_script": "apiscript.js", } </pre > </td> </tr> </tbody> </table> Instructs the browser to load a script packaged in the extension, known as the API script, this script is used to export a set of custom API methods for use in user scripts. The API script path, relative to the manifest.json file, is defined as a `string` in `"api_script"`. > **Note:** The `user_script` key is required for the {{WebExtAPIRef("userScripts")}} API to function, even if no API script is specified. For example. `user_scripts: {}`. The API script: - runs in the content processes. - has access to the window and document globals related to the webpage it is attached to. - has access to the same subset of WebExtension APIs usually available in a content script. The script executes automatically on any webpage defined in `matches` by {{WebExtAPIRef("userScripts.register")}}. However, this is before the user script sandbox object is created and the custom API methods can be exported. To export the custom API methods, the script listens for {{WebExtAPIRef("userScripts.onBeforeScript")}} and then export the custom API methods. Not every user script may need to consume all of the custom API methods. You can, therefore, include details of the APIs needed in `scriptMetadata` when running {{WebExtAPIRef("userScripts.register")}}. The API script then accesses the `scriptMetadata` through the `script` parameter received by the {{WebExtAPIRef("userScripts.onBeforeScript")}} listener (as `script.metadata`). ## Browser compatibility {{Compat}} ## See also - {{WebExtAPIRef("userScripts")}} - {{WebExtAPIRef("contentScripts")}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/background/index.md
--- title: background slug: Mozilla/Add-ons/WebExtensions/manifest.json/background page-type: webextension-manifest-key browser-compat: webextensions.manifest.background --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "background": { "scripts": ["background.js"] }</pre > </td> </tr> </tbody> </table> Use the `background` key to include one or more background scripts, a background page, or a Service worker in your extension. Background scripts are the place to put code that needs to maintain a long-term state or perform long-term operations independently of the lifetime of any particular web pages or browser windows. Background scripts are loaded as soon as the extension is loaded and stay loaded until the extension is disabled or uninstalled unless `persistent` is specified as `false`. You can use any WebExtension APIs in the script if you have requested the necessary [permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). See [Background scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Background_scripts) for some more details. The `background` key is an object that must have one of these properties (for more information on how these properties are supported, see [Browser support](#browser_support)): <table class="standard-table"> <tbody> <tr> <td><code>page</code></td> <td> <p> If you need specific content in the background page, you can define a page using the <code>page</code> property. This is a <code>String</code> representing a path relative to the manifest.json file to an HTML document included in your extension bundle. </p> <p> If you use this property, you can not specify background scripts using <code>scripts</code>, but you can include scripts from the page, just like a normal web page. </p> </td> </tr> <tr> <td><code>scripts</code></td> <td> <p> An <code>Array</code> of <code>Strings</code>, each of which is a path to a JavaScript source. The path is relative to the manifest.json file itself. These are the scripts that are executed in the extension's background page. </p> <p>The scripts share the same <code>window</code> global context.</p> <p>The scripts are loaded in the order they appear in the array.</p> <p> If you specify <code>scripts</code>, an empty page is created where your scripts run. </p> <div class="note"> <p> <strong>Note:</strong> If you want to fetch a script from a remote location with the <code>&#x3C;script></code> tag (e.g., <code >&#x3C;script src = "https://code.jquery.com/jquery-3.6.0.min.js"></code >), you have to change the <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy" >content_security_policy</a ></code > key in the manifest.json file of your extension. </p> </div> </td> </tr> <tr> <td><code>service_worker</code></td> <td> <p> Specify a JavaScript file as the extension <a href="/en-US/docs/Web/API/Service_Worker_API">service worker</a>. A service worker is a background script that acts as the extension's main event handler. </p> </td> </tr> </tbody> </table> The `background` key can also contain this optional property: <table class="standard-table"> <tbody> <tr> <td><code>persistent</code></td> <td> <p>A <code>Boolean</code> value.</p> <p>If omitted, this property defaults to <code>true</code> in Manifest V2 and <code>false</code> in Manifest V3. Setting to <code>true</code> in Manifest V3 results in an error.</p> <ul> <li> <code>true</code> indicates the background page is to be kept in memory from when the extension is loaded or the browser starts until the extension is unloaded or disabled, or the browser is closed (that is, the background page is persistent). </li> <li> <code>false</code> indicates the background page may be unloaded from memory when idle and recreated when needed. Such background pages are often called Event Pages, because they are loaded into memory to allow the background page to handle the events to which it has added listeners. Registration of listeners is persistent when the page is unloaded from memory, but other values are not persistent. If you want to store data persistently in an event page, then you should use the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage" >storage API</a >. </li> </ul> </td> </tr> <tr> <td><code>type</code></td> <td> <p>A <code>String</code> value.</p> <p>Determines whether the scripts specified in <code>"scripts"</code> are loaded as ES modules.</p> <ul> <li> <code>classic</code> indicates the background scripts or service workers are not included as an ES Module. </li> <li> <code>module</code> indicates the background scripts or service workers are included as an ES Module. This enables the background page or service worker to <code>import</code> code. </li> </ul> <p>If omitted, this property defaults to <code>classic</code>.</p> </td> </tr> </tbody> </table> ## Browser support Support for the `scripts`, `page`, and `service_worker` properties varies between browsers like this: - Chrome: - supports `background.service_worker`. - supports `background.scripts` (and `background.page`) in Manifest V2 extensions only. - before Chrome 121, Chrome refuses to load a Manifest V3 extension with `background.scripts` or `background.page` present. From Chrome 121, their presence in a Manifest V3 extension is ignored. - Firefox: - `background.service_worker` is not supported (see [Firefox bug 1573659](https://bugzilla.mozilla.org/show_bug.cgi?id=1573659)). - supports `background.scripts` (or `background.page`) if `service_worker` is not specified or the service worker feature is disabled. Before Firefox 120, Firefox did not start the background page if `service_worker` was present (see [Firefox bug 1860304](https://bugzil.la/1860304)). From Firefox 121, the background page starts as expected, regardless of the presence of `service_worker`. - Safari: - supports `background.service_worker`. - supports `background.scripts` (or `background.page`) if `service_worker` is not specified. To illustrate, this is a simple example of a cross-browser extension that supports `scripts` and `service_worker`. The example has this manifest.json file: ```json { "name": "Demo of service worker + event page", "version": "1", "manifest_version": 3, "background": { "scripts": ["background.js"], "service_worker": "background.js" } } ``` And, background.js contains: ```javascript if (typeof browser == "undefined") { // Chrome does not support the browser namespace yet. globalThis.browser = chrome; } browser.runtime.onInstalled.addListener(() => { browser.tabs.create({ url: "http://example.com/firstrun.html" }); }); ``` When the extension is executed, this happens: - in Chrome, the `service_worker` property is used, and a service worker starts that opens the tab because, in a Manifest V3 extension, Chrome only supports service workers for background scripts. - in Firefox, the `scripts` property is used, and a script starts that opens the tab because Firefox only supports scripts for background scripts. - in Safari, the `service_worker` property is used, and a service worker starts that opens the tab because Safari gives priority to using service workers for background scripts. ## Examples ```json "background": { "scripts": ["jquery.js", "my-background.js"] } ``` Load two background scripts. ```json "background": { "page": "my-background.html" } ``` Load a custom background page. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/incognito/index.md
--- title: incognito slug: Mozilla/Add-ons/WebExtensions/manifest.json/incognito page-type: webextension-manifest-key browser-compat: webextensions.manifest.incognito --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>String</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json">"incognito": "spanning"</pre> <pre class="brush: json">"incognito": "split"</pre> <pre class="brush: json">"incognito": "not_allowed"</pre> </td> </tr> </tbody> </table> Use the `incognito` key to control how the extension works with private browsing windows. > **Note:** By default, extensions do not run in private browsing windows. Whether an extension can access private browsing windows is under user control. For details, see [Extensions in Private Browsing](https://support.mozilla.org/en-US/kb/extensions-private-browsing). Your extension can check whether it can access private browsing windows using {{WebExtAPIRef("extension.isAllowedIncognitoAccess")}}. This is a string that can take any of these values: - "spanning" (the default): the extension will see events from private and non-private windows and tabs. Windows and tabs will get an `incognito` property in the [`Window`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/windows/Window) or [`Tab`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/Tab) that represents them. This property indicates whether or not the object is private: ```js browser.windows.getLastFocused().then((windowInfo) => { console.log(`Window is private: ${windowInfo.incognito}`); }); ``` - "split": the extension will be split between private and non-private windows. There are effectively two copies of the extension running: one sees only non-private windows, the other sees only private windows. Each copy has isolated access to Web APIs (so, for example, [`localStorage`](/en-US/docs/Web/API/Window/localStorage) is not shared). However, the WebExtension API [`storage.local`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/local) is shared. (**Note:** this setting is not supported by Firefox.) - "not_allowed": private tabs and windows are invisible to the extension. ## Example ```json "incognito": "spanning" ``` ```json "incognito": "split" ``` ```json "incognito": "not_allowed" ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/description/index.md
--- title: description slug: Mozilla/Add-ons/WebExtensions/manifest.json/description page-type: webextension-manifest-key browser-compat: webextensions.manifest.description --- {{AddonSidebar}} <table class="fullwidth-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>String</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "description": "Replaces pictures with pictures of cats."</pre > </td> </tr> </tbody> </table> A short description of the extension, intended for display in the browser's user interface. In Firefox and Chrome this value can be up to 132 characters. The limit in other browsers may differ. This is a [localizable property](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json). ## Example ```json "description": "Replaces pictures with pictures of cats." ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/dictionaries/index.md
--- title: dictionaries slug: Mozilla/Add-ons/WebExtensions/manifest.json/dictionaries page-type: webextension-manifest-key browser-compat: webextensions.manifest.dictionaries --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "dictionaries": { "en-US": "dictionaries/en-US.dic" }</pre > </td> </tr> </tbody> </table> The `dictionaries` key specifies the `locale_code` for which your extension supplies a dictionary. Although the dictionary consists of two files, one with a `.dic` and one with an `.aff` file extension, only the one with the `.dic` extension is referenced in the manifest.json. If you use the `dictionaries` key, you must also set an ID for your extension using the [`browser_specific_settings`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) manifest.json key. ## Example ```json "dictionaries": { "en-US": "dictionaries/en-US.dic" } ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/chrome_url_overrides/index.md
--- title: chrome_url_overrides slug: Mozilla/Add-ons/WebExtensions/manifest.json/chrome_url_overrides page-type: webextension-manifest-key browser-compat: webextensions.manifest.chrome_url_overrides --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "chrome_url_overrides" : { "newtab": "my-new-tab.html" }</pre > </td> </tr> </tbody> </table> Use the `chrome_url_overrides` key to provide a custom replacement for the documents loaded into various special pages usually provided by the browser itself. ## Syntax The `chrome_url_overrides` key is an object that may have the following properties: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>bookmarks</code></td> <td><code>String</code></td> <td> <p>Provide a replacement for the page that shows the bookmarks. </p> </td> </tr> <tr> <td><code>history</code></td> <td><code>String</code></td> <td> <p> Provide a replacement for the page that shows the browsing history. </p> </td> </tr> <tr> <td><code>newtab</code></td> <td><code>String</code></td> <td> <p> Provide a replacement for the document that's shown in the "new tab" page. This is the page that's shown when the user has opened a new tab but has not loaded any document into it: for example, by using the <kbd>Ctrl</kbd>/<kbd>Command</kbd>+<kbd>T</kbd> keyboard shortcut. </p> <p> The replacement is given as a URL to an HTML file. The file must be bundled with the extension: you can't specify a remote URL here. You can specify it relative to the extension's root folder, like: "path/to/newtab.html". </p> <p> The document can load CSS and JavaScript, just like a normal web page. JavaScript running in the page gets access to the same <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API" >privileged "browser.*" APIs</a > as the extension's background script. </p> <p> It's very good practice to include a <a href="/en-US/docs/Web/HTML/Element/title">&#x3C;title></a> for the page, or the tab's title will be the "moz-extension://..." URL. </p> <p> A common use case is to let the user define a new tab page: to do this, provide a custom new tab page that navigates to the page the user defined. </p> <p> If two or more extensions both define custom new tab pages, then the last one to be installed or enabled gets to use its value. </p> <p> To override the browser's homepage, use "<a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_settings_overrides" >chrome_settings_overrides</a >" instead. </p> </td> </tr> </tbody> </table> All properties are [localizable](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json). ## Example ```json "chrome_url_overrides" : { "newtab": "my-new-tab.html" } ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/short_name/index.md
--- title: short_name slug: Mozilla/Add-ons/WebExtensions/manifest.json/short_name page-type: webextension-manifest-key browser-compat: webextensions.manifest.short_name --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>String</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td><pre class="brush: json">"short_name": "My Extension"</pre></td> </tr> </tbody> </table> Short name for the extension. If given, this will be used in contexts where the [name](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name) field is too long. It's recommended that the short name should not exceed 12 characters. If the short name field is not included in manifest.json, then name will be used instead and may be truncated. This is a [localizable property](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json). ## Example ```json "short_name": "My Extension" ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/action/index.md
--- title: action slug: Mozilla/Add-ons/WebExtensions/manifest.json/action page-type: webextension-manifest-key browser-compat: webextensions.manifest.action --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>3 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "action": { "default_icon": { "16": "button/geo-16.png", "32": "button/geo-32.png" }, "default_title": "Whereami?", "default_popup": "popup/geo.html", "theme_icons": [{ "light": "icons/geo-16-light.png", "dark": "icons/geo-16.png", "size": 16 }, { "light": "icons/geo-32-light.png", "dark": "icons/geo-32.png", "size": 32 }] }</pre > </td> </tr> </tbody> </table> An action is a button that your extension adds to the browser's toolbar. The button has an icon, and may optionally have a popup whose content is specified using HTML, CSS, and JavaScript. This key replaces [`browser_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) in Manifest V3 extensions. If you supply a popup, then the popup is opened when the user clicks the button, and your JavaScript running in the popup can handle the user's interaction with it. If you don't supply a popup, then a click event is dispatched to your extension's [background scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Background_scripts) when the user clicks the button. You can also create and manipulate actions programmatically using the {{WebExtAPIRef("action")}} . ## Syntax The `action` key is an object that may have any of these properties, all optional: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td> <code> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles"> browser_style </a> </code> <br />{{optional_inline}} <br />{{deprecated_inline}} </td> <td><code>Boolean</code></td> <td> <p>Optional, defaulting to <code>false</code>.</p> <div class="notecard warning"> <p> Do not set <code>browser_style</code> to true: its support in Manifest V3 was removed in Firefox 118. See <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles#manifest_v3_migration">Manifest V3 migration for <code>browser_style</code></a>. </p> </div> </td> </tr> <tr> <td><code>default_area</code> <br />{{optional_inline}}</td> <td><code>String</code></td> <td> <p> Defines the part of the browser in which the button is initially placed. This is a string that may take one of four values: </p> <ul> <li> "navbar": the button is placed in the main browser toolbar, alongside the URL bar. </li> <li>"menupanel": the button is placed in a popup panel.</li> <li> "tabstrip": the button is placed in the toolbar that contains browser tabs. </li> <li> "personaltoolbar": the button is placed in the bookmarks toolbar. </li> </ul> <p>This property is only supported in Firefox.</p> <p>This property is optional, and defaults to "menupanel".</p> <p> Firefox remembers the <code>default_area</code> setting for an extension, even if that extension is uninstalled and subsequently reinstalled. To force the browser to acknowledge a new value for <code>default_area</code>, the id of the extension must be changed. </p> <p> An extension can't change the location of the button after it has been installed, but the user may be able to move the button using the browser's built-in UI customization mechanism. </p> </td> </tr> <tr> <td><code>default_icon</code> <br />{{optional_inline}}</td> <td><code>Object</code> or <code>String</code></td> <td> <p> Use this to specify one or more icons for the action. The icon is shown in the browser toolbar by default. </p> <p> Icons are specified as URLs relative to the manifest.json file itself. </p> <p>You can specify a single icon file by supplying a string here:</p> <pre class="brush: json">"default_icon": "path/to/geo.svg"</pre> <p> To specify multiple icons in different sizes, specify an object here. The name of each property is the icon's height in pixels, and must be convertible to an integer. The value is the URL. For example: </p> <pre class="brush: json"> "default_icon": { "16": "path/to/geo-16.png", "32": "path/to/geo-32.png" }</pre > <p> You cannot specify multiple icons of the same sizes.<br /><br />See <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/action#choosing_icon_sizes" >Choosing icon sizes</a > for more guidance on this. </p> </td> </tr> <tr> <td><code>default_popup</code> <br />{{optional_inline}}</td> <td><code>String</code></td> <td> <p> The path to an HTML file containing the specification of the popup. </p> <p> The HTML file may include CSS and JavaScript files using <code ><a href="/en-US/docs/Web/HTML/Element/link">&#x3C;link></a></code > and <code ><a href="/en-US/docs/Web/HTML/Element/script" >&#x3C;script></a ></code > elements, just like a normal web page. However, <code ><a href="/en-US/docs/Web/HTML/Element/script" >&#x3C;script> </a></code >must have <code><a href="/en-US/docs/Web/HTML/Element/script">src</a></code> attribute to load a file. Don't use <code ><a href="/en-US/docs/Web/HTML/Element/script" >&#x3C;script></a ></code > with embedded code, because you'll get a confusing Content Violation Policy error. </p> <p> Unlike a normal web page, JavaScript running in the popup can access all the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API" >WebExtension APIs</a > (subject, of course, to the extension having the appropriate <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions" >permissions</a >). </p> <p> This is a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json" >localizable property</a >. </p> </td> </tr> <tr> <td><code>default_title</code> <br />{{optional_inline}}</td> <td><code>String</code></td> <td> <p> Tooltip for the button, displayed when the user moves their mouse over it. If the button is added to the browser's menu panel, this is also shown under the app icon. </p> <p> This is a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json" >localizable property</a >. </p> </td> </tr> <tr> <td><code>theme_icons</code> <br />{{optional_inline}}</td> <td><code>Array</code></td> <td> <p> This property enables you to specify different icons for themes depending on whether Firefox detects that the theme uses dark or light text. </p> <p> If this property is present, it's an array containing at least one <code>ThemeIcons</code> object. A <code>ThemeIcons</code> object contains three mandatory properties: </p> <dl> <dt><code>"dark"</code></dt> <dd> A URL pointing to an icon. This icon displays when a theme using dark text is active (such as the Firefox Light theme, and the Default theme if no default_icon is specified). </dd> <dt><code>"light"</code></dt> <dd> A URL pointing to an icon. This icon displays when a theme using light text is active (such as the Firefox Dark theme). </dd> <dt><code>"size"</code></dt> <dd>The size of the two icons in pixels.</dd> </dl> <p>Icons are specified as URLs relative to the manifest.json file.</p> <p> You should supply 16x16 and 32x32 (for retina display) <code>ThemeIcons</code>. </p> </td> </tr> </tbody> </table> ## Choosing icon sizes The action's icon may need to be displayed in different sizes in different contexts: - The icon is displayed in the browser toolbar. Older versions of Firefox supported the option of placing the icon in the browser's menu panel (the panel that opens when the user clicks the "hamburger" icon). In those versions of Firefox the icon in the menu panel was larger than the icon in the toolbar. - On a high-density display like a Retina screen, icons needs to be twice as big. If the browser can't find an icon of the right size in a given situation, it will pick the best match and scale it. Scaling may make the icon appear blurry, so it's important to choose icon sizes carefully. There are two main approaches to this. You can supply a single icon as an SVG file, and it will be scaled correctly: ```json "default_icon": "path/to/geo.svg" ``` Alternatively, you can supply several icons in different sizes, and the browser will pick the best match. In Firefox: - The default height and width for icons in the toolbar is 16 \* [`window.devicePixelRatio`](/en-US/docs/Web/API/Window/devicePixelRatio). - The default height and width for icons in the menu panel is 32 \* [`window.devicePixelRatio`](/en-US/docs/Web/API/Window/devicePixelRatio). So you can specify icons that match exactly, on both normal and Retina displays, by supplying three icon files, and specifying them like this: ```json "default_icon": { "16": "path/to/geo-16.png", "32": "path/to/geo-32.png", "64": "path/to/geo-64.png" } ``` If Firefox can't find an exact match for the size it wants, then it will pick the smallest icon specified that's bigger than the ideal size. If all icons are smaller than the ideal size, it will pick the biggest icon specified. ## Example ```json "action": { "default_icon": { "16": "button/geo-16.png", "32": "button/geo-32.png" } } ``` An action with just an icon, specified in 2 sizes. The extension's background scripts can receive click events when the user clicks the icon using code like this: ```js browser.action.onClicked.addListener(handleClick); ``` ```json "action": { "default_icon": { "16": "button/geo-16.png", "32": "button/geo-32.png" }, "default_title": "Whereami?", "default_popup": "popup/geo.html" } ``` An action with an icon, a title, and a popup. The popup is shown when the user clicks the button. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/web_accessible_resources/index.md
--- title: web_accessible_resources slug: Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources page-type: webextension-manifest-key browser-compat: webextensions.manifest.web_accessible_resources --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Array</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "web_accessible_resources": [ "images/my-image.png" ]</pre > </td> </tr> </tbody> </table> ## Description Sometimes you want to package resources—for example, images, HTML, CSS, or JavaScript—with your extension and make them available to web pages and other extensions. > **Note:** Until Firefox 105, extensions could access resources packaged in other extensions by default. From Firefox 105 onwards, to enable other extensions to access an extension's resources they must be included in this key. For example, the [Beastify example extension](https://github.com/mdn/webextensions-examples/tree/main/beastify) replaces a web page with an image of a beast selected by the user. The beast images are packaged with the extension. To make the selected image visible, the extension adds [`<img>`](/en-US/docs/Web/HTML/Element/img) elements whose `src` attribute points to the beast's image. For the web page to be able to load the images, they must be made web accessible. With the `web_accessible_resources` key, you list all the packaged resources that you want to make available to web pages. You specify them as paths relative to the manifest.json file. Note that content scripts don't need to be listed as web accessible resources. If an extension wants to use {{WebExtAPIRef("webRequest")}} or {{WebExtAPIRef("declarativeNetRequest")}} to redirect a public URL (e.g., HTTPS) to a page that's packaged in the extension, then the extension must list the page in the `web_accessible_resources` key. ### Manifest V2 syntax In Manifest V2, web accessible resources are added as an array under the key, like this: ```json "web_accessible_resources": [ "images/my-image.png" ] ``` ### Manifest V3 syntax In Manifest V3, the `web_accessible_resources` key is an array of objects like this: ```json { // … "web_accessible_resources": [ { "resources": ["test1.png", "test2.png"], "matches": ["https://web-accessible-resources-1.glitch.me/*"] }, { "resources": ["test3.png", "test4.png"], "matches": ["https://web-accessible-resources-2.glitch.me/*"], "use_dynamic_url": true } ] // … } ``` Each object must include a `"resources"` property and either a `"matches"` or `"extension_ids"` property from the following properties: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td> <code>extension_ids</code> </td> <td><code>Array</code> of <code>String</code></td> <td> Optional. Defaults to <code>[]</code>, meaning that other extensions cannot access the resource. <p> A list of extension IDs specifying the extensions that can access the resources. "*" matches all extensions. </td> </tr> <tr> <td><code>matches</code></td> <td><code>Array</code> of <code>String</code></td> <td> Optional. Defaults to <code>[]</code>, meaning that other websites cannot access the resource. <p> A list of URL <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns">match patterns</a> specifying the pages that can access the resources. Only the origin is used to match URLs. Origins include subdomain matching. Paths must be set to <code>/*</code>. </td> </tr> <tr> <td><code>resources</code></td> <td><code>Array</code> of <code>String</code></td> <td> An array of resources to be exposed. Resources are specified as strings and may contain <code>*</code> for wildcard matches. For example, <code>"/images/*"</code> exposes everything in the extension's <code>/images</code> directory recursively, while <code>"*.png"</code> exposes all PNG files. </td> </tr> <tr> <td><code>use_dynamic_url</code></td> <td><code>Boolean</code></td> <td> Optional. Defaults to <code>false</code>. <p> Whether resources to be accessible through the dynamic ID. The dynamic ID is generated per session and regenerated on browser restart or extension reload. </td> </tr> </tbody> </table> ### Using web_accessible_resources Suppose your extension includes an image file at `images/my-image.png`, like this: ```plain my-extension-files/ manifest.json my-background-script.js images/ my-image.png ``` To enable a web page to use an [`<img>`](/en-US/docs/Web/HTML/Element/img) element whose `src` attribute points to this image, you would specify `web_accessible_resources` like this: ```json "web_accessible_resources": ["images/my-image.png"] ``` The file is then available using a URL like: ```plain moz-extension://<extension-UUID>/images/my-image.png" ``` `<extension-UUID>` is **not** your extension's ID. This ID is randomly generated for every browser instance. This prevents websites from fingerprinting a browser by examining the extensions it has installed. > **Note:** In Chrome in Manifest V2, an extension's ID is fixed. When a resource is listed in `web_accessible_resources`, it is accessible as `chrome-extension://<your-extension-id>/<path/to/resource>`. In Manifest V3, Chrome can use a dynamic URL by setting `use_dynamic_url` to `true`. The recommended approach to obtaining the URL of the resource is to use [`runtime.getURL`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/getURL) passing the path relative to manifest.json, for example: ```js browser.runtime.getURL("images/my-image.png"); // something like: // moz-extension://944cfddf-7a95-3c47-bd9a-663b3ce8d699/images/my-image.png ``` This approach gives you the correct URL regardless of the browser your extension is running on. ### Wildcards `web_accessible_resources` entries can contain wildcards. For example, the following entry would also work to include the resource at "images/my-image.png": ```json "web_accessible_resources": ["images/*.png"] ``` ### Security If you make a page web-accessible, any website may link or redirect to that page. The page should then treat any input (POST data, for example) as if it came from an untrusted source, just as a normal web page should. Web-accessible extension resources are not blocked by [CORS](/en-US/docs/Web/HTTP/CORS) or [CSP](/en-US/docs/Web/HTTP/CSP). Because of this ability to bypass security checks, extensions should avoid using web-accessible scripts when possible. A web-accessible extension script can unexpectedly be misused by malicious websites to weaken the security of other websites. Follow the [security best practices](https://extensionworkshop.com/documentation/develop/build-a-secure-extension/) by avoiding injection of moz-extension:-URLs in web pages and ensuring that third-party libraries are up to date. ## Example ### Manifest V2 example ```json "web_accessible_resources": ["images/my-image.png"] ``` Make the file at "images/my-image.png" web accessible to any website and extension. ### Manifest V3 example ```json "web_accessible_resources": [ { "resources": [ "images/my-image.png" ], "extension_ids": ["*"], "matches": [ "*://*/*" ] } ] ``` Make the file at "images/my-image.png" web accessible to any website and extension. It is recommended to only specify `extension_ids` or `matches` if needed. For example, if the resource only needs to be accessible to web pages at example.com: ```json "web_accessible_resources": [ { "resources": [ "images/my-image.png" ], "matches": [ "https://example.com/*" ] } ] ``` ## Example extensions <!-- Ideally we'd use the WebExtExamples template, but examples are not categorized by manifest keys yet - https://github.com/mdn/webextensions-examples/issues/524 --> - [beastify](https://github.com/mdn/webextensions-examples/tree/main/beastify) - [dnr-redirect-url](https://github.com/mdn/webextensions-examples/tree/main/dnr-redirect-url) ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/author/index.md
--- title: author slug: Mozilla/Add-ons/WebExtensions/manifest.json/author page-type: webextension-manifest-key browser-compat: webextensions.manifest.author --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>String</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td><pre class="brush: json">"author": "Walt Whitman"</pre></td> </tr> </tbody> </table> The extension's author, intended for display in the browser's user interface. If the [developer](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/developer) key is supplied and it contains the "name" property, it will override the author key. There's no way to specify multiple authors. This is a [localizable property](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json). ## Example ```json "author": "Walt Whitman" ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/theme/index.md
--- title: theme slug: Mozilla/Add-ons/WebExtensions/manifest.json/theme page-type: webextension-manifest-key browser-compat: webextensions.manifest.theme --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "theme": { "images": { "theme_frame": "images/sun.jpg" }, "colors": { "frame": "#CF723F", "tab_background_text": "#000" } }</pre > </td> </tr> </tbody> </table> Use the theme key to define a static theme to apply to Firefox. > **Note:** If you want to include a theme with an extension, please see the {{WebExtAPIRef("theme")}} API. > **Note:** Since May 2019, themes need to be signed to be installed ([Firefox bug 1545109](https://bugzil.la/1545109)). See [Signing and distributing your add-on](https://extensionworkshop.com/documentation/publish/signing-and-distribution-overview/#distributing-your-addon) for more details. > **Note:** A new version of Firefox for Android, based on GeckoView, is under development. A [pre-release version](https://play.google.com/store/apps/details?id=org.mozilla.fenix) is available. The pre-release version does not support themes. ## Image formats The following image formats are supported in all theme image properties: - JPEG - PNG - APNG - SVG (animated SVG is supported from Firefox 59) - GIF (animated GIF isn't supported) ## Syntax The theme key is an object that takes the following properties: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>images</code></td> <td><code>Object</code></td> <td> <p>Optional as of Firefox 60. Mandatory before Firefox 60.</p> <p> A JSON object whose properties represent the images to display in various parts of the browser. See <code><a href="#images">images</a></code> for details on the properties that this object can contain. </p> </td> </tr> <tr> <td><code>colors</code></td> <td><code>Object</code></td> <td> <p>Mandatory.</p> <p> A JSON object whose properties represent the colors of various parts of the browser. See <code><a href="#colors">colors</a></code> for details on the properties that this object can contain. </p> </td> </tr> <tr> <td><code>properties</code></td> <td><code>Object</code></td> <td> <p>Optional</p> <p> This object has properties that affect how the <code>"additional_backgrounds"</code> images are displayed and color schemes are applied. See <code><a href="#properties">properties</a></code> for details on the properties that this object can contain. </p> </td> </tr> </tbody> </table> ### images All URLs are relative to the manifest.json file and cannot reference an external URL. Images should be 200 pixels high to ensure they always fill the header space vertically. <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>theme_frame</code></td> <td><code>String</code></td> <td> <p> The URL of a foreground image to be added to the header area and anchored to the upper right corner of the header area. </p> <div class="notecard note"> <p> <strong>Note:</strong> Chrome anchors the image to the top left of the header and if the image doesn't fill the header area tile the image. </p> </div> <p> Optional in desktop Firefox 60 onwards. Required in Firefox for Android. </p> </td> </tr> <tr> <td><code>additional_backgrounds</code></td> <td><code>Array </code>of <code>String</code></td> <td> <div class="warning"> <p> <strong>Warning:</strong> The <code>additional_backgrounds</code> property is experimental. It is currently accepted in release versions of Firefox, but its behavior is subject to change. It is not supported in Firefox for Android. </p> </div> <p> An array of URLs for additional background images to be added to the header area and displayed behind the <code>"theme_frame":</code> image. These images layer the first image in the array on top, the last image in the array at the bottom. </p> <p>Optional.</p> <p> By default all images are anchored to the upper right corner of the header area, but their alignment and repeat behavior can be controlled by properties of <code>"properties":</code>. </p> </td> </tr> </tbody> </table> ### colors These properties define the colors used for different parts of the browser. They are all optional. How these properties affect the Firefox UI is shown here: <table class="fullwidth-table standard-table"> <tbody> <tr> <td> <p> <img alt="Overview of the color properties and how they apply to Firefox UI components" src="themes_components_annotations.png" /> </p> </td> </tr> </tbody> </table> > **Note:** Where a component is affected by multiple color properties, the properties are listed in order of precedence. All these properties can be specified as either a string containing any valid [CSS color string](/en-US/docs/Web/CSS/color_value) (including hexadecimal), or an RGB array, such as `"tab_background_text": [ 107 , 99 , 23 ]`. > **Note:** [In Chrome, colors may only be specified as RGB arrays](#chrome_compatibility). > > In Firefox for Android colors can be specified using: > > - full hexadecimal notation, that is #RRGGBB only. _alpha_ and shortened syntax, as in #RGB\[A], are not supported. > - [Functional notation](/en-US/docs/Web/CSS/color_value#rgb_syntax_variations) (RGB arrays) for themes targeting Firefox 68.2 or later. > > Colors for Firefox for Android themes cannot be specified using color names. <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>bookmark_text</code></td> <td> <p> The color of text and icons in the bookmark and find bars. Also, if <code>tab_text</code> isn't defined it sets the color of the active tab text and if <code>icons</code> isn't defined the color of the toolbar icons. Provided as Chrome compatible alias for <code>toolbar_text</code>. </p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure any color used contrasts well with those used in <code>frame</code> and <code>frame_inactive</code> or <code>toolbar</code> if you're using that property. </p> <p> Where <code>icons</code> isn't defined, also ensure good contrast with<code> button_background_active</code> and <code>button_background_hover</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "tab_text": "white", "toolbar": "black", "bookmark_text": "red" } }</pre > </details> <p> <img alt="Browser Firefox is black. Browser's tab is black with white text. URL bar and the find in page bar are white with black text but all the browser and the find in page bar icons are red." src="theme-bookmark_text.png" /> </p> </td> </tr> <tr> <td><code>button_background_active</code></td> <td> <p>The color of the background of the pressed toolbar buttons.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "button_background_active": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tabs and URL bar are grey with white text. The customize toolbar icon in the url bar in white with a red background is pressed and a popup is open displaying a short list of thing to add to the toolbar such as the browser's library and the sidebars." src="theme-button_background_active.png" /></p> </td> </tr> <tr> <td><code>button_background_hover</code></td> <td> <p>The color of the background of the toolbar buttons on hover.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "button_background_hover": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tabs and URL bar are grey with white text. The go back one page icon is white with a red circle background." src="theme-button_background_hover.png" /></p> </td> </tr> <tr> <td><code>icons</code></td> <td> <p>The color of toolbar icons, excluding those in the find toolbar.</p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with those used in <code>frame</code>, <code>frame_inactive</code>, <code>button_background_active</code>, and <code>button_background_hover</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "icons": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tabs and URL bar are grey with white text. The URL bar and open a new tab icons are red. The red icons contrast well with the black background color of the header area." src="theme-icons.png" /></p> </td> </tr> <tr> <td><code>icons_attention</code></td> <td> <p> The color of toolbar icons in attention state such as the starred bookmark icon or finished download icon. </p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with those used in <code>frame</code>, <code>frame_inactive</code>, <code>button_background_active</code>, and <code>button_background_hover</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "icons_attention": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tabs and URL bar are grey with white text. The bookmark this page icon is red and pressed, an open popup name edit this bookmark is displayed. While in attention state, the toolbar icons contrast well with the black background of the header area." src="theme-icons_attention.png" /></p> </td> </tr> <tr> <td><code>frame</code></td> <td> <p> The color of the header area background, displayed in the part of the header not covered or visible through the images specified in <code>"theme_frame"</code> and <code>"additional_backgrounds"</code>. </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "red", "tab_background_text": "white" } }</pre > </details> <p><img alt="Browser firefox is red with white text. Browsers tabs are lighter red, also with white text. URL bar is very light red with black text" src="theme-frame.png" /></p> </td> </tr> <tr> <td><code>frame_inactive</code></td> <td> <p> The color of the header area background when the browser window is inactive, displayed in the part of the header not covered or visible through the images specified in <code>"theme_frame"</code> and <code>"additional_backgrounds"</code>. </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "red", "frame_inactive": "gray", "tab_text": "white" } }</pre > </details> <p> <img alt="Browser firefox is grey. Browser's tabs and URL bar are lighter grey. The tab text is white and the URL bar icon are darker grey." src="theme-frame_inactive.png" /> </p> </td> </tr> <tr> <td><code>ntp_background</code></td> <td> <p>The new tab page background color.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "ntp_background": "red" } }</pre > </details> <p><img alt="Firefox showing a new tab page. The background of the page is red." src="ntp-background.png" /></p> </td> </tr> <tr> <td><code>ntp_card_background</code></td> <td> <p>The new tab page card background color.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "ntp_card_background": "red" } }</pre > </details> <p><img alt="Firefox showing a new tab page. On the page, the background to the search bar and shortcut buttons is red." src="ntp-card-background.png" /></p> </td> </tr> <tr> <td><code>ntp_text</code></td> <td> <p>The new tab page text color.</p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with that used in <code>ntp_background</code> and <code>ntp_card_background</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "ntp_text": "red" } }</pre > </details> <p><img alt="Firefox showing a new tab page. On the page, the text is in red." src="ntp-text.png" /></p> </td> </tr> <tr> <td><code>popup</code></td> <td> <p> The background color of popups (such as the URL bar dropdown and the arrow panels). </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "popup": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tabs and URL bar are lighter grey with icons and text in white. The bookmark this page icon is blue and pressed, an open popup name 'edit this bookmark' is displayed with a red background. The background color of the popup is red." src="theme-popup.png" /></p> </td> </tr> <tr> <td><code>popup_border</code></td> <td> <p>The border color of popups.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "popup": "black", "popup_text": "white", "popup_border": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tabs and URL bar are lighter grey with icons and text in white. The bookmark this page icon is blue and pressed, an open popup name 'edit this bookmark' is displayed with a red outline and black background. The popup's border is red." src="theme-popup_border.png" /></p> </td> </tr> <tr> <td><code>popup_highlight</code></td> <td> <p> The background color of items highlighted using the keyboard inside popups (such as the selected URL bar dropdown item). </p> <div class="notecard note"> <p> <strong>Note:</strong> It's recommended to define <code>popup_highlight_text</code> to override the browser default text color on various platforms. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "popup_highlight": "red", "popup_highlight_text": "white" } }</pre > </details> <p><img alt="screenshot of firefox is black. Browser's tabs and URL bar are lighter grey with icons and text in white. A search results popup is displayed with a highlighted item's background in red. The background color of the highlighted item inside the popup is red." src="theme-popup_highlight.png" /></p> </td> </tr> <tr> <td><code>popup_highlight_text</code></td> <td> <p>The text color of items highlighted inside popups.</p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with that used in <code>popup_highlight</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "popup_highlight": "black", "popup_highlight_text": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tabs and URL bar are lighter grey with icons and text in white. A search results popup is displayed with a highlighted item's text in red with a black background. The text color of the highlighted item contrasts well with the black background color of this item." src="theme-popup_highlight_text.png" /></p> </td> </tr> <tr> <td><code>popup_text</code></td> <td> <p>The text color of popups.</p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with that used in <code>popup</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "popup": "black", "popup_text": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tabs and URL bar are lighter grey with icons and text in white. A search results popup is displayed with items texts in red. The text color contrasts well with the black background color of the popup." src="popup_text.png" /></p> </td> </tr> <tr> <td><code>sidebar</code></td> <td> <p>The background color of the sidebar.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "sidebar": "red", "sidebar_highlight": "white", "sidebar_highlight_text": "green", "sidebar_text": "white" } }</pre > </details> <p><img alt="A close-up screenshot of a browser windows's open sidebar. The background color of the sidebar is red." src="sidebar-colors.png" /></p> </td> </tr> <tr> <td><code>sidebar_border</code></td> <td> <p>The border and splitter color of the browser sidebar</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "sidebar_border": "red" } }</pre > </details> <p><img alt="A closeup of the firefox browser bookmarks sidebar with a red horizontal separator between the sidebar title and the sidebar menu. The border and splitter color of the sidebar is red." src="sidebar-border.png" /></p> </td> </tr> <tr> <td><code>sidebar_highlight</code></td> <td> <p>The background color of highlighted rows in built-in sidebars</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "sidebar_highlight": "red", "sidebar_highlight_text": "white" } }</pre > </details> <p><img alt="A closeup of the firefox browser bookmarks sidebar with a highlighted item. The background color of a highlighted row in the sidebar is red with white text." src="sidebar-highlight.png" /></p> </td> </tr> <tr> <td><code>sidebar_highlight_text</code></td> <td> <p>The text color of highlighted rows in sidebars.</p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with that used in <code>sidebar_highlight</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "sidebar_highlight": "pink", "sidebar_highlight_text": "red", } }</pre > </details> <p><img alt="A closeup of the firefox browser bookmarks sidebar with a highlighted item. The color of the text of a highlighted row in the sidebar is red. The text color contrasts well with the pink background color of the highlighted row." src="sidebar-highlight-text.png" /></p> </td> </tr> <tr> <td><code>sidebar_text</code></td> <td> <p>The text color of sidebars.</p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with that used in <code>sidebar</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "sidebar": "red", "sidebar_highlight": "white", "sidebar_highlight_text": "green", "sidebar_text": "white" } }</pre > </details> <p><img alt="A close-up screenshot of a browser windows's open sidebar. The color of the text inside the sidebar is white. The text color contrasts well with the red background of the sidebar." src="sidebar-colors.png" /></p> </td> </tr> <tr> <td> <code>tab_background_separator</code> {{Deprecated_Inline}} </td> <td> <div class="notecard warning"> <p> <strong>Warning:</strong> <code>tab_background_separator</code> is not supported starting with Firefox 89. </p> </div> <p>The color of the vertical separator of the background tabs.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "tab_background_separator": "red" } }</pre > </details> <p> <img alt="A closeup of browser tabs to highlight the separator." src="theme-tab-background-separator.png" /> </p> </td> </tr> <tr> <td><code>tab_background_text</code></td> <td> <p> The color of the text displayed in the inactive page tabs. If <code>tab_text</code> or <code>bookmark_text</code> isn't specified, applies to the active tab text. </p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with those used in <code>tab_selected</code> or <code>frame</code> and <code>frame_inactive</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "toolbar": "white", "tab_background_text": "red" } }</pre > </details> <p><img alt="A screenshot of a browser window with one open tab. Browser is black. Browser's tabs and URL bar are white with red icons and red text. The color of the text in the open tab is red. The text color contrasts well with the black background color of the tab." src="theme-tab_background_text.png" /></p> </td> </tr> <tr> <td><code>tab_line</code></td> <td> <p>The color of the selected tab line.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "tab_line": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tabs and URL bar are darker grey with lighter grey icons and white text. The selected tab has a red outline." src="theme-tab_line.png" /></p> </td> </tr> <tr> <td><code>tab_loading</code></td> <td> <p>The color of the tab loading indicator and the tab loading burst.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "tab_loading": "red" } }</pre > </details> <p><img alt="A screenshot of a browser window with one open tab. Browser is black. Browser's tabs and URL bar are darker grey with icons and text in white. Inside the selected tab an animated loading indicator is red." src="theme-tab_loading.gif" /></p> </td> </tr> <tr> <td><code>tab_selected</code></td> <td> <p> The background color of the selected tab. When not in use selected tab color is set by <code>frame</code> and the <code>frame_inactive</code>. </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "images": { "theme_frame": "weta.png" }, "colors": { "frame": "black", "tab_background_text": "white", "tab_selected": "red" } }</pre > </details> <p><img alt="A screenshot of a browser window with one open tab. Browser is black. Browser's tabs and URL bar are darker grey with icons and text in white. The selected tab has red background and white text." src="theme-tab_selected.png" /></p> </td> </tr> <tr> <td><code>tab_text</code></td> <td> <p> From Firefox 59, it represents the text color for the selected tab. If <code>tab_line</code> isn't specified, it also defines the color of the selected tab line. </p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with those used in <code>tab_selected</code> or <code>frame</code> and <code>frame_inactive</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "images": { "theme_frame": "weta.png" }, "colors": { "frame": "black", "tab_background_text": "white", "tab_selected": "white", "tab_text": "red" } }</pre > </details> <p><img alt="Browser firefox has a picture of an insect theme. URL bar is lighter grey with white icons. The selected tab text is red with white background." src="theme-tab_text.png" /></p> </td> </tr> <tr> <td><code>toolbar</code></td> <td> <p> The background color for the navigation bar, the bookmarks bar, and the selected tab. </p> <p>This also sets the background color of the "Find" bar.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "toolbar": "red", "tab_background_text": "white" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tab, find in page bar and URL bar are red with white text and icons, except for the find in page bar where the text and icon are black." src="toolbar.png" /></p> </td> </tr> <tr> <td><code>toolbar_bottom_separator</code></td> <td> <p> The color of the line separating the bottom of the toolbar from the region below. </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "toolbar_bottom_separator": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tab and URL bar are lighter grey with white text and icons. A horizontal red line separates the bottom of the toolbar and the beginning of the display of the web page." src="theme-toolbar_bottom_separator.png" /></p> </td> </tr> <tr> <td><code>toolbar_field</code></td> <td> <p> The background color for fields in the toolbar, such as the URL bar. </p> <p> This also sets the background color of the <strong>Find in page</strong> field. </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "toolbar_field": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tab, find in page bar and URL bar are lighter grey with white text and icons. The background color of the URL bar is red. The find in page bar is white with black text. The find in page field is red with black text." src="toolbar-field.png" /></p> </td> </tr> <tr> <td><code>toolbar_field_border</code></td> <td> <p>The border color for fields in the toolbar.</p> <p> This also sets the border color of the <strong>Find in page</strong> field. </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "toolbar": "black", "tab_background_text": "white", "toolbar_field": "black", "toolbar_field_text": "white", "toolbar_field_border": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tab, find in page and URL bar are black with white text and icons. The URL bar and find in page fields are outlined in red." src="toolbar-field-border.png" /></p> </td> </tr> <tr> <td><code>toolbar_field_border_focus</code></td> <td> <p>The focused border color for fields in the toolbar.</p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "toolbar": "black", "tab_background_text": "white", "toolbar_field": "black", "toolbar_field_text": "white", "toolbar_field_border_focus": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tab and URL bar are black with white text and icons. The url bar field is focused and outlined in red." src="theme-toolbar_field_border_focus.png" /></p> </td> </tr> <tr> <td><code>toolbar_field_focus</code></td> <td> <p> The focused background color for fields in the toolbar, such as the URL bar. </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "toolbar": "black", "tab_background_text": "white", "toolbar_field": "black", "toolbar_field_text": "white", "toolbar_field_focus": "red" } }</pre > </details> <p><img alt="Browser firefox is black. Browser's tab, find in page and URL bar are black with white text and icons. The background color of the focused URL bar is red and the text is white." src="theme-toolbar_field_focus.png" /></p> </td> </tr> <tr> <td><code>toolbar_field_highlight</code></td> <td> The background color used to indicate the current selection of text in the URL bar (and the search bar, if it's configured to be separate). <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "toolbar_field": "rgb(255 255 255 / 91%)", "toolbar_field_text": "rgb(0 100 0)", "toolbar_field_highlight": "rgb(180 240 180 / 90%)", "toolbar_field_highlight_text": "rgb(0 80 0)" } }</pre > </details> <p> <img alt="Browser firefox is white. Browser's tab and URL bar are white with text and icons in black. The URL bar field is focused and outlined in blue and URL bar text is selected." src="toolbar_field_highlight.png" /> </p> <p> Here, the <code>toolbar_field_highlight</code> field specifies that the highlight color is a light green, while the text is set to a dark-to-medium green using <code>toolbar_field_highlight_text</code>. </p> </td> </tr> <tr> <td><code>toolbar_field_highlight_text</code></td> <td> <p> The color used to draw text that's currently selected in the URL bar (and the search bar, if it's configured to be separate box). </p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with those used in <code>toolbar_field_highlight</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "toolbar_field": "rgb(255 255 255 / 91%)", "toolbar_field_text": "rgb(0 100 0)", "toolbar_field_highlight": "rgb(180 240 180 / 90%)", "toolbar_field_highlight_text": "rgb(0 80 0)" } }</pre > </details> <p> <img alt="Browser firefox is white. Browser's tab and URL bar are white with text and icons in black. The URL bar field is focused and outlined in blue and URL bar text is selected." src="toolbar_field_highlight.png" /> </p> <p> Here, the <code>toolbar_field_highlight_text</code> field is used to set the text color to a dark medium-dark green, while the highlight color is a light green. </p> </td> </tr> <tr> <td><code>toolbar_field_separator</code> {{Deprecated_Inline}}</td> <td> <div class="notecard warning"> <p> <strong>Warning:</strong> <code>toolbar_field_separator</code> is not supported starting with Firefox 89. </p> </div> <p> The color of separators inside the URL bar. In Firefox 58 this was implemented as <code>toolbar_vertical_separator</code>. </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "toolbar": "black", "tab_background_text": "white", "toolbar_field_separator": "red" } }</pre > </details> <p><img alt="A screenshot of a browser window with one open tab. Browser firefox is black. Browser's tab and URL bar are black with text and icons in white. Inside the white URL bar field, after the reader mode icon a red vertical line separating the rest of URL bar icons. The color of the vertical separator line inside the URL bar is red." src="theme-toolbar_field_separator.png" /></p> <p> In this screenshot, <code>"toolbar_vertical_separator"</code> is the red vertical line in the URL bar dividing the Reader Mode icon from the other icons. </p> </td> </tr> <tr> <td><code>toolbar_field_text</code></td> <td> <p> The color of text in fields in the toolbar, such as the URL bar. This also sets the color of text in the <strong>Find in page</strong> field. </p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with those used in <code>toolbar_field</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "toolbar": "black", "tab_background_text": "white", "toolbar_field": "black", "toolbar_field_text": "red" } }</pre > </details> <p><img alt="A screenshot of a browser window with one open tab. Browser is black. Browser's tab and URL bar are black with white text and icons. The text inside the URL bar is red. The icons and find in page field have red text with black background." src="toolbar-field-text.png" /></p> </td> </tr> <tr> <td><code>toolbar_field_text_focus</code></td> <td> <p> The color of text in focused fields in the toolbar, such as the URL bar. </p> <div class="notecard note"> <p> <strong>Note:</strong> Ensure the color used contrasts well with those used in <code>toolbar_field_focus</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "toolbar": "black", "tab_background_text": "white", "toolbar_field": "black", "toolbar_field_text": "white", "toolbar_field_text_focus": "red" } }</pre > </details> <p><img alt="A screenshot of a browser window with two open tabs. Browser is black. Browser's tab and URL bar are black with text and icons in white. The URL bar has focus; the bar's text and icons are red with black background." src="theme-toolbar_field_text_focus.png" /></p> </td> </tr> <tr> <td><code>toolbar_text</code></td> <td> <p> The color of toolbar text. This also sets the color of text in the "Find" bar. </p> <div class="notecard note"> <p> <strong>Note:</strong> For compatibility with Chrome, use the alias <code>bookmark_text</code>. </p> </div> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "toolbar": "black", "toolbar_text": "red" } }</pre > </details> <p><img alt="A screenshot of a browser window with one open tab. Browser is black. Browser's tab, find in page bar, and URL bar are black with red text and icons. The text inside the active tab, the navigator bar and the find bar is red." src="toolbar-text.png" /></p> </td> </tr> <tr> <td><code>toolbar_top_separator</code></td> <td> <p> The color of the line separating the top of the toolbar from the region above. </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "toolbar": "black", "toolbar_top_separator": "red" } }</pre > </details> <p><img alt="A screenshot of a browser window with one open tab. Browser is black. Browser's tab and URL bar are black with white text and icons. A red line separates the top of the URL bar from the browser." src="theme-toolbar_top_separator.png" /></p> </td> </tr> <tr> <td><code>toolbar_vertical_separator</code></td> <td> <p> The color of the separator in the bookmarks toolbar. In Firefox 58, it corresponds to the color of separators inside the URL bar. </p> <details open> <summary>See example</summary> <pre class="brush: json"> "theme": { "colors": { "frame": "black", "tab_background_text": "white", "toolbar": "black", "toolbar_vertical_separator": "red" } }</pre > </details> <p><img alt="A screenshot of a browser window with one open tab. Browser is black. Browser's tab and URL bar are black with text and icons in white. The color of the vertical line separating the bookmarks toolbar from the content to the right is red." src="theme-toolbar_vertical_separator.png" /></p> </td> </tr> </tbody> </table> #### Aliases Additionally, this key accepts various properties that are aliases for one of the properties above. These are provided for compatibility with Chrome. If an alias is given, and the non-alias version is also given, then the value will be taken from the non-alias version. <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Alias for</th> </tr> </thead> <tbody> <tr> <td><code>bookmark_text</code></td> <td><code>toolbar_text</code></td> </tr> </tbody> </table> ### properties <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>additional_backgrounds_alignment</code></td> <td> <p><code>Array</code> of <code>String</code></p> </td> <td> <p>Optional</p> <p> An array of enumeration values defining the alignment of the corresponding <code>"additional_backgrounds":</code> array item.<br />The alignment options include: </p> <ul> <li><code>"bottom"</code></li> <li><code>"center"</code></li> <li><code>"left"</code></li> <li><code>"right"</code></li> <li><code>"top"</code></li> <li><code>"center bottom"</code></li> <li><code>"center center"</code></li> <li><code>"center top"</code></li> <li><code>"left bottom"</code></li> <li><code>"left center"</code></li> <li><code>"left top"</code></li> <li><code>"right bottom"</code></li> <li><code>"right center"</code></li> <li><code>"right top"</code>.</li> </ul> <p>If not specified, defaults to <code>"right top"</code>.</p> </td> </tr> <tr> <td><code>additional_backgrounds_tiling</code></td> <td> <p><code>Array</code> of <code>String</code></p> </td> <td> <p>Optional</p> <p> An array of enumeration values defining how the corresponding <code>"additional_backgrounds":</code> array item repeats. Options include: </p> <ul> <li><code>"no-repeat"</code></li> <li><code>"repeat"</code></li> <li><code>"repeat-x"</code></li> <li><code>"repeat-y"</code></li> </ul> <p>If not specified, defaults to <code>"no-repeat"</code>.</p> </td> </tr> <tr> <td><code>color_scheme</code></td> <td> <p><code>String</code></p> </td> <td> <p>Optional</p> <p> Determines which color scheme is applied to the chrome (for example, context menus) and content (for example, built-in pages and the preferred color scheme for web pages). Options include: </p> <ul> <li><code>"auto"</code> – a light or dark scheme based automatically on the theme.</li> <li><code>"light"</code> – a light scheme.</li> <li><code>"dark"</code> – a dark scheme.</li> <li><code>"system"</code> – uses the system scheme.</li> </ul> <p>If not specified, defaults to <code>"auto"</code>.</p> </td> </tr> <tr> <td><code>content_color_scheme</code></td> <td> <p><code>String</code></p> </td> <td> <p>Optional</p> <p> Determines which color scheme is applied to the content (for example, built-in pages and preferred color scheme for web pages). Overrides <code>color_scheme</code>. Options include: </p> <ul> <li><code>"auto"</code> – a light or dark scheme based automatically on the theme.</li> <li><code>"light"</code> – a light scheme.</li> <li><code>"dark"</code> – a dark scheme.</li> <li><code>"system"</code> – the system scheme.</li> </ul> <p>If not specified, defaults to <code>"auto"</code>.</p> </td> </tr> </tbody> </table> ## Examples A basic theme must define an image to add to the header, the accent color to use in the header, and the color of text used in the header: ```json "theme": { "images": { "theme_frame": "images/sun.jpg" }, "colors": { "frame": "#CF723F", "tab_background_text": "#000" } } ``` Multiple images can be used to fill the header. Before Firefox version 60, use a blank or transparent header image to gain control over the placement of each additional image: ```json "theme": { "images": { "additional_backgrounds": [ "images/left.png", "images/middle.png", "images/right.png"] }, "properties": { "additional_backgrounds_alignment": [ "left top", "top", "right top"] }, "colors": { "frame": "blue", "tab_background_text": "#ffffff" } } ``` You can also fill the header with a repeated image, or images, in this case a single image anchored in the middle top of the header and repeated across the rest of the header: ```json "theme": { "images": { "additional_backgrounds": [ "images/logo.png"] }, "properties": { "additional_backgrounds_alignment": [ "top" ], "additional_backgrounds_tiling": [ "repeat" ] }, "colors": { "frame": "green", "tab_background_text": "#000" } } ``` The following example uses most of the different values for `theme.colors`: ```json "theme": { "images": { "theme_frame": "weta.png" }, "colors": { "frame": "darkgreen", "tab_background_text": "white", "toolbar": "blue", "bookmark_text": "cyan", "toolbar_field": "orange", "toolbar_field_border": "white", "toolbar_field_text": "green", "toolbar_top_separator": "red", "toolbar_bottom_separator": "white", "toolbar_vertical_separator": "white" } } ``` It will give you a browser that looks like this: ![A browser window with two open tabs and dark green background color in the header area. The inactive tab has a white text color. The active tab and the toolbar have a blue background color with cyan-colored text. The URL bar has an orange background with white borders, a green text color and a white-colored vertical line separator. A red-colored line is used to separate the tabs on the top and a white line to separate the tabs from the content bellow them.](theme.png) In this screenshot, `"toolbar_vertical_separator"` is the white vertical line in the URL bar dividing the Reader Mode icon from the other icons. ## Browser compatibility {{Compat}} ### Chrome compatibility In Chrome: - `colors/toolbar_text` is not used, use `colors/bookmark_text` instead. - `images/theme_frame` anchors the image to the top left of the header and if the image doesn't fill the header area tile the image. - all colors must be specified as an array of RGB values, like this: ```json "theme": { "colors": { "frame": [255, 0, 0], "tab_background_text": [0, 255, 0], "bookmark_text": [0, 0, 255] } } ``` From Firefox 59 onward, both the array form and the CSS color form are accepted for all properties. Before that, `colors/frame` and `colors/tab_background_text` required the array form, while other properties required the CSS color form.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/page_action/index.md
--- title: page_action slug: Mozilla/Add-ons/WebExtensions/manifest.json/page_action page-type: webextension-manifest-key browser-compat: webextensions.manifest.page_action --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "page_action": { "default_icon": { "19": "button/geo-19.png", "38": "button/geo-38.png" }, "default_title": "Whereami?", "default_popup": "popup/geo.html" }</pre > </td> </tr> </tbody> </table> A page action is an icon that your extension adds inside the browser's URL bar. Your extension may optionally also supply an associated popup whose content is specified using HTML, CSS, and JavaScript. If you supply a popup, then the popup is opened when the user clicks the icon, and your JavaScript running in the popup can handle the user's interaction with it. If you don't supply a popup, then a click event is dispatched to your extension's [background scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#background_pages) when the user clicks the icon. You can also create and manipulate page actions programmatically using the {{WebExtAPIRef("pageAction", "pageAction API")}}. Page actions are like browser actions, except that they are associated with particular web pages rather than with the browser as a whole. If an action is only relevant on certain pages, then you should use a page action and display it only on relevant pages. If an action is relevant to all pages or to the browser itself, use a browser action. While browser actions are displayed by default, page actions are hidden by default. They can be shown for a particular tab by calling {{WebExtAPIRef("pageAction.show()")}}, passing in the tab's `id`. You can also change this default behavior using the `show_matches` property. ## Syntax The `page_action` key is an object that may have any of three properties, all optional: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td> <code> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles"> browser_style </a> </code> <br />{{optional_inline}} <br />{{deprecated_inline}} in Manifest V3. </td> <td><code>Boolean</code></td> <td> <p>Optional. Defaults to <code>false</code>.</p> <div class="notecard warning"> <p> Do not set <code>browser_style</code> to true: its not support in Manifest V3 from Firefox 118. See <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles#manifest_v3_migration">Manifest V3 migration for <code>browser_style</code></a>. </p> </div> <p> In Firefox, the stylesheet can be seen at <code>chrome://browser/content/extension.css</code> or <code>chrome://browser/content/extension-mac.css</code> on macOS. </p> <p> The <a href="https://github.com/mdn/webextensions-examples/tree/main/latest-download" >latest-download</a > example extension uses <code>browser_style</code> in its popup. </p> </td> </tr> <tr> <td><code>default_icon</code></td> <td><code>Object</code> or <code>String</code></td> <td> <p>Use this to specify an icon for the action.</p> <p> It's recommended that you supply two icons here (19×19 pixels and 38×38 pixels), and specify them in an object with properties named <code>"19"</code> and <code>"38"</code>, like this: </p> <pre class="brush: json"> "default_icon": { "19": "geo-19.png", "38": "geo-38.png" }</pre > <p> If you do this, then the browser will pick the right size icon for the screen's pixel density. </p> <p>You can just supply a string here:</p> <pre class="brush: json">"default_icon": "geo.png"</pre> <p> If you do this, then the icon will be scaled to fit the toolbar, and may appear blurry. </p> </td> </tr> <tr> <td><code>default_popup</code></td> <td><code>String</code></td> <td> <p> The path to an HTML file containing the specification of the popup. </p> <p> The HTML file may include CSS and JavaScript files using <code ><a href="/en-US/docs/Web/HTML/Element/link">&#x3C;link></a></code > and <code ><a href="/en-US/docs/Web/HTML/Element/script" >&#x3C;script></a ></code > elements, just like a normal web page. However, don't use <code ><a href="/en-US/docs/Web/HTML/Element/script" >&#x3C;script></a ></code > with embedded code, because you'll get a Content Violation Policy error. Instead, <code ><a href="/en-US/docs/Web/HTML/Element/script" >&#x3C;script></a ></code > must use the <code><a href="/en-US/docs/Web/HTML/Element/script">src</a></code> attribute to load a separate script file. </p> <p> Unlike a normal web page, JavaScript running in the popup can access all the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API" >WebExtension APIs</a > (subject, of course, to the extension having the appropriate <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions" >permissions</a >). </p> <p> This is a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json" >localizable property</a >. </p> </td> </tr> <tr> <td><code>default_title</code></td> <td><code>String</code></td> <td> <p> Tooltip for the icon, displayed when the user moves their mouse over it. </p> <p> This is a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json" >localizable property</a >. </p> </td> </tr> <tr> <td><code>hide_matches</code></td> <td> <code>Array</code> of <code>Match Pattern</code> except <code>&#x3C;all_urls></code> </td> <td> <p> Hide the page action by default for pages whose URLs match any of the given <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns" >match patterns</a >. </p> <p> Note that page actions are always hidden by default unless <code>show_matches</code> is given. Therefore, it only makes sense to include this property if <code>show_matches</code> is also given, and will override the patterns in <code>show_matches</code>. </p> <p>For example, consider a value like:</p> <pre class="brush: json"> "page_action": { "show_matches": ["https://*.mozilla.org/*"], "hide_matches": ["https://developer.mozilla.org/*"] }</pre > <p> This shows the page action by default for all HTTPS URLs under the <code>"mozilla.org"</code> domain, except for pages under <code>"developer.mozilla.org"</code>. </p> </td> </tr> <tr> <td><code>show_matches</code></td> <td><code>Array</code> of <code>Match Pattern</code></td> <td> <p> Show the page action by default for pages whose URLs match any of the given patterns. </p> <p>See also <code>hide_matches</code>.</p> </td> </tr> <tr> <td><code>pinned</code> {{deprecated_inline}}</td> <td><code>Boolean</code></td> <td> <p>Optional. Defaults to <code>true</code>.</p> <p> Controls whether or not the page action should appear in the location bar by default when the user installs the extension. This property is no longer supported since Firefox 89. </p> </td> </tr> </tbody> </table> ## Example ```json "page_action": { "default_icon": { "19": "button/geo-19.png", "38": "button/geo-38.png" } } ``` A page action with just an icon, specified in 2 different sizes. The extension's background scripts can receive click events when the user clicks the icon using code like this: ```js browser.pageAction.onClicked.addListener(handleClick); ``` ```json "page_action": { "default_icon": { "19": "button/geo-19.png", "38": "button/geo-38.png" }, "default_title": "Whereami?", "default_popup": "popup/geo.html" } ``` A page action with an icon, a title, and a popup. The popup will be shown when the user clicks the icon. ## Browser compatibility {{Compat}} ## See also - [`browser_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) - [`sidebar_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action) - [Browser styles](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles)
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/optional_permissions/index.md
--- title: optional_permissions slug: Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions page-type: webextension-manifest-key browser-compat: webextensions.manifest.optional_permissions --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Array</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "optional_permissions": [ "webRequest" ]</pre> </td> </tr> </tbody> </table> Use the `optional_permissions` key to list permissions that you want to ask for at runtime, after your extension has been installed. The [`permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) key lists permissions that your extension needs before it can be installed. In contrast, `optional_permissions` lists permissions that your extension doesn't need at install time but it may ask for after it has been installed. To ask for a permission, use the {{webextapiref("permissions")}} API. Asking for a permission may present the user with a dialog requesting them to grant the permission to your extension. For advice on designing your request for runtime permissions, to maximize the likelihood that users grant them, see [Request permissions at runtime](https://extensionworkshop.com/documentation/develop/request-the-right-permissions/#request_permissions_at_runtime). Starting with Firefox 84, users will be able to manage optional permissions from the Firefox Add-ons Manager. Extensions that use optional permissions should listen for [browser.permissions.onAdded](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/permissions/onAdded) and [browser.permissions.onRemoved](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/permissions/onRemoved) API events to know when a user grants or revokes these permissions. The key can contain two kinds of permissions: host permissions and API permissions. ## Host permissions These are the same as the host permissions you can specify in the [`permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) key. > **Note:** When using Manifest V3 or higher: > > - in Chrome, host permissions must be specified in the [`host_permission`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/host_permissions) manifest key. > - in Firefox, during the Manifest V3 developer preview, hosts can be in either `host_permissions` or `optional_permissions`. Subject to completion of [bug 1766026](https://bugzil.la/1766026), hosts will be specified in either `host_permissions` or `optional_host_permissions`. ## API permissions You can include any of the following here, but not in all browsers: check the compatibility table for browser-specific details. - `activeTab` - `background` - `bookmarks` - `browserSettings` - `browsingData` - `clipboardRead` - `clipboardWrite` - `contentSettings` - `contextMenus` - `cookies` - `debugger` - `declarativeNetRequest` - `declarativeNetRequestFeedback` - `declarativeNetRequestWithHostAccess` - `devtools` - `downloads` - `downloads.open` - `find` - `geolocation` - `history` - `idle` - `management` - `nativeMessaging` - `notifications` - `pageCapture` - `pkcs11` - `privacy` - `proxy` - `scripting` - `search` - `sessions` - `tabHide` - `tabs` - `topSites` - `webNavigation` - `webRequest` - `webRequestBlocking` - `webRequestFilterResponse` - `webRequestFilterResponse.serviceWorkerScript` Note that this is a subset of the API permissions allowed in [`permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions). Of this set, the following permissions are granted silently, without a user prompt: - `activeTab` - `cookies` - `idle` - `webRequest` - `webRequestBlocking` - `webRequestFilterResponse` - `webRequestFilterResponse.serviceWorkerScript` ## Example ```json "optional_permissions": ["*://developer.mozilla.org/*"] ``` In Manifest V2 only, enable the extension to ask for privileged access to pages under developer.mozilla.org. ```json "optional_permissions": ["tabs"] ``` Enable the extension to ask for access to the privileged pieces of the `tabs` API. ```json "optional_permissions": ["*://developer.mozilla.org/*", "tabs"] ``` In Manifest V2 only, enable the extension to ask for both of the above permissions. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/commands/index.md
--- title: commands slug: Mozilla/Add-ons/WebExtensions/manifest.json/commands page-type: webextension-manifest-key browser-compat: webextensions.manifest.commands --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "commands": { "toggle-feature": { "suggested_key": { "default": "Ctrl+Shift+Y", "linux": "Ctrl+Shift+U" }, "description": "Send a 'toggle-feature' event" } }</pre > </td> </tr> </tbody> </table> Use the **`commands`** key to define one or more keyboard shortcuts for your extension. Each keyboard shortcut is defined with a **name**, a **combination of keys**, and a **description**. Once you've defined commands in your extension's `manifest.json`, you can listen for their associated key combinations with the {{WebExtAPIRef("commands")}} JavaScript API. ## Syntax The `commands` key is an object, and each shortcut is a property of it. **The property's name is the name of the shortcut.** Each shortcut's value is an object, with up to 2 properties: 1. `suggested_key`: the combination of keys that activate the shortcut. 2. `description`: a string that describes the shortcut; i.e. what it does. The `suggested_key` property is an object with any of the following properties (all strings): - `"default"` - `"mac"` - `"linux"` - `"windows"` - `"chromeos"` - `"android"` - `"ios"` The value of each property is the keyboard shortcut for the command on that platform, as a string containing keys separated by "`+`". The value for `"default"` is used on all platforms that are not explicitly listed. For example: ```json "commands": { "toggle-feature": { "suggested_key": { "default": "Alt+Shift+U", "linux": "Ctrl+Shift+U" }, "description": "Send a 'toggle-feature' event to the extension" }, "do-another-thing": { "suggested_key": { "default": "Ctrl+Shift+Y" } } } ``` This JSON defines 2 shortcuts: 1. `"toggle-feature"`, accessed with <kbd>Ctrl</kbd> \+ <kbd>Shift</kbd> \+ <kbd>U</kbd> on Linux, and <kbd>Alt</kbd> \+ <kbd>Shift</kbd> \+ <kbd>U</kbd> on all other platforms. 2. `"do-another-thing"`, accessed with <kbd>Ctrl</kbd> \+ <kbd>Shift</kbd> \+ <kbd>Y</kbd> on all platforms. You could then listen for the `"toggle-feature"` command with code like this: ```js browser.commands.onCommand.addListener((command) => { if (command === "toggle-feature") { console.log("Toggling the feature!"); } }); ``` ### Special shortcuts There are these 4 **special shortcuts with default actions** for which the {{WebExtAPIRef("commands.onCommand")}} event does not fire: - `_execute_browser_action`: works like a click on a [toolbar button](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button) created with {{WebExtAPIRef("browserAction")}} or specified in the [browser_action](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) key in the manifest.json key. - `_execute_action`: works like a click on a [toolbar button](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button) created with {{WebExtAPIRef("action")}} or specified in the [action](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/action) key in the manifest.json key. - `_execute_page_action`: works like a click on an [address bar button](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions) created with {{WebExtAPIRef("pageAction")}} or specified in the [page_action](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action) key in the manifest.json key. - `_execute_sidebar_action`: opens the extension's [sidebar](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars) specified in the [sidebar_action](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action) manifest.json key. The availability of these special shortcuts varies between manifest versions and browsers, like this: <table> <thead> <tr> <th></th> <th>Manifest V2</th> <th>Manifest V3</th> </tr> </thead> <tbody> <tr> <td><code>_execute_browser_action</code></td> <td>Yes</td> <td>No</td> </tr> <tr> <td><code>_execute_action</code></td> <td>No</td> <td>Yes</td> </tr> <tr> <td><code>_execute_page_action</code></td> <td>Yes</td> <td>Not available in Chromium-based browsers</td> </tr> <tr> <td><code>_execute_sidebar_action</code></td> <td>Firefox only</td> <td>Firefox only</td> </tr> </tbody> </table> For example, this JSON defines a key combination that clicks the extension's browser action: ```json "commands": { "_execute_browser_action": { "suggested_key": { "default": "Ctrl+Shift+Y" } } } ``` ## Shortcut values There are two valid formats for shortcut keys: as a **key combination** or as a **media key**. ### Key combinations > **Note:** On Macs, `"Ctrl"` is interpreted as `"Command"`, so if you actually need `"Ctrl"`, specify `"MacCtrl"`. Key combinations must consist of 2 or 3 keys: 1. **modifier** (mandatory, except for function keys). This can be any of: `"Ctrl"`, `"Alt"`, `"Command"`, or `"MacCtrl"`. 2. **secondary modifier** (optional). If supplied, this must be either `"Shift"` or (for Firefox ≥ 63) any one of `"Ctrl"`, `"Alt"`, `"Command"`, or `"MacCtrl"`. Must not be the modifier already used as the main modifier. 3. **key** (mandatory). This can be any one of: - the letters `A` – `Z` - the numbers `0` – `9` - the function keys `F1` – `F12` - `Comma`, `Period`, `Home`, `End`, `PageUp`, `PageDown`, `Space`, `Insert`, `Delete`, `Up`, `Down`, `Left`, `Right` The key is then given as a string containing the set of key values, in the order listed above, separated by "`+`". For example, `"Ctrl+Shift+Z"`. If a key combination is already used by the browser (like `"Ctrl+P"`) or by an existing add-on, then you can't override it. You can define it, but your event handler will not be called when the user presses the key combination. ### Media keys Alternatively, the shortcut may be specified as one of the following media keys: - `"MediaNextTrack"` - `"MediaPlayPause"` - `"MediaPrevTrack"` - `"MediaStop"` ## Updating shortcuts Shortcuts can be updated via {{WebExtAPIRef("commands.update()")}}. Users can also update shortcuts via the "Manage Extension Shortcuts" option at `about:addons` in Firefox, as shown in [this video](https://bug1303384.bmoattachments.org/attachment.cgi?id=9051647). In Chrome, users can change shortcuts at `chrome://extensions/shortcuts`. ## Example Define a single keyboard shortcut, using only the default key combination: ```json "commands": { "toggle-feature": { "suggested_key": { "default": "Ctrl+Shift+Y" }, "description": "Send a 'toggle-feature' event" } } ``` Define two keyboard shortcuts, one with a platform-specific key combination: ```json "commands": { "toggle-feature": { "suggested_key": { "default": "Alt+Shift+U", "linux": "Ctrl+Shift+U" }, "description": "Send a 'toggle-feature' event" }, "do-another-thing": { "suggested_key": { "default": "Ctrl+Shift+Y" } } } ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/icons/index.md
--- title: icons slug: Mozilla/Add-ons/WebExtensions/manifest.json/icons page-type: webextension-manifest-key browser-compat: webextensions.manifest.icons --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> </tbody> </table> The `icons` key specifies icons for your extension. Those icons will be used to represent the extension in components such as the Add-ons Manager. It consists of key-value pairs of image size in px and image path relative to the root directory of the extension. If `icons` is not supplied, a standard extension icon will be used by default. You should supply at least a main extension icon, ideally 48x48 px in size. This is the default icon that will be used in the Add-ons Manager. You may, however, supply icons of any size and Firefox will attempt to find the best icon to display in different components. Firefox will consider the screen resolution when choosing an icon. To deliver the best visual experience to users with high-resolution displays, such as Retina displays, provide double-sized versions of all your icons. ## Example The keys in the `icons` object specify the icon size in px, values specify the relative icon path. This example contains a 48px extension icon and a larger version for high-resolution displays. ```json "icons": { "48": "icon.png", "96": "[email protected]" } ``` ## SVG You can use SVG and the browser will scale your icon appropriately. There are currently two caveats though: 1. You need to specify a viewBox in the image. E.g.: ```html <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48" height="48"> <!-- your svg content --> </svg> ``` 2. Even though you can use one file, you still need to specify various size of the icon in your manifest. E.g.: ```json "icons": { "48": "icon.svg", "96": "icon.svg" } ``` > **Note:** Only Firefox is known to support SVG icons. Chromium has a bug about [unsupported SVG icons](https://crbug.com/29683). > **Note:** Remember to include the `xmlns` attribute when creating the SVG. Otherwise, Firefox won't be able to display the icon. > **Note:** If you are using a program like Inkscape for creating SVG, you might want to save it as a "plain SVG". Firefox might be confused by various special namespaces and not display your icon. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/externally_connectable/index.md
--- title: externally_connectable slug: Mozilla/Add-ons/WebExtensions/manifest.json/externally_connectable page-type: webextension-manifest-key browser-compat: webextensions.manifest.externally_connectable --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre> "externally_connectable": { "ids": [ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "cccccccccccccccccccccccccccccccc" ], "matches": [ "https://example1.com/*", "*://*.example2.com/*" ] }</pre > </td> </tr> </tbody> </table> Externally connectable controls which other extensions and web pages can communicate with an extension using {{WebExtAPIRef("runtime.connect","runtime.connect()")}} and {{WebExtAPIRef("runtime.sendMessage", "runtime.sendMessage()")}} message passing. If `externally_connectable` is not specified, all extensions can communicate with each other but not with web pages. > **Note:** > For communication with web pages: > > - In Chrome, `chrome.runtime.connect` and `chrome.runtime.sendMessage` are used. These methods are only available when there is at least one extension listening for messages, see [chrome.runtime will no longer be defined unconditionally in Chrome 106](https://groups.google.com/a/chromium.org/g/chromium-extensions/c/tCWVZRq77cg/m/KB6-tvCdAgAJ) for more details. > - In Safari, `browser.runtime.connect` and `browser.runtime.sendMessage` are used. > - In Firefox, neither API is supported. See [Firefox bug 1319168](https://bugzil.la/1319168). ### "ids" attribute `ids` enables communication between this extension and other installed extensions specified by extension identifiers. Use the pattern `"*"` to communicate with all extensions. ### "matches" attribute `matches` is a list of regular expressions that enables communication between an extension and the web pages that match the expression. > **Note:** If `externally_connectable` is not specified, communication among extensions is allowed as if `externally_connectable` specified `{"ids": ["*"] }`. Therefore, if you specify `externally_connectable.matches`, don't forget to add `ids` if you want to communicate with other extensions. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/declarative_net_request/index.md
--- title: declarative_net_request slug: Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request page-type: webextension-manifest-key browser-compat: webextensions.manifest.declarative_net_request --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "declarative_net_request" : { "rule_resources" : [{ "id": "ruleset", "enabled": true, "path": "rules.json" }] }</pre > </td> </tr> </tbody> </table> Specify static rulesets for use with {{WebExtAPIRef("declarativeNetRequest")}}. See <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest#permissions">Permissions</a> for more information on permission requirements. ## Syntax The `"declarative_net_request"` key is an object that must contain the `"rule_resources"` property, an array that must include at least one object with these properties: <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>"id"</code></td> <td><code>String</code></td> <td>A non-empty string uniquely identifying the ruleset. IDs beginning with '_' are reserved for internal use.</td> </tr> <tr> <td><code>"enabled"</code></td> <td><code>Boolean</code></td> <td>Whether the ruleset is enabled by default. The {{WebExtAPIRef("declarativeNetRequest.updateEnabledRulesets")}} method can be used to enable or disable a ruleset at runtime.</td> </tr> <tr> <td><code>"path"</code></td> <td><code>String</code></td> <td>The path of the JSON ruleset relative to the extension directory. See the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest#rules">Rules</a> section of the <code>declarativeNetRequest</code> API for information on the content of the ruleset JSON file.</td> </tr> </tbody> </table> ## Example ```json "declarative_net_request" : { "rule_resources" : [{ "id": "ruleset_1", "enabled": true, "path": "rules_1.json" }, { "id": "ruleset_2", "enabled": false, "path": "rules_2.json" }] } ``` ## Example extensions <!-- Ideally we'd use the WebExtExamples template, but examples are not categorized by manifest keys yet - https://github.com/mdn/webextensions-examples/issues/524 --> - [dnr-block-only](https://github.com/mdn/webextensions-examples/tree/main/dnr-block-only) - [dnr-redirect-url](https://github.com/mdn/webextensions-examples/tree/main/dnr-redirect-url) ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/permissions/index.md
--- title: permissions slug: Mozilla/Add-ons/WebExtensions/manifest.json/permissions page-type: webextension-manifest-key browser-compat: webextensions.manifest.permissions --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Array</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json;"> "permissions": [ "webRequest" ]</pre > </td> </tr> </tbody> </table> Use the `permissions` key to request special powers for your extension. This key is an array of strings, and each string is a request for a permission. If you request permissions using this key, then the browser may inform the user at install time that the extension is requesting certain privileges, and ask them to confirm that they are happy to grant these privileges. The browser may also allow the user to inspect an extension's privileges after installation. As the request to grant privileges may impact on users' willingness to install your extension, requesting privileges is worth careful consideration. For example, you want to avoid requesting unnecessary permissions and may want to provide information about why you are requesting permissions in your extension's store description. More information on the issues you should consider is provided in the article [Request the right permissions](https://extensionworkshop.com/documentation/develop/request-the-right-permissions/). For information on how to test and preview permission requests, see [Test permission requests](https://extensionworkshop.com/documentation/develop/test-permission-requests/) on the Extension Workshop site. The key can contain three kinds of permissions: - host permissions (Manifest V2 only, host permissions are specified in the [`host_permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/host_permissions) manifest key for Manifest V3 or higher.) - API permissions - the `activeTab` permission ## Host permissions > **Note:** When using Manifest V3 or higher, host permissions must be specified in the [`host_permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/host_permissions) manifest key. Host permissions are specified as [match patterns](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns), and each pattern identifies a group of URLs for which the extension is requesting extra privileges. For example, a host permission could be `"*://developer.mozilla.org/*"`. The extra privileges include: - [XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest) and [fetch](/en-US/docs/Web/API/Fetch_API) access to those origins without cross-origin restrictions (even for requests made from content scripts) - the ability to read tab-specific metadata without the "tabs" permission, such as the `url`, `title`, and `favIconUrl` properties of {{WebExtAPIRef("tabs.Tab")}} objects - the ability to [inject content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#loading_content_scripts) and styles programmatically into pages served from those origins. - the ability to receive events from the {{webextAPIref("webrequest")}} API for these hosts - the ability to access cookies for that host using the {{webextAPIref("cookies")}} API, as long as the `"cookies"` API permission is also included. - bypassing tracking protection for extension pages where a host is specified as a full domain or with wildcards. Content scripts, however, can only bypass tracking protection for hosts specified with a full domain. In Firefox, from version 56 onwards, extensions automatically get host permissions for their own origin, which is of the form: ```url moz-extension://60a20a9b-1ad4-af49-9b6c-c64c98c37920/ ``` where `60a20a9b-1ad4-af49-9b6c-c64c98c37920` is the extension's internal ID. The extension can get this URL programmatically by calling {{webextAPIref("extension/getURL", "extension.getURL()")}}: ```js browser.extension.getURL(""); // moz-extension://60a20a9b-1ad4-af49-9b6c-c64c98c37920/ ``` ## API permissions API permissions are specified as keywords, and each keyword names a [WebExtension API](/en-US/docs/Mozilla/Add-ons/WebExtensions/API) that the extension would like to use. These permissions are available in Manifest V2 and above unless otherwise noted: - `activeTab` - `alarms` - `background` - `bookmarks` - `browserSettings` - `browsingData` - `captivePortal` - `clipboardRead` - `clipboardWrite` - `contentSettings` - `contextMenus` - `contextualIdentities` - `cookies` - `debugger` - `declarativeNetRequest` - `declarativeNetRequestFeedback` - `declarativeNetRequestWithHostAccess` - `devtools` (This permission is granted implicitly when the [`devtools_page`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page) manifest key is present.) - `dns` - `downloads` - `downloads.open` - `find` - `geolocation` - `history` - `identity` - `idle` - `management` - `menus` - `menus.overrideContext` - `nativeMessaging` - `notifications` - `pageCapture` - `pkcs11` - `privacy` - `proxy` - `scripting` - `search` - `sessions` - `storage` - `tabHide` - `tabs` - `theme` - `topSites` - `unlimitedStorage` - `webNavigation` - `webRequest` - `webRequestAuthProvider` (Manifest V3 and above) - `webRequestBlocking` - `webRequestFilterResponse` - `webRequestFilterResponse.serviceWorkerScript` In most cases the permission just grants access to the API, with the following exceptions: - `tabs` gives you access to {{webextAPIref("tabs", "privileged parts of the <code>tabs</code> API")}} without the need for [host permissions](#host_permissions): `Tab.url`, `Tab.title`, and `Tab.faviconUrl`. - In Firefox 85 and earlier, you also need `tabs` if you want to include `url` in the `queryInfo` parameter to {{webextAPIref("tabs/query", "tabs.query()")}}. The rest of the `tabs` API can be used without requesting any permission. - As of Firefox 86 and Chrome 50, matching [host permissions](#host_permissions) can also be used instead of the "tabs" permission. - `webRequestBlocking` enables you to use the `"blocking"` argument, so you can {{webextAPIref("WebRequest", "modify and cancel requests")}}. - `downloads.open` lets you use the {{WebExtAPIRef("downloads.open()")}} API. - `tabHide` lets you use the {{WebExtAPIRef("tabs.hide()")}} API. ## activeTab permission This permission is specified as `"activeTab"`. If an extension has the `activeTab` permission, then when the user interacts with the extension, the extension is granted extra privileges for the active tab only. "User interaction" includes: - the user clicks the extension's {{webextAPIref("browserAction", "browser action", "", 1)}} or [page action](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions) - the user selects its context menu item - the user activates a keyboard shortcut defined by the extension The extra privileges are: - The ability to inject JavaScript or CSS into the tab programmatically (see [Loading content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#loading_content_scripts)). - Access to the privileged parts of the tabs API for the current tab: `Tab.url`, `Tab.title`, and `Tab.faviconUrl`. The intention of this permission is to enable extensions to fulfill a common use case, without having to give them very powerful permissions. Many extensions want to "do something to the current page when the user asks". For example, consider an extension that wants to run a script in the current page when the user clicks a browser action. If the `activeTab` permission did not exist, the extension would need to ask for the host permission `<all_urls>`. But this gives the extension more power than it needs: it could now execute scripts in _any tab_, _any time_ it likes, instead of just the active tab and only in response to a user action. > **Note:** You can only get access to the tab/data that was there, when the user interaction occurred (e.g. the click). When the active tab navigates away (e.g., due to finishing loading or some other event), the permission does not grant you access to the tab anymore. The `activeTab` permission enables scripting access to the top level tab's page and same origin frames. Running scripts or modifying styles inside [cross-origin](/en-US/docs/Web/Security/Same-origin_policy#cross-origin_network_access) frames may require additional [host permissions](#host_permissions). Of course, [restrictions and limitations](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#permissions_restrictions_and_limitations) related to particular sites and URI schemes are applied as well. Usually the tab that's granted `activeTab` is just the currently active tab, except in one case. The {{webextAPIref("menus")}} API enables an extension to create a menu item which is shown if the user context-clicks on a tab (that is, on the element in the tabstrip that enables the user to switch from one tab to another). If the user clicks such an item, then the `activeTab` permission is granted for the tab the user clicked, even if it's not the currently active tab (as of Firefox 63, [Firefox bug 1446956](https://bugzil.la/1446956)). ## Clipboard access There are two permissions which enables the extension to interact with the clipboard: - `clipboardWrite` - : Write to the clipboard using {{DOMxRef("Clipboard.write()")}}, {{DOMxRef("Clipboard.writeText()")}}, `document.execCommand("copy")` or `document.execCommand("cut")` - `clipboardRead` - : Read from the clipboard using {{DOMxRef("Clipboard.read()")}}, {{DOMxRef("Clipboard.readText()")}} or `document.execCommand("paste")` See [Interact with the clipboard](/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard) for more details. ## Unlimited storage The `unlimitedStorage` permission: - Enables extensions to exceed any quota imposed by the {{WebExtAPIRef("storage/local", "storage.local")}} API - In Firefox, enables extensions to create a ["persistent" IndexedDB database](/en-US/docs/Web/API/IndexedDB_API) without the browser prompting the user for permission at the time the database is created. ## Example ```json "permissions": ["*://developer.mozilla.org/*"] ``` In Manifest V2 only, request privileged access to pages under `developer.mozilla.org`. ```json "permissions": ["tabs"] ``` Request access to the privileged pieces of the `tabs` API. ```json "permissions": ["*://developer.mozilla.org/*", "tabs"] ``` In Manifest V2 only, request both of the above permissions. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/storage/index.md
--- title: storage slug: Mozilla/Add-ons/WebExtensions/manifest.json/storage page-type: webextension-manifest-key browser-compat: webextensions.manifest.storage --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "storage": { "managed_schema": "schema.json" }</pre > </td> </tr> </tbody> </table> Use the `storage` key to specify the name of the schema file that defines the structure of data in managed storage. Managed data declares the enterprise policies supported by the app. Policies are analogous to options but are configured by a system administrator instead of the user, enabling the app to be configured for all users of an organization. After declaring the policies, they are read from the {{WebExtAPIRef("storage.managed")}} API. However, if a policy value does not conform to the schema, then it is not published by the `storage.managed` API. It's up to the app to enforce the policies configured by the administrator. > **Note:** Firefox does not define a schema for managed storage, see {{WebExtAPIRef("storage.managed")}} for more details. The `storage` key is an object that has the following required property: <table class="standard-table"> <tbody> <tr> <td><code>managed_schema</code></td> <td> <p> A <code>String</code> specifying the full path of the file within the extension that defines the schema of the manage storage. </p> </td> </tr> </tbody> </table> ## Browser compatibility {{Compat}} > **Note:** > > This page includes details from the Chrome developer website page [Manifest for storage areas](https://developer.chrome.com/docs/extensions/mv2/manifest/storage/) included here under the Creative Commons Attribution 3.0 United States License.
0
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/manifest.json/sidebar_action/index.md
--- title: sidebar_action slug: Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action page-type: webextension-manifest-key browser-compat: webextensions.manifest.sidebar_action --- {{AddonSidebar}} <table class="fullwidth-table standard-table"> <tbody> <tr> <th scope="row">Type</th> <td><code>Object</code></td> </tr> <tr> <th scope="row">Mandatory</th> <td>No</td> </tr> <tr> <th scope="row">Manifest version</th> <td>2 or higher</td> </tr> <tr> <th scope="row">Example</th> <td> <pre class="brush: json"> "sidebar_action": { "default_icon": { "16": "button/geo-16.png", "32": "button/geo-32.png" }, "default_title": "My sidebar", "default_panel": "sidebar/sidebar.html", "open_at_install":true }</pre > </td> </tr> <tr> <th scope="row"> </th> <td></td> </tr> </tbody> </table> A [sidebar](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars) is a pane that is displayed at the left-hand side of the browser window, next to the web page. The browser provides a UI that enables the user to see the currently available sidebars and to select a sidebar to display. The sidebar_action key enables you to define the default properties for the sidebar. You can change these properties at runtime using the {{WebExtAPIRef("sidebarAction")}} API. ## Syntax The `sidebar_action` key is an object that may have any of the properties listed below. The only mandatory property is `default_panel`. <table class="fullwidth-table standard-table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td> <code> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles"> browser_style </a> </code> <br />{{optional_inline}} <br />{{deprecated_inline}} in Manifest V3. </td> <td><code>Boolean</code></td> <td> <p>Optional, defaulting to:</p> <ul> <li><code>true</code> in Manifest V2 and prior to Firefox 115 in Manifest V3.</li> <li><code>false</code> in Manifest V3 from Firefox 115.</li> </ul> <div class="notecard warning"> <p> Do not set <code>browser_style</code> to true: its not support in Manifest V3 from Firefox 118. See <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles#manifest_v3_migration">Manifest V3 migration for <code>browser_style</code></a>. </p> </div> <p> In Firefox, the stylesheet can be seen at chrome://browser/content/extension.css or chrome://browser/content/extension-mac.css on macOS. When setting dimensions, be aware that this stylesheet sets <code>box-sizing: border-box</code> (see <a href="/en-US/docs/Web/CSS/box-sizing">box-sizing</a>). </p> </td> </tr> <tr> <td><code>default_icon</code> <br />{{optional_inline}}</td> <td><code>Object</code> or <code>String</code></td> <td> <p> Use this to specify one or more icons for the sidebar. The icon is shown in the browser's UI for opening and closing sidebars. </p> <p> Icons are specified as URLs relative to the manifest.json file itself. </p> <p>You can specify a single icon file by supplying a string here:</p> <pre class="brush: json">"default_icon": "path/to/geo.svg"</pre> <p> To specify multiple icons in different sizes, specify an object here. The name of each property is the icon's height in pixels, and must be convertible to an integer. The value is the URL. For example: </p> <pre class="brush: json"> "default_icon": { "16": "path/to/geo-16.png", "32": "path/to/geo-32.png" }</pre > <p> See <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action#choosing_icon_sizes" >Choosing icon sizes</a > for more guidance on this. </p> <p> This property is optional: if it is omitted, the sidebar doesn't get an icon. </p> </td> </tr> <tr> <td><code>default_panel</code></td> <td><code>String</code></td> <td> <p>The path to an HTML file that specifies the sidebar's contents.</p> <p> The HTML file may include CSS and JavaScript files using <code ><a href="/en-US/docs/Web/HTML/Element/link">&#x3C;link></a></code > and <code ><a href="/en-US/docs/Web/HTML/Element/script" >&#x3C;script></a ></code > elements, just like a normal web page. </p> <p> Unlike a normal web page, JavaScript running in the panel can access all the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API" >WebExtension APIs</a > (subject, of course, to the extension having the appropriate <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions" >permissions</a >). </p> <p>This property is mandatory.</p> <p> This is a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json" >localizable property</a >. </p> </td> </tr> <tr> <td><code>default_title</code> <br />{{optional_inline}}</td> <td><code>String</code></td> <td> <p> Title for the sidebar. This is used in the browser UI for listing and opening sidebars, and is displayed at the top of the sidebar when it is open. </p> <p> This property is optional: if it is omitted, the sidebar's title is the extension's <code ><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name" >name</a ></code >. </p> <p> This is a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization#internationalizing_manifest.json" >localizable property</a >. </p> </td> </tr> <tr> <td><code>open_at_install</code> <br />{{optional_inline}}</td> <td>Boolean</td> <td> Optional, defaulting to <code>true</code>. Determines whether the sidebar should open on install. The default behavior is to open the sidebar when installation is completed. </td> </tr> </tbody> </table> ## Example ```json "sidebar_action": { "default_icon": "sidebar.svg", "default_title": "My sidebar!", "default_panel": "sidebar.html" } ``` For a simple example of an extension that uses a sidebar, see [annotate-page](https://github.com/mdn/webextensions-examples/tree/main/annotate-page). ## Browser compatibility {{Compat}} ## See also - [`browser_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) - [`page_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action) - [Browser styles](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles)
0