title
stringlengths
2
136
text
stringlengths
20
75.4k
What next? - Mozilla
What next? ========== You'll now be ready to start turning your idea for a browser extension into reality. Before you start that journey, it's worth being aware of a few things that will help to make it a smooth one. You can find more about many of the things discussed on this page on Extension Workshop, a website dedicated to helping you write, test, publish, and distribute extensions for Firefox. Your development environment ---------------------------- You don't need any special development or build environment tools to create browser extensions: It's entirely possible to create great browser extensions with no more than a text editor. However, you may have been developing for the web and have a set of tools and an environment you want to reuse. If you do, you need to be aware of a couple of things. If you use minification or obfuscation tools to deliver your final code, you'll need to provide your source code to the AMO review process. Also, the tools you use—those for minification, obfuscation, and build processes—will need to be open source (or offer unlimited free use) and be available to run on the reviewer's computer (Windows, Mac, or Linux). Unfortunately, our reviewers can't work with commercial or web-based tools. Learn more about development tools on Extension Workshop Third-party libraries --------------------- Third-party libraries are a great way to add complex features or functionality to your browser extensions quickly. When you submit an extension to the AMO review process, the process will also consider any third-party libraries used. To streamline the review, make sure you always download third-party libraries from their official website or repository, and if the library is minified provide a link to the source code. Please note that third-party libraries cannot be modified in any way. Learn more about submitting source code on Extension Workshop The Firefox Add-on Distribution Agreement ----------------------------------------- Browser extensions need to be signed to install into the release or beta versions of Firefox. Signing takes place in addons.mozilla.org (AMO) and is subject to the terms and conditions of the Firefox Add-on Distribution Agreement. The goal of the agreement is to ensure Firefox users get access to well supported, quality add-ons that enhance the Firefox experience. Read the agreement on Extension Workshop Learn more about signing on Extension Workshop The review process ------------------ When a browser extension is submitted for signing, it's subject to automated review. It may also be subject to a manual review, when the automated review determines that a manual review is needed. Your browser extension won't be signed until it's passed the automated review and may have its signing revoked if it fails to pass the manual review. The review process follows a strict set of guidelines, so it's easy to check and avoid any likely review problems. Check out the review policy and guidelines on Extension Workshop AMO featured browser extensions ------------------------------- If you choose to list your browser extension on AMO, your extension could be featured on the AMO website, in the Firefox browser's add-on manager, or elsewhere on a Mozilla website. We've compiled a list of guidelines about how extensions are selected for featuring, by following these guidelines you give your extension the best chance of being featured. Learn more about getting your add-ons featured on Extension Workshop Continue your learning experience --------------------------------- Now you know what lies ahead, it's time to dive into more details about browser extension development. In the sections that follow, you'll discover: * More about the fundamental concepts behind browser extensions, starting with details on how to use the JavaScript APIs. * A guide to the user interface components available to your browser extensions. * A collection of how-to guides on achieving key tasks in your extensions or making use of the JavaScript APIs. * A full reference guide to the JavaScript APIs. * A full reference guide to the Manifest keys. You'll also want to head on over to Extension Workshop where you'll find everything you need to know about creating extensions for Firefox, including: * an overview of the Firefox extension features * details of the tools and processes for developing and testing * how to publish your extension on addons.mozilla.org or distribute it yourself * how to manage your published extension * an enterprise guide for developing and using extensions * how to develop themes for Firefox * details about the Firefox developer communities
Browser compatibility for manifest.json - Mozilla
Browser compatibility for manifest.json ======================================= BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * Browser support for JavaScript APIs
Intercept HTTP requests - Mozilla
Intercept HTTP requests ======================= To intercept HTTP requests, use the `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 `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 means you intercept HTTP requests to all URLs. To test it: * Install the extension * Open the Browser Console (use `Ctrl + Shift + J`) * Enable *Show Content Messages* in the menu: ![Browser console menu: Show Content Messages](/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests/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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests/browser_console_url_from_extension.png) 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`. This extra permission is needed when an extension wants to modify a request. * Replace the `<all_urls>` permission with individual 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 `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. 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 `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 `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), reload the extension, and then reload the MDN page. You see something like this: ![Images on a page replaced with a frog image](/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests/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 `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. 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 `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 and check that it identifies the browser as Firefox. Then reload the extension, reload useragentstring.com, and see that Firefox is now identified as Opera. ![useragentstring.com showing details of the modified user agent string](/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests/modified_request_header.png) Learn more ---------- To learn about all the things you can do with the `webRequest` API, see its reference documentation.
Share objects with page scripts - Mozilla
Share objects with page scripts =============================== **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, 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 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, 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 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()`: export a function to page scripts. * `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 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 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 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. 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 ```
manifest.json - Mozilla
manifest.json ============= **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 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-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 (Manifest V3 and above) * author * background * browser\_action (Manifest V2 only) * browser\_specific\_settings * chrome\_settings\_overrides * chrome\_url\_overrides * commands * content\_scripts * content\_security\_policy * declarative\_net\_request * default\_locale * description * developer * devtools\_page * dictionaries * externally\_connectable * homepage\_url * host\_permissions (Manifest V3 and above) * icons * incognito * manifest\_version * name * offline\_enabled * omnibox * optional\_permissions * options\_page * options\_ui * page\_action (Manifest V2 only in Chrome) * permissions * protocol\_handlers * short\_name * sidebar\_action * storage * theme * theme\_experiment * user\_scripts (Manifest V2 only) * version * version\_name * 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 `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. ```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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. For a full overview of all manifest keys and their sub-keys, see the full manifest.json browser compatibility table. See also -------- `permissions` JavaScript API
Firefox workflow overview - Mozilla
Firefox workflow overview ========================= | | | | | | | --- | --- | --- | --- | --- | | Firefox workflow prepare step graphic | Firefox workflow code step graphic | Firefox workflow publish step graphic | Firefox workflow enhance step graphic | Firefox workflow retire step graphic | | * Choose a Firefox version for web extension development * Choose your IDE or code editor * Install web-ext * Get familiar with the add-on policies and developer agreement | * Code your extension * Run your extension withweb-ext run or about: debugging) * Test persistent and restart features * Debug with theAddon Debugging Window | * Package your extension withweb-ext build * Create an addons.mozilla.org account * Submit your extension * Submit your source code (if required) * Create an appealing listing | * Responded to Mozilla extension review * Promote your extension * Nominate your extension to be featured * Update and improve your extension | * Retire your extension | \* Or distribute your extension for sideloading, desktop apps, or in an 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.
Content Security Policy - Mozilla
Content Security Policy ======================= Extensions developed with WebExtension APIs have a Content Security Policy (CSP) applied to them by default. This restricts the sources from which they can load code such as <script> and disallows potentially unsafe practices such as using `eval()`. This article briefly explains what a CSP is, what the default policy is and what it means for an extension, and how an extension can change the default CSP. Content Security Policy (CSP) is a mechanism to help prevent websites from inadvertently executing malicious content. A website specifies a CSP using an HTTP header sent from the server. The CSP is mostly concerned with specifying legitimate sources of various types of content, such as scripts or embedded plugins. For example, a website can use it to specify that the browser should only execute JavaScript served from the website itself, and not from any other sources. A CSP can also instruct the browser to disallow potentially unsafe practices, such as the use of `eval()`. Like websites, extensions can load content from different sources. For example, a browser action's popup is specified as an HTML document, and it can include JavaScript and CSS from different sources, just like a normal web page: ```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> </head> <body> <!--Some HTML content here--> <!-- Include a third-party script. See also https://developer.mozilla.org/en-US/docs/Web/Security/Subresource\_Integrity. --> <script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script> <!-- Include my popup's own script--> <script src="popup.js"></script> </body> </html> ``` Compared to a website, extensions have access to additional privileged APIs, so if they are compromised by malicious code, the risks are greater. For this reason: * a fairly strict content security policy is applied to extensions by default. See default content security policy. * the extension's author can change the default policy using the `content_security_policy` manifest.json key, but there are restrictions on the policies that are allowed. See `content_security_policy`. Default content security policy ------------------------------- The default content security policy for extensions using Manifest V2 is: ``` "script-src 'self'; object-src 'self';" ``` While for extensions using Manifest V3, the default content security policy is: ``` "script-src 'self'; upgrade-insecure-requests;" ``` These policies are applied to any extension that has not explicitly set its own content security policy using the `content_security_policy` manifest.json key. It has the following consequences: * You may only load <script> and <object> resources that are local to the extension. * The extension is not allowed to evaluate strings as JavaScript. * Inline JavaScript is not executed. * WebAssembly cannot be used by default. * Insecure network requests are upgraded in Manifest V3. ### Location of script and object resources Under the default CSP, you can only load code that is local to the extension. The CSP limits `script-src` to secure sources only, which covers <script> resources, ES6 modules and web workers. In browsers that support obsolete plugins, the `object-src` directive is also restricted. For more information on object-src in extensions, see the WECG issue Remove object-src from the CSP (at least in MV3)). For example, consider a line like this in an extension's document: ```html <script src="https://code.jquery.com/jquery-2.2.4.js"></script> ``` This doesn't load the requested resource: it fails silently, and any object that you expect to be present from the resource is not found. There are two main solutions to this: * download the resource, package it in your extension, and refer to this version of the resource. * allow the remote origin you need using the `content_security_policy` key or, in Manifest V3, the `content_scripts` property. **Note:** If your modified CSP allows remote script injection, your extension will get rejected from addons.mozilla.org (AMO) during the review. For more information, see details about security best practices. ### eval() and friends Under the default CSP, extensions cannot evaluate strings as JavaScript. This means that the following are not permitted: ```js eval("console.log('some output');"); ``` ```js setTimeout("alert('Hello World!');", 500); ``` ```js const f = new Function("console.log('foo');"); ``` ### Inline JavaScript Under the default CSP, inline JavaScript is not executed. This disallows both JavaScript placed directly in `<script>` tags and inline event handlers, meaning that the following are not permitted: ```html <script> console.log("foo"); </script> ``` ```html <div onclick="console.log('click')">Click me!</div> ``` If you are currently using code like `<body onload="main()">` to run your script when the page has loaded, listen for DOMContentLoaded or load instead. ### WebAssembly Extensions wishing to use WebAssembly require `'wasm-unsafe-eval'` to be specified in the `script-src` directive. From Firefox 102 and Chrome 103, `'wasm-unsafe-eval'` can be included in the `content_security_policy` manifest.json key to enable the use of WebAssembly in extensions. Manifest V2 extensions in Firefox can use WebAssembly without `'wasm-unsafe-eval'` in their CSP for backward compatibility. However, this behavior isn't guaranteed, see Firefox bug 1770909. Extensions using WebAssembly are therefore encouraged to declare `'wasm-unsafe-eval'` in their CSP. For Chrome, extensions cannot use WebAssembly in version 101 or earlier. In 102, extensions can use WebAssembly (the same behavior as Firefox 101 and earlier). From version 103, extensions can use WebAssembly if they include `'wasm-unsafe-eval'` in the `content_security_policy` in the manifest key. ### Upgrade insecure network requests in Manifest V3 Extensions should use `https:` and `wss:` when communicating with external servers. To encourage this as the standard behavior, the default Manifest V3 CSP includes the `upgrade-insecure-requests` directive. This directive automatically upgrades network requests to `http:` to use `https:`. While requests are automatically upgraded, it is still recommended to use `https:`-URLs in the extension's source code where possible. In particular, entries in the `host_permissions` section of manifest.json should start with `https://` or `*://` instead of only `http://`. Manifest V3 Extensions that need to make `http:` or `ws:` requests can opt out of this behavior by overriding the default CSP using the `content_security_policy` manifest.json key with a policy that excludes the `upgrade-insecure-requests` directive. However, to comply with the security requirements of the Add-on Policies, all user data must be transmitted securely. CSP for content scripts ----------------------- In Manifest V2, content scripts have no CSP. As of Manifest V3, content scripts share the default CSP as extensions. It is currently not possible to specify a separate CSP for content scripts (source). The extent to which the CSP controls loads from content scripts varies by browser. In Firefox, JavaScript features such as eval are restricted by the extension CSP. Generally, most DOM-based APIs are subjected to the CSP of the web page. In Chrome, many DOM APIs are covered by the extension CSP instead of the web page's CSP (crbug 896041).
Add a button to the toolbar - Mozilla
Add a button to the toolbar =========================== Toolbar buttons are one of the main UI components available to extensions. Toolbar buttons live in the main browser toolbar and contain an icon. When the user clicks the icon, one of two things can happen: * If you have specified a popup for the icon, the popup is shown. Popups are transient dialogs specified using HTML, CSS, and JavaScript. * If you have not specified a popup, a click event is generated, which you can listen for in your code and perform some other kind of action in response to. With WebExtension APIs, these kinds of buttons are called "browser actions", and are set up like so: * The manifest.json key `browser_action` is used to define the button. * The JavaScript API `browserAction` is used to listen for clicks and change the button or perform actions via your code. A simple button --------------- In this section we'll create an extension that adds a button to the toolbar. When the user clicks the button, we'll open https://developer.mozilla.org in a new tab. First, create a new directory, "button", and create a file called "manifest.json" inside it with the following contents: ```json { "description": "Demonstrating toolbar buttons", "manifest\_version": 2, "name": "button-demo", "version": "1.0", "background": { "scripts": ["background.js"] }, "browser\_action": { "default\_icon": { "16": "icons/page-16.png", "32": "icons/page-32.png" } } } ``` This specifies that we'll have a background script named "background.js", and a browser action (button) whose icons will live in the "icons" directory. Next, create the "icons" directory inside the "buttons" directory, and save the two icons shown below inside it: **"page-16.png":** !["16 pixel icon of a lined sheet of paper"](/en-US/docs/Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar/page-16.png) **"page-32.png":** !["32 pixel icon of a lined sheet of paper"](/en-US/docs/Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar/page-32.png) **Note:** These icons are from the bitsies! iconset created by Recep Kütük. We have two icons so we can use the bigger one in high-density displays. The browser will take care of selecting the best icon for the current display. Next, create "background.js" in the extension's root directory, and give it the following contents: ```js function openPage() { browser.tabs.create({ url: "https://developer.mozilla.org", }); } browser.browserAction.onClicked.addListener(openPage); ``` This listens for the browser action's click event; when the event fires, the `openPage()` function is run, which opens the specified page using the `tabs` API. At this point the complete extension should look like this: ``` button/ icons/ page-16.png page-32.png background.js manifest.json ``` Now install the extension and click the button: ![The toolbar button added by the extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar/toolbar_button.png) Adding a popup -------------- Let's try adding a popup to the button. Replace manifest.json with this: ```json { "description": "Demonstrating toolbar buttons", "manifest\_version": 2, "name": "button-demo", "version": "1.0", "browser\_action": { "default\_popup": "popup/choose\_page.html", "default\_icon": { "16": "icons/page-16.png", "32": "icons/page-32.png" } } } ``` We've made two changes from the original: * removed the reference to "background.js", because now we're going to handle the extension's logic in the popup's script (you are allowed background.js as well as a popup, it's just that we don't need it in this case). * added `"default_popup": "popup/choose_page.html"`, which is telling the browser that this browser action is now going to display a popup when clicked, the document for which can be found at "popup/choose\_page.html". So now we need to create that popup. Create a directory called "popup" then create a file called "choose\_page.html" inside it. Give it the following contents: ```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="choose\_page.css" /> </head> <body> <div class="page-choice">developer.mozilla.org</div> <div class="page-choice">support.mozilla.org</div> <div class="page-choice">addons.mozilla.org</div> <script src="choose\_page.js"></script> </body> </html> ``` You can see that this is a normal HTML page containing three `<div>` elements, each with the name of a Mozilla site inside. It also includes a CSS file and a JavaScript file, which we'll add next. Create a file called "choose\_page.css" inside the "popup" directory, and give it these contents: ```css html, body { width: 300px; } .page-choice { width: 100%; padding: 4px; font-size: 1.5em; text-align: center; cursor: pointer; } .page-choice:hover { background-color: #cff2f2; } ``` This is just a bit of styling for our popup. Next, create a "choose\_page.js" file inside the "popup" directory, and give it these contents: ```js document.addEventListener("click", (event) => { if (!event.target.classList.contains("page-choice")) { return; } const chosenPage = `https://${event.target.textContent}`; browser.tabs.create({ url: chosenPage, }); }); ``` In our JavaScript, we listen for clicks on the popup choices. We first check to see if the click landed on one of the page-choices; if not, we don't do anything else. If the click did land on a page-choice, we construct a URL from it, and open a new tab containing the corresponding page. Note that we can use WebExtension APIs in popup scripts, just as we can in background scripts. The extension's final structure should look like this: ``` button/ icons/ page-16.png page-32.png popup/ choose_page.css choose_page.html choose_page.js manifest.json ``` Now reload the extension, click the button again, and try clicking on the choices in the popup: ![The toolbar button added by the extension with a popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar/toolbar_button_with_popup.png) Page actions ------------ Page actions are just like browser actions, except that they are for actions which are relevant only for particular pages, rather than the browser as a whole. While browser actions are always shown, page actions are only shown in tabs where they are relevant. Page action buttons are displayed in the URL bar, rather than the browser toolbar. Learn more ---------- * `browser_action` manifest key * `browserAction` API * Browser action examples: + beastify + Bookmark it! + favourite-colour + open-my-page-button * `page_action` manifest key * `pageAction` API * Page action examples: + chill-out
Modify a web page - Mozilla
Modify a web page ================= 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` 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, and visit https://developer.mozilla.org/. The page should look like this: ![developer.mozilla.org page "eaten" by the script](/en-US/docs/Mozilla/Add-ons/WebExtensions/Modify_a_web_page/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`: To inject scripts into pages we need permissions for the page we're modifying. The `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`: We're using this to load a persistent "background script" 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, 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()` 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: ``` modify-page/ background.js manifest.json page-eater.js ``` Now reload the extension, 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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Modify_a_web_page/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: | | In content script | In background script | | --- | --- | --- | | Send a message | `browser.runtime.sendMessage()` | `browser.tabs.sendMessage()` | | Receive a message | `browser.runtime.onMessage` | `browser.runtime.onMessage` | **Note:** In addition to this method of communication, which sends one-off messages, you can also use a connection-based approach to exchange messages. For advice on choosing between the options, see 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()` to get the currently active tab, and then use `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`. 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()` 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 `Ctrl`+`Shift`+`J` (or `Cmd`+`Shift`+`J` on macOS) OR `web-ext run --bc` to open Browser Console to view `console.log` in background script. Alternatively, use Add-on Debugger which allows you set breakpoint. There is currently no way to start Add-on Debugger directly from web-ext. If we want send messages back from the content script to the background page, we would use `runtime.sendMessage()` instead of `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()` function. Learn more ---------- * Content scripts guide * `content_scripts` manifest key * `permissions` manifest key * `tabs.executeScript()` * `tabs.insertCSS()` * `tabs.sendMessage()` * `runtime.sendMessage()` * `runtime.onMessage` * Examples using `content_scripts`: + borderify + emoji-substitution + notify-link-clicks-i18n + page-to-extension-messaging * Examples using `tabs.executeScript()`: + beastify + context-menu-copy-link-with-types
What are extensions? - Mozilla
What are extensions? ==================== **Note:** If you are already familiar with the basic concepts of browser extensions, skip this section to see how extension files are put together. Then, use the reference documentation to start building your extension. Visit Firefox Extension Workshop to learn more about the workflow for testing, publishing, and extensions for Firefox. An extension adds features and functions to a browser. It's created using familiar web-based technologies — HTML, CSS, and JavaScript. It can take advantage of the same web APIs as JavaScript on a web page, but an extension also has access to its own set of JavaScript APIs. This means that you can do a lot more in an extension than you can with code in a web page. Here are just a few examples of the things you can do: **Enhance or complement a website**: Use an add-on to deliver additional in-browser features or information from your website. Allow users to collect details from pages they visit to enhance the service you offer. ![Amazon add-on example providing price comparison features](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_are_WebExtensions/amazon_add_on.png) Examples: Amazon Assistant for Firefox, OneNote Web Clipper, and Grammarly for Firefox. **Let users show their personality**: Browser extensions can manipulate the content of web pages; for example, letting users add their favorite logo or picture as a background to every page they visit. Extensions may also enable users to update the look of the Firefox UI, the same way standalone theme add-ons do. ![My Web New Tab add-on showing a Batman theme](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_are_WebExtensions/myweb_new_tab_add_on.png) Examples: MyWeb New Tab, Tabliss, and VivaldiFox. **Add or remove content from web pages**: You might want to help users block intrusive ads from web pages, provide access to a travel guide whenever a country or city is mentioned in a web page, or reformat page content to offer a consistent reading experience. With the ability to access and update both a page's HTML and CSS, extensions can help users see the web the way they want to. ![uBlock origin add-on example with blocked tracker statistics](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_are_WebExtensions/ublock_origin_add_on.png) Examples: uBlock Origin, Reader, and Toolbox for Google Play Store™. **Add tools and new browsing features**: Add new features to a taskboard, or generate QR code images from URLs, hyperlinks, or page text. With flexible UI options and the power of the WebExtensions APIs you can easily add new features to a browser. And, you can enhance almost any website's features or functionality, it doesn't have to be your website. ![QR code generator add-on example](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_are_WebExtensions/qr_code_image_generator_add_on.png) Examples: Swimlanes for Trello and Tomato Clock. **Games**: Offer traditional computer games with off-line play features, or explore new game possibilities; for example, by incorporating gameplay into everyday browsing. Examples: Solitaire Card Game, and 2048 Prime. **Add development tools**: You may provide web development tools as your business or have developed a useful technique or approach to web development that you want to share. Either way, you can enhance the built-in Firefox developer tools by adding a new tab to the developer toolbar. ![Axe accessibility testing addon example](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_are_WebExtensions/axe_developer_tools_add_on.png) Examples: Web Developer, Web React Developer Tools, and aXe Developer Tools. Extensions for Firefox are built using the WebExtensions APIs, a cross-browser system for developing extensions. To a large extent, the API is compatible with the extension API supported by Google Chrome and Opera. Extensions written for these browsers will in most cases run in Firefox or Microsoft Edge with just a few changes. If you have ideas or questions, you can reach us on the Add-ons Discourse or in the Add-ons room on Matrix. What's next? ------------ * Walk through the development of a simple extension in Your first extension. * Learn about the structure of an extension in Anatomy of an extension. * Try out some example extensions in Example extensions.
Developing WebExtensions for Thunderbird - Mozilla
Developing WebExtensions for Thunderbird ======================================== You'll approach the coding of an extension for Thunderbird in the same way as you would for a Firefox extension; using a text editor or tool of your choice to write the code. API differences --------------- **Note:** See ReadTheDocs for Thunderbird specific WebExtension API documentation. Being both Gecko based, Thunderbird supports many of the APIs Firefox supports, with some differences, see browser compatibility for manifest.json and browser support for JavaScript APIs for details. See also -------- * Introduction to Thunderbird Add-On development * Thunderbird specific WebExtension API documentation * Browser support for JavaScript APIs * Browser compatibility for manifest.json
Your first extension - Mozilla
Your first extension ==================== **Note:** If you're familiar with the basic concepts of browser extensions, skip this section to see how extension files are put together. Then, use the reference documentation to start building your extension. Visit Firefox Extension Workshop 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. 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, 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`, `name`, and `version`, are mandatory and contain basic metadata for the extension. * `description` is optional, but recommended: it's displayed in the Add-ons Manager. * `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`, 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. * Learn more about match patterns. **Warning:** In some situations you need to specify an ID for your extension. If you do need to specify an add-on ID, include the `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, which is taken from the Google Material Design iconset, and is used under the terms of the Creative Commons Attribution-ShareAlike 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. ### 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. Trying it out ------------- First, double check that you have the right files in the right places: ``` borderify/ icons/ border-48.png borderify.js manifest.json ``` ### Installing In Firefox: Open the about:debugging 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 tool. ### Testing **Note:** By default extensions don't work in 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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension/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 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". What's next? ------------ Now you've had an introduction to the process of developing a WebExtension for Firefox: * write a more complex extension * read more about the anatomy of an extension * explore the extension examples * find out what you need to develop, test, and publish your extension * take your learning further.
Chrome incompatibilities - Mozilla
Chrome incompatibilities ======================== 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 for details. * Support for `manifest.json` keys differs across browsers. See the "Browser compatibility" section on the `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) * 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 on most appropriate methods. (cf. Chrome bug 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 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 `runtime.lastError` to communicate errors. In Manifest V3, callbacks are supported for backward compatibility, along with support for 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 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 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. 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 property or proxy.onRequest to provide ProxyInfo dynamically. See proxy for more information on the API. * **In Chrome**: Proxy settings are defined in a `proxy.ProxyConfig` object. Depending on Chrome's proxy settings, the settings may contain `proxy.ProxyRules` or a `proxy.PacScript`. Proxies are set using the proxy.settings property. See chrome.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: ``` /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) + 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 `webRequest.onAuthRequired` for proxy authorization. See the documentation for `webRequest.onAuthRequired`. + If an extension wants to redirect a public (e.g., HTTPS) URL to an extension page, the extension's `manifest.json` file must contain a `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 `windows` API triggers multiple times for a focus change. ### Unsupported APIs #### DeclarativeContent API * **In Firefox:** Chrome's declarativeContent API is not implemented. In addition, Firefox will not support 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()`, `confirm()`, and `prompt()` are not supported in background pages. #### web\_accessible\_resources * **In Firefox:** Resources are assigned a random 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). * **In Chrome:** When working with an unpacked extension, the manifest may include a `"key"` property 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()`) 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 is not strictly equal to `window` (Firefox bug 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 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:** `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. * **In Chrome:** `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. #### 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. To mimic the behavior of Chrome, listen for the pageshow and pagehide 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 `tabs.ZoomSettingsScope`. manifest.json keys ------------------ The main `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. 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 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 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` flag. Data cloning algorithm ---------------------- Some extension APIs allow an extension to send data from one part of the extension to another, such as `runtime.sendMessage()`, `tabs.sendMessage()`, `runtime.onMessage`, the `postMessage()` method of `runtime.port`, and `tabs.executeScript()`. * **In Firefox:** The Structured clone algorithm is used. * **In Chrome:** The JSON serialization algorithm is used. It may switch to structured cloning in the future (issue 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 `URL` and `PerformanceEntry`. Extensions that rely on the `toJSON()` method of the JSON serialization algorithm can use `JSON.stringify()` followed by `JSON.parse()` to ensure that a message can be exchanged because a parsed JSON value is always structurally cloneable.
Anatomy of an extension - Mozilla
Anatomy of an extension ======================= An extension consists of a collection of files, packaged for distribution and installation. In this article, we will quickly go through the files that might be present in an extension. manifest.json ------------- This is the only file that must be present in every extension. It contains basic metadata such as its name, version, and the permissions it requires. It also provides pointers to other files in the extension. The manifest can also contain pointers to several other types of files: Background scripts Scripts that respond to browser events. Icons For the extension and any buttons it might define. Sidebars, popups, and options pages HTML documents that provide content for various user interface components. Content scripts JavaScript included with your extension, that you will inject into web pages. Web-accessible resources Make packaged content accessible to web pages and content scripts. ![The components of a web extension. The manifest.JSON must be present in all extensions. It provides pointers to background pages, content scripts, browser actions, page actions, options pages, and web accessible resources. Background pages consist of HTML and JS. Content scripts consist of JS and CSS. The user clicks on an icon to trigger browser actions and page actions and the resulting pop-up consists of HTML, CSS, and JS. Options pages consist of HTML, CSS, and JS.](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension/webextension-anatomy.png) See the `manifest.json` reference page for all the details. Along with those already listed in the manifest, an extension may also include additional Extension pages and supporting files. Background scripts ------------------ Extensions often need to respond to events that occur in the browser independently of the lifetime of any particular web page or browser window. That is what background scripts are for. Background scripts can be persistent or non-persistent. Persistent background scripts load as soon as the extension loads and stay loaded until the extension is disabled or uninstalled. This background script behavior is only available in Manifest V2. Non-persistent background scripts load when needed to respond to an event and unload when they become idle. This background script behavior is an option in Manifest V2 and the only background script behavior available in Manifest V3. You can use any of the WebExtension APIs in the script, if you have requested the necessary permissions. See the background scripts article to learn more. Sidebars, popups, and options pages ----------------------------------- Your extension can include various user interface components whose content is defined using an HTML document: Sidebar A pane that is displayed at the left-hand side of the browser window, next to the web page. Popup A dialog that you can display when the user clicks on a toolbar button or address bar button Options A page that's shown when the user accesses your add-on's preferences in the browser's native add-ons manager. For each of these components, you create an HTML file and point to it using a specific property in `manifest.json`. The HTML file can include CSS and JavaScript files, just like a normal web page. All of these are a type of Extension pages. Unlike a normal web page, your JavaScript can use all the same privileged WebExtension APIs as your background script. Extension pages --------------- You can also include HTML documents in your extension which are not attached to some predefined user interface component. Unlike the documents you might provide for sidebars, popups, or options pages, these don't have an entry in `manifest.json`. However, they do also get access to all the same privileged WebExtension APIs as your background script. You'd typically load a page like this using `windows.create()` or `tabs.create()`. See Extension pages to learn more. Content scripts --------------- Use content scripts to access and manipulate web pages. Content scripts are loaded into web pages and run in the context of that particular page. Content scripts are extension-provided scripts which run in the context of a web page; this differs from scripts which are loaded by the page itself, including those which are provided in `<script>` elements within the page. Content scripts can see and manipulate the page's DOM, just like normal scripts loaded by the page. Unlike normal page scripts, content scripts can: * Make cross-domain XHR requests. * Use a small subset of the WebExtension APIs. * Exchange messages with their background scripts and can in this way indirectly access all the WebExtension APIs. Content scripts cannot directly access normal page scripts but can exchange messages with them using the standard `window.postMessage()` API. Usually, when we talk about content scripts, we are referring to JavaScript, but you can inject CSS into web pages using the same mechanism. See the content scripts article to learn more. Web accessible resources ------------------------ Web accessible resources are resources—such as images, HTML, CSS, and JavaScript—that you include in the extension and want to make accessible to content scripts and page scripts. Resources which are made web-accessible can be referenced by page scripts and content scripts using a special URI scheme. For example, if a content script wants to insert some images into web pages, you could include them in the extension and make them web accessible. Then the content script could create and append `img` tags which reference the images via the `src` attribute. To learn more, see the documentation for the `"web_accessible_resources"` `manifest.json` key.
JavaScript APIs - Mozilla
JavaScript APIs =============== JavaScript APIs for WebExtensions can be used inside the extension's background scripts and in any other documents bundled with the extension, including browser action or page action popups, sidebars, options pages, or new tab pages. A few of these APIs can also be accessed by an extension's content scripts. (See the list in the content script guide.) To use the more powerful APIs, you need to request permission in your extension's `manifest.json`. You can access the APIs using the `browser` namespace: ```js function logTabs(tabs) { console.log(tabs); } browser.tabs.query({ currentWindow: true }, logTabs); ``` Many of the APIs are asynchronous, returning a `Promise`: ```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); ``` Browser API differences ----------------------- Note that this is different from Google Chrome's extension system, which uses the `chrome` namespace instead of `browser`, and which uses callbacks instead of promises for asynchronous functions. As a porting aid, the Firefox implementation of WebExtensions APIs supports `chrome` and callbacks as well as `browser` and promises. Mozilla has also written a polyfill which enables code that uses `browser` and promises to work unchanged in Chrome: https://github.com/mozilla/webextension-polyfill. Firefox also implements these APIs under the `chrome` namespace using callbacks. This allows code written for Chrome to run largely unchanged in Firefox for the APIs documented here. Microsoft Edge uses the `browser` namespace, but doesn't yet support promise-based asynchronous APIs. In Edge, for the time being, asynchronous APIs must use callbacks. Not all browsers support all the APIs: for the details, see Browser support for JavaScript APIs and Chrome incompatibilities. Examples -------- Throughout the JavaScript API listings, short code examples illustrate how the API is used. You can experiment with most of these examples using the console in the Toolbox. However, you need Toolbox running in the context of a web extension. To do this, open `about:debugging` then **This Firefox**, click **Inspect** against any installed or temporary extension, and open **Console**. You can then paste and run the example code in the console. For example, here is the first code example on this page running in the Toolbox console in Firefox Developer Edition: ![Illustration of a snippet of web extension code run from the console in the Toolbox](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/javascript_exercised_in_console.jpg) JavaScript API listing ---------------------- See below for a complete list of JavaScript APIs: actionAdds a button to the browser's toolbar. alarmsSchedule code to run at a specific time in the future. This is like `setTimeout()` and `setInterval()`, except that those functions don't work with background pages that are loaded on demand. bookmarksThe WebExtensions `bookmarks` API lets an extension interact with and manipulate the browser's bookmarking system. You can use it to bookmark pages, retrieve existing bookmarks, and edit, remove, and organize bookmarks. browserActionAdds a button to the browser's toolbar. browserSettingsEnables an extension to modify certain global browser settings. Each property of this API is a `types.BrowserSetting` object, providing the ability to modify a particular setting. browsingDataEnables extensions to clear the data that is accumulated while the user is browsing. captivePortalDetermine the captive portal state of the user's connection. A captive portal is a web page displayed when a user first connects to a Wi-Fi network. The user provides information or acts on the captive portal web page to gain broader access to network resources, such as accepting terms and conditions or making a payment. clipboardThe WebExtension `clipboard` API (which is different from the standard Clipboard API) enables an extension to copy items to the system clipboard. Currently the WebExtension `clipboard` API only supports copying images, but it's intended to support copying text and HTML in the future. commandsListen for the user executing commands that you have registered using the `commands` manifest.json key. contentScriptsUse this API to register content scripts. Registering a content script instructs the browser to insert the given content scripts into pages that match the given URL patterns. contextualIdentitiesWork with contextual identities: list, create, remove, and update contextual identities. cookiesEnables extensions to get and set cookies, and be notified when they change. declarativeNetRequestThis API enables extensions to specify conditions and actions that describe how network requests should be handled. These declarative rules enable the browser to evaluate and modify network requests without notifying extensions about individual network requests. devtoolsEnables extensions to interact with the browser's Developer Tools. You use this API to create Developer Tools pages, interact with the window that is being inspected, inspect the page network usage. dnsEnables an extension to resolve domain names. domAccess special extension only DOM features. downloadsEnables extensions to interact with the browser's download manager. You can use this API module to download files, cancel, pause, resume downloads, and show downloaded files in the file manager. eventsCommon types used by APIs that dispatch events. extensionUtilities related to your extension. Get URLs to resources packages with your extension. Get the `Window` object for your extension's pages. Get the values for various settings. extensionTypesSome common types used in other WebExtension APIs. findFinds text in a web page, and highlights matches. historyUse the `history` API to interact with the browser history. i18nFunctions to internationalize your extension. You can use these APIs to get localized strings from locale files packaged with your extension, find out the browser's current language, and find out the value of its Accept-Language header. identityUse the identity API to get an OAuth2 authorization code or access token, which an extension can then use to access user data from a service that supports OAuth2 access (such as Google or Facebook). idleFind out when the user's system is idle, locked, or active. managementGet information about installed add-ons. menusAdd items to the browser's menu system. notificationsDisplay notifications to the user, using the underlying operating system's notification mechanism. Because this API uses the operating system's notification mechanism, the details of how notifications appear and behave may differ according to the operating system and the user's settings. omniboxEnables extensions to implement customized behavior when the user types into the browser's address bar. pageActionThe API to control address bar button. permissionsEnables extensions to request extra permissions at runtime, after they have been installed. pkcs11The `pkcs11` API enables an extension to enumerate PKCS #11 security modules and to make them accessible to the browser as sources of keys and certificates. privacyAccess and modify various privacy-related browser settings. proxyUse the proxy API to proxy web requests. You can use the `proxy.onRequest` event listener to intercept web requests, and return an object that describes whether and how to proxy them. runtimeThis module provides information about your extension and the environment it's running in. scriptingInserts JavaScript and CSS into websites. This API offers two approaches to inserting content: searchUse the search API to retrieve the installed search engines and execute searches. sessionsUse the sessions API to list, and restore, tabs and windows that have been closed while the browser has been running. sidebarActionGets and sets properties of an extension's sidebar. storageEnables extensions to store and retrieve data, and listen for changes to stored items. tabsInteract with the browser's tab system. themeEnables browser extensions to get details of the browser's theme and update the theme. topSitesUse the topSites API to get an array containing pages that the user has visited frequently. typesDefines the `BrowserSetting` type, which is used to represent a browser setting. userScriptsUse this API to register user scripts, third-party scripts designed to manipulate webpages or provide new features. Registering a user script instructs the browser to attach the script to pages that match the URL patterns specified during registration. webNavigationAdd event listeners for the various stages of a navigation. A navigation consists of a frame in the browser transitioning from one URL to another, usually (but not always) in response to a user action like clicking a link or entering a URL in the location bar. webRequestAdd event listeners for the various stages of making an HTTP request, which includes websocket requests on `ws://` and `wss://`. The event listener receives detailed information about the request and can modify or cancel the request. windowsInteract with browser windows. You can use this API to get information about open windows and to open, modify, and close windows. You can also listen for window open, close, and activate events.
Build a cross-browser extension - Mozilla
Build a cross-browser extension =============================== The introduction of the browser extensions API created a uniform landscape for the development of browser extensions. However, there are differences in the API implementations and the scope of coverage among the browsers that use the extensions API (the major ones being Chrome, Edge, Firefox, Opera, and Safari). Maximizing the reach of your browser extension means developing it for at least two browsers, possibly more. This article looks at the main challenges faced when creating a cross-browser extension and suggests how to address these challenges. **Note:** The main browsers have adopted Manifest V3. This manifest version provides better compatibility between the browser extension environments, such as promises for handling asynchronous events. In addition to the information in this guide, refer to the Manifest V3 migration guides for Firefox and Chrome. Cross-platform extension coding hurdles --------------------------------------- You need to address the following areas when tackling a cross-platform extension: * API namespace * API asynchronous event handling * API function coverage * Content script execution contexts * Background page versus extension service worker (in Manifest V3) * Manifest keys * Extension packaging * Extension publishing ### API namespace There are two API namespaces in use among the main browsers: * `browser.*`, the proposed standard for the extensions API used by Firefox and Safari. * `chrome.*` used by Chrome, Opera, and Edge. Firefox also supports the `chrome.*` namespace for APIs that are compatible with Chrome, primarily to assist with porting. However, using the `browser.*` namespace is preferred. In addition to being the proposed standard, `browser.*` uses promises—a modern and convenient mechanism for handling asynchronous events. Only in the most trivial extensions is namespace likely to be the only cross-platform issue to be addressed. Therefore, it's rarely, if ever, helpful to address this issue alone. The best approach is to address this with asynchronous event handling. ### API asynchronous event handling With the introduction of Manifest V3, all the main browsers adopted the standard of returning *Promises* from asynchronous methods. Firefox and Safari have full support for Promises on all asynchronous APIs. Starting from Chrome 121, all asynchronous extension APIs support promises unless documented otherwise. The `devtools` API is the only API namespace without Promise support (Chromium bug 1510416). In Manifest V2, Firefox and Safari support Promises for asynchronous methods. At the same time, Chrome methods invoke *callbacks*. For compatibility, all the main browsers support callbacks across all manifest versions. See Callbacks and Promises for details. Some handlers of extension API events are expected to respond asynchronously through a `Promise` or callback function. For example, a handler of the `runtime.onMessage` event can send an asynchronous response using a `Promise` or using a callback. A `Promise` as the return value from an event handler is supported in Firefox and Safari, but not yet in Chrome. Firefox also supports callbacks for the APIs that support the `chrome.*` namespace. However, using promises is recommended. Promises greatly simplifies asynchronous event handling, particularly where you need to chain events together. This means using a polyfill or similar so your extension uses the `browser.*` namespace in Firefox and Safari and `chrome.*` in Chrome, Opera, and Edge. **Note:** If you're unfamiliar with the differences between these two methods, look at Getting to know asynchronous JavaScript: Callbacks, Promises and Async/Await or the MDN Using promises page. #### The WebExtension browser API Polyfill So, how do you take advantage of promises easily? The solution is to code for Firefox using promises and use the WebExtension browser API Polyfill to address Chrome, Opera, and Edge. This polyfill addresses the API namespace and asynchronous event handling across Firefox, Chrome, Opera, and Edge. To use the polyfill, install it into your development environment using npm or download it directly from GitHub releases. Then, reference `browser-polyfill.js` in: * `manifest.json` to make it available to background and content scripts. * HTML documents, such as `browserAction` popups or tab pages. * The `executeScript` call in dynamically-injected content scripts loaded by `tabs.executeScript`, where it hasn't been loaded using a `content_scripts` declaration in `manifest.json`. So, for example, this `manifest.json` code makes the polyfill available to background scripts: ```json { // … "background": { "scripts": ["browser-polyfill.js", "background.js"] } } ``` Your goal is to ensure that the polyfill executes in your extension before any other scripts that expect the `browser.*` API namespace execute. **Note:** For more details and information on using the polyfill with a module bundler, see the project's readme on GitHub. There are other polyfill options. However, at the time of writing, none of the other options provide the coverage of the WebExtension browser API Polyfill. So, where you haven't targeted Firefox as your first choice, your options are to accept the limitations of alternative polyfills, port to Firefox and add cross-browser support, or develop your own polyfill. ### API function coverage The differences in the API functions offered in each of the main browsers fall into three broad categories: 1. **Lack of support for an entire function.** For example, at the time of writing, Edge didn't support the `browserSettings` function. 2. **Variations in the support for features within a function.** For example, at the time of writing, Firefox doesn't support the notification function method `notifications.onButtonClicked`, while Firefox is the only browser that supports `notifications.onShown`. 3. **Proprietary functions, supporting browser-specific features.** For example, at the time of writing, containers was a Firefox-specific feature supported by the `contextualIdentities` function. Details about the support for the extension APIs among the main browsers and Firefox for Android and Safari on iOS can be found on the Mozilla Developer Network Browser support for JavaScript APIs page. Browser compatibility information is also included with each function and its methods, types, and events in the Mozilla Developer Network JavaScript APIs reference pages. #### Handling API differences A simple approach to addressing API differences is to limit the functions used in your extension to functions that offer the same functionality across your range of targeted browsers. In practice, this approach is likely to be too restrictive for most extensions. Instead, where there are differences among the APIs, you should either offer alternative implementations or fallback functionality. (Remember: you may also need to do this to allow for differences in API support between versions of the *same* browser.) Using runtime checks on the availability of a function's features is the recommended approach to implementing alternative or fallback functionality. The benefit of performing a runtime check is that you don't need to update and redistribute the extension to take advantage of a function when it becomes available. The following code enables you to perform a runtime check: ```js if (typeof fn === "function") { // safe to use the function } ``` ### Content script execution contexts Content scripts can access and modify the page's DOM, just as page scripts can. They can also see any changes made to the DOM by page scripts. However, content scripts get a "clean" view of the DOM. Firefox and Chrome use fundamentally different approaches to handle this behavior: in Firefox it's called Xray vision, while Chrome uses isolated worlds. For more details, see Content script environment section of the Content scripts concept article. However, Firefox provides some APIs that enable content scripts to access JavaScript objects created by page scripts and to expose their JavaScript objects to page scripts. See Sharing objects with page scripts for details. There are also differences between the Content Security Policy (CSP) for content scripts. ### Background page and extension service worker As part of its implementation of Manifest V3, Chrome replaced background pages with extension service workers. Firefox retains the use of background pages, while Safari supports background pages and service workers. For more information, see the browser support section on the `"background"` manifest key page. This includes a simple example of how to implement a cross-browser script. ### Manifest keys The differences in the `manifest.json` file keys supported by the main browsers fall broadly into three categories: 1. **Extension information attributes.** For example, at the time of writing, Firefox and Opera include the `developer` key for details about the developer of the extension. 2. **Extension features.** For example, at the time of writing, Chrome did not support the `browser_specific_settings` key. 3. **Key optionality.** At the time of writing, generally, only `"manifest_version"`, `"version"`, and `"name"` are mandatory keys. Browser compatibility information is included with each key in the Mozilla Developer Network `manifest.json` key reference pages. As `manifest.json` files tend to change little—except for release numbers, which may differ between the various browsers—creating and editing a static version for each browser is usually the simplest approach. ### Extension packaging Packaging an extension for distribution through the browser extension stores is relatively straightforward. Firefox, Chrome, Edge, and Opera all use a simple zip format that requires the `manifest.json` file to be at the root of the zip package. Safari requires extensions to be packaged in a similar way to apps. For details on packaging, refer to the guidance on the respective extension's developer portals. ### Extension publishing Each of the major browsers maintains browser extension stores. Each store also reviews your extension to check for security vulnerabilities. As a consequence, you need to approach adding and updating your extension for each store separately. In some cases, you can upload your extension using a utility. This table summarizes the approach and features of each store: | Browser | Registration fee | Upload utility | Pre-publication review process | Account two-factor authentication | | --- | --- | --- | --- | --- | | Chrome | Yes | Yes | Automatic, less than an hour | Yes | | Edge | No | No | No SLA provided | Yes | | Firefox | No | web-ext | Automatic, a few seconds. A manual review of the extension takes place after publication, which may result in the extension being suspended where issues that need fixing are found. | Yes | | Opera | No | No | Manual, no SLA provided | No | | Safari | Yes | No | Yes with, according to Apple, on average, 50% of apps reviewed in 24 hours and over 90% reviewed in 48 hours. | Yes | ### Other considerations #### Version numbering The Firefox, Chrome, and Edge stores require that each uploaded version has a different version number. This means you cannot revert to an earlier version number if you come across issues in a release. Conclusion ---------- When approaching a cross-platform extension development, the differences between extension API implementations can be addressed by targeting Firefox and using the WebExtension browser API Polyfill. The bulk of your cross-platform work is likely to focus on handling variations among the API features supported by the main browsers. You may also need to account for differences between the content script and background script implementations. Creating your `manifest.json` files should be relatively straightforward and something you can do manually. You then need to account for the variations in the processes for submitting to each extension store. Following the advice in this article, you should be able to create an extension that works well on all of the four main browsers, enabling you to deliver your extension features to more people.
Background scripts - Mozilla
Background scripts ================== Background scripts or a background page enable you to monitor and react to events in the browser, such as navigating to a new page, removing a bookmark, or closing a tab. Background scripts or a page are: * Persistent – loaded when the extension starts and unloaded when the extension is disabled or uninstalled. * Non-persistent (which are also known as event pages) – loaded only when needed to respond to an event and unloaded when they become idle. However, a background page does not unload until all visible views and message ports are closed. Opening a view does not cause the background page to load but does prevent it from closing. **Note:** In Firefox, if the extension process crashes: * persistent background scripts running at the time of the crash are reloaded automatically. * non-persistent background scripts (also known as "Event Pages") running at the time of the crash are not reloaded. However, they are restarted automatically when Firefox calls one of their WebExtensions API events listeners. * extension pages loaded in tabs at the time of the crash are not automatically restored. A warning message in each tab informs the user the page has crashed and enables the user to close or restore the tab. ![Browser window displaying the user message indicating that a page has crashed with the options to close or restart the tab](/en-US/docs/Mozilla/Add-ons/WebExtensions/Background_scripts/your-tab-crashed-screenshot.png) You can test this condition by opening a new tab and navigating to `about:crashextensions`, which silently triggers a crash of the extension process. In Manifest V2, background scripts or a page can be persistent or non-persistent. Non-persistent background scripts are recommended as they reduce the resource cost of your extension. In Manifest V3, only non-persistent background scripts or a page are supported. If you have persistent background scripts or a page in Manifest V2 and want to prepare your extension for migration to Manifest V3, Convert to non-persistent provides advice on transitioning the scripts or page to the non-persistent model. Background script environment ----------------------------- ### DOM APIs Background scripts run in the context of a special page called a background page. This gives them a `window` global, along with all the standard DOM APIs provided by that object. **Warning:** In Firefox, background pages do not support the use of `alert()`, `confirm()`, or `prompt()`. ### WebExtension APIs Background scripts can use any WebExtension APIs, as long as their extension has the necessary permissions. ### Cross-origin access Background scripts can make XHR requests to hosts they have host permissions for. ### Web content Background scripts do not get direct access to web pages. However, they can load content scripts into web pages and communicate with these content scripts using a message-passing API. ### Content security policy Background scripts are restricted from certain potentially dangerous operations, such as the use of `eval()`, through a Content Security Policy. See Content Security Policy for more details. Implementing background scripts ------------------------------- This section describes how to implement a non-persistent background script. ### Specify the background scripts In your extension, you include a background script or scripts, if you need them, using the `"background"` key in `manifest.json`. For Manifest V2 extensions, the `persistent` property must be `false` to create a non-persistent script. It can be omitted for Manifest V3 extensions or must be set to `false`, as script are always non-persistent in Manifest V3. Including `"type": "module"` loads the background scripts as ES modules. ```json "background": { "scripts": ["background-script.js"], "persistent": false, "type": "module" } ``` These scripts execute in the extension's background page, so they run in the same context, like scripts loaded into a web page. However, if you need certain content in the background page, you can specify one. You then specify your script from the page rather than using the `"scripts"` property. Before the introduction of the `"type"` property to the `"background"` key, this was the only option to include ES modules. You specify a background page like this: * manifest.json ```json "background": { "page": "background-page.html", "persistent": false } ``` * background-page.html ```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <script type="module" src="background-script.js"></script> </head> </html> ``` You cannot specify background scripts and a background page. ### Initialize the extension Listen to `runtime.onInstalled` to initialize an extension on installation. Use this event to set a state or for one-time initialization. For extensions with event pages, this is where stateful APIs, such as a context menu created using `menus.create`, should be used. This is because stateful APIs don't need to be run each time the event page reloads; they only need to run when the extension is installed. ```js browser.runtime.onInstalled.addListener(() => { browser.contextMenus.create({ id: "sampleContextMenu", title: "Sample Context Menu", contexts: ["selection"], }); }); ``` ### Add listeners Structure background scripts around events the extension depends on. Defining relevant events enables background scripts to lie dormant until those events are fired and prevents the extension from missing essential triggers. Listeners must be registered synchronously from the start of the page. ```js browser.runtime.onInstalled.addListener(() => { browser.contextMenus.create({ id: "sampleContextMenu", title: "Sample Context Menu", contexts: ["selection"], }); }); // This will run when a bookmark is created. browser.bookmarks.onCreated.addListener(() => { // do something }); ``` Do not register listeners asynchronously, as they will not be properly triggered. So, rather than: ```js window.onload = () => { // WARNING! This event is not persisted, and will not restart the event page. browser.bookmarks.onCreated.addListener(() => { // do something }); }; ``` Do this: ```js browser.tabs.onUpdated.addListener(() => { // This event is run in the top level scope of the event page, and will persist, allowing // it to restart the event page if necessary. }); ``` Extensions can remove listeners from their background scripts by calling `removeListener`, such as with `runtime.onMessage` `removeListener`. If all listeners for an event are removed, the browser no longer loads the extension's background script for that event. ```js browser.runtime.onMessage.addListener( function messageListener(message, sender, sendResponse) { browser.runtime.onMessage.removeListener(messageListener); }, ); ``` ### Filter events Use APIs that support event filters to restrict listeners to the cases the extension cares about. If an extension is listening for `tabs.onUpdated`, use the `webNavigation.onCompleted` event with filters instead, as the tabs API does not support filters. ```js browser.webNavigation.onCompleted.addListener( () => { console.log("This is my favorite website!"); }, { url: [{ urlMatches: "https://www.mozilla.org/" }] }, ); ``` ### React to listeners Listeners exist to trigger functionality once an event has fired. To react to an event, structure the desired reaction inside the listener event. When responding to events in the context of a specific tab or frame, use the `tabId` and `frameId` from the event details instead of relying on the "current tab". Specifying the target ensures your extension does not invoke an extension API on the wrong target when the "current tab" changes while waking the event page. For example, `runtime.onMessage` can respond to `runtime.sendMessage` calls as follows: ```js browser.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.data === "setAlarm") { browser.alarms.create({ delayInMinutes: 5 }); } else if (message.data === "runLogic") { browser.scripting.executeScript({ target: { tabId: sender.tab.id, frameIds: [sender.frameId], }, files: ["logic.js"], }); } else if (message.data === "changeColor") { browser.scripting.executeScript({ target: { tabId: sender.tab.id, frameIds: [sender.frameId], }, func: () => { document.body.style.backgroundColor = "orange"; }, }); } }); ``` ### Unload background scripts Data should be persisted periodically to not lose important information if an extension crashes without receiving `runtime.onSuspend`. Use the storage API to assist with this. ```js // Or storage.session if the variable does not need to persist pass browser shutdown. browser.storage.local.set({ variable: variableInformation }); ``` Message ports cannot prevent an event page from shutting down. If an extension uses message passing, the ports are closed when the event page idles. Listening to the `runtime.Port` `onDisconnect` lets you discover when open ports are closing, however the listener is under the same time constraints as `runtime.onSuspend`. ```js browser.runtime.onConnect.addListener((port) => { port.onMessage.addListener((message) => { if (message === "hello") { let response = { greeting: "welcome!" }; port.postMessage(response); } else if (message === "goodbye") { console.log("Disconnecting port from this end"); port.disconnect(); } }); port.onDisconnect.addListener(() => { console.log("Port was disconnected from the other end"); }); }); ``` Background scripts unload after a few seconds of inactivity. However, if during the suspension of a background script another event wakes the background script, `runtime.onSuspendCanceled` is called and the background script continues running. If any cleanup is required, listen to `runtime.onSuspend`. ```js browser.runtime.onSuspend.addListener(() => { console.log("Unloading."); browser.browserAction.setBadgeText({ text: "" }); }); ``` However, persisting data should be preferred rather than relying on `runtime.onSuspend`. It doesn't allow for as much cleanup as may be needed and does not help in case of a crash. Convert to non-persistent ------------------------- If you've a persistent background script, this section provides instructions on converting it to the non-persistent model. ### Update your manifest.json file In your extension's `manifest.json` file, change the persistent property of `"background"` key to `false` for your script or page. ```json "background": { …, "persistent": false } ``` ### Move event listeners Listeners must be at the top-level to activate the background script if an event is triggered. Registered listeners may need to be restructured to the synchronous pattern and moved to the top-level. ```js browser.runtime.onStartup.addListener(() => { // run startup function }); ``` ### Record state changes Scripts now open and close as needed. So, do not rely on global variables. ```js var count = 101; browser.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message === "count") { ++count; sendResponse(count); } }); ``` Instead, use the storage API to set and return states and values: * Use `storage.session` for in-memory storage that is cleared when the extension or browser shuts down. By default, `storage.session` is only available to extension contexts and not to content scripts. * Use `storage.local` for a larger storage area that persists across browser and extension restarts. ```js browser.runtime.onMessage.addListener(async (message, sender) => { if (message === "count") { let items = await browser.storage.session.get({ myStoredCount: 101 }); let count = items.myStoredCount; ++count; await browser.storage.session.set({ myStoredCount: count }); return count; } }); ``` The preceding example sends an asynchronous response using a promise, which is not supported in Chrome until Chrome bug 1185241 is resolved. A cross-browser alternative is to return true and use `sendResponse`. ```js browser.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message === "count") { browser.storage.session.get({ myStoredCount: 101 }).then(async (items) => { let count = items.myStoredCount; ++count; await browser.storage.session.set({ myStoredCount: count }); sendResponse(count); }); return true; } }); ``` ### Change timers into alarms DOM-based timers, such as `setTimeout()`, do not remain active after an event page has idled. Instead, use the `alarms` API if you need a timer to wake an event page. ```js browser.alarms.create({ delayInMinutes: 3.0 }); ``` Then add a listener. ```js browser.alarms.onAlarm.addListener(() => { alert("Hello, world!"); }); ``` ### Update calls for background script functions Extensions commonly host their primary functionality in the background script. Some extensions access functions and variables defined in the background page through the `window` returned by `extension.getBackgroundPage`. The method returns `null` when: * extension pages are isolated, such as extension pages in Private Browsing mode or container tabs. * the background page is not running. This is uncommon with persistent background pages but very likely when using an Event Page, as an Event Page can be suspended. **Note:** The recommended way to invoke functionality in the background script is to communicate with it through `runtime.sendMessage()` or `runtime.connect()`. The `getBackgroundPage()` methods discussed in this section cannot be used in a cross-browser extension, because Manifest Version 3 extensions in Chrome cannot use background or event pages. If your extension requires a reference to the `window` of the background page, use `runtime.getBackgroundPage` to ensure the event page is running. If the call is optional (that is, only needed if the event page is alive) then use `extension.getBackgroundPage`. ```js document.getElementById("target").addEventListener("click", async () => { let backgroundPage = browser.extension.getBackgroundPage(); // Warning: backgroundPage is likely null. backgroundPage.backgroundFunction(); }); ``` ```js document.getElementById("target").addEventListener("click", async () => { // runtime.getBackgroundPage() wakes up the event page if it was not running. let backgroundPage = await browser.runtime.getBackgroundPage(); backgroundPage.backgroundFunction(); }); ```
protocol_handlers - Mozilla
protocol\_handlers ================== | | | | --- | --- | | Type | `Array` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "protocol\_handlers": [ { "protocol": "ircs", "name": "IRC Mozilla Extension", "uriTemplate": "https://irccloud.mozilla.com/#!/%s" } ] ``` | 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. Your extension can check whether it can access private browsing windows using `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()` 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 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. 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. ```json "protocol\_handlers": [ { "protocol": "magnet", "name": "Magnet Extension", "uriTemplate": "/example.xhtml#!/%s" } ] ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
options_page - Mozilla
options\_page ============= | | | | --- | --- | | Type | `String` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "options\_page": "options/options.html" ``` | **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. **Warning:** This manifest key has been deprecated. Use `options_ui` instead. Use the `options_page` key to define an options page 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 `runtime.openOptionsPage()`. Unlike options pages specified using the newer `options_ui` key, options pages specified using the deprecated `options_page` key don't receive browser styles and always open in a normal browser tab. Example ------- ```json "options\_page": "options/options.html" ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * `options_ui` * Options pages
content_security_policy - Mozilla
content\_security\_policy ========================= | | | | --- | --- | | Type | `String` | | Mandatory | No | | Manifest version | 2 or higher | | Example | Manifest V2: ```json "content\_security\_policy": "default-src 'self'" ``` Manifest V3: ```json "content\_security\_policy": { "extension\_pages": "default-src 'self'" } ``` | 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> resources) and disallows potentially unsafe practices such as the use of `eval()`. See 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 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. * Allow the extension to take advantage of WebAssembly by including the `'wasm-unsafe-eval'` source in the `script-src` directive. * Loosen the default `script-src` policies (Manifest V2 only): + Allow the extension to load scripts from outside its package by supplying their URL in the `script-src` directive. + Allow the extension to execute inline scripts by supplying the hash of the script in the `script-src` directive. + Allow the extension to use `eval()` and similar features by including `'unsafe-eval'` in the `script-src` directive. There are restrictions on the policy you can specify with this manifest key: * The `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 `default-src` alone (without `script-src`) if its sources meet the requirement for the `script-src` directive. * The `object-src` keyword may be required, see object-src directive for details. * Directives that reference code – `script-src`, `script-src-elem`, `worker-src`, and `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 `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 (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 are: `'none'`, `'self'`, `'unsafe-eval'`, and `'wasm-unsafe-eval'`. object-src directive -------------------- The ``object-src`` directive may be required in some browsers that support obsolete plugins 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, 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: | Name | Type | Description | | --- | --- | --- | | `extension_pages` | `String` | The content security policy used for extension pages. The `script-src` and `worker-src` directives may only have these values: * `'self'` * `'none'` * `'wasm-unsafe-eval'` | | `sandbox` | `String` | The content security policy used for sandboxed extension pages. | 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 and due to significant security issues. **Note:** Some examples include the ``object-src`` directive, which provides backward compatibility for older browser versions. See 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: * 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: * 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. Extensions using WebAssembly are therefore encouraged to declare `'wasm-unsafe-eval'` in their CSP. See 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 "content\_security\_policy": "script-src 'self' https://\*.jquery.com;" ``` However, this is only invalid in browsers that support obsolete plugins. See object-src directive for more details.. Policy that omits the `"self"` keyword in the `"script-src"` directive: ```json "content\_security\_policy": "script-src https://\*.jquery.com; object-src 'self'" ``` Scheme for a remote source is not `https`: ```json "content\_security\_policy": "script-src 'self' http://code.jquery.com; object-src 'self'" ``` Wildcard is used with a generic domain: ```json "content\_security\_policy": "script-src 'self' https://\*.blogspot.com; object-src 'self'" ``` Source specifies a scheme but no host: ```json "content\_security\_policy": "script-src 'self' https:; object-src 'self'" ``` Directive includes the unsupported keyword `'unsafe-inline'`: ```json "content\_security\_policy": "script-src 'self' 'unsafe-inline'; object-src 'self'" ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
author - Mozilla
author ====== | | | | --- | --- | | Type | `String` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "author": "Walt Whitman" ``` | The extension's author, intended for display in the browser's user interface. If the 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. Example ------- ```json "author": "Walt Whitman" ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
chrome_url_overrides - Mozilla
chrome\_url\_overrides ====================== | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "chrome\_url\_overrides" : { "newtab": "my-new-tab.html" } ``` | 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: | Name | Type | Description | | --- | --- | --- | | `bookmarks` | `String` | Provide a replacement for the page that shows the bookmarks. | | `history` | `String` | Provide a replacement for the page that shows the browsing history. | | `newtab` | `String` | 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 `Ctrl`/`Command`+`T` keyboard shortcut. 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". The document can load CSS and JavaScript, just like a normal web page. JavaScript running in the page gets access to the same privileged "browser.\*" APIs as the extension's background script. It's very good practice to include a <title> for the page, or the tab's title will be the "moz-extension://..." URL. 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. 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. To override the browser's homepage, use "chrome\_settings\_overrides" instead. | All properties are localizable. Example ------- ```json "chrome\_url\_overrides" : { "newtab": "my-new-tab.html" } ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
theme_experiment - Mozilla
theme\_experiment ================= | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "theme\_experiment": { "stylesheet": "style.css", "colors": { "popup\_affordance": "--arrowpanel-dimmed" }, "images": { "theme\_toolbar": "--toolbar-bgimage" }, "properties": { "toolbar\_image\_alignment": "--toolbar-bgalignment" } } ``` | This key enables the definition of experimental `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. **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: | Name | Type | Description | | --- | --- | --- | | `stylesheet` | `String` | Optional Name of a stylesheet providing mapping of Firefox UI element CSS selectors to CSS variables. | | `images` | `Object` | Optional Mappings of CSS variables (as defined in Firefox or by the stylesheet defined in `stylesheet`) to `images` property names for use in the `theme` key. | | `colors` | `Object` | Optional Mappings of CSS variables (as defined in Firefox or by the stylesheet defined in `stylesheet`) to `colors` property names for use in the `theme` key. | | `properties` | `Object` | Optional Mappings of CSS variables (as defined in Firefox or by the stylesheet defined in `stylesheet`) to `properties` property names for use in the `theme` key. | 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` 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.](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme_experiment/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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
sidebar_action - Mozilla
sidebar\_action =============== | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```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 } ``` | | | | A sidebar 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 `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`. | Name | Type | Description | | --- | --- | --- | | `browser\_style`Optional Deprecated in Manifest V3. | `Boolean` | Optional, defaulting to:* `true` in Manifest V2 and prior to Firefox 115 in Manifest V3. * `false` in Manifest V3 from Firefox 115. Do not set `browser_style` to true: its not support in Manifest V3 from Firefox 118. See Manifest V3 migration for `browser_style`. 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 `box-sizing: border-box` (see box-sizing). | | `default_icon`Optional | `Object` or `String` | 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. Icons are specified as URLs relative to the manifest.json file itself. You can specify a single icon file by supplying a string here: ```json "default\_icon": "path/to/geo.svg" ``` 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: ```json "default\_icon": { "16": "path/to/geo-16.png", "32": "path/to/geo-32.png" } ``` See Choosing icon sizes for more guidance on this. This property is optional: if it is omitted, the sidebar doesn't get an icon. | | `default_panel` | `String` | The path to an HTML file that specifies the sidebar's contents. The HTML file may include CSS and JavaScript files using `<link>` and `<script>` elements, just like a normal web page. Unlike a normal web page, JavaScript running in the panel can access all the WebExtension APIs (subject, of course, to the extension having the appropriate permissions). This property is mandatory. This is a localizable property. | | `default_title`Optional | `String` | 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. This property is optional: if it is omitted, the sidebar's title is the extension's `name`. This is a localizable property. | | `open_at_install`Optional | Boolean | Optional, defaulting to `true`. Determines whether the sidebar should open on install. The default behavior is to open the sidebar when installation is completed. | 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. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * `browser_action` * `page_action` * Browser styles
page_action - Mozilla
page\_action ============ | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```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 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 when the user clicks the icon. You can also create and manipulate page actions programmatically using the `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 `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: | Name | Type | Description | | --- | --- | --- | | `browser\_style`Optional Deprecated in Manifest V3. | `Boolean` | Optional. Defaults to `false`. Do not set `browser_style` to true: its not support in Manifest V3 from Firefox 118. See Manifest V3 migration for `browser_style`. In Firefox, the stylesheet can be seen at `chrome://browser/content/extension.css` or `chrome://browser/content/extension-mac.css` on macOS. The latest-download example extension uses `browser_style` in its popup. | | `default_icon` | `Object` or `String` | Use this to specify an icon for the action. 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 `"19"` and `"38"`, like this: ```json "default\_icon": { "19": "geo-19.png", "38": "geo-38.png" } ``` If you do this, then the browser will pick the right size icon for the screen's pixel density. You can just supply a string here: ```json "default\_icon": "geo.png" ``` If you do this, then the icon will be scaled to fit the toolbar, and may appear blurry. | | `default_popup` | `String` | The path to an HTML file containing the specification of the popup. The HTML file may include CSS and JavaScript files using `<link>` and `<script>` elements, just like a normal web page. However, don't use `<script>` with embedded code, because you'll get a Content Violation Policy error. Instead, `<script>` must use the `src` attribute to load a separate script file. Unlike a normal web page, JavaScript running in the popup can access all the WebExtension APIs (subject, of course, to the extension having the appropriate permissions). This is a localizable property. | | `default_title` | `String` | Tooltip for the icon, displayed when the user moves their mouse over it. This is a localizable property. | | `hide_matches` | `Array` of `Match Pattern` except `<all_urls>` | Hide the page action by default for pages whose URLs match any of the given match patterns. Note that page actions are always hidden by default unless `show_matches` is given. Therefore, it only makes sense to include this property if `show_matches` is also given, and will override the patterns in `show_matches`. For example, consider a value like: ```json "page\_action": { "show\_matches": ["https://\*.mozilla.org/\*"], "hide\_matches": ["https://developer.mozilla.org/\*"] } ``` This shows the page action by default for all HTTPS URLs under the `"mozilla.org"` domain, except for pages under `"developer.mozilla.org"`. | | `show_matches` | `Array` of `Match Pattern` | Show the page action by default for pages whose URLs match any of the given patterns. See also `hide_matches`. | | `pinned` Deprecated | `Boolean` | Optional. Defaults to `true`. 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. | 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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * `browser_action` * `sidebar_action` * Browser styles
devtools_page - Mozilla
devtools\_page ============== | | | | --- | --- | | Type | `String` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "devtools\_page": "devtools/my-page.html" ``` | Use this key to enable your extension to extend the browser's built-in devtools. This key is defined as a URL to an HTML file. The HTML file must be bundled with the extension, and the URL is relative to the extension's root. The use of this manifest key triggers an install-time permission warning about devtools. To avoid an install-time permission warning, mark the feature as optional by listing the `"devtools"` permission in the `optional_permissions` manifest key. See Extending the developer tools to learn more. Example ------- ```json "devtools\_page": "devtools/my-page.html" ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
chrome_settings_overrides - Mozilla
chrome\_settings\_overrides =========================== | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "chrome\_settings\_overrides" : { "homepage": "https://developer.mozilla.org/" }, ``` | Use the `chrome_settings_overrides` key to override the browser's home page and add a new search engine. Syntax ------ The `chrome_settings_overrides` key is an object that may have the following properties: | Name | Type | Description | | --- | --- | --- | | `homepage` | `String` | Defines the page to be used as the browser's homepage. The replacement is given as a URL. The URL may:* point to a file bundled with the extension, in which case it is given as a URL relative to the manifest.json file * be a remote URL, such as "https://developer.mozilla.org/". If two or more extensions both set this value, then the setting from the most recently installed one will take precedence. To override new tabs, use "chrome\_url\_overrides" instead. This is a localizable property. | | `search_provider` | `Object` | Defines a search provider to add to the browser. The search provider has a name and a primary search URL. Alternative URLs may be provided, including URLs for more specialized searches like image search. In the URL you supply, use "`{searchTerms}`" to interpolate the search term into the URL, like: `https://www.discogs.com/search/?q={searchTerms}`. You can also provide POST parameters to be sent along with the search. The search provider will be presented to the user alongside the built-in providers. If you include the `is_default` property and set it to `true`, the new search provider will be the default option. By supplying the `keyword` property, you enable the user to select your search provider by typing the keyword into the search/address bar before the search term. This is an object with the properties listed below. All string properties are localizable. `name` String: The search engine's name, displayed to the user. `search_url` String: URL used by the search engine. This must be an HTTPS URL. `is_default Optional` Boolean: True if the search engine should be the default choice. On Firefox, this is opt-in and the user will only be asked the first time the extension is installed. They will not be asked again if a search engine is added later. `alternate_urls Optional` Array of String: An array of alternative URLs that can be used instead of `search_url`. `encoding Optional` String: Encoding of the search term, specified as a standard character encoding name, such as "UTF-8". `favicon_url Optional` String: URL pointing to an icon for the search engine. In Manifest V2, this must be an absolute HTTP or HTTPS URL. In Manifest V3, this must reference an icon provided in the extension as a path relative to the extension's root. `image_url Optional` String: URL used for image search. `image_url_post_params Optional` String: POST parameters to send to `image_url`. `instant_url Optional` String: URL used for instant search. `instant_url_post_params Optional` String: POST parameters to send to `instant_url`. `keyword Optional` String: Address bar keyword for the search engine. `prepopulated_id Optional` The ID of a built-in search engine to use. `search_url_post_params Optional` String: POST parameters to send to `search_url`. `suggest_url Optional` String: URL used for search suggestions. This must be an HTTPS URL. `suggest_url_post_params Optional` String: POST parameters to send to `suggest_url`. | Example ------- This example shows how to set a search provider. ```json "chrome\_settings\_overrides": { "search\_provider": { "name": "Discogs", "search\_url": "https://www.discogs.com/search/?q={searchTerms}", "keyword": "disc", "favicon\_url": "https://www.discogs.com/favicon.ico" } } ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
permissions - Mozilla
permissions =========== | | | | --- | --- | | Type | `Array` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "permissions": [ "webRequest" ] ``` | 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. For information on how to test and preview permission requests, see 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` 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` manifest key. Host permissions are specified as 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 and fetch 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 `tabs.Tab` objects * the ability to inject content scripts and styles programmatically into pages served from those origins. * the ability to receive events from the `webrequest` API for these hosts * the ability to access cookies for that host using the `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 `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 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` 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 `privileged parts of the `tabs` API` without the need for 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 `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 can also be used instead of the "tabs" permission. * `webRequestBlocking` enables you to use the `"blocking"` argument, so you can `modify and cancel requests`. * `downloads.open` lets you use the `downloads.open()` API. * `tabHide` lets you use the `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 browser action or page action * 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). * 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 frames may require additional host permissions. Of course, 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 `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). Clipboard access ---------------- There are two permissions which enables the extension to interact with the clipboard: `clipboardWrite` Write to the clipboard using `Clipboard.write()`, `Clipboard.writeText()`, `document.execCommand("copy")` or `document.execCommand("cut")` `clipboardRead` Read from the clipboard using `Clipboard.read()`, `Clipboard.readText()` or `document.execCommand("paste")` See Interact with the clipboard for more details. Unlimited storage ----------------- The `unlimitedStorage` permission: * Enables extensions to exceed any quota imposed by the `storage.local` API * In Firefox, enables extensions to create a "persistent" IndexedDB database 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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
storage - Mozilla
storage ======= | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "storage": { "managed\_schema": "schema.json" } ``` | 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 `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 `storage.managed` for more details. The `storage` key is an object that has the following required property: | | | | --- | --- | | `managed_schema` | A `String` specifying the full path of the file within the extension that defines the schema of the manage storage. | Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. **Note:** This page includes details from the Chrome developer website page Manifest for storage areas included here under the Creative Commons Attribution 3.0 United States License.
theme - Mozilla
theme ===== | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "theme": { "images": { "theme\_frame": "images/sun.jpg" }, "colors": { "frame": "#CF723F", "tab\_background\_text": "#000" } } ``` | 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 `theme` API. **Note:** Since May 2019, themes need to be signed to be installed (Firefox bug 1545109). See Signing and distributing your add-on for more details. **Note:** A new version of Firefox for Android, based on GeckoView, is under development. A pre-release version 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: | Name | Type | Description | | --- | --- | --- | | `images` | `Object` | Optional as of Firefox 60. Mandatory before Firefox 60. A JSON object whose properties represent the images to display in various parts of the browser. See `images` for details on the properties that this object can contain. | | `colors` | `Object` | Mandatory. A JSON object whose properties represent the colors of various parts of the browser. See `colors` for details on the properties that this object can contain. | | `properties` | `Object` | Optional This object has properties that affect how the `"additional_backgrounds"` images are displayed and color schemes are applied. See `properties` for details on the properties that this object can contain. | ### 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. | Name | Type | Description | | --- | --- | --- | | `theme_frame` | `String` | The URL of a foreground image to be added to the header area and anchored to the upper right corner of the header area. **Note:** Chrome anchors the image to the top left of the header and if the image doesn't fill the header area tile the image. Optional in desktop Firefox 60 onwards. Required in Firefox for Android. | | `additional_backgrounds` | `Array` of `String` | **Warning:** The `additional_backgrounds` 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. An array of URLs for additional background images to be added to the header area and displayed behind the `"theme_frame":` image. These images layer the first image in the array on top, the last image in the array at the bottom. Optional. 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 `"properties":`. | ### 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: | | | --- | | Overview of the color properties and how they apply to Firefox UI components | **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 (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. 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 (RGB arrays) for themes targeting Firefox 68.2 or later. Colors for Firefox for Android themes cannot be specified using color names. | Name | Description | | --- | --- | | `bookmark_text` | The color of text and icons in the bookmark and find bars. Also, if `tab_text` isn't defined it sets the color of the active tab text and if `icons` isn't defined the color of the toolbar icons. Provided as Chrome compatible alias for `toolbar_text`. **Note:** Ensure any color used contrasts well with those used in `frame` and `frame_inactive` or `toolbar` if you're using that property. Where `icons` isn't defined, also ensure good contrast with `button_background_active` and `button_background_hover`. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "tab\_text": "white", "toolbar": "black", "bookmark\_text": "red" } } ``` 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. | | `button_background_active` | The color of the background of the pressed toolbar buttons. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "button\_background\_active": "red" } } ``` 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. | | `button_background_hover` | The color of the background of the toolbar buttons on hover. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "button\_background\_hover": "red" } } ``` 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. | | `icons` | The color of toolbar icons, excluding those in the find toolbar. **Note:** Ensure the color used contrasts well with those used in `frame`, `frame_inactive`, `button_background_active`, and `button_background_hover`. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "icons": "red" } } ``` 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. | | `icons_attention` | The color of toolbar icons in attention state such as the starred bookmark icon or finished download icon. **Note:** Ensure the color used contrasts well with those used in `frame`, `frame_inactive`, `button_background_active`, and `button_background_hover`. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "icons\_attention": "red" } } ``` 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. | | `frame` | The color of the header area background, displayed in the part of the header not covered or visible through the images specified in `"theme_frame"` and `"additional_backgrounds"`. See example ```json "theme": { "colors": { "frame": "red", "tab\_background\_text": "white" } } ``` 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 | | `frame_inactive` | 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 `"theme_frame"` and `"additional_backgrounds"`. See example ```json "theme": { "colors": { "frame": "red", "frame\_inactive": "gray", "tab\_text": "white" } } ``` 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. | | `ntp_background` | The new tab page background color. See example ```json "theme": { "colors": { "ntp\_background": "red" } } ``` Firefox showing a new tab page. The background of the page is red. | | `ntp_card_background` | The new tab page card background color. See example ```json "theme": { "colors": { "ntp\_card\_background": "red" } } ``` Firefox showing a new tab page. On the page, the background to the search bar and shortcut buttons is red. | | `ntp_text` | The new tab page text color. **Note:** Ensure the color used contrasts well with that used in `ntp_background` and `ntp_card_background`. See example ```json "theme": { "colors": { "ntp\_text": "red" } } ``` Firefox showing a new tab page. On the page, the text is in red. | | `popup` | The background color of popups (such as the URL bar dropdown and the arrow panels). See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "popup": "red" } } ``` 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. | | `popup_border` | The border color of popups. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "popup": "black", "popup\_text": "white", "popup\_border": "red" } } ``` 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. | | `popup_highlight` | The background color of items highlighted using the keyboard inside popups (such as the selected URL bar dropdown item). **Note:** It's recommended to define `popup_highlight_text` to override the browser default text color on various platforms. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "popup\_highlight": "red", "popup\_highlight\_text": "white" } } ``` 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. | | `popup_highlight_text` | The text color of items highlighted inside popups. **Note:** Ensure the color used contrasts well with that used in `popup_highlight`. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "popup\_highlight": "black", "popup\_highlight\_text": "red" } } ``` 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. | | `popup_text` | The text color of popups. **Note:** Ensure the color used contrasts well with that used in `popup`. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "popup": "black", "popup\_text": "red" } } ``` 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. | | `sidebar` | The background color of the sidebar. See example ```json "theme": { "colors": { "sidebar": "red", "sidebar\_highlight": "white", "sidebar\_highlight\_text": "green", "sidebar\_text": "white" } } ``` A close-up screenshot of a browser windows's open sidebar. The background color of the sidebar is red. | | `sidebar_border` | The border and splitter color of the browser sidebar See example ```json "theme": { "colors": { "sidebar\_border": "red" } } ``` 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. | | `sidebar_highlight` | The background color of highlighted rows in built-in sidebars See example ```json "theme": { "colors": { "sidebar\_highlight": "red", "sidebar\_highlight\_text": "white" } } ``` 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. | | `sidebar_highlight_text` | The text color of highlighted rows in sidebars. **Note:** Ensure the color used contrasts well with that used in `sidebar_highlight`. See example ```json "theme": { "colors": { "sidebar\_highlight": "pink", "sidebar\_highlight\_text": "red", } } ``` 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. | | `sidebar_text` | The text color of sidebars. **Note:** Ensure the color used contrasts well with that used in `sidebar`. See example ```json "theme": { "colors": { "sidebar": "red", "sidebar\_highlight": "white", "sidebar\_highlight\_text": "green", "sidebar\_text": "white" } } ``` 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. | | `tab_background_separator` Deprecated | **Warning:** `tab_background_separator` is not supported starting with Firefox 89. The color of the vertical separator of the background tabs. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "tab\_background\_separator": "red" } } ``` A closeup of browser tabs to highlight the separator. | | `tab_background_text` | The color of the text displayed in the inactive page tabs. If `tab_text` or `bookmark_text` isn't specified, applies to the active tab text. **Note:** Ensure the color used contrasts well with those used in `tab_selected` or `frame` and `frame_inactive`. See example ```json "theme": { "colors": { "frame": "black", "toolbar": "white", "tab\_background\_text": "red" } } ``` 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. | | `tab_line` | The color of the selected tab line. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "tab\_line": "red" } } ``` 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. | | `tab_loading` | The color of the tab loading indicator and the tab loading burst. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "tab\_loading": "red" } } ``` 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. | | `tab_selected` | The background color of the selected tab. When not in use selected tab color is set by `frame` and the `frame_inactive`. See example ```json "theme": { "images": { "theme\_frame": "weta.png" }, "colors": { "frame": "black", "tab\_background\_text": "white", "tab\_selected": "red" } } ``` 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. | | `tab_text` | From Firefox 59, it represents the text color for the selected tab. If `tab_line` isn't specified, it also defines the color of the selected tab line. **Note:** Ensure the color used contrasts well with those used in `tab_selected` or `frame` and `frame_inactive`. See example ```json "theme": { "images": { "theme\_frame": "weta.png" }, "colors": { "frame": "black", "tab\_background\_text": "white", "tab\_selected": "white", "tab\_text": "red" } } ``` 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. | | `toolbar` | The background color for the navigation bar, the bookmarks bar, and the selected tab. This also sets the background color of the "Find" bar. See example ```json "theme": { "colors": { "frame": "black", "toolbar": "red", "tab\_background\_text": "white" } } ``` 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. | | `toolbar_bottom_separator` | The color of the line separating the bottom of the toolbar from the region below. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "toolbar\_bottom\_separator": "red" } } ``` 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. | | `toolbar_field` | The background color for fields in the toolbar, such as the URL bar. This also sets the background color of the **Find in page** field. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "toolbar\_field": "red" } } ``` 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. | | `toolbar_field_border` | The border color for fields in the toolbar. This also sets the border color of the **Find in page** field. See example ```json "theme": { "colors": { "frame": "black", "toolbar": "black", "tab\_background\_text": "white", "toolbar\_field": "black", "toolbar\_field\_text": "white", "toolbar\_field\_border": "red" } } ``` 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. | | `toolbar_field_border_focus` | The focused border color for fields in the toolbar. See example ```json "theme": { "colors": { "frame": "black", "toolbar": "black", "tab\_background\_text": "white", "toolbar\_field": "black", "toolbar\_field\_text": "white", "toolbar\_field\_border\_focus": "red" } } ``` 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. | | `toolbar_field_focus` | The focused background color for fields in the toolbar, such as the URL bar. See example ```json "theme": { "colors": { "frame": "black", "toolbar": "black", "tab\_background\_text": "white", "toolbar\_field": "black", "toolbar\_field\_text": "white", "toolbar\_field\_focus": "red" } } ``` 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. | | `toolbar_field_highlight` | 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). See example ```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)" } } ``` 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. Here, the `toolbar_field_highlight` field specifies that the highlight color is a light green, while the text is set to a dark-to-medium green using `toolbar_field_highlight_text`. | | `toolbar_field_highlight_text` | 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). **Note:** Ensure the color used contrasts well with those used in `toolbar_field_highlight`. See example ```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)" } } ``` 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. Here, the `toolbar_field_highlight_text` field is used to set the text color to a dark medium-dark green, while the highlight color is a light green. | | `toolbar_field_separator` Deprecated | **Warning:** `toolbar_field_separator` is not supported starting with Firefox 89. The color of separators inside the URL bar. In Firefox 58 this was implemented as `toolbar_vertical_separator`. See example ```json "theme": { "colors": { "frame": "black", "toolbar": "black", "tab\_background\_text": "white", "toolbar\_field\_separator": "red" } } ``` 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. In this screenshot, `"toolbar_vertical_separator"` is the red vertical line in the URL bar dividing the Reader Mode icon from the other icons. | | `toolbar_field_text` | The color of text in fields in the toolbar, such as the URL bar. This also sets the color of text in the **Find in page** field. **Note:** Ensure the color used contrasts well with those used in `toolbar_field`. See example ```json "theme": { "colors": { "frame": "black", "toolbar": "black", "tab\_background\_text": "white", "toolbar\_field": "black", "toolbar\_field\_text": "red" } } ``` 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. | | `toolbar_field_text_focus` | The color of text in focused fields in the toolbar, such as the URL bar. **Note:** Ensure the color used contrasts well with those used in `toolbar_field_focus`. See example ```json "theme": { "colors": { "frame": "black", "toolbar": "black", "tab\_background\_text": "white", "toolbar\_field": "black", "toolbar\_field\_text": "white", "toolbar\_field\_text\_focus": "red" } } ``` 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. | | `toolbar_text` | The color of toolbar text. This also sets the color of text in the "Find" bar. **Note:** For compatibility with Chrome, use the alias `bookmark_text`. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "toolbar": "black", "toolbar\_text": "red" } } ``` 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. | | `toolbar_top_separator` | The color of the line separating the top of the toolbar from the region above. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "toolbar": "black", "toolbar\_top\_separator": "red" } } ``` 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. | | `toolbar_vertical_separator` | The color of the separator in the bookmarks toolbar. In Firefox 58, it corresponds to the color of separators inside the URL bar. See example ```json "theme": { "colors": { "frame": "black", "tab\_background\_text": "white", "toolbar": "black", "toolbar\_vertical\_separator": "red" } } ``` 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. | #### 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. | Name | Alias for | | --- | --- | | `bookmark_text` | `toolbar_text` | ### properties | Name | Type | Description | | --- | --- | --- | | `additional_backgrounds_alignment` | `Array` of `String` | Optional An array of enumeration values defining the alignment of the corresponding `"additional_backgrounds":` array item.The alignment options include: * `"bottom"` * `"center"` * `"left"` * `"right"` * `"top"` * `"center bottom"` * `"center center"` * `"center top"` * `"left bottom"` * `"left center"` * `"left top"` * `"right bottom"` * `"right center"` * `"right top"`. If not specified, defaults to `"right top"`. | | `additional_backgrounds_tiling` | `Array` of `String` | Optional An array of enumeration values defining how the corresponding `"additional_backgrounds":` array item repeats. Options include: * `"no-repeat"` * `"repeat"` * `"repeat-x"` * `"repeat-y"` If not specified, defaults to `"no-repeat"`. | | `color_scheme` | `String` | Optional 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: * `"auto"` – a light or dark scheme based automatically on the theme. * `"light"` – a light scheme. * `"dark"` – a dark scheme. * `"system"` – uses the system scheme. If not specified, defaults to `"auto"`. | | `content_color_scheme` | `String` | Optional Determines which color scheme is applied to the content (for example, built-in pages and preferred color scheme for web pages). Overrides `color_scheme`. Options include: * `"auto"` – a light or dark scheme based automatically on the theme. * `"light"` – a light scheme. * `"dark"` – a dark scheme. * `"system"` – the system scheme. If not specified, defaults to `"auto"`. | 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.](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme/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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### 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.
icons - Mozilla
icons ===== | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | 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. **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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
browser_action - Mozilla
browser\_action =============== | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 | | Example | ```json "browser\_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 }] } ``` | A browser 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 is replaced by `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 when the user clicks the button. You can also create and manipulate browser actions programmatically using the browserAction API. Syntax ------ The `browser_action` key is an object that may have any of the following properties, all optional: | Name | Type | Description | | --- | --- | --- | | `browser\_style`Optional | `Boolean` | Optional, defaulting to `false`. Do not set `browser_style` to true: it isn't supported in Manifest V3, starting with Firefox 118. See Manifest V3 migration for `browser_style`. 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 `box-sizing: border-box` (see box-sizing). Browser styles describes the classes you can apply to elements in the popup to get particular styles. The latest-download example extension uses `browser_style` in its popup. **Note:** Setting `browser_style` to `true` prevents users from selecting text in an extension's popup or sidebar content. This is normal behavior. You can't select parts of the UI in the browser. However, you can work around this limitation to allow your users to select text in two ways: 1. Set `browser_style` to `false`. 2. Use CSS styling on the body of your sidebar or popup's HTML to allow text selection by adding the rule `-moz-user-select` with a value of `all` or `text`. | | `default_area`Optional | `String` | Defines the part of the browser in which the button is initially placed. This is a string that may take one of four values: * "navbar": the button is placed in the main browser toolbar, alongside the URL bar. * "menupanel": the button is placed in a popup panel. * "tabstrip": the button is placed in the toolbar that contains browser tabs. * "personaltoolbar": the button is placed in the bookmarks toolbar. This property is only supported in Firefox. This property is optional, and defaults to "menupanel". Firefox remembers the `default_area` setting for an extension, even if that extension is uninstalled and subsequently reinstalled. To force the browser to acknowledge a new value for `default_area`, the id of the extension must be changed. 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. | | `default_icon`Optional | `Object` or `String` | Use this to specify one or more icons for the browser action. The icon is shown in the browser toolbar by default. Icons are specified as URLs relative to the manifest.json file itself. You can specify a single icon file by supplying a string here: ```json "default\_icon": "path/to/geo.svg" ``` 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: ```json "default\_icon": { "16": "path/to/geo-16.png", "32": "path/to/geo-32.png" } ``` You cannot specify multiple icons of the same sizes.See Choosing icon sizes for more guidance on this. | | `default_popup`Optional | `String` | The path to an HTML file containing the specification of the popup. The HTML file may include CSS and JavaScript files using `<link>` and `<script>` elements, just like a normal web page. However, `<script>`must have `src` attribute to load a file. Don't use `<script>` with embedded code, because you'll get a confusing Content Violation Policy error. Unlike a normal web page, JavaScript running in the popup can access all the WebExtension APIs (subject, of course, to the extension having the appropriate permissions). This is a localizable property. | | `default_title`Optional | `String` | 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. This is a localizable property. | | `theme_icons`Optional | `Array` | This property enables you to specify different icons for themes depending on whether Firefox detects that the theme uses dark or light text. If this property is present, it's an array containing at least one `ThemeIcons` object. A `ThemeIcons` object contains three mandatory properties: `"dark"` 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). `"light"` A URL pointing to an icon. This icon displays when a theme using light text is active (such as the Firefox Dark theme). `"size"` The size of the two icons in pixels. Icons are specified as URLs relative to the manifest.json file. You should supply 16x16 and 32x32 (for retina display) `ThemeIcons`. | Choosing icon sizes ------------------- The browser 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`. * The default height and width for icons in the menu panel is 32 \* `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 "browser\_action": { "default\_icon": { "16": "button/geo-16.png", "32": "button/geo-32.png" } } ``` A browser 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.browserAction.onClicked.addListener(handleClick); ``` ```json "browser\_action": { "default\_icon": { "16": "button/geo-16.png", "32": "button/geo-32.png" }, "default\_title": "Whereami?", "default\_popup": "popup/geo.html" } ``` A browser action with an icon, a title, and a popup. The popup will be shown when the user clicks the button. For a simple, but complete, extension that uses a browser action, see the walkthrough tutorial. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * `page_action` * `sidebar_action` * Browser styles
dictionaries - Mozilla
dictionaries ============ | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "dictionaries": { "en-US": "dictionaries/en-US.dic" } ``` | 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` manifest.json key. Example ------- ```json "dictionaries": { "en-US": "dictionaries/en-US.dic" } ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
version_name - Mozilla
version\_name ============= | | | | --- | --- | | Type | `String` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "version\_name": "0.1 beta" ``` | In addition to the version field, which is used for update purposes, version\_name 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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
version - Mozilla
version ======= | | | | --- | --- | | Type | `String` | | Mandatory | Yes | | Example | ```json "version": "0.1" ``` | The **version string** for the extension. Version format -------------- The version string consists of 1 to 4 numbers separated by dots, for example, `1.2.3.4`. Non-zero numbers must not include a leading zero. For example, `2.01` is not allowed; however, `0.2`, `2.0.1`, and `2.10` are allowed. Extension stores and browsers may enforce or warn if the version string doesn't comply with this format. They may also apply restrictions to the range of numbers available. For example: * addons.mozilla.org (AMO) allows version strings using numbers of up to nine digits, complying with this regular expression `^(0|[1-9][0-9]{0,8})([.](0|[1-9][0-9]{0,8})){0,3}$`. Also, from Firefox 108, a warning is provided if an extension is installed with a version number that doesn't match this format. * The Chrome Web Store requires numbers between 0 and 65535 and does not permit all-zero extension strings. For example, 0.0 or 0.0.0.0 are not permitted. It may be possible to create an extension that appears to have a valid version number when run in a browser but doesn't comply with store requirements. Particular care should be taken when developing cross-browser extensions that use large number elements. Some browsers and web stores may recognize the version\_name key. This key enables you to provide a descriptive version string that may be displayed instead of the version number. For example, `1.0 beta`. ### Comparing versions To determine which of two extension versions is the most recent, the version string numbers are compared left to right. A missing version string element is equivalent to `0`. For example, 1.0 is equivalent to 1.0.0.0. The first version string with a number greater than the corresponding number in the other version string is the most recent. For example, 1.10 is a more recent version than 1.9. Legacy version formats ---------------------- See Legacy version formats for details of previously supported version strings. Access the version number in code --------------------------------- You obtain the extension version in your JavaScript code using: ```js console.log(browser.runtime.getManifest().version); ``` If the manifest contains: ```json "version": "0.1" ``` You see this in the console log: ``` "0.1" ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
content_scripts - Mozilla
content\_scripts ================ | | | | --- | --- | | Type | `Array` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "content\_scripts": [ { "matches": ["\*://\*.mozilla.org/\*"], "js": ["borderify.js"] } ] ``` | Instructs the browser to load content scripts into web pages whose URL matches a given pattern. This key is an array. Each item is an object which: * **must** contain a key named **`matches`**, which specifies the URL patterns to be matched in order for the scripts to be loaded; * **may** contain keys named **`js`** and **`css`**, which list scripts and/or stylesheets to be loaded into matching pages; and * **may** contain a number of other properties that control finer aspects of how and when content scripts are loaded. Details of all the keys you can include are given in the table below. | Name | Type | Description | | --- | --- | --- | | `all_frames` | `Boolean` | `true` Inject the scripts specified in `js` and `css` into all frames matching the specified URL requirements, even if the frame is not the topmost frame in a tab. This does not inject into child frames where only their parent matches the URL requirements and the child frame does not match the URL requirements. The URL requirements are checked for each frame independently. **Note:** This also applies to any tracker or ad that uses iframes, which means that enabling this could make your content script get called dozens of times on some pages. `false` Inject only into frames matching the URL requirements which are the topmost frame in a tab. Defaults to `false`. | | `css` | `Array` | An array of paths, relative to `manifest.json`, referencing CSS files that will be injected into matching pages. Files are injected in the order given, and at the time specified by `run\_at`. **Note:** Firefox resolves URLs in injected CSS files relative to the CSS file itself, rather than to the page it's injected into. | | `exclude_globs` | `Array` | An array of strings containing wildcards. See Matching URL patterns below. | | `exclude_matches` | `Array` | An array of match patterns. See Matching URL patterns below. | | `include_globs` | `Array` | An array of strings containing wildcards. See Matching URL patterns below. | | `js` | `Array` | An array of paths, relative to `manifest.json`, referencing JavaScript files that will be injected into matching pages. Files are injected in the order given. This means that, for example, if you include jQuery here followed by another content script, like this: ```json "js": ["jquery.js", "my-content-script.js"] ``` Then, `"my-content-script.js"` can use jQuery. The files are injected after any files in `css`, and at the time specified by `run\_at`. | | `match\_about\_blank` | `Boolean` | Insert the content scripts into pages whose URL is `"about:blank"` or `"about:srcdoc"`, if the URL of the page that opened or created this page matches the patterns specified in the rest of the `content_scripts` key. This is especially useful to run scripts in empty iframes, whose URL is `"about:blank"`. To do this you should also set the `all_frames` key. For example, suppose you have a `content_scripts` key like this: ```json "content\_scripts": [ { "js": ["my-script.js"], "matches": ["https://example.org/"], "match\_about\_blank": true, "all\_frames": true } ] ``` If the user loads `https://example.org/`, and this page embeds an empty iframe, then `"my-script.js"` will be loaded into the iframe. **Note:** `match_about_blank` is supported in Firefox from version 52. Note that in Firefox, content scripts won't be injected into empty iframes at `"document_start"`, even if you specify that value in `run\_at` . | | `matches` | `Array` | An array of match patterns. See Matching URL patterns below. This is the only mandatory key. | | `run_at` | `String` | This option determines when the files specified in `css` and `js` are injected. You can supply one of three strings here, each of which identifies a state in the process of loading a document. The states directly correspond to `Document.readyState`: `"document_start"` Corresponds to `loading`. The DOM is still loading. `"document_end"` Corresponds to `interactive`. The DOM has finished loading, but resources such as scripts and images may still be loading. `"document_idle"` Corresponds to `complete`. The document and all its resources have finished loading. The default value is `"document_idle"`. In all cases, files in `js` are injected after files in `css`. | Matching URL patterns --------------------- The `"content_scripts"` key attaches content scripts to documents based on URL matching: if the document's URL matches the specification in the key, then the script will be attached. There are four properties inside `"content_scripts"` that you can use for this specification: `matches` an array of match patterns `exclude_matches` an array of match patterns `include_globs` an array of globs `exclude_globs` an array of globs To match one of these properties, a URL must match at least one of the items in its array. For example, given a property like: ```json "matches": ["\*://\*.example.org/\*", "\*://\*.example.com/\*"] ``` Both `http://example.org/` and `http://example.com/` will match. Since `matches` is the only mandatory key, the other three keys are used to limit further the URLs that match. To match the key as a whole, a URL must: * match the `matches` property * AND match the `include_globs` property, if present * AND NOT match the `exclude_matches` property, if present * AND NOT match the `exclude_globs` property, if present ### globs A *glob* is just a string that may contain wildcards. There are two types of wildcard, and you can combine them in the same glob: 1. `*` matches zero or more characters 2. `?` matches exactly one character. For example: `"*na?i"` would match `"illuminati"` and `"annunaki"`, but not `"sagnarelli"`. Example ------- ```json "content\_scripts": [ { "matches": ["\*://\*.mozilla.org/\*"], "js": ["borderify.js"] } ] ``` This injects a single content script `borderify.js` into all pages under `mozilla.org` or any of its subdomains, whether served over HTTP or HTTPS. ```json "content\_scripts": [ { "exclude\_matches": ["\*://developer.mozilla.org/\*"], "matches": ["\*://\*.mozilla.org/\*"], "js": ["jquery.js", "borderify.js"] } ] ``` This injects two content scripts into all pages under `mozilla.org` or any of its subdomains except `developer.mozilla.org`, whether served over HTTP or HTTPS. The content scripts see the same view of the DOM and are injected in the order they appear in the array, so `borderify.js` can see global variables added by `jquery.js`. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
optional_permissions - Mozilla
optional\_permissions ===================== | | | | --- | --- | | Type | `Array` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "optional\_permissions": [ "webRequest" ] ``` | Use the `optional_permissions` key to list permissions that you want to ask for at runtime, after your extension has been installed. The `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 `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. 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 and browser.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` key. **Note:** When using Manifest V3 or higher: * in Chrome, host permissions must be specified in the `host_permission` 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, 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` * `sessions` * `tabHide` * `tabs` * `topSites` * `webNavigation` * `webRequest` * `webRequestBlocking` * `webRequestFilterResponse` * `webRequestFilterResponse.serviceWorkerScript` Note that this is a subset of the API permissions allowed in `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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
short_name - Mozilla
short\_name =========== | | | | --- | --- | | Type | `String` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "short\_name": "My Extension" ``` | Short name for the extension. If given, this will be used in contexts where the 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. Example ------- ```json "short\_name": "My Extension" ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
user_scripts - Mozilla
user\_scripts ============= | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 | | Example | ```json "user\_scripts": { "api\_script": "apiscript.js", } ``` | 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 `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 `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 `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 `userScripts.register`. The API script then accesses the `scriptMetadata` through the `script` parameter received by the `userScripts.onBeforeScript` listener (as `script.metadata`). Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * `userScripts` * `contentScripts`
externally_connectable - Mozilla
externally\_connectable ======================= | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ``` "externally_connectable": { "ids": [ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "cccccccccccccccccccccccccccccccc" ], "matches": [ "https://example1.com/*", "*://*.example2.com/*" ] } ``` | Externally connectable controls which other extensions and web pages can communicate with an extension using `runtime.connect()` and `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 for more details. * In Safari, `browser.runtime.connect` and `browser.runtime.sendMessage` are used. * In Firefox, neither API is supported. See Firefox bug 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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
action - Mozilla
action ====== | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 3 or higher | | Example | ```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 }] } ``` | 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` 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 when the user clicks the button. You can also create and manipulate actions programmatically using the `action` . Syntax ------ The `action` key is an object that may have any of these properties, all optional: | Name | Type | Description | | --- | --- | --- | | `browser\_style`Optional Deprecated | `Boolean` | Optional, defaulting to `false`. Do not set `browser_style` to true: its support in Manifest V3 was removed in Firefox 118. See Manifest V3 migration for `browser_style`. | | `default_area`Optional | `String` | Defines the part of the browser in which the button is initially placed. This is a string that may take one of four values: * "navbar": the button is placed in the main browser toolbar, alongside the URL bar. * "menupanel": the button is placed in a popup panel. * "tabstrip": the button is placed in the toolbar that contains browser tabs. * "personaltoolbar": the button is placed in the bookmarks toolbar. This property is only supported in Firefox. This property is optional, and defaults to "menupanel". Firefox remembers the `default_area` setting for an extension, even if that extension is uninstalled and subsequently reinstalled. To force the browser to acknowledge a new value for `default_area`, the id of the extension must be changed. 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. | | `default_icon`Optional | `Object` or `String` | Use this to specify one or more icons for the action. The icon is shown in the browser toolbar by default. Icons are specified as URLs relative to the manifest.json file itself. You can specify a single icon file by supplying a string here: ```json "default\_icon": "path/to/geo.svg" ``` 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: ```json "default\_icon": { "16": "path/to/geo-16.png", "32": "path/to/geo-32.png" } ``` You cannot specify multiple icons of the same sizes.See Choosing icon sizes for more guidance on this. | | `default_popup`Optional | `String` | The path to an HTML file containing the specification of the popup. The HTML file may include CSS and JavaScript files using `<link>` and `<script>` elements, just like a normal web page. However, `<script>`must have `src` attribute to load a file. Don't use `<script>` with embedded code, because you'll get a confusing Content Violation Policy error. Unlike a normal web page, JavaScript running in the popup can access all the WebExtension APIs (subject, of course, to the extension having the appropriate permissions). This is a localizable property. | | `default_title`Optional | `String` | 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. This is a localizable property. | | `theme_icons`Optional | `Array` | This property enables you to specify different icons for themes depending on whether Firefox detects that the theme uses dark or light text. If this property is present, it's an array containing at least one `ThemeIcons` object. A `ThemeIcons` object contains three mandatory properties: `"dark"` 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). `"light"` A URL pointing to an icon. This icon displays when a theme using light text is active (such as the Firefox Dark theme). `"size"` The size of the two icons in pixels. Icons are specified as URLs relative to the manifest.json file. You should supply 16x16 and 32x32 (for retina display) `ThemeIcons`. | 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`. * The default height and width for icons in the menu panel is 32 \* `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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
host_permissions - Mozilla
host\_permissions ================= | | | | --- | --- | | Type | `Array` | | Mandatory | No | | Manifest version | 3 or higher | | Example | ```json "host\_permissions": [ "\*://developer.mozilla.org/\*", "\*://\*.example.org/\*" ] ``` | Use the `host_permissions` key to request access for the APIs in your extension that read or modify host data, such as `cookies`, `webRequest`, and `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. Your extension can check whether it has all the required permissions immediately after installation using `permissions.contains`. If it doesn't have the necessary permissions, it can request them using `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 provides more information on the issues you should consider. For information on how to test and preview permission requests, see Test permission requests on the Extension Workshop site. ### Format Host permissions are specified as 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 and fetch 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 `tabs.Tab` objects. * the ability to inject scripts programmatically (using `tabs.executeScript()`) into pages served from those origins. * the ability to receive events from the `webrequest` API for these hosts. * the ability to access cookies for that host using the `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 `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 ------------------ * dnr-redirect-url Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
description - Mozilla
description =========== | | | | --- | --- | | Type | `String` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "description": "Replaces pictures with pictures of cats." ``` | 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. Example ------- ```json "description": "Replaces pictures with pictures of cats." ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
web_accessible_resources - Mozilla
web\_accessible\_resources ========================== | | | | --- | --- | | Type | `Array` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "web\_accessible\_resources": [ "images/my-image.png" ] ``` | 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 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>` 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 `webRequest` or `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: | Name | Type | Description | | --- | --- | --- | | `extension_ids` | `Array` of `String` | Optional. Defaults to `[]`, meaning that other extensions cannot access the resource. A list of extension IDs specifying the extensions that can access the resources. "\*" matches all extensions. | | `matches` | `Array` of `String` | Optional. Defaults to `[]`, meaning that other websites cannot access the resource. A list of URL match patterns 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 `/*`. | | `resources` | `Array` of `String` | An array of resources to be exposed. Resources are specified as strings and may contain `*` for wildcard matches. For example, `"/images/*"` exposes everything in the extension's `/images` directory recursively, while `"*.png"` exposes all PNG files. | | `use_dynamic_url` | `Boolean` | Optional. Defaults to `false`. Whether resources to be accessible through the dynamic ID. The dynamic ID is generated per session and regenerated on browser restart or extension reload. | ### Using web\_accessible\_resources Suppose your extension includes an image file at `images/my-image.png`, like this: ``` my-extension-files/ manifest.json my-background-script.js images/ my-image.png ``` To enable a web page to use an `<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: ``` 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` 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 or 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 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 ------------------ * beastify * dnr-redirect-url Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
background - Mozilla
background ========== | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "background": { "scripts": ["background.js"] } ``` | 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. See 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): | | | | --- | --- | | `page` | If you need specific content in the background page, you can define a page using the `page` property. This is a `String` representing a path relative to the manifest.json file to an HTML document included in your extension bundle. If you use this property, you can not specify background scripts using `scripts`, but you can include scripts from the page, just like a normal web page. | | `scripts` | An `Array` of `Strings`, 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. The scripts share the same `window` global context. The scripts are loaded in the order they appear in the array. If you specify `scripts`, an empty page is created where your scripts run. **Note:** If you want to fetch a script from a remote location with the `<script>` tag (e.g., `<script src = "https://code.jquery.com/jquery-3.6.0.min.js">`), you have to change the `content\_security\_policy` key in the manifest.json file of your extension. | | `service_worker` | Specify a JavaScript file as the extension service worker. A service worker is a background script that acts as the extension's main event handler. | The `background` key can also contain this optional property: | | | | --- | --- | | `persistent` | A `Boolean` value. If omitted, this property defaults to `true` in Manifest V2 and `false` in Manifest V3. Setting to `true` in Manifest V3 results in an error.* `true` 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). * `false` 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 storage API. | | `type` | A `String` value. Determines whether the scripts specified in `"scripts"` are loaded as ES modules.* `classic` indicates the background scripts or service workers are not included as an ES Module. * `module` indicates the background scripts or service workers are included as an ES Module. This enables the background page or service worker to `import` code. If omitted, this property defaults to `classic`. | 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). + 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). 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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
homepage_url - Mozilla
homepage\_url ============= | | | | --- | --- | | Type | `String` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "homepage\_url": "https://example.org/my-addon" ``` | URL for the extension's home page. If a developer key containing the "url" property and "homepage\_url" are defined, Firefox uses "developer.url" while Opera uses "homepage\_url". Chrome and Safari do not support the "developer" key. This is a localizable property. Example ------- ```json "homepage\_url": "https://github.com/mdn/webextensions-examples/tree/main/beastify" ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
offline_enabled - Mozilla
offline\_enabled ================ | | | | --- | --- | | Type | `Boolean` | | Mandatory | No | | Manifest version | 2 | | Example | ```json "offline\_enabled": true ``` | **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. Whether the app or extension is expected to work offline. When Chrome detects that it is offline, apps with this field set to true will be highlighted on the New Tab page. As of Chrome 35, apps (ChromeOS only from 2018) are assumed to be offline enabled and the default value of `"offline_enabled"` is `true` unless `"webview"` permission is requested. In this case, network connectivity is assumed to be required and `"offline_enabled"` defaults to `false`. The `"offline_enabled"` value is also used to determine whether a network connectivity check will be performed when launching an app in ChromeOS kiosk mode. A network connectivity check will be performed when apps are not offline enabled, and app launching put on hold until the device obtains connectivity to the Internet. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
browser_specific_settings - Mozilla
browser\_specific\_settings =========================== | | | | --- | --- | | Type | `Object` | | Mandatory | Usually, no (but see also When do you need an Add-on ID?). Mandatory if the extension ID cannot be determined, see `browser_specific_settings.gecko.id`. | | Example | ```json "browser\_specific\_settings": { "gecko": { "id": "[email protected]", "strict\_min\_version": "42.0" } } ``` | Description ----------- The `browser_specific_settings` key contains keys that are specific to a particular host application. ### Firefox (Gecko) properties Firefox stores browser-specific settings in these sub-keys: * `gecko` for the desktop version of Firefox. * `gecko_android` for the Android version of Firefox. The `gecko` subkey supports these properties: `id` The extension ID. When provided, this property must contain 80 characters or less. See Extensions and the Add-on ID to determine when to specify the ID. `strict_min_version` Minimum version of Gecko to support. If the Firefox version on which the extension is being installed or run is below this version, the extension is not installed or not run. If not provided, all versions earlier than `strict_max_version` are supported. "\*" is not valid in this field. `strict_max_version` Maximum version of Gecko to support. If the Firefox version on which the extension is being installed or run is above this version, the extension is not installed or not run. Defaults to "\*", which disables checking for a maximum version. `update_url` A link to an extension update manifest. Note that the link must begin with "https". This key is for managing extension updates yourself (i.e., not through AMO). The `gecko_android` subkey supports these properties: `strict_min_version` Minimum version of Gecko to support on Android. If the Firefox for Android version on which the extension is being installed or run is below this version, the extension is not installed or not run. If not provided, defaults to the version determined by `gecko.strict_min_version`. "\*" is not valid in this field. `strict_max_version` Maximum version of Gecko to support on Android. If the Firefox version on which the extension is being installed or run is above this version, the extension is not installed or not run. Defaults to the version determined by `gecko.strict_max_version`. See the list of valid Gecko versions. #### Extension ID format The extension ID must be one of the following: * GUID * A string formatted like an email address: `[email protected]` The latter format is easier to generate and manipulate. Be aware that using a real email address here may attract spam. For example: ```json "id": "[email protected]" ``` ```json "id": "{daf44bf7-a45e-4450-979c-91cf07434c3d}" ``` ### Safari properties Safari stores its browser-specific settings in the `safari` subkey, which has these properties: `strict_min_version` Minimum version of Safari to support. `strict_max_version` Maximum version of Safari to support. Examples -------- Example with all possible keys. Note that most extensions omit `strict_max_version` and `update_url`. ```json "browser\_specific\_settings": { "gecko": { "id": "[email protected]", "strict\_min\_version": "42.0", "strict\_max\_version": "50.\*", "update\_url": "https://example.com/updates.json" }, "safari": { "strict\_min\_version": "14", "strict\_max\_version": "20" } } ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
options_ui - Mozilla
options\_ui =========== | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "options\_ui": { "page": "options/options.html" } ``` | Use the `options_ui` key to define an options page 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 `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 that the extension has 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 of your background scripts by using `extension.getBackgroundPage()`, or a reference to the `Window` of any of the pages running within your extension with `extension.getViews()`. Alternately, you can communicate between the JavaScript for your options page and your background script(s) using `runtime.sendMessage()`, `runtime.onMessage`, or `runtime.connect()`. The latter (or `runtime.Port` equivalents) can also be used to share options between your background script(s) and your **content script(s).** In general, you will want to store options changed on option pages using the storage API to either `storage.sync` (if you want the settings synchronized across all instances of that browser that the user is logged into), or `storage.local` (if the settings are local to the current machine/profile). If you do so and your background script(s) (or content script(s)) need to know about the change, your script(s) might choose to add a listener to `storage.onChanged`. Syntax ------ The `options_ui` key is an object with the following contents: | Name | Type | Description | | --- | --- | --- | | `browser\_style`Optional Deprecated in Manifest V3. | `Boolean` | Optional, defaulting to:* `true` in Manifest V2 and prior to Firefox 115 in Manifest V3. * `false` in Manifest V3 from Firefox 115. Do not set `browser_style` to true: its not support in Manifest V3 from Firefox 118. See Manifest V3 migration for `browser_style`. 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 `box-sizing: border-box` (see box-sizing). | | `open_in_tab`Optional | `Boolean` | Defaults to `false`. If `true`, the options page will open in a normal browser tab, rather than being integrated into the browser's add-ons manager. | | `page` | `String` | Mandatory. The path to an HTML file containing the specification of your options page. The path is relative to the location of `manifest.json` itself. | Example ------- ```json "options\_ui": { "page": "options/options.html" } ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * `options_page` Deprecated * Browser styles * Options pages
developer - Mozilla
developer ========= | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "developer": { "name": "Walt Whitman", "url": "https://en.wikipedia.org/wiki/Walt\_Whitman" } ``` | 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 and homepage\_url keys, respectively. This object only allows for a single developer name and URL to be specified. This is a localizable property. Example ------- ```json "developer": { "name": "Walt Whitman", "url": "https://en.wikipedia.org/wiki/Walt\_Whitman" } ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
default_locale - Mozilla
default\_locale =============== | | | | --- | --- | | Type | `String` | | Mandatory | Contingent: must be present if the \_locales subdirectory is present, must be absent otherwise. | | Example | ```json "default\_locale": "en" ``` | This key must be present if the extension contains the \_locales directory, and must be absent otherwise. It identifies a subdirectory of \_locales, and this subdirectory will be used to find the default strings for your extension. See Internationalization. Example ------- ```json "default\_locale": "en" ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
name - Mozilla
name ==== | | | | --- | --- | | Type | `String` | | Mandatory | Yes | | Example | ```json "name": "My Extension" ``` | 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. Example ------- ```json "name": "My Extension" ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
omnibox - Mozilla
omnibox ======= | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "omnibox": { "keyword": "mdn" } ``` | 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` 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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
commands - Mozilla
commands ======== | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "commands": { "toggle-feature": { "suggested\_key": { "default": "Ctrl+Shift+Y", "linux": "Ctrl+Shift+U" }, "description": "Send a 'toggle-feature' event" } } ``` | 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 `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 `Ctrl` + `Shift` + `U` on Linux, and `Alt` + `Shift` + `U` on all other platforms. 2. `"do-another-thing"`, accessed with `Ctrl` + `Shift` + `Y` 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 `commands.onCommand` event does not fire: * `_execute_browser_action`: works like a click on a toolbar button created with `browserAction` or specified in the browser\_action key in the manifest.json key. * `_execute_action`: works like a click on a toolbar button created with `action` or specified in the action key in the manifest.json key. * `_execute_page_action`: works like a click on an address bar button created with `pageAction` or specified in the page\_action key in the manifest.json key. * `_execute_sidebar_action`: opens the extension's sidebar specified in the sidebar\_action manifest.json key. The availability of these special shortcuts varies between manifest versions and browsers, like this: | | Manifest V2 | Manifest V3 | | --- | --- | --- | | `_execute_browser_action` | Yes | No | | `_execute_action` | No | Yes | | `_execute_page_action` | Yes | Not available in Chromium-based browsers | | `_execute_sidebar_action` | Firefox only | Firefox only | 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 `commands.update()`. Users can also update shortcuts via the "Manage Extension Shortcuts" option at `about:addons` in Firefox, as shown in this video. 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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
incognito - Mozilla
incognito ========= | | | | --- | --- | | Type | `String` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "incognito": "spanning" ``` ```json "incognito": "split" ``` ```json "incognito": "not\_allowed" ``` | 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. Your extension can check whether it can access private browsing windows using `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` or `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` is not shared). However, the WebExtension 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 --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
declarative_net_request - Mozilla
declarative\_net\_request ========================= | | | | --- | --- | | Type | `Object` | | Mandatory | No | | Manifest version | 2 or higher | | Example | ```json "declarative\_net\_request" : { "rule\_resources" : [{ "id": "ruleset", "enabled": true, "path": "rules.json" }] } ``` | Specify static rulesets for use with `declarativeNetRequest`. See Permissions 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: | Name | Type | Description | | --- | --- | --- | | `"id"` | `String` | A non-empty string uniquely identifying the ruleset. IDs beginning with '\_' are reserved for internal use. | | `"enabled"` | `Boolean` | Whether the ruleset is enabled by default. The `declarativeNetRequest.updateEnabledRulesets` method can be used to enable or disable a ruleset at runtime. | | `"path"` | `String` | The path of the JSON ruleset relative to the extension directory. See the Rules section of the `declarativeNetRequest` API for information on the content of the ruleset JSON file. | 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 ------------------ * dnr-block-only * dnr-redirect-url Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
manifest_version - Mozilla
manifest\_version ================= | | | | --- | --- | | Type | `Number` | | Mandatory | Yes | | Example | ```json "manifest\_version": 3 ``` | This key specifies the version of manifest.json used by this extension. Example ------- ```json "manifest\_version": 3 ``` Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Legacy Version Formats - Mozilla
Legacy Version Formats ====================== This page describes legacy web extension version string formats. See the manifest version key documentation for information on the current version string format. Firefox legacy version number ----------------------------- A **version string** consists of one or more *version parts*, separated by dots. Each **version part** is parsed as a sequence of four parts: `<number-a><string-b><number-c><string-d>`. Each of the parts is optional. Numbers are integers base 10 (may be negative), and strings are non-numeric ASCII characters. Here are a few examples of valid version parts: * `0` (as in `1.0`): `<number-a>=0` * `5a` (as in `1.5a`): `<number-a>=5`, `<string-b>=a` * `5pre4` (as in `3.5pre4`): `<number-a>=5`, `<string-b>=pre`, `<number-c>=4` * `*` (as in `1.0.*`): `<string-b>=*` A few special parsing rules are applied for backward compatibility and readability: * if the version part is a single asterisk, it is interpreted as an infinitely-large number: `1.5.0.*` is the same as `1.5.0.(infinity)` * if string-b is a plus sign, number-a is incremented to be compatible with the Firefox 1.0.x version format: `1.0+` is the same as `1.1pre` The rationale behind splitting a version part into a sequence of strings and numbers is that when comparing version parts, the numeric parts are compared as numbers, for example, '1.0pre1' < '1.0pre10', while the strings are compared byte-wise. See the next section for details on how versions are compared. From Firefox 108, web extensions using this version string trigger a warning on installation. Comparing versions ------------------ When two version strings are compared, their version parts are compared left to right. An empty or missing version part is equivalent to `0`. If at some point, a version part of one version string is greater than the corresponding version part of another version string, then the first version string is greater than the other one. Otherwise, the version strings are equal. As missing version parts are treated as if they were `0`, these version strings are equal: `1`, `1.0`, `1.0.`, `1.0.0`, and even `1.0..`. ### Comparing version parts Version parts are also compared left to right; parts A and C are compared as numbers, while parts B and D are compared byte-wise. A string part that exists is always less than a string part that doesn't exist (`1.6a` is less than `1.6`). Examples -------- ``` 1.-1 < 1 == 1. == 1.0 == 1.0.0 < 1.1a < 1.1aa < 1.1ab < 1.1b < 1.1c < 1.1pre == 1.1pre0 == 1.0+ < 1.1pre1a < 1.1pre1aa < 1.1pre1b < 1.1pre1 < 1.1pre2 < 1.1pre10 < 1.1.-1 < 1.1 == 1.1.0 == 1.1.00 < 1.10 < 1.* < 1.*.1 < 2.0 ```
i18n - Mozilla
i18n ==== Functions to internationalize your extension. You can use these APIs to get localized strings from locale files packaged with your extension, find out the browser's current language, and find out the value of its Accept-Language header. See the Internationalization page for a guide on using this API. Types ----- `i18n.LanguageCode` A language tag such as `"en-US"` or "`fr`". Functions --------- `i18n.getAcceptLanguages()` Gets the accept-languages of the browser. This is different from the locale used by the browser. To get the locale, use `i18n.getUILanguage`. `i18n.getMessage()` Gets the localized string for the specified message. `i18n.getUILanguage()` Gets the UI language of the browser. This is different from `i18n.getAcceptLanguages` which returns the preferred user languages. `i18n.detectLanguage()` Detects the language of the provided text using the Compact Language Detector. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * menu-accesskey-visible * menu-demo * notify-link-clicks-i18n **Note:** This API is based on Chromium's `chrome.i18n` API. This documentation is derived from `i18n.json` in the Chromium code. See also -------- * Internationalization: a guide to using the WebExtension i18n system. * Locale-Specific Message reference: extensions supply locale-specific strings in files called `messages.json`. This page describes the format of `messages.json`.
webNavigation - Mozilla
webNavigation ============= Add event listeners for the various stages of a navigation. A navigation consists of a frame in the browser transitioning from one URL to another, usually (but not always) in response to a user action like clicking a link or entering a URL in the location bar. Compared with the `webRequest` API: navigations usually result in the browser making web requests, but the webRequest API is concerned with the lower-level view from the HTTP layer, while the webNavigation API is more concerned with the view from the browser UI itself. Each event corresponds to a particular stage in the navigation. The sequence of events is like this: ![Visualization of the primary flow and additional flows described below.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation/we-flow.png) * The primary flow is: + ``onBeforeNavigate`` + ``onCommitted`` + ``onDOMContentLoaded`` + ``onCompleted``. * Additionally: + ``onCreatedNavigationTarget`` is fired before `onBeforeNavigate` if the browser needed to create a new tab or window for the navigation (for example, because the user opened a link in a new tab). + `onHistoryStateUpdated` is fired if a page uses the history API (2011) to update the URL displayed in the browser's location bar. + `onReferenceFragmentUpdated` is fired if the fragment identifier for a page is changed. + `onErrorOccurred` can be fired at any point. Each navigation is a URL transition in a particular browser frame. The browser frame is identified by a tab ID and a frame ID. The frame may be the top-level browsing context in the tab, or may be a nested browsing context implemented as an iframe. Each event's `addListener()` call accepts an optional filter parameter. The filter will specify one or more URL patterns, and the event will then only be fired for navigations in which the target URL matches one of the patterns. The `onCommitted` event listener is passed two additional properties: a `TransitionType` indicating the cause of the navigation (for example, because the user clicked a link, or because the user selected a bookmark), and a `TransitionQualifier` providing further information about the navigation. To use this API you need to have the "webNavigation" permission. Types ----- `webNavigation.TransitionType` Cause of the navigation: for example, the user clicked a link, or typed an address, or clicked a bookmark. `webNavigation.TransitionQualifier` Extra information about a transition. Functions --------- `webNavigation.getFrame()` Retrieves information about a particular frame. A frame may be the top-level frame in a tab or a nested iframe, and is uniquely identified by a tab ID and a frame ID. `webNavigation.getAllFrames()` Given a tab ID, retrieves information about all the frames it contains. Events ------ `webNavigation.onBeforeNavigate` Fired when the browser is about to start a navigation event. `webNavigation.onCommitted` Fired when a navigation is committed. At least part of the new document has been received from the server and the browser has decided to switch to the new document. `webNavigation.onDOMContentLoaded` Fired when the DOMContentLoaded event is fired in the page. `webNavigation.onCompleted` Fired when a document, including the resources it refers to, is completely loaded and initialized. This is equivalent to the DOM `load` event. `webNavigation.onErrorOccurred` Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, or the user aborted the navigation. `webNavigation.onCreatedNavigationTarget` Fired when a new window, or a new tab in an existing window, is created to host a navigation: for example, if the user opens a link in a new tab. `webNavigation.onReferenceFragmentUpdated` Fired if the fragment identifier for a page is changed. `webNavigation.onTabReplaced` Fired when the contents of the tab is replaced by a different (usually previously pre-rendered) tab. `webNavigation.onHistoryStateUpdated` Fired when the page used the history API (2011) to update the URL displayed in the browser's location bar. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * navigation-stats **Note:** This API is based on Chromium's `chrome.webNavigation` API. This documentation is derived from `web_navigation.json` in the Chromium code.
browserSettings - Mozilla
browserSettings =============== Enables an extension to modify certain global browser settings. Each property of this API is a `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()` for details of how conflicts are handled. To use this API you need to have the "browserSettings" permission. Properties ---------- `browserSettings.allowPopupsForUserEvents` Determines whether code running in web pages can display popups in response to user events. `browserSettings.cacheEnabled` Determines whether the browser cache is enabled or not. `browserSettings.closeTabsByDoubleClick` Determines whether the selected tab can be closed with a double click. `browserSettings.colorManagement` Determines various settings for color management. `browserSettings.contextMenuShowEvent` Determines the mouse event that triggers a context menu popup. `browserSettings.ftpProtocolEnabled` Determines whether the FTP protocol is enabled. `browserSettings.homepageOverride` Read the value of the browser's home page. `browserSettings.imageAnimationBehavior` Determines how the browser treats animated images. `browserSettings.newTabPageOverride` Reads the value of the browser's new tab page. `browserSettings.newTabPosition` Controls the position of newly opened tabs relative to already open tabs. `browserSettings.openBookmarksInNewTabs` Determines whether bookmarks are opened in the current tab or a new tab. `browserSettings.openSearchResultsInNewTabs` Determines whether search results are opened in the current tab or a new tab. `browserSettings.openUrlbarResultsInNewTabs` Determines whether address bar autocomplete suggestions are opened in the current tab or a new tab. `browserSettings.overrideContentColorScheme` Controls whether to override the browser theme (light or dark) when setting pages' preferred color scheme. `browserSettings.overrideDocumentColors` Controls whether the user-chosen colors override the page's colors. `browserSettings.tlsVersionRestrictionConfig` Read the highest and lowest versions of TLS supported by the browser. `browserSettings.useDocumentFonts` Controls whether the browser will use the fonts specified by a web page or use only built-in fonts. `browserSettings.webNotificationsDisabled` Prevents websites from showing notifications using the `Notification` Web API. `browserSettings.zoomFullPage` Controls whether zoom is applied to the entire page or to text only. `browserSettings.zoomSiteSpecific` Controls whether page zoom is applied on a per-site or per-tab basis. If `privacy.websites``.resistFingerprinting` is true, this setting has no effect and zoom is applied on a per-tab basis. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
sessions - Mozilla
sessions ======== Use the sessions API to list, and restore, tabs and windows that have been closed while the browser has been running. The `sessions.getRecentlyClosed()` function returns an array of `tabs.Tab` and `windows.Window` objects, representing tabs and windows that have been closed since the browser was running, up to the maximum defined in `sessions.MAX_SESSION_RESULTS`. You can then restore a window or tab using the `sessions.restore()` function. Restoring doesn't just reopen the tab: it also restores the tab's navigation history so the back/forward buttons will work. This API also provides a group of functions that enable an extension to store additional state associated with a tab or a window. Then, if the tab or window is closed and subsequently restored, the extension can retrieve the state. For example, a tab grouping extension might use this to remember which group a tab is in, so as to restore it into the right group if the user restores the tab. To use the sessions API you must have the "sessions" API permission. Types ----- `sessions.Filter` Enables you to restrict the number of `Session` objects returned by a call to `sessions.getRecentlyClosed()`. `sessions.Session` Represents a tab or window that the user has closed in the current browsing session. Properties ---------- `sessions.MAX_SESSION_RESULTS` The maximum number of sessions that will be returned by a call to `sessions.getRecentlyClosed()`. Functions --------- `sessions.forgetClosedTab()` Removes a closed tab from the browser's list of recently closed tabs. `sessions.forgetClosedWindow()` Removes a closed window from the browser's list of recently closed windows. `sessions.getRecentlyClosed()` Returns an array of `Session` objects, representing windows and tabs that were closed in the current browsing session (that is: the time since the browser was started). `sessions.restore()` Restores a closed tab or window. `sessions.setTabValue()` Store a key/value pair associated with a given tab. `sessions.getTabValue()` Retrieve a previously stored value for a given tab, given its key. `sessions.removeTabValue()` Remove a key/value pair from a given tab. `sessions.setWindowValue()` Store a key/value pair associated with a given window. `sessions.getWindowValue()` Retrieve a previously stored value for a given window, given its key. `sessions.removeWindowValue()` Remove a key/value pair from a given window. Events ------ `sessions.onChanged` Fired when a tab or window is closed. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * session-state **Note:** This API is based on Chromium's `chrome.sessions` API.
search - Mozilla
search ====== Use the search API to retrieve the installed search engines and execute searches. To use this API you need to have the `"search"` permission. When choosing between `search.query()` and `search.search()`, consider the following: * `search.query()` is available in most major browsers, making it ideal for use in cross-browser extensions. However, it can only issue searches against the browser's default search engine. * `search.search()` is available only in Firefox. However, it has the advantage of being able to issue a search against any search engine installed in the browser. Functions --------- `search.get()` Retrieve all search engines. `search.query()` Search using the browser's default search engine. `search.search()` Search using a specified search engine. Example extensions ------------------ * menu-search Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
menus - Mozilla
menus ===== Add items to the browser's menu system. This API is modeled on Chrome's "contextMenus" API, which enables Chrome extensions to add items to the browser's context menu. The `browser.menus` API adds a few features to Chrome's API. Before Firefox 55 this API was also originally named `contextMenus`, and that name has been retained as an alias, so you can use `contextMenus` to write code that works in Firefox and also in other browsers. To use this API you need to have the `menus` permission. You may also use the `contextMenus` alias instead of `menus`, but if you do, the APIs must be accessed as `browser.contextMenus` instead. Except for `menus.getTargetElement()`, this API cannot be used from content scripts. Creating menu items ------------------- To create a menu item call the `menus.create()` method. You pass this method an object containing options for the item, including the item ID, item type, and the contexts in which it should be shown. In a Firefox extension using non-persistent background pages (Event pages) or in any Chrome extension, you call `menus.create` from within a `runtime.onInstalled` listener. In a Firefox extension using persistent background pages, you make a top-level call. See `menus.create()` for more information. Listen for clicks on your menu item by adding a listener to the `menus.onClicked` event. This listener will be passed a `menus.OnClickData` object containing the event's details. You can create four different types of menu item, based on the value of the `type` property you supply in the options to `create()`: * "normal": a menu item that just displays a label * "checkbox": a menu item that represents a binary state. It displays a checkmark next to the label. Clicking the item toggles the checkmark. The click listener will be passed two extra properties: "checked", indicating whether the item is checked now, and "wasChecked", indicating whether the item was checked before the click event. * "radio": a menu item that represents one of a group of choices. Just like a checkbox, this also displays a checkmark next to the label, and its click listener is passed "checked" and "wasChecked". However, if you create more than one radio item, then the items function as a group of radio items: only one item in the group can be checked, and clicking an item makes it the checked item. * "separator": a line separating a group of items. If you have created more than one context menu item or more than one tools menu item, then the items will be placed in a submenu. The submenu's parent will be labeled with the name of the extension. For example, here's an extension called "Menu demo" that's added two context menu items: ![Context menu with two items labeled click me, and click me too!](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/menus-1.png) Icons ----- If you've specified icons for your extension using the "icons" manifest key, your menu item will display the specified icon next to its label. The browser will try to choose a 16x16 pixel icon for a normal display or a 32x32 pixel icon for a high-density display: ![Context menu with two items labeled click me, and click me too!](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/menus-2.png) Only for items in a submenu, you can specify custom icons by passing the `icons` option to `menus.create()`: ![Context menu with two items labeled click me, and click me too!. The click me option is labeled with a green paint can icon. The click me too option is labeled with a blue paint can icon.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/menus-3.png) Example ------- Here's a context menu containing 4 items: a normal item, two radio items with separators on each side, and a checkbox. The radio items are given custom icons. ![Context menu with four items labeled remove me, Greenify, Bluify, and uncheck me. Greenify and Bluify are radio buttons given custom icons.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/menus-4.png) You could create a submenu like this using code like: ```js browser.menus.create( { id: "remove-me", title: browser.i18n.getMessage("menuItemRemoveMe"), contexts: ["all"], }, onCreated, ); browser.menus.create( { id: "separator-1", type: "separator", contexts: ["all"], }, onCreated, ); browser.menus.create( { id: "greenify", type: "radio", title: browser.i18n.getMessage("menuItemGreenify"), contexts: ["all"], checked: true, icons: { 16: "icons/paint-green-16.png", 32: "icons/paint-green-32.png", }, }, onCreated, ); browser.menus.create( { id: "bluify", type: "radio", title: browser.i18n.getMessage("menuItemBluify"), contexts: ["all"], checked: false, icons: { 16: "icons/paint-blue-16.png", 32: "icons/paint-blue-32.png", }, }, onCreated, ); browser.menus.create( { id: "separator-2", type: "separator", contexts: ["all"], }, onCreated, ); let checkedState = true; browser.menus.create( { id: "check-uncheck", type: "checkbox", title: browser.i18n.getMessage("menuItemUncheckMe"), contexts: ["all"], checked: checkedState, }, onCreated, ); ``` Types ----- `menus.ContextType` The different contexts a menu can appear in. `menus.ItemType` The type of menu item: "normal", "checkbox", "radio", "separator". `menus.OnClickData` Information sent when a menu item is clicked. Properties ---------- `menus.ACTION_MENU_TOP_LEVEL_LIMIT` The maximum number of top level extension items that can be added to a menu item whose ContextType is "browser\_action" or "page\_action". Functions --------- `menus.create()` Creates a new menu item. `menus.getTargetElement()` Returns the element for a given `info.targetElementId`. `menus.overrideContext()` Hide all default Firefox menu items in favor of providing a custom context menu UI. `menus.refresh()` Update a menu that's currently being displayed. `menus.remove()` Removes a menu item. `menus.removeAll()` Removes all menu items added by this extension. `menus.update()` Updates a previously created menu item. Events ------ `menus.onClicked` Fired when a menu item is clicked. `menus.onHidden` Fired when the browser hides a menu. `menus.onShown` Fired when the browser shows a menu. Browser compatibility --------------------- Example extensions ------------------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. * menu-accesskey-visible * menu-demo * menu-labelled-open * menu-remove-element * menu-search * session-state **Note:** This API is based on Chromium's `chrome.contextMenus` API. This documentation is derived from `context_menus.json` in the Chromium code.
pageAction - Mozilla
pageAction ========== The API to control address bar button. ![Paw print icon representing a page action](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction/page-action.png) You can listen for clicks on the icon in a background script, or specify a popup that opens when the icon is clicked. If you specify a popup, you define its contents and behavior using HTML, CSS, and JavaScript. JavaScript running in the popup gets access to all the same WebExtension APIs as your background scripts. Despite being named `pageAction`, the action code doesn't get access to web page content. To access web page DOM, you need to add a content script and interact with it. The button also has a context menu, and you can add items to this menu with the `menus` API using the `page_action` `menus.ContextType`. You can define most of a page action's properties declaratively using the `page_action` key in your `manifest.json`, and redefine them programmatically using this API. Page actions are for actions that are only relevant to particular pages (such as "bookmark the current tab"). If they are relevant to the browser as a whole (such as "show all bookmarks"), use a browser action instead. Types ----- `pageAction.ImageDataType` Pixel data for an image. Functions --------- `pageAction.show()` Shows the page action for a given tab. `pageAction.hide()` Hides the page action for a given tab. `pageAction.isShown()` Checks whether the page action is shown or not. `pageAction.setTitle()` Sets the page action's title. This is displayed in a tooltip over the page action. `pageAction.getTitle()` Gets the page action's title. `pageAction.setIcon()` Sets the page action's icon. `pageAction.setPopup()` Sets the URL for the page action's popup. `pageAction.getPopup()` Gets the URL for the page action's popup. `pageAction.openPopup()` Opens the page action's popup. Events ------ `pageAction.onClicked` Fired when a page action icon is clicked. This event will not fire if the page action has a popup. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * apply-css * chill-out * history-deleter * menu-remove-element **Note:** This API is based on Chromium's `chrome.pageAction` API. This documentation is derived from `page_action.json` in the Chromium code.
windows - Mozilla
windows ======= Interact with browser windows. You can use this API to get information about open windows and to open, modify, and close windows. You can also listen for window open, close, and activate events. Types ----- `windows.WindowType` The type of browser window this is. `windows.WindowState` The state of this browser window. `windows.Window` Contains information about a browser window. `windows.CreateType` Specifies the type of browser window to create. Constants --------- `windows.WINDOW_ID_NONE` The `windowId` value that represents the absence of a browser window. `windows.WINDOW_ID_CURRENT` A value that can be used in place of a `windowId` in some APIs to represent the current window. Methods ------- `windows.get()` Gets details about a window, given its ID. `windows.getCurrent()` Gets the current window. `windows.getLastFocused()` Gets the window that was most recently focused — typically the window 'on top'. `windows.getAll()` Gets all windows. `windows.create()` Creates a new window. `windows.update()` Updates the properties of a window. Use this to move, resize, and (un)focus a window, etc. `windows.remove()` Closes a window, and all its tabs. Events ------ `windows.onCreated` Fired when a window is created. `windows.onRemoved` Fired when a window is closed. `windows.onFocusChanged` Fired when the currently focused window changes. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * annotate-page * bookmark-it * private-browsing-theme * store-collected-images * theme-integrated-sidebar * window-manipulator **Note:** This API is based on Chromium's `chrome.windows` API. This documentation is derived from `windows.json` in the Chromium code.
contentScripts - Mozilla
contentScripts ============== Use this API to register content scripts. Registering a content script instructs the browser to insert the given content scripts into pages that match the given URL patterns. **Note:** When using Manifest V3 or higher, use `scripting.registerContentScripts()` to register scripts. This API is very similar to the `"content_scripts"` `manifest.json` key, except that with `"content_scripts"`, the set of content scripts and associated patterns is fixed at install time. With the `contentScripts` API, an extension can register and unregister scripts at runtime. To use the API, call `contentScripts.register()` passing in an object defining the scripts to register, the URL patterns, and other options. This returns a `Promise` that is resolved with a `contentScripts.RegisteredContentScript` object. The `RegisteredContentScript` object represents the scripts that were registered in the `register()` call. It defines an `unregister()` method that you can use to unregister the content scripts. Content scripts are also unregistered automatically when the page that created them is destroyed. For example, if they are registered from the background page they will be unregistered automatically when the background page is destroyed, and if they are registered from a sidebar or a popup, they will be unregistered automatically when the sidebar or popup is closed. There is no `contentScripts` API permission, but an extension must have the appropriate host permissions for any patterns it passes to `register()`. Types ----- `contentScripts.RegisteredContentScript` An object of this type is returned by the `contentScripts.register()` function. It represents the content scripts that were registered by that call, and can be used to unregister the content script. Functions --------- `contentScripts.register()` Registers the given content scripts. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * content-script-register
alarms - Mozilla
alarms ====== Schedule code to run at a specific time in the future. This is like `setTimeout()` and `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` event in background script, options page, popup page and extension tabs (and vice versa). Alarms API is not available in `Content scripts`. To use this API you need to have the "alarms" permission. Types ----- `alarms.Alarm` Information about a particular alarm. Methods ------- `alarms.clear()` Clear a specific alarm, given its name. `alarms.clearAll()` Clear all scheduled alarms. `alarms.create()` Create a new alarm. `alarms.get()` Retrieves a specific alarm, given its name. `alarms.getAll()` Retrieve all scheduled alarms. Events ------ `alarms.onAlarm` Fired when an alarm goes off. Example extensions ------------------ * chill-out * dynamic-theme Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. **Note:** This API is based on Chromium's `chrome.alarms` API.
identity - Mozilla
identity ======== Use the identity API to get an OAuth2 authorization code or access token, which an extension can then use to access user data from a service that supports OAuth2 access (such as Google or Facebook). OAuth2 flows vary between service provider so, to use this API with a particular service provider, consult their documentation. For example: * Google * GitHub The identity API provides the `identity.launchWebAuthFlow()` function. This authenticates the user with the service, if necessary, and asks the user to authorize the extension to access data, if necessary. The function completes with an access token or authorization code, depending on the provider. The extension then completes the OAuth2 flow to get a validated access token, and uses the token in HTTPS requests to access the user's data according to the authorization the user gave. To use this API, you must have the "identity" API permission. Setup ----- There's some setup you must do before publishing your extension. ### Getting the redirect URL The redirect URL represents the end point of `identity.launchWebAuthFlow()`, in which the access token or authorization code is delivered to the extension. The browser extracts the result from the redirect URL without loading its response. You get the redirect URL by calling `identity.getRedirectURL()`. This function derives a redirect URL from the add-on's ID. To simplify testing, set your add-on's ID explicitly using the `browser_specific_settings` key (otherwise, each time you temporarily install the add-on, you get a different redirect URL). `identity.getRedirectURL()` returns a URL at a fixed domain name and a subdomain derived from the add-on's ID. Some OAuth servers (such as Google) only accept domains with a verified ownership as the redirect URL. As the dummy domain cannot be controlled by extension developers, the default domain cannot always be used. However, loopback addresses are an accepted alternative that do not require domain validation (based on RFC 8252, section 7.3). Starting from Firefox 86, a loopback address with the format `http://127.0.0.1/mozoauth2/[subdomain of URL returned by identity.getRedirectURL()]` is permitted as a value for the redirect URL. **Note:** Starting with Firefox 75, you must use the redirect URL returned by `identity.getRedirectURL()`. Earlier versions allowed you to supply any redirect URL. Starting with Firefox 86, the special loopback address described above can be used too. You'll use the redirect URL in two places: * supply it when registering your extension as an OAuth2 client. * pass it into `identity.launchWebAuthFlow()`, as a URL parameter added to that function's `url` argument. ### Registering your extension Before you use OAuth2 with a service provider, you must register the extension with the provider as an OAuth2 client. This will tend to be specific to the service provider, but in general it means creating an entry for your extension on the provider's website. In this process you supply your redirect URL, and receive a client ID (and sometimes also a secret). You need to pass both of these into `identity.launchWebAuthFlow()`. Functions --------- `identity.getRedirectURL()` Gets the redirect URL. `identity.launchWebAuthFlow()` Launches WAF. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * google-userinfo **Note:** This API is based on Chromium's `chrome.identity` API.
tabs - Mozilla
tabs ==== Interact with the browser's tab system. **Note:** When using Manifest V3 or higher, the methods to execute scripts, insert CSS, and remove CSS are provided by the `scripting` API through the `scripting.executeScript()`, `scripting.insertCSS()` and `scripting.removeCSS()` methods. You can use this API to get a list of opened tabs, filtered by various criteria, and to open, update, move, reload, and remove tabs. You can't directly access the content hosted by tabs using this API, but you can insert JavaScript and CSS into tabs using the `tabs.executeScript()` or `tabs.insertCSS()` APIs. You can use most of this API without any special permission. However: * To access `Tab.url`, `Tab.title`, and `Tab.favIconUrl` (or to filter by these properties via `tabs.query()`), you need to have the `"tabs"` permission, or have host permissions that match `Tab.url`. + Access to these properties by host permissions is supported since Firefox 86 and Chrome 50. In Firefox 85 and earlier, the "tabs" permission was required instead. * To use `tabs.executeScript()` or `tabs.insertCSS()`, you must have the host permission for the tab Alternatively, you can get these permissions temporarily, only for the currently active tab and only in response to an explicit user action, by asking for the `"activeTab"` permission. Many tab operations use a Tab `id`. Tab `id`s are guaranteed to be unique to a single tab only within a browser session. If the browser is restarted, then it can and will reuse tab `id`s. To associate information with a tab across browser restarts, use `sessions.setTabValue()`. Types ----- `tabs.MutedInfoReason` Specifies the reason a tab was muted or unmuted. `tabs.MutedInfo` This object contains a boolean indicating whether the tab is muted, and the reason for the last state change. `tabs.PageSettings` Used to control how a tab is rendered as a PDF by the `tabs.saveAsPDF()` method. `tabs.Tab` This type contains information about a tab. `tabs.TabStatus` Indicates whether the tab has finished loading. `tabs.WindowType` The type of window that hosts this tab. `tabs.ZoomSettingsMode` Defines whether zoom changes are handled by the browser, by the extension, or are disabled. `tabs.ZoomSettingsScope` Defines whether zoom changes will persist for the page's origin, or only take effect in this tab. `tabs.ZoomSettings` Defines zoom settings `mode`, `scope`, and default zoom factor. Properties ---------- `tabs.TAB_ID_NONE` A special ID value given to tabs that are not browser tabs (for example, tabs in devtools windows). Functions --------- `tabs.captureTab()` Creates a data URL encoding an image of the visible area of the given tab. `tabs.captureVisibleTab()` Creates a data URL encoding an image of the visible area of the currently active tab in the specified window. `tabs.connect()` Sets up a messaging connection between the extension's background scripts (or other privileged scripts, such as popup scripts or options page scripts) and any content scripts running in the specified tab. `tabs.create()` Creates a new tab. `tabs.detectLanguage()` Detects the primary language of the content in a tab. `tabs.discard()` Discards one or more tabs. `tabs.duplicate()` Duplicates a tab. `tabs.executeScript()` (Manifest V2 only) Injects JavaScript code into a page. `tabs.get()` Retrieves details about the specified tab. `tabs.getAllInWindow()` Deprecated Gets details about all tabs in the specified window. `tabs.getCurrent()` Gets information about the tab that this script is running in, as a `tabs.Tab` object. `tabs.getSelected()` Deprecated Gets the tab that is selected in the specified window. **Deprecated: use `tabs.query({active: true})` instead.** `tabs.getZoom()` Gets the current zoom factor of the specified tab. `tabs.getZoomSettings()` Gets the current zoom settings for the specified tab. `tabs.goForward()` Go forward to the next page, if one is available. `tabs.goBack()` Go back to the previous page, if one is available. `tabs.hide()` Experimental Hides one or more tabs. `tabs.highlight()` Highlights one or more tabs. `tabs.insertCSS()` (Manifest V2 only) Injects CSS into a page. `tabs.move()` Moves one or more tabs to a new position in the same window or to a different window. `tabs.moveInSuccession()` Modifies the succession relationship for a group of tabs. `tabs.print()` Prints the contents of the active tab. `tabs.printPreview()` Opens print preview for the active tab. `tabs.query()` Gets all tabs that have the specified properties, or all tabs if no properties are specified. `tabs.reload()` Reload a tab, optionally bypassing the local web cache. `tabs.remove()` Closes one or more tabs. `tabs.removeCSS()` (Manifest V2 only) Removes from a page CSS which was previously injected by calling `tabs.insertCSS()`. `tabs.saveAsPDF()` Saves the current page as a PDF. `tabs.sendMessage()` Sends a single message to the content script(s) in the specified tab. `tabs.sendRequest()` Deprecated Sends a single request to the content script(s) in the specified tab. **Deprecated**: use `tabs.sendMessage()` instead. `tabs.setZoom()` Zooms the specified tab. `tabs.setZoomSettings()` Sets the zoom settings for the specified tab. `tabs.show()` Experimental Shows one or more tabs that have been `hidden`. `tabs.toggleReaderMode()` Toggles Reader mode for the specified tab. `tabs.update()` Navigate the tab to a new URL, or modify other properties of the tab. `tabs.warmup()` Prepare the tab to make a potential following switch faster. Events ------ `tabs.onActivated` Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired. `tabs.onActiveChanged` Deprecated Fires when the selected tab in a window changes. **Deprecated:** use `tabs.onActivated` instead. `tabs.onAttached` Fired when a tab is attached to a window, for example because it was moved between windows. `tabs.onCreated` Fired when a tab is created. Note that the tab's URL may not be set at the time this event fired. `tabs.onDetached` Fired when a tab is detached from a window, for example because it is being moved between windows. `tabs.onHighlightChanged` Deprecated Fired when the highlighted or selected tabs in a window change. **Deprecated:** use `tabs.onHighlighted` instead. `tabs.onHighlighted` Fired when the highlighted or selected tabs in a window change. `tabs.onMoved` Fired when a tab is moved within a window. `tabs.onRemoved` Fired when a tab is closed. `tabs.onReplaced` Fired when a tab is replaced with another tab due to prerendering. `tabs.onSelectionChanged` Deprecated Fires when the selected tab in a window changes. **Deprecated:** use `tabs.onActivated` instead. `tabs.onUpdated` Fired when a tab is updated. `tabs.onZoomChange` Fired when a tab is zoomed. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * annotate-page * apply-css * beastify * bookmark-it * chill-out * commands * context-menu-copy-link-with-types * contextual-identities * cookie-bg-picker * devtools-panels * find-across-tabs * firefox-code-search * history-deleter * imagify * list-cookies * menu-demo * menu-labelled-open * menu-remove-element * open-my-page-button * permissions * session-state * store-collected-images * tabs-tabs-tabs **Note:** This API is based on Chromium's `chrome.tabs` API. This documentation is derived from `tabs.json` in the Chromium code.
bookmarks - Mozilla
bookmarks ========= The WebExtensions `bookmarks` API lets an extension interact with and manipulate the browser's bookmarking system. You can use it to bookmark pages, retrieve existing bookmarks, and edit, remove, and organize bookmarks. To use this API, an extension must request the "bookmarks" permission in its `manifest.json` file. Extensions cannot create, modify, or delete bookmarks in the root node of the bookmarks tree. Doing so causes an error with the message: "*The bookmark root cannot be modified*" Types ----- `bookmarks.BookmarkTreeNode` Represents a bookmark or folder in the bookmarks tree. `bookmarks.BookmarkTreeNodeType` A `String` enum which describes whether a node in the tree is a bookmark, a folder, or a separator. `bookmarks.BookmarkTreeNodeUnmodifiable` A `String` enum which specifies why a bookmark or folder is unmodifiable. `bookmarks.CreateDetails` Contains information which is passed to the `bookmarks.create()` function when creating a new bookmark. Functions --------- `bookmarks.create()` Creates a bookmark or folder. `bookmarks.get()` Retrieves one or more `BookmarkTreeNode`s, given a bookmark's ID or an array of bookmark IDs. `bookmarks.getChildren()` Retrieves the children of the specified `BookmarkTreeNode`. `bookmarks.getRecent()` Retrieves a requested number of recently added bookmarks. `bookmarks.getSubTree()` Retrieves part of the bookmarks tree, starting at the specified node. `bookmarks.getTree()` Retrieves the entire bookmarks tree into an array of `BookmarkTreeNode` objects. `bookmarks.move()` Moves the specified `BookmarkTreeNode` to a new location in the bookmark tree. `bookmarks.remove()` Removes a bookmark or an empty bookmark folder, given the node's ID. `bookmarks.removeTree()` Recursively removes a bookmark folder; that is, given the ID of a folder node, removes that node and all its descendants. `bookmarks.search()` Searches for `BookmarkTreeNode`s matching a specified set of criteria. `bookmarks.update()` Updates the title and/or URL of a bookmark, or the name of a bookmark folder, given the bookmark's ID. Events ------ `bookmarks.onCreated` Fired when a bookmark or folder is created. `bookmarks.onRemoved` Fired when a bookmark or folder is removed. When a folder is removed recursively, a single notification is fired for the folder, and none for its contents. `bookmarks.onChanged` Fired when a bookmark or folder changes. Currently, only `title` and `url` changes trigger this. `bookmarks.onMoved` Fired when a bookmark or folder is moved to a different parent folder or to a new offset within its folder. `bookmarks.onChildrenReordered` Fired when the user has sorted the children of a folder in the browser's UI. This is not called as a result of a `move()`. `bookmarks.onImportBegan` Fired when a bookmark import session is begun. Expensive observers should ignore `bookmarks.onCreated` updates until `bookmarks.onImportEnded` is fired. Observers should still handle other notifications immediately. `bookmarks.onImportEnded` Fired when a bookmark import session has finished. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * bookmark-it **Note:** This API is based on Chromium's `chrome.bookmarks` API. This documentation is derived from `bookmarks.json` in the Chromium code.
cookies - Mozilla
cookies ======= Enables extensions to get and set cookies, and be notified when they change. Permissions ----------- To use this API, an add-on must specify the "cookies" API permission in its manifest.json file, along with host permissions for any sites for which it wishes to access cookies. The add-on may read or write any cookies which could be read or written by a URL matching the host permissions. For example: `http://*.example.com/` An add-on with this host permission may: * Read a non-secure cookie for `www.example.com`, with any path. * Write a secure or non-secure cookie for `www.example.com`, with any path. It may *not*: * Read a secure cookie for `www.example.com`. `http://www.example.com/` An add-on with this host permission may: * Read a non-secure cookie for `www.example.com`, with any path. * Read a non-secure cookie for `.example.com`, with any path. * Write a secure or non-secure cookie for `www.example.com` with any path. * Write a secure or non-secure cookie for `.example.com` with any path. It may *not*: * Read or write a cookie for `foo.example.com`. * Read or write a cookie for `foo.www.example.com`. `*://*.example.com/` An add-on with this host permission may: * Read or write a secure or non-secure cookie for `www.example.com` with any path. Tracking protection ------------------- Trackers use third-party cookies, that is, cookies set by a website other than the one you are on, to identify the websites you visit. For example: 1. You visit `a-shopping-site.com`, which uses `ad-tracker.com` to deliver its adverts on the web. `ad-tracker.com` sets a cookie associated with the `ad-tracker.com` domain. While you are on `a-shopping-site.com`, `ad-tracker.com` receives information about the products you browse. 2. You now visit `a-news-site.com` that uses `ad-tracker.com` to deliver adverts. `ad-tracker.com` read its cookie and use the information collected from `a-shopping-site.com` to decide which adverts to display to you. Firefox includes features to prevent tracking. These features separate cookies so that trackers cannot make an association between websites visited. So, in the preceding example, `ad-tracker.com` cannot see the cookie created on `a-news-site.com` when visiting `a-shopping-site.com`. The first iteration of this protection was first-party isolation which is now being superseded by dynamic partitioning. **Note:** First-party isolation and dynamic partitioning will not be active at the same time. If the user or an extension turns on first-party isolation, it takes precedence over dynamic partitioning. However, when private browsing uses dynamic partitioning, normal browsing may not be partitioning cookies. See Status of partitioning in Firefox, for details. ### Storage partitioning When using dynamic partitioning, Firefox partitions the storage accessible to JavaScript APIs by top-level site while providing appropriate access to unpartitioned storage to enable common use cases. This feature is being rolled out progressively. See Status of partitioning in Firefox, for implementation details. Storage partitions are keyed by the schemeful URL of the top-level website and, when dynamic partitioning is active, the key value is available through the `partitionKey.topLevelSite` property in the cookies API, for example, `partitionKey: {topLevelSite: "http://site"}`. Generally, top-level documents are in unpartitioned storage, while third-party iframes are in partitioned storage. If a partition key cannot be determined, the default (unpartitioned storage) is used. For example, while all HTTP(S) sites can be used as a partition key, `moz-extension:-` URLs cannot. Therefore, iframes in Firefox's extension documents do not use partitioned storage. By default, `cookies.get()`, `cookies.getAll()`, `cookies.set()`, and `cookies.remove()` work with cookies in unpartitioned storage. To work with cookies in partitioned storage in these APIs, `topLevelSite` in `partitionKey` must be set. The exception is `getAll` where setting `partitionKey` without `topLevelSite` returns cookies in partitioned and unpartitioned storage. `cookies.onChanged` fires for any cookie that the extension can access, including cookies in partitioned storage. To ensure that the correct cookie is modified, extensions should read the `cookie.partitionKey` property from the event and pass its value to `cookies.set()` and `cookies.remove()`. ### First-party isolation When first-party isolation is on, cookies are qualified by the domain of the original page the user visited (essentially, the domain shown to the user in the URL bar, also known as the "first party domain"). First-party isolation can be enabled by the user by adjusting the browser's configuration and set by extensions using the `firstPartyIsolate` setting in the `privacy` API. Note that first-party isolation is enabled by default in Tor Browser. In the `cookies` API, the first party domain is represented using the `firstPartyDomain` attribute. All cookies set while first-party isolation is on have this attribute set to the domain of the original page. In the preceding example, this is `a-shopping-site.com` for one cookie and `a-news-site.com` for the other. When first-party isolation is off, all cookies set by websites have this property set to an empty string. The `cookies.get()`, `cookies.getAll()`, `cookies.set()` and `cookies.remove()` APIs all accept a `firstPartyDomain` option. When first-party isolation is on, you must provide this option or the API call will fail and return a rejected promise. For `get()`, `set()`, and `remove()` you must pass a string value. For `getAll()`, you may also pass `null` here, and this will get all cookies, whether or not they have a non-empty value for `firstPartyDomain`. When first-party isolation is off, the `firstPartyDomain` parameter is optional and defaults to an empty string. A non-empty string can be used to retrieve or modify first-party isolation cookies. Likewise, passing `null` as `firstPartyDomain` to `getAll()` will return all cookies. Types ----- `cookies.Cookie` Represents information about an HTTP cookie. `cookies.CookieStore` Represents a cookie store in the browser. `cookies.OnChangedCause` Represents the reason a cookie changed. `cookies.SameSiteStatus` Represents the same-site status of the cookie. Methods ------- `cookies.get()` Retrieves information about a single cookie. `cookies.getAll()` Retrieves all cookies that match a given set of filters. `cookies.set()` Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. `cookies.remove()` Deletes a cookie by name. `cookies.getAllCookieStores()` Lists all existing cookie stores. Event handlers -------------- `cookies.onChanged` Fired when a cookie is set or removed. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * cookie-bg-picker * list-cookies **Note:** This API is based on Chromium's `chrome.cookies` API. This documentation is derived from `cookies.json` in the Chromium code.
storage - Mozilla
storage ======= Enables extensions to store and retrieve data, and listen for changes to stored items. The storage system is based on the Web Storage API, with a few differences. Among other differences, these include: * It's asynchronous. * Values are scoped to the extension, not to a specific domain (i.e. the same set of key/value pairs are available to all scripts in the background context and content scripts). * The values stored can be any JSON-ifiable value, not just `String`. Among other things, this includes: `Array` and `Object`, but only when their contents can be represented as JSON, which does not include DOM nodes. You don't need to convert your values to JSON `Strings` prior to storing them, but they are represented as JSON internally, thus the requirement that they be JSON-ifiable. * Multiple key/value pairs can be set or retrieved in the same API call. To use this API you need to include the `"storage"` permission in your `manifest.json` file. Each extension has its own storage area, which can be split into different types of storage. Although this API is similar to `Window.localStorage` it is recommended that you don't use `Window.localStorage` in the extension code to store extension-related data. Firefox will clear data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons, while data saved using the `storage.local` API will be correctly persisted in these scenarios. You can examine the stored data under the Extension Storage item in the Storage Inspector tab of the developer toolbox, accessible from `about:debugging`. **Note:** The storage area is not encrypted and shouldn't be used for storing confidential user information. Types ----- `storage.StorageArea` An object representing a storage area. `storage.StorageChange` An object representing a change to a storage area. Properties ---------- `storage` has four properties, which represent the different types of available storage area. `storage.local` Represents the `local` storage area. Items in `local` storage are local to the machine the extension was installed on. `storage.managed` Represents the `managed` storage area. Items in `managed` storage are set by the domain administrator and are read-only for the extension. Trying to modify this namespace results in an error. `storage.session` Represents the `session` storage area. Items in `session` storage are stored in memory and are not persisted to disk. `storage.sync` Represents the `sync` storage area. Items in `sync` storage are synced by the browser, and are available across all instances of that browser that the user is logged into, across different devices. Events ------ `storage.onChanged` Fired when one or more items change in any of the storage areas. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * annotate-page * favourite-colour * forget-it * navigation-stats * proxy-blocker * quicknote * stored-credentials **Note:** This API is based on Chromium's `chrome.storage` API. This documentation is derived from `storage.json` in the Chromium code.
notifications - Mozilla
notifications ============= Display notifications to the user, using the underlying operating system's notification mechanism. Because this API uses the operating system's notification mechanism, the details of how notifications appear and behave may differ according to the operating system and the user's settings. To use this API you need to have the "notifications" permission. The notification looks the same on all desktop operating systems. Something like: ![Example notification with a bold title and regular text](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications/notification.png) Types ----- `notifications.NotificationOptions` Defines the content of a notification. `notifications.TemplateType` The type of notification. For example, this defines whether the notification can contain an image. Functions --------- `notifications.clear()` Clear a specific notification, given its ID. `notifications.create()` Create and display a new notification. `notifications.getAll()` Get all notifications. `notifications.update()` Update a notification. Events ------ `notifications.onButtonClicked` Fired when the user clicked a button in the notification. `notifications.onClicked` Fired when the user clicked the notification, but not on a button. `notifications.onClosed` Fired when a notification closed, either by the system or because the user dismissed it. `notifications.onShown` Fired immediately after a notification has been shown. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * export-helpers * forget-it * google-userinfo * notify-link-clicks-i18n * runtime-examples **Note:** This API is based on Chromium's `chrome.notifications` API.
privacy - Mozilla
privacy ======= Access and modify various privacy-related browser settings. To use the privacy API, you must have the "privacy" API permission. Properties ---------- `privacy.network` Access and modify privacy settings relating to the network. `privacy.services` Access and modify privacy settings relating to the services provided by the browser or third parties. `privacy.websites` Access and modify privacy settings relating to the behavior of websites. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. **Note:** This API is based on Chromium's `chrome.privacy` API.
dom - Mozilla
dom === Access special extension only DOM features. Functions --------- `dom.openOrClosedShadowRoot()` Gets the open shadow root or the closed shadow root hosted by the specified element. If the shadow root isn't attached to the element, it will return `null`. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
proxy - Mozilla
proxy ===== Use the proxy API to proxy web requests. You can use the `proxy.onRequest` event listener to intercept web requests, and return an object that describes whether and how to proxy them. The advantage of the `proxy.onRequest` approach is that the code that implements your proxy policy runs in your extension's background script, so it gets full access to the WebExtension APIs available to your extension (including, for example, access to your extension's `storage` and networking APIs like `dns`). Apart from this API, extensions can also use the `browserSettings.proxyConfig` property to configure global proxy settings. Google Chrome provides an extension API also called "proxy" which is functionally similar to this API, in that extensions can use it to implement a proxying policy. However, the design of the Chrome API is completely different to this API. Because this API is incompatible with the Chrome `proxy` API, this API is only available through the `browser` namespace. To use this API you need to have the "proxy" permission. Also, where you want to intercept requests, you also need host permission for the URLs of intercepted requests. **Note:** The "proxy" permission requires `"strict_min_version"` to be set to "91.1.0" or above. To use this permission, add or update the `"browser_specific_settings"` key in your manifest.json to specify a minimum Firefox version. See Securing the proxy API for Firefox add-ons for more information. **Note:** The browser can make speculative connections, where it determines that a request to a URI may be coming soon. This type of connection does not provide valid tab information, so request details such as `tabId`, `frameId`, `parentFrameId`, etc. are inaccurate. These connections have a `webRequest.ResourceType` of `speculative`. Types ----- `proxy.ProxyInfo` Describes a proxy. `proxy.RequestDetails` Contains information about a web request that the browser is about to make. Properties ---------- `proxy.settings` Get and set proxy settings. Events ------ `proxy.onError` Fired when the system encounters an error running the PAC script or the `onRequest` listener. `proxy.onRequest` Fired when a web request is about to be made, giving the extension an opportunity to proxy it. Example extensions ------------------ * proxy-blocker Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
sidebarAction - Mozilla
sidebarAction ============= Gets and sets properties of an extension's sidebar. A sidebar is a pane that is displayed at the left-hand or right-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. Using the `sidebar_action` manifest.json key, an extension can define its own sidebar. Using the `sidebarAction` API described here, an extension can get and set the sidebar's properties. The `sidebarAction` API is closely modeled on the `browserAction` API. The sidebarAction API is based on Opera's sidebarAction API. However, note that the following are not yet supported: `setBadgeText()`, `getBadgeText()`, `setBadgeBackgroundColor()`, `getBadgeBackgroundColor()`, `onFocus`, `onBlur`. Types ----- `sidebarAction.ImageDataType` Pixel data for an image. Must be an `ImageData` object (for example, from a `<canvas>` element). Functions --------- `sidebarAction.close()` Closes the sidebar. `sidebarAction.getPanel()` Gets the sidebar's panel. `sidebarAction.getTitle()` Gets the sidebar's title. `sidebarAction.isOpen()` Checks whether the sidebar is open or not. `sidebarAction.open()` Opens the sidebar. `sidebarAction.setIcon()` Sets the sidebar's icon. `sidebarAction.setPanel()` Sets the sidebar's panel. `sidebarAction.setTitle()` Sets the sidebar's title. This will be displayed in any UI provided by the browser to list sidebars, such as a menu. `sidebarAction.toggle()` Toggles the visibility of the sidebar. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example add-ons --------------- * annotate-page **Note:** This API is based on Opera's `chrome.sidebarAction` API.
userScripts - Mozilla
userScripts =========== Use this API to register user scripts, third-party scripts designed to manipulate webpages or provide new features. Registering a user script instructs the browser to attach the script to pages that match the URL patterns specified during registration. **Note:** When using Manifest V3 or higher, use `scripting.registerContentScripts()` to register scripts. This API offers similar capabilities to `contentScripts` but with features suited to handling third-party scripts: * execution is in an isolated sandbox: each user script is run in an isolated sandbox within the web content processes, preventing accidental or deliberate interference among scripts. * access to the `window` and `document` global values related to the webpage the user script is attached to. * no access to WebExtension APIs or associated permissions granted to the extension: the API script, which inherits the extension's permissions, can provide packaged WebExtension APIs to registered user scripts. An API script is declared in the extension's manifest file using the "user\_scripts" manifest key. **Warning:** This API requires the presence of the `user_scripts` key in the manifest.json, even if no API script is specified. For example. `user_scripts: {}`. To use the API, call ``register()`` passing in an object defining the scripts to register. The method returns a Promise that is resolved with a ``RegisteredUserScript`` object. **Note:** User scripts are unregistered when the related extension page (from which the user scripts were registered) is unloaded, so you should register a user script from an extension page that persists at least as long as you want the user scripts to stay registered. Types ----- `userScripts.RegisteredUserScript` The `object` returned by the `register()` method. It represents the registered user scripts and is used to deregister the user scripts. Methods ------- `userScripts.register()` Registers user scripts. Events ------ `userScripts.onBeforeScript` An event available to the API script, registered in`"user_scripts"`, that execute before a user script executes. Use it to trigger the export of the additional APIs provided by the API script, so they are available to the user script. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * Working with `userScripts` * `browser.contentScripts`
contextualIdentities - Mozilla
contextualIdentities ==================== Work with contextual identities: list, create, remove, and update contextual identities. "Contextual identities", also known as "containers", are a browser feature that lets users assume multiple identities when browsing the web, and maintain some separation between these identities. For example, a user might consider their "work identity" separate from their "personal identity", and not want to share cookies between these two contexts. With the contextual identities feature, each contextual identity has a name, a color, and an icon. New tabs can be assigned to an identity, and the name, icon, and color appears in the address bar. Internally, each identity gets a cookie store that is not shared with other tabs. This cookie store is identified by the `cookieStoreId` in this and other APIs. ![A context menu with "open in new container tab" submenu highlighted. The submenu shows personal, work, banking, and shopping contextual identities.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/contextualIdentities/containers.png)Contextual identities are an experimental feature in Firefox and are only enabled by default in Firefox Nightly. To enable them in other versions of Firefox, set the `privacy.userContext.enabled` preference to `true`. Note that although contextual identities are available in Firefox for Android, there's no UI to work with them in this version of the browser. Before Firefox 57, the `contextualIdentities` API is only available if the contextual identities feature is itself enabled. If an extension tried to use the `contextualIdentities` API without the feature being enabled, then method calls would resolve their promises with `false`. From Firefox 57 onwards, if an extension that uses the `contextualIdentities` API is installed, then the contextual identities feature will be enabled automatically. Note though that it's still possible for the user to disable the feature using the "privacy.userContext.enabled" preference. If this happens, then `contextualIdentities` method calls will reject their promises with an error message. See Work with contextual identities for more information. Contextual identities are not supported in any other browsers. To use this API you need to include the "contextualIdentities" and "cookies" permissions in your manifest.json file. Types ----- `contextualIdentities.ContextualIdentity` Contains information about a contextual identity. Functions --------- `contextualIdentities.create()` Creates a new contextual identity. `contextualIdentities.get()` Retrieves a contextual identity, given its cookie store ID. `contextualIdentities.move()` Moves one or more contextual identities within the list of contextual identities. `contextualIdentities.query()` Retrieves all contextual identities, or all contextual identities with a particular name. `contextualIdentities.update()` Updates properties of an existing contextual identity. `contextualIdentities.remove()` Deletes a contextual identity. Events ------ `contextualIdentities.onCreated` Fired when a contextual identity is created. `contextualIdentities.onRemoved` Fired when a contextual identity is removed. `contextualIdentities.onUpdated` Fired when one or more properties of a contextual identity is updated. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * contextual-identities
runtime - Mozilla
runtime ======= This module provides information about your extension and the environment it's running in. It also provides messaging APIs enabling you to: * Communicate between different parts of your extension. For advice on choosing between the messaging options, see Choosing between one-off messages and connection-based messaging. * Communicate with other extensions. * Communicate with native applications. Types ----- `runtime.Port` Represents one end of a connection between two specific contexts, which can be used to exchange messages. `runtime.MessageSender` Contains information about the sender of a message or connection request. `runtime.PlatformOs` Identifies the browser's operating system. `runtime.PlatformArch` Identifies the browser's processor architecture. `runtime.PlatformInfo` Contains information about the platform the browser is running on. `runtime.RequestUpdateCheckStatus` Result of a call to `runtime.requestUpdateCheck()`. `runtime.OnInstalledReason` The reason that the `runtime.onInstalled` event is being dispatched. `runtime.OnRestartRequiredReason` The reason that the `runtime.onRestartRequired` event is being dispatched. Properties ---------- `runtime.lastError` This value is set when an asynchronous function has an error condition that it needs to report to its caller. `runtime.id` The ID of the extension. Functions --------- `runtime.getBackgroundPage()` Retrieves the Window object for the background page running inside the current extension. `runtime.openOptionsPage()` Opens your extension's options page. `runtime.getFrameId()` Gets the frame ID of any window global or frame element. `runtime.getManifest()` Gets the complete manifest.json file, serialized as an object. `runtime.getURL()` Given a relative path from the manifest.json to a resource packaged with the extension, returns a fully-qualified URL. `runtime.setUninstallURL()` Sets a URL to be visited when the extension is uninstalled. `runtime.reload()` Reloads the extension. `runtime.requestUpdateCheck()` Checks for updates to this extension. `runtime.connect()` Establishes a connection from a content script to the main extension process, or from one extension to a different extension. `runtime.connectNative()` Connects the extension to a native application on the user's computer. `runtime.sendMessage()` Sends a single message to event listeners within your extension or a different extension. Similar to `runtime.connect` but only sends a single message, with an optional response. `runtime.sendNativeMessage()` Sends a single message from an extension to a native application. `runtime.getPlatformInfo()` Returns information about the current platform. `runtime.getBrowserInfo()` Returns information about the browser in which this extension is installed. `runtime.getPackageDirectoryEntry()` Returns a DirectoryEntry for the package directory. Events ------ `runtime.onStartup` Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started. `runtime.onInstalled` Fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version. `runtime.onSuspend` Sent to the event page just before the extension is unloaded. This gives the extension an opportunity to do some cleanup. `runtime.onSuspendCanceled` Sent after `runtime.onSuspend` to indicate that the extension won't be unloaded after all. `runtime.onUpdateAvailable` Fired when an update is available, but isn't installed immediately because the extension is currently running. `runtime.onBrowserUpdateAvailable` Deprecated Fired when an update for the browser is available, but isn't installed immediately because a browser restart is required. `runtime.onConnect` Fired when a connection is made with either an extension process or a content script. `runtime.onConnectExternal` Fired when a connection is made with another extension. `runtime.onMessage` Fired when a message is sent from either an extension process or a content script. `runtime.onMessageExternal` Fired when a message is sent from another extension. Cannot be used in a content script. `runtime.onRestartRequired` Fired when the device needs to be restarted. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * beastify * content-script-register * cookie-bg-picker * devtools-panels * export-helpers * favourite-colour * find-across-tabs * imagify * menu-demo * mocha-client-tests * native-messaging * notify-link-clicks-i18n * permissions * runtime-examples * store-collected-images * user-script-register * webpack-modules **Note:** This API is based on Chromium's `chrome.runtime` API. This documentation is derived from `runtime.json` in the Chromium code.
browserAction - Mozilla
browserAction ============= Adds a button to the browser's toolbar. A browser action is a button in the browser's toolbar. You can associate a popup with the button. Like a web page, the popup is specified using HTML, CSS, and JavaScript. JavaScript running in the popup gets access to all the same WebExtension APIs as your background scripts, but its global context is the popup, not the current page displayed in the browser. To affect web pages, you need to communicate with them via messages. If you specify a popup, it is shown — and the content loaded — when the user clicks the icon. If you do not specify a popup, an event is dispatched to your extension when the user clicks the icon. The button also has a context menu, and you can add items to this menu with the `menus` API using the `browser_action` `menus.ContextType`. You can define most of a browser action's properties declaratively using the `browser_action` key in the manifest.json. With the `browserAction` API, you can: * use `browserAction.onClicked` to listen for clicks on the icon. * get and set the icon's properties — icon, title, popup, and so on. You can get and set these globally across all tabs or for a tab by passing the tab ID as an additional argument. Types ----- `browserAction.ColorArray` An array of four integers in the range 0-255 defining an RGBA color. `browserAction.ImageDataType` Pixel data for an image. Must be an `ImageData` object (for example, from a `<canvas>` element). Functions --------- `browserAction.setTitle()` Sets the browser action's title. This will be displayed in a tooltip. `browserAction.getTitle()` Gets the browser action's title. `browserAction.setIcon()` Sets the browser action's icon. `browserAction.setPopup()` Sets the HTML document to be opened as a popup when the user clicks on the browser action's icon. `browserAction.getPopup()` Gets the HTML document set as the browser action's popup. `browserAction.openPopup()` Open the browser action's popup. `browserAction.setBadgeText()` Sets the browser action's badge text. The badge is displayed on top of the icon. `browserAction.getBadgeText()` Gets the browser action's badge text. `browserAction.setBadgeBackgroundColor()` Sets the badge's background color. `browserAction.getBadgeBackgroundColor()` Gets the badge's background color. `browserAction.setBadgeTextColor()` Sets the badge's text color. `browserAction.getBadgeTextColor()` Gets the badge's text color. `browserAction.enable()` Enables the browser action for a tab. By default, browser actions are enabled for all tabs. `browserAction.disable()` Disables the browser action for a tab, meaning that it cannot be clicked when that tab is active. `browserAction.isEnabled()` Checks whether the browser action is enabled or not. Events ------ `browserAction.onClicked` Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * bookmark-it * favourite-colour * find-across-tabs * forget-it * google-userinfo * native-messaging * open-my-page-button * permissions * runtime-examples * store-collected-images * tabs-tabs-tabs **Note:** This API is based on Chromium's `chrome.browserAction` API. This documentation is derived from `browser_action.json` in the Chromium code.
permissions - Mozilla
permissions =========== Enables extensions to request extra permissions at runtime, after they have been installed. Extensions need permissions to access more powerful WebExtension APIs. They can ask for permissions at install time, by including the permissions they need in the `permissions` manifest.json key. The main advantages of asking for permissions at install time are: * The user is only asked once, so it's less disruptive for them, and a simpler decision. * The extension can rely on the access to the APIs it needs, because if already running, the permissions have been granted. In most major browsers, users can see if their installed extensions request advanced permissions through the browser's extensions manager. With the permissions API, an extension can ask for additional permissions at runtime. These permissions need to be listed in the `optional_permissions` manifest.json key. Note that some permissions are not allowed in `optional_permissions`. The main advantages of this are: * The extension can run with a smaller set of permissions, except when it actually needs them. * The extension can handle permission denial in a graceful manner, instead of presenting the user with a global "all or nothing" choice at install time. You can still get a lot out of that map extension, without giving it access to your location, for example. * The extension may need host permissions, but not know at install time which host permissions it needs. For example, the list of hosts may be a user setting. In this scenario, asking for a more specific range of hosts at runtime, can be an alternative to asking for "<all\_urls>" at install time. To use the permissions API, decide which permissions your extension can request at runtime, and list them in `optional_permissions`. After this, you can request any permissions that were included in `optional_permissions`. Requests may only be made in the handler for a user action (for example, a click handler). Starting with Firefox 84, users will be able to manage optional permissions of installed extensions from the Add-ons Manager. Extensions that use optional permissions should listen for browser.permissions.onAdded and browser.permissions.onRemoved API events to know when a user grants or revokes these permissions. For advice on designing your request for runtime permissions, to maximize the likelihood that users grant them, see Request permissions at runtime. Types ----- `permissions.Permissions` Represents a set of permissions. Methods ------- `permissions.contains()` Discover an extension's given set of permissions. `permissions.getAll()` Get all the permissions this extension currently has. `permissions.remove()` Give up a set of permissions. `permissions.request()` Ask for a set of permissions. Event handlers -------------- `permissions.onAdded` Fired when a new permission is granted. `permissions.onRemoved` Fired when a permission is removed. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * `manifest.json` `permissions` property * `manifest.json` `optional_permissions` property Example extensions ------------------ * dnr-dynamic-with-options * dnr-redirect-url * permissions **Note:** This API is based on Chromium's `chrome.permissions` API.
declarativeNetRequest - Mozilla
declarativeNetRequest ===================== This API enables extensions to specify conditions and actions that describe how network requests should be handled. These declarative rules enable the browser to evaluate and modify network requests without notifying extensions about individual network requests. Permissions ----------- To use this API, an extension must request the `"declarativeNetRequest"` or `"declarativeNetRequestWithHostAccess"` permission in its `manifest.json` file. The `"declarativeNetRequest"` permission allows extensions to block and upgrade requests without any host permissions. Host permissions are required if the extension wants to redirect requests or modify headers on requests or when the `"declarativeNetRequestWithHostAccess"` permission is used instead of the `"declarativeNetRequest"` permission. To act on requests in these cases, host permissions are required for the request URL. For all requests, except for navigation requests (i.e., resource type `main_frame` and `sub_frame`), host permissions are also required for the request's initiator. The initiator of a request is usually the document or worker that triggered the request. Some requests are restricted and cannot be matched by extensions. These include privileged browser requests, requests to or from restricted domains, and requests from other extensions. The `"declarativeNetRequestFeedback"` permission is required to use `getMatchedRules` and `onRuleMatchedDebug` as they return information on declarative rules matched. See Testing for more information. Rules ----- The declarative rules are defined by four fields: * `id` – An ID that uniquely identifies a rule within a ruleset. Mandatory and should be >= 1. * `priority` – The rule priority. When specified, it should be >= 1. Defaults to 1. See Matching precedents for details on how priority affects which rules are applied. * `condition` – The `condition` under which this rule is triggered. * `action` – The `action` to take when the rule is matched. Rules can do one of these things: + block a network request. + redirect a network request. + modify headers from a network request. + prevent another matching rule from being applied. **Note:** A redirect action does not redirect the request, and the request continues as usual when: * the action does not change the request. * the redirect URL is invalid (e.g., the value of `redirect.regexSubstitution` is not a valid URL). This is an example rule that blocks all script requests originating from `"foo.com"` to any URL with `"abc"` as a substring: ```json { "id": 1, "priority": 1, "action": { "type": "block" }, "condition": { "urlFilter": "abc", "initiatorDomains": ["foo.com"], "resourceTypes": ["script"] } } ``` The `urlFilter` field of a rule condition is used to specify the pattern matched against the request URL. See `RuleCondition` for details. Some examples of URL filters are: | `urlFilter` | Matches | Does not match | | --- | --- | --- | | `"abc"` | https://abcd.comhttps://example.com/abcd | https://ab.com | | `"abc*d"` | https://abcd.comhttps://example.com/abcxyzd | https://abc.com | | `"||a.example.com"` | https://a.example.com/https://b.a.example.com/xyz | https://example.com/ | | `"|https*"` | https://example.com | http://example.com/http://https.com | Rulesets -------- Rules are organized into rulesets: * **static rulesets**: collections of rules defined with the `"declarative_net_request"` manifest key and stored in the extension. An extension can enable and disable static rulesets using `updateEnabledRulesets`. The set of enabled static rulesets is persisted across sessions but not across extension updates. The static rulesets enabled on extension installation and update are determined by the content of the `"declarative_net_request"` manifest key. * **dynamic ruleset**: rules added or removed using `updateDynamicRules`. These rules persist across sessions and extension updates. * **session ruleset**: rules added or removed using `updateSessionRules`. These rules do not persist across browser sessions. **Note:** Errors and warnings about invalid static rules are only displayed during testing. Invalid static rules in permanently installed extensions are ignored. Therefore, it's important to verify that your static rulesets are valid by testing. Limits ------ ### Static ruleset limits An extension can: * specify static rulesets as part of the `"declarative_net_request"` manifest key up to the value of `MAX_NUMBER_OF_STATIC_RULESETS`. * enable static rulesets up to at least the value of `GUARANTEED_MINIMUM_STATIC_RULES`, and the number of enabled static rulesets must not exceed the value of `MAX_NUMBER_OF_ENABLED_STATIC_RULESETS`. In addition, the number of rules in enabled static rulesets for all extensions must not exceed the global limit. Extensions shouldn't depend on the global limit having a specific value and should instead use `getAvailableStaticRuleCount` to find the number of additional rules they can enable. ### Dynamic and session-scoped rules The number of dynamic and session-scoped rules an extension can add is limited to the value of `MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES`. Matching precedents ------------------- When the browser evaluates how to handle requests, it checks each extension's rules that have a condition that matches the request and chooses the one to consider applying as follows: 1. the rule priority, where 1 is the lowest priority (and rules default to 1 where priority is not set). If this doesn't result in one rule to apply: 2. the rule action, in the following order of precedence: 1. "allow" which means any other remaining rules are ignored. 2. "allowAllRequests" (for main\_frame and sub\_frame resourceTypes only) has the same effect as allow but also applies to future subresource loads in the document (including descendant frames) generated from the request. 3. "block" cancels the request. 4. "upgradeScheme" upgrades the scheme of the request. 5. "redirect" redirects the request. 6. "modifyHeaders" rewrites request or response headers or both. **Note:** When multiple matching rules have the same rule priority and rule action type, the outcome can be ambiguous when the matched action support additional properties. These properties can result in outcomes that cannot be combined. For example: * The "block" action does not support additional properties, and therefore there is no ambiguity: all matching "block" actions would result in the same outcome. * The "redirect" action redirects a request to one destination. When multiple "redirect" actions match, all but one "redirect" action is ignored. It is still possible to redirect repeatedly when the redirected request matches another rule condition. * Multiple "modifyHeaders" actions can be applied independently when they touch different headers. The result is ambiguous when they touch the same header, because some combination of operations are not allowed (as explained at `declarativeNetRequest.ModifyHeaderInfo`). The evaluation order of "modifyHeaders" actions is therefore important. To control the order in which actions are applied, assign distinct `priority` values to rules whose order of precedence is important. **Note:** After rule priority and rule action, Firefox considers the ruleset the rule belongs to, in this order of precedence: session > dynamic > session rulesets. This cannot be relied upon across browsers, see WECG issue 280. If only one extension provides a rule for the request, that rule is applied. However, where more than one extension has a matching rule, the browser chooses the one to apply in this order of precedence: 1. "block" 2. "redirect" and "upgradeScheme" 3. "allow" and "allowAllRequests" If the request was not blocked or redirected, the matching `modifyHeaders` actions are applied, as documented in `declarativeNetRequest.ModifyHeaderInfo`. Testing ------- `testMatchOutcome`, `getMatchedRules`, and `onRuleMatchedDebug` are available to assist with testing rules and rulesets. These APIs require the `"declarativeNetRequestFeedback"` permissions. In addition: * in Chrome, these APIs are only available to unpacked extensions. * in Firefox, these APIs are only available after setting the `extensions.dnr.feedback` preference to `true`. Set this preference using `about:config` or the `--pref` flag of the `web-ext` CLI tool. Comparison with the webRequest API ---------------------------------- * The declarativeNetRequest API evaluates network requests in the browser itself. This makes it more performant than the webRequest API, where each network request is evaluated in JavaScript in the extension process. * Because the requests are not intercepted by the extension process, declarativeNetRequest removes the need for extensions to have a background page. * Unlike the webRequest API, blocking or upgrading requests using the declarativeNetRequest API requires no host permissions when used with the `declarativeNetRequest` permission. * The declarativeNetRequest API provides better privacy to users because extensions do not read the network requests made on the user's behalf. * (Chrome only:) Unlike the webRequest API, any images or iframes blocked using the declarativeNetRequest API are automatically collapsed in the DOM. * While deciding whether a request is to be blocked or redirected, the declarativeNetRequest API is given priority over the webRequest API because it allows for synchronous interception. Similarly, any headers removed through declarativeNetRequest API are not made visible to web request extensions. * The webRequest API is more flexible than the declarativeNetRequest API because it allows extensions to evaluate a request programmatically. Types ----- `declarativeNetRequest.MatchedRule` Details of a matched rule. `declarativeNetRequest.ModifyHeaderInfo` The request or response headers to modify for the request. `declarativeNetRequest.Redirect` Details of how the redirect should be performed. Only valid for redirect rules. `declarativeNetRequest.ResourceType` The resource type of a request. `declarativeNetRequest.Rule` An object containing details of a rule. `declarativeNetRequest.RuleAction` An object defining the action to take if a rule is matched. `declarativeNetRequest.RuleCondition` An object defining the condition under which a rule is triggered. `declarativeNetRequest.URLTransform` An object containing details of a URL transformation to perform for a redirect action. Properties ---------- `declarativeNetRequest.DYNAMIC_RULESET_ID` Ruleset ID for the dynamic rules added by the extension. `declarativeNetRequest.GETMATCHEDRULES_QUOTA_INTERVAL` The time interval within which `declarativeNetRequest.MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL` `declarativeNetRequest.getMatchedRules` calls can be made. `declarativeNetRequest.GUARANTEED_MINIMUM_STATIC_RULES` The minimum number of static rules guaranteed to an extension across its enabled static rulesets. `declarativeNetRequest.MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL` The number of times `declarativeNetRequest.getMatchedRules` can be called within a period of `declarativeNetRequest.GETMATCHEDRULES_QUOTA_INTERVAL`. `declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES` The maximum number of combined dynamic and session scoped rules an extension can add. `declarativeNetRequest.MAX_NUMBER_OF_ENABLED_STATIC_RULESETS` The maximum number of static rulesets an extension can enable. `declarativeNetRequest.MAX_NUMBER_OF_REGEX_RULES` The maximum number of regular expression rules that an extension can add. `declarativeNetRequest.MAX_NUMBER_OF_STATIC_RULESETS` The maximum number of static rulesets an extension can specify as part of the `declarative_net_request.rule_resources` manifest key. `declarativeNetRequest.SESSION_RULESET_ID` The ruleset ID for the session-scoped rules added by the extension. Functions --------- `declarativeNetRequest.getAvailableStaticRuleCount()` Returns the number of static rules an extension can enable before the global static rule limit is reached. `declarativeNetRequest.getDynamicRules()` Returns the set of dynamic rules for the extension. `declarativeNetRequest.getEnabledRulesets()` Returns the IDs for the set of enabled static rulesets. `declarativeNetRequest.getMatchedRules()` Returns all the rules matched for the extension. `declarativeNetRequest.getSessionRules()` Returns the set of session scoped rules for the extension. `declarativeNetRequest.isRegexSupported()` Checks if a regular expression is supported as a `declarativeNetRequest.RuleCondition``.regexFilter` rule condition. `declarativeNetRequest.setExtensionActionOptions()` Configures how the action count for tabs are handled. `declarativeNetRequest.testMatchOutcome()` Checks if any of the extension's `declarativeNetRequest` rules would match a hypothetical request. `declarativeNetRequest.updateDynamicRules()` Modifies the active set of dynamic rules for the extension. `declarativeNetRequest.updateEnabledRulesets()` Updates the set of active static rulesets for the extension. `declarativeNetRequest.updateSessionRules()` Modifies the set of session scoped rules for the extension. Events ------ `declarativeNetRequest.onRuleMatchedDebug` Fired when a rule is matched with a request when debugging an extension with the "declarativeNetRequestFeedback" permission. Example extensions ------------------ * dnr-block-only * dnr-dynamic-with-options * dnr-redirect-url Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
idle - Mozilla
idle ==== Find out when the user's system is idle, locked, or active. To use this API you need to have the "idle" permission. Types ----- `idle.IdleState` String describing the device's idle state. Functions --------- `idle.queryState()` Returns `"locked"` if the system is locked, `"idle"` if the user has not generated any input for a specified number of seconds, or `"active"` otherwise. `idle.setDetectionInterval()` Sets the interval used to determine when the system is in an idle state for `idle.onStateChanged` events. Events ------ `idle.onStateChanged` Fired when the system changes state. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. **Note:** This API is based on Chromium's `chrome.idle` API. This documentation is derived from `idle.json` in the Chromium code.
webRequest - Mozilla
webRequest ========== Add event listeners for the various stages of making an HTTP request, which includes websocket requests on `ws://` and `wss://`. The event listener receives detailed information about the request and can modify or cancel the request. Each event is fired at a particular stage of the request. The typical sequence of events is like this: ![Order of requests is onBeforeRequest, onBeforeSendHeader, onSendHeaders, onHeadersReceived, onResponseStarted, and onCompleted. The onHeadersReceived can cause an onBeforeRedirect and an onAuthRequired. Events caused by onHeadersReceived start at the beginning onBeforeRequest. Events caused by onAuthRequired start at onBeforeSendHeader.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/webrequest-flow.png) `onErrorOccurred` can fire at any time during the request. Also, note that sometimes the sequence of events may differ from this. For example, in Firefox, on an HSTS upgrade, the `onBeforeRedirect` event is triggered immediately after `onBeforeRequest`. `onErrorOccurred` is also fired if Firefox Tracking Protection blocks a request. All events – *except* `onErrorOccurred` – can take three arguments to `addListener()`: * the listener itself * a `filter` object, so you can only be notified for requests made to particular URLs or for particular types of resource * an optional `extraInfoSpec` object. You can use this to pass additional event-specific instructions. The listener function is passed a `details` object containing information about the request. This includes a request ID, which is provided to enable an add-on to correlate events associated with a single request. It is unique within a browser session and the add-on's context. It stays the same throughout a request, even across redirections and authentication exchanges. To use the `webRequest` API for a given host, an extension must have the `"webRequest"` API permission and the host permission for that host. To use the `"blocking"` feature, the extension must also have the `"webRequestBlocking"` API permission. To intercept resources loaded by a page (such as images, scripts, or stylesheets), the extension must have the host permission for the resource as well as for the main page requesting the resource. For example, if a page at `https://developer.mozilla.org` loads an image from `https://mdn.mozillademos.org`, then an extension must have both host permissions if it is to intercept the image request. Modifying requests ------------------ On some of these events, you can modify the request. Specifically, you can: * cancel the request in: + `onBeforeRequest` + `onBeforeSendHeaders` + `onAuthRequired` * redirect the request in: + `onBeforeRequest` + `onHeadersReceived` * modify request headers in: + `onBeforeSendHeaders` * modify response headers in: + `onHeadersReceived` * supply authentication credentials in: + `onAuthRequired` To do this, you need to pass an option with the value `"blocking"` in the `extraInfoSpec` argument to the event's `addListener()`. This makes the listener synchronous. In the listener, you can then return a `BlockingResponse` object, which indicates the modification you need to make: for example, the modified request header you want to send. Requests at browser startup --------------------------- When a listener is registered with the `"blocking"` option and is registered during the extension startup, if a request is made during the browser startup that matches the listener the extension starts early. This enables the extension to observe the request at browser startup. If you don't take these steps, requests made at startup could be missed. Speculative requests -------------------- The browser can make speculative connections, where it determines that a request to a URI may be coming soon. This type of connection does not provide valid tab information, so request details such as `tabId`, `frameId`, `parentFrameId`, etc. are inaccurate. These connections have a `webRequest.ResourceType` of `speculative`. Accessing security information ------------------------------ In the `onHeadersReceived` listener you can access the TLS properties of a request by calling `getSecurityInfo()`. To do this you must also pass "blocking" in the `extraInfoSpec` argument to the event's `addListener()`. You can read details of the TLS handshake, but can't modify them or override the browser's trust decisions. Modifying responses ------------------- To modify the HTTP response bodies for a request, call `webRequest.filterResponseData`, passing it the ID of the request. This returns a `webRequest.StreamFilter` object that you can use to examine and modify the data as it is received by the browser. To do this, you must have the `"webRequestBlocking"` API permission as well as the `"webRequest"` API permission and the host permission for the relevant host. Types ----- `webRequest.BlockingResponse` An object of this type is returned by event listeners that have set `"blocking"` in their `extraInfoSpec` argument. By setting particular properties in `BlockingResponse`, the listener can modify network requests. `webRequest.CertificateInfo` An object describing a single X.509 certificate. `webRequest.HttpHeaders` An array of HTTP headers. Each header is represented as an object with two properties: `name` and either `value` or `binaryValue`. `webRequest.RequestFilter` An object describing filters to apply to `webRequest` events. `webRequest.ResourceType` Represents a particular kind of resource fetched in a web request. `webRequest.SecurityInfo` An object describing the security properties of a particular web request. `webRequest.StreamFilter` An object that can be used to monitor and modify HTTP responses while they are being received. `webRequest.UploadData` Contains data uploaded in a URL request. Properties ---------- `webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES` The maximum number of times that `handlerBehaviorChanged()` can be called in a 10 minute period. Methods ------- `webRequest.handlerBehaviorChanged()` This method can be used to ensure that event listeners are applied correctly when pages are in the browser's in-memory cache. `webRequest.filterResponseData()` Returns a `webRequest.StreamFilter` object for a given request. `webRequest.getSecurityInfo()` Gets detailed information about the TLS connection associated with a given request. Events ------ `webRequest.onBeforeRequest` Fired when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel or redirect the request. `webRequest.onBeforeSendHeaders` Fired before sending any HTTP data, but after HTTP headers are available. This is a good place to listen if you want to modify HTTP request headers. `webRequest.onSendHeaders` Fired just before sending headers. If your add-on or some other add-on modified headers in ``onBeforeSendHeaders``, you'll see the modified version here. `webRequest.onHeadersReceived` Fired when the HTTP response headers associated with a request have been received. You can use this event to modify HTTP response headers. `webRequest.onAuthRequired` Fired when the server asks the client to provide authentication credentials. The listener can do nothing, cancel the request, or supply authentication credentials. `webRequest.onResponseStarted` Fired when the first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available. `webRequest.onBeforeRedirect` Fired when a server-initiated redirect is about to occur. `webRequest.onCompleted` Fired when a request is completed. `webRequest.onErrorOccurred` Fired when an error occurs. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Additional notes on Chrome incompatibilities. Example extensions ------------------ * http-response * root-cert-stats * stored-credentials * user-agent-rewriter **Note:** This API is based on Chromium's `chrome.webRequest` API. This documentation is derived from `web_request.json` in the Chromium code.
history - Mozilla
history ======= Use the `history` API to interact with the browser history. If you are looking for information about the browser session history, see the History interface. **Note:** Downloads are treated as `HistoryItem` objects. Therefore, events such as `history.onVisited` fire for downloads. Browser history is a chronological record of pages the user has visited. The history API enables you to: * search for pages that appear in the browser history * remove individual pages from the browser history * add pages to the browser history * remove all pages from the browser history. However, the user may have visited a single page multiple times, so the API also has the concept of "visits". So you can also use this API to: * retrieve the complete set of visits the user made to a particular page * remove visits to any pages made during a given time period. To use this API, an extension must request the "history" permission in its `manifest.json` file. Types ----- `history.TransitionType` Describes how the browser navigated to a particular page. `history.HistoryItem` Provides information about a particular page in the browser history. `history.VisitItem` Describes a single visit to a page. Functions --------- `history.search()` Searches the browser history for `history.HistoryItem` objects matching the given criteria. `history.getVisits()` Retrieves information about visits to a given page. `history.addUrl()` Adds a record to the browser history of a visit to the given page. `history.deleteUrl()` Removes all visits to the given URL from the browser history. `history.deleteRange()` Removes all visits to pages that the user made during the given time range. `history.deleteAll()` Removes all visits from the browser history. Events ------ `history.onTitleChanged` Fired when the title of a page visited by the user is recorded. `history.onVisited` Fired each time the user visits a page, providing the `history.HistoryItem` data for that page. `history.onVisitRemoved` Fired when a URL is removed completely from the browser history. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * history-deleter **Note:** This API is based on Chromium's `chrome.history` API. This documentation is derived from `history.json` in the Chromium code.
theme - Mozilla
theme ===== Enables browser extensions to get details of the browser's theme and update the theme. You can use this API to include a theme in your extension, which you define as a `theme.Theme` and apply using `theme.update()`. You cannot include a static theme in your extension, defined with the "theme" manifest key. The "theme" manifest key is used to define static themes only. See Themes on Extension Workshop for more information. Types ----- `theme.Theme` Represents the content of a theme. Functions --------- `theme.getCurrent()` Gets the current browser theme. `theme.update()` Updates the browser's theme. `theme.reset()` Removes any theme updates made in a call to `theme.update()`. Events ------ `theme.onUpdated` Fired when the browser theme changes. Example extensions ------------------ * dynamic-theme * private-browsing-theme * theme-integrated-sidebar Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
action - Mozilla
action ====== Adds a button to the browser's toolbar. **Note:** This API is available in Manifest V3 or higher. It replaces the Manifest V2 APIs `browserAction` and, in Chrome and Safari, `pageAction`. A browser action is a button in the browser's toolbar. You can associate a popup with the button. Like a web page, the popup is specified using HTML, CSS, and JavaScript. JavaScript running in the popup gets access to all the same WebExtension APIs as your background scripts, but its global context is the popup, not the current page displayed in the browser. To affect web pages, you need to communicate with them via messages. If you specify a popup, it is shown — and the content loaded — when the user clicks the icon. If you do not specify a popup, an event is dispatched to your extension when the user clicks the icon. The button also has a context menu, and you can add items to this menu with the `menus` API using the `action` `menus.ContextType`. You can define most of a browser action's properties declaratively using the `action` key in the manifest.json. With the `action` API, you can: * use `action.onClicked` to listen for clicks on the icon. * get and set the icon's properties — icon, title, popup, and so on. You can get and set these globally across all tabs or for a tab by passing the tab ID as an additional argument. Types ----- `action.ColorArray` An array of four integers in the range 0-255 defining an RGBA color. `action.ImageDataType` Pixel data for an image. Must be an `ImageData` object (for example, from a `<canvas>` element). Functions --------- `action.setTitle()` Sets the browser action's title. This will be displayed in a tooltip. `action.getTitle()` Gets the browser action's title. `action.setIcon()` Sets the browser action's icon. `action.setPopup()` Sets the HTML document to be opened as a popup when the user clicks on the browser action's icon. `action.getPopup()` Gets the HTML document set as the browser action's popup. `action.openPopup()` Open the browser action's popup. `action.setBadgeText()` Sets the browser action's badge text. The badge is displayed on top of the icon. `action.getBadgeText()` Gets the browser action's badge text. `action.setBadgeBackgroundColor()` Sets the badge's background color. `action.getBadgeBackgroundColor()` Gets the badge's background color. `action.setBadgeTextColor()` Sets the badge's text color. `action.getBadgeTextColor()` Gets the badge's text color. `action.getUserSettings()` Gets the user-specified settings for the browser action. `action.enable()` Enables the browser action for a tab. By default, browser actions are enabled for all tabs. `action.disable()` Disables the browser action for a tab, meaning that it cannot be clicked when that tab is active. `action.isEnabled()` Checks whether the browser action is enabled or not. Events ------ `action.onClicked` Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. **Note:** This API is based on Chromium's `chrome.action` API. This documentation is derived from `action.json` in the Chromium code.
downloads - Mozilla
downloads ========= Enables extensions to interact with the browser's download manager. You can use this API module to download files, cancel, pause, resume downloads, and show downloaded files in the file manager. To use this API you need to have the "downloads" API permission specified in your manifest.json file. Types ----- `downloads.FilenameConflictAction` Defines options for what to do if the name of a downloaded file conflicts with an existing file. `downloads.InterruptReason` Defines a set of possible reasons why a download was interrupted. `downloads.DangerType` Defines a set of common warnings of possible dangers associated with downloadable files. `downloads.State` Defines different states that a current download can be in. `downloads.DownloadItem` Represents a downloaded file. `downloads.StringDelta` Represents the difference between two strings. `downloads.DoubleDelta` Represents the difference between two doubles. `downloads.BooleanDelta` Represents the difference between two booleans. `downloads.DownloadTime` Represents the time a download took to complete. `downloads.DownloadQuery` Defines a set of parameters that can be used to search the downloads manager for a specific set of downloads. Functions --------- `downloads.download()` Downloads a file, given its URL and other optional preferences. `downloads.search()` Queries the `DownloadItems` available in the browser's downloads manager, and returns those that match the specified search criteria. `downloads.pause()` Pauses a download. `downloads.resume()` Resumes a paused download. `downloads.cancel()` Cancels a download. `downloads.getFileIcon()` Retrieves an icon for the specified download. `downloads.open()` Opens the downloaded file with its associated application. `downloads.show()` Opens the platform's file manager application to show the downloaded file in its containing folder. `downloads.showDefaultFolder()` Opens the platform's file manager application to show the default downloads folder. `downloads.erase()` Erases matching `DownloadItems` from the browser's download history, without deleting the downloaded files from disk. `downloads.removeFile()` Removes a downloaded file from disk, but not from the browser's download history. `downloads.acceptDanger()` Prompts the user to accept or cancel a dangerous download. `downloads.setShelfEnabled()` Enables or disables the gray shelf at the bottom of every window associated with the current browser profile. The shelf will be disabled as long as at least one extension has disabled it. Events ------ `downloads.onCreated` Fires with the `DownloadItem` object when a download begins. `downloads.onErased` Fires with the `downloadId` when a download is erased from history. `downloads.onChanged` When any of a `DownloadItem`'s properties except `bytesReceived` changes, this event fires with the `downloadId` and an object containing the properties that changed. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * latest-download **Note:** This API is based on Chromium's `chrome.downloads` API.
pkcs11 - Mozilla
pkcs11 ====== The `pkcs11` API enables an extension to enumerate PKCS #11 security modules and to make them accessible to the browser as sources of keys and certificates. To use this API you need to have the "pkcs11" permission. Using the Firefox Preferences Dialog to Install PKCS #11 Modules ---------------------------------------------------------------- Perform the following steps: 1. Save the PKCS #11 module to a permanent location on your local computer 2. Select **Tools > Options** or select the **Firefox menu** and then **Options** 3. Once the Options page opens, select **Privacy & Security** 4. Scroll down to the bottom of the page and under **Certificates** click or tap on **Security Devices…** ![Security modules and devices](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pkcs11/device_manager.png) 5. Click or tap the **Load** button ![Load PKCS#11 device driver](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pkcs11/load_device_driver.png) 6. Enter a name for the security module, such as "*My Client Database*" **Warning:** Be careful about using international characters as there is currently a bug in Firefox where international characters may cause problems. 7. Choose **Browse…** to find the location of the PKCS #11 module on your local computer, and then click or tap **OK** to confirm. Provisioning PKCS #11 modules ----------------------------- **Note:** Starting with Firefox 58, extensions can use this API to enumerate PKCS #11 modules and make them accessible to the browser as sources of keys and certificates. There are two environmental prerequisites for using this **API**: * One or more `PKCS #11` modules must be installed on the user's computer * For each installed `PKCS #11` module, there must be a native manifest file that enables the browser to locate the module. Most probably, the user or device administrator would install the `PKCS #11` module, and its installer would install the native manifest file at the same time. However, the module and manifest can't be installed as part of the extension's own installation process. For details about the manifest file's contents and location, see Native manifests. Functions --------- `pkcs11.getModuleSlots()` For each slot in a module, get its name and whether it contains a token. `pkcs11.installModule()` Installs the named PKCS #11 module. `pkcs11.isModuleInstalled()` Checks whether the named PKCS #11 module is installed. `pkcs11.uninstallModule()` Uninstalls the named PKCS #11 module. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
omnibox - Mozilla
omnibox ======= Enables extensions to implement customized behavior when the user types into the browser's address bar. When the user focuses the browser's address bar and starts typing, the browser displays a drop-down list containing suggested pages based on what they typed. This gives the user a quick way to access, for example, pages from their history or bookmarks. The omnibox API provides the extension a way to customize the suggestions displayed in the drop-down, when the user enters a keyword defined by the extension. It works as follows: 1. First, the extension must include an "omnibox" key in its manifest.json file, which defines a keyword. 2. When the user focuses the address bar and types the keyword followed by a space, the extension gets an `omnibox.onInputStarted` event. 3. Optionally, the extension can call `omnibox.setDefaultSuggestion()` to define the first suggestion displayed in the address bar drop-down. 4. As the user continues to type characters, the extension gets `omnibox.onInputChanged` events. The event listener is passed the value the user has typed and can populate the address bar drop-down with suggestions. If the extension sets a default suggestion using `omnibox.setDefaultSuggestion()`, this suggestion is displayed first in the drop-down. 5. If the user accepts a suggestion, the extension gets an `omnibox.onInputEntered` event. The event listener is passed the accepted suggestion. 6. If the user deletes a suggestion, the extension gets an `omnibox.onDeleteSuggestion` event. 7. If the user dismisses the drop-down, the extension gets an `omnibox.onInputCancelled` event. Types ----- `omnibox.OnInputEnteredDisposition` Describes the recommended method to handle the selected suggestion: open in the current tab, open in a new foreground tab, or open in a new background tab. `omnibox.SuggestResult` An object representing a suggestion to add to the address bar drop-down. Functions --------- `omnibox.setDefaultSuggestion()` Defines the first suggestion displayed in the drop-down when the user enters your extension's keyword followed by a space. Events ------ `omnibox.onDeleteSuggestion` Fired whenever the user deletes a suggestion. `omnibox.onInputStarted` Fired when the user focuses the address bar and types your extension's omnibox keyword, followed by a space. `omnibox.onInputChanged` Fired whenever the user's input changes after they have focused the address bar and typed your extension's keyword followed by a space. `omnibox.onInputEntered` Fired when the user accepts one of your extension's suggestions. `omnibox.onInputCancelled` Fired when the user dismisses the address bar drop-down after they have focused the address bar and typed your extension's keyword followed by a space. Example extensions ------------------ * firefox-code-search Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. **Note:** This API is based on Chromium's `chrome.omnibox` API.
captivePortal - Mozilla
captivePortal ============= Determine the captive portal state of the user's connection. A captive portal is a web page displayed when a user first connects to a Wi-Fi network. The user provides information or acts on the captive portal web page to gain broader access to network resources, such as accepting terms and conditions or making a payment. To use this API you need to have the "captivePortal" permission. Properties ---------- `captivePortal.canonicalURL` Return the canonical URL of the captive-portal detection page. Read-only. Functions --------- `captivePortal.getLastChecked()` Returns the time, in milliseconds, since the last request was completed. `captivePortal.getState()` Returns the portal state as one of `unknown`, `not_captive`, `unlocked_portal`, or `locked_portal`. Events ------ `captivePortal.onConnectivityAvailable` Fires when the captive portal service determines that the user can connect to the internet. `captivePortal.onStateChanged` Fires when the captive portal state changes. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
browsingData - Mozilla
browsingData ============ 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 `browsingData.remove()` function to remove any combination of these types. There are also dedicated functions to remove each particular type of data, such as `removePasswords()`, `removeHistory()` and so on. All the `browsingData.remove[X]()` functions take a `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 `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. Types ----- `browsingData.DataTypeSet` Object used to specify the type of data to remove: for example, history, downloads, passwords, and so on. `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 ------- `browsingData.remove()` Removes browsing data for the data types specified. `browsingData.removeCache()` Clears the browser's cache. `browsingData.removeCookies()` Removes cookies. `browsingData.removeDownloads()` Removes the list of downloaded files. `browsingData.removeFormData()` Clears saved form data. `browsingData.removeHistory()` Clears the browser's history. `browsingData.removeLocalStorage()` Clears any local storage created by websites. `browsingData.removePasswords()` Clears saved passwords. `browsingData.removePluginData()` Clears data associated with plugins. `browsingData.settings()` Gets the current value of settings in the browser's "Clear History" feature. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * forget-it **Note:** This API is based on Chromium's `chrome.browsingData` API.
commands - Mozilla
commands ======== Listen for the user executing commands that you have registered using the `commands` manifest.json key. Types ----- `commands.Command` Object representing a command. This contains the information specified for the command in the `commands` manifest.json key. Functions --------- `commands.getAll` Gets all registered commands for this extension. `commands.reset` Reset the given command's description and shortcut to the values given in the manifest key. `commands.update` Change the description or shortcut for the given command. Events ------ `commands.onChanged` Fired when the keyboard shortcut for a command is changed. `commands.onCommand` Fired when a command is executed using its associated keyboard shortcut. Example extensions ------------------ * commands Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. **Note:** This API is based on Chromium's `chrome.commands` API.
types - Mozilla
types ===== Defines the `BrowserSetting` type, which is used to represent a browser setting. Types ----- `types.BrowserSetting` Represents a browser setting. Browser compatibility --------------------- **Note:** This API is based on Chromium's `chrome.types` API.
topSites - Mozilla
topSites ======== Use the topSites API to get an array containing pages that the user has visited frequently. Browsers maintain this to help the user get back to these places easily. For example, Firefox by default provides a list of the most-visited pages in the "New Tab" page. To use the topSites API you must have the "topSites" API permission. Types ----- `topSites.MostVisitedURL` An object containing the title and URL of a website. Methods ------- `topSites.get()` Gets an array containing all the sites listed in the browser's "New Tab" page. Note that the number of sites returned here is browser-specific, and the particular sites returned will probably be specific to the user, based on their browsing history. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * top-sites **Note:** This API is based on Chromium's `chrome.topSites` API.
scripting - Mozilla
scripting ========= Inserts JavaScript and CSS into websites. This API offers two approaches to inserting content: * `scripting.executeScript()`, `scripting.insertCSS()`, and `scripting.removeCSS()` that provide for one-off injections. * `scripting.registerContentScripts()` that registers content scripts dynamically, which can then be retrieved with `scripting.getRegisteredContentScripts()` and unregistered with `scripting.unregisterContentScripts()`). **Note:** Chrome restricts this API to Manifest V3. Firefox and Safari support this API in Manifest V2 and V3. This API requires the `"scripting"` permission and host permission for the target in the tab into which JavaScript or CSS is injected. Alternatively, you can get permission temporarily in the active tab and only in response to an explicit user action, by asking for the `"activeTab"` permission. However, the `"scripting"` permission is still required. Types ----- `scripting.ContentScriptFilter` Specifies the IDs of scripts to retrieve with `scripting.getRegisteredContentScripts()` or to unregister with `scripting.unregisterContentScripts()`. `scripting.ExecutionWorld` Specifies the execution environment of a script injected with `scripting.executeScript()` or registered with `scripting.registerContentScripts()`. `scripting.InjectionTarget` Details of an injection target. `scripting.RegisteredContentScript` Details of a content script to be registered or that is registered. Functions --------- `scripting.executeScript()` Injects JavaScript code into a page. `scripting.getRegisteredContentScripts()` Gets a list of registered content scripts. `scripting.insertCSS()` Injects CSS into a page. `scripting.registerContentScripts()` Registers a content script for future page loads. `scripting.removeCSS()` Removes CSS which was previously injected into a page by a `scripting.insertCSS()` call. `scripting.updateContentScripts()` Updates one or more content scripts already registered. `scripting.unregisterContentScripts()` Unregisters one or more content scripts. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. **Note:** This API is based on Chromium's `chrome.scripting` API.
extensionTypes - Mozilla
extensionTypes ============== Some common types used in other WebExtension APIs. Types ----- `extensionTypes.ImageDetails` Details about the format and quality of an image. `extensionTypes.ImageFormat` The format of an image. `extensionTypes.InjectDetails` Injects details into a page. `extensionTypes.RunAt` The soonest that the JavaScript or CSS will be injected into the tab. `extensionTypes.CSSOrigin` Indicates whether a CSS stylesheet injected by `tabs.insertCSS` should be treated as an "author" or "user" stylesheet. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. **Note:** This API is based on Chromium's `chrome.extensionTypes` API. This documentation is derived from `extension_types.json` in the Chromium code.
management - Mozilla
management ========== Get information about installed add-ons. With the `management` API you can: * get information about installed add-ons * enable/disable add-ons * uninstall add-ons * find out which permission warnings are given for particular add-ons or manifests * get notifications of add-ons being installed, uninstalled, enabled, or disabled. Most of these operations require the "management" API permission. Operations that don't provide access to other add-ons don't require this permission. Types ----- `management.ExtensionInfo` An object that contains information about an installed add-on. Functions --------- `management.getAll()` Returns information about all installed add-ons. `management.get()` Returns information about a particular add-on, given its ID. `management.getSelf()` Returns information about the calling add-on. `management.install()` Installs a particular theme, given its URL at addons.mozilla.org. `management.uninstall()` Uninstalls a particular add-on, given its ID. `management.uninstallSelf()` Uninstalls the calling add-on. `management.getPermissionWarningsById()` Get the set of permission warnings for a particular add-on, given its ID. `management.getPermissionWarningsByManifest()` Get the set of permission warnings that would be displayed for the given manifest string. `management.setEnabled()` Enable/disable a particular add-on, given its ID. Events ------ `management.onInstalled` Fired when an add-on is installed. `management.onUninstalled` Fired when an add-on is uninstalled. `management.onEnabled` Fired when an add-on is enabled. `management.onDisabled` Fired when an add-on is disabled. Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Example extensions ------------------ * theme-switcher **Note:** This API is based on Chromium's `chrome.management` API. This documentation is derived from `management.json` in the Chromium code.