repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/mozilla/firefox/releases/3 | data/mdn-content/files/en-us/mozilla/firefox/releases/3/svg_improvements/index.md | ---
title: SVG improvements in Firefox 3
slug: Mozilla/Firefox/Releases/3/SVG_improvements
page-type: guide
---
{{FirefoxSidebar}}
Firefox 3 offers improved [Scalable Vector Graphics](/en-US/docs/Web/SVG) (SVG) support over prior versions of Firefox. While these features are documented elsewhere, this article serves as a convenient list so you can easily determine which features were added in Firefox 3.
- The `foreignObject` element is now supported ([Firefox bug 326966](https://bugzil.la/326966)). See the [specification](https://www.w3.org/TR/SVG11/extend.html#ForeignObjectElement) or [this article](https://robert.ocallahan.org/2006/06/future-is-now_20.html) for details.
- `pattern` element support ([spec](https://www.w3.org/TR/SVG11/pservers.html#PatternElement))
- `mask` element support ([spec](https://www.w3.org/TR/SVG11/masking.html#MaskElement))
- Support for all SVG 1.1 filters ([spec](https://www.w3.org/TR/SVG11/filters.html)):
- `filter`
- `feDistantLight`
- `fePointLight`
- `feSpotLight`
- `feBlend`
- `feColorMatrix`
- `feConvolveMatrix`
- `feComponentTransfer`, `feFuncR`, `feFuncG`, `feFuncB`, `feFuncA`
- `feComposite`
- `feConvolveMatrix`
- `feDiffuseLighting`
- `feDisplacementMap`
- `feDistantLight`
- `feFlood`
- `feGaussianBlur`
- `feImage`
- `feMerge`, `feMergeNode`
- `feMorphology`
- `feOffset`
- `fePointLight`
- `feSpecularLighting`
- `feTurbulence`
- `feTile`
- `<a>` element handling in SVG has had several bugs fixed; see [Firefox bug 267664](https://bugzil.la/267664), [Webkit bug 268135](https://bugzil.la/268135), [Webkit bug 316248](https://bugzil.la/316248), [Webkit bug 317270](https://bugzil.la/317270) and [Webkit bug 320724](https://bugzil.la/320724).
- The SVG DOM Methods `getNumberOfChars()`, `getComputedTextLength()`, `getSubStringLength()`, `getStartPositionOfChar()`, `getEndPositionOfChar()`, `getRotationOfChar()`, and `getCharNumAtPosition()` have been implemented.
- the `xml:space` attribute support ([spec](https://www.w3.org/TR/SVG/text.html#WhiteSpace))
- fallback `fill`/`stroke` are now supported ([spec](https://www.w3.org/TR/SVG/painting.html#SpecifyingPaint))
- `em` and `ex` units are now supported for indicating lengths ([Firefox bug 305859](https://bugzil.la/305859)).
## See also
- [SVG](/en-US/docs/Web/SVG)
- [Firefox 3 for developers](/en-US/docs/Mozilla/Firefox/Releases/3)
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases/3 | data/mdn-content/files/en-us/mozilla/firefox/releases/3/wai_aria_live_regions_api_support/index.md | ---
title: WAI ARIA Live Regions/API Support
slug: Mozilla/Firefox/Releases/3/WAI_ARIA_Live_Regions_API_Support
page-type: guide
---
{{FirefoxSidebar}}
> **Warning:** These notes are for developers of screen readers. Developers should use the [ARIA live regions developer documentation](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions).
Firefox 3 contains important improvements to the way the Mozilla engine exposes live changes in a document.
These features will help screen reader developers improve the quality and performance of live region support, both for pages that are marked up with ARIA live region markup, and for pages where the author did not add any additional markup.
As always, we're open to questions and suggestions for changes in [community forums](https://support.mozilla.org/en-US/kb/get-community-support).
## Events fired for web page mutations
| What changed in document? | ATK/AT-SPI event | IAccessible2 event |
| --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| Object about to be hidden or removed | children_changed::remove (fired on the parent, with event data pointing to the child index of the accessible object to be removed) | EVENT_OBJECT_HIDE\* (fired on the actual accessible object about to go away) |
| Object shown or inserted | children_changed::add (fired on the parent, with event data pointing to the child index of the inserted accessible object) | EVENT_OBJECT_SHOW\* (fired on the actual new accessible object) |
| Object replaced with different object (this happens especially if an object's interfaces or role changes) | children_changed::remove followed immediately by children_change::add | EVENT_OBJECT_HIDE followed immediately by EVENT_OBJECT_SHOW |
| Text removed | text_changed::delete | IA2_EVENT_TEXT_REMOVED (use IAccessibleText::get_oldText to retrieve the offsets and removed text) |
| Text inserted | text_changed::insert | IA2_EVENT_TEXT_INSERTED (use IAccessibleText::get_newText to retrieve the offsets and inserted text) |
| Text replaced | text_changed::delete followed immediately by text_changed::insert | IA2_EVENT_TEXT_REMOVED followed immediately by IA2_EVENT_TEXT_INSERTED |
\* We do not use MSAA's CREATE/DESTROY at the request of screen reader vendors, who avoid those events because they cause crashes on some important system β SHOW/HIDE are the equivalent of those events.
## Retrieving author-supplied ARIA live region semantics from an event
For any mutation event in a page, the author can get the following object attributes from the event object, if they are defined on some ancestor element (closest ancestor wins):
| Object attribute name | Possible values | Default value | ARIA markup if required | Meaning |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `container-live` | `"off" \| "polite" \| "assertive"` | `"off"` | `aria-live` on ancestor element | Interruption |
| `container-relevant` | `'additions'` `'removals'` `'text' \| "all"` | `"additions text"` | `aria-relevant` on ancestor element | What types of mutations are possibly relevant? See [section](#events_fired_for_web_page_mutations_the_mutation_events_list) to match the type of event with this attribute's value, to determine whether the author believed the event should be presented to the user or not. |
| `container-busy` | `"true" \| "false" \| "error"` | `"false"` | `aria-busy` on ancestor element | The current changes are not yet complete. A state change event for the A11y API's BUSY state will be fired on the container object currently marked as BUSY, once it is no longer BUSY. This is especially important in atomic regions. The entire atomic region should be presented once when it is finally no longer BUSY. |
| `container-atomic` | `"true" \| "false"` | `"false"` | `aria-atomic` on ancestor element | Is this change inside a region that should always be presented at once. If yes, member-of relation will point to the root of the region (see next section) |
| `member-of` | If `container-atomic=true`, points to an ancestor accessible object (thus it is actually an accessible relation, not object attribute) | Not in atomic region if not provided | `aria-atomic` on ancestor element | Points to the root of the atomic container that this object is in. This will always be an ancestor of the current object. |
| `event-from-input` | `"true" \| "false"` (described more below) | Browser could not calculate this | Does not require author's cooperation. | Was the root cause of this event explicit user input? |
The "container-" prefix is so named because the attribute describes what the final computed property of similar name is for that node. This means that the AT does not need to traverse up the parent chain to get this information. At this time, for properties where the `container-`_name_ attribute has not been set, the AT must have code to fall back on the default value as defined in the W3C spec.
## Determining if event was from user input
All events will now provide information about whether the event was caused by user input, or was something that the web page caused. This information is retrieved differently on each platform, because some platforms use asynchronous events.
In IAccessible2, this is retrieved from the object attribute "event-from-input", which will be set to "true" or "false". If it is not present, then something went wrong and Mozilla was not able to provide this information. This information is available only for EVENT_SHOW, EVENT_HIDE, IA2_EVENT_TEXT_INSERTED and IA2_EVENT_TEXT_REMOVED.
For ATK/AT-SPI, this information is retrieved by checking the event name. If the event name has ":system" appended to it, then it is /not/ from user input. The ":system" string is calculated for children-changed and text-changed events.
Why is this useful? The majority of AJAX pages do not provide live region markup, but still need to be as usable as possible. It is difficult for a screen reader to decide when to interrupt a user with changes on a page. If the screen reader automatically reads too much, then the web page will be too annoying to use. If the screen reader doesn't read anything, then the user may miss important information.
It is believed this information will be useful for heuristics. Often, changes in a page that are directly caused by a user's keystrokes should be read. They are synchronous with what the user is doing and can thus likely be read without disorienting the user. Once the user presses the next key the speech will move on to echoing that key anyway. The screen reader may wish to take other factors into account, such as the type of change, the size of the change, where the change occurred, etc. This is a potential area for innovation in screen readers.
| Most recent occurrence | User input? |
| ---------------------- | ----------- |
| Key presses | Yes |
| Mouse clicks | Yes |
| Mouse hovers | No |
| Page load events | No |
Everything else, including focus changes, timer callbacks, XMLHttpRequest callbacks, etc. are neutral. They are only counted as user input if the original reason they happened was because of user input.
## What Should Screen Readers Present?
Please read the live region section of the [WAI-ARIA Screen Reader Implementor's Guide](/en-US/docs/Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide#live_regions).
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases/3 | data/mdn-content/files/en-us/mozilla/firefox/releases/3/templates/index.md | ---
title: Templates in Firefox 3
slug: Mozilla/Firefox/Releases/3/Templates
page-type: guide
---
{{FirefoxSidebar}}
Templates have been significantly improved in Firefox 3. The key improvement allows the use of [custom query processors](/en-US/docs/How_to_implement_a_custom_XUL_query_processor_component) to handle other types of datasources besides RDF. A new query syntax makes this possible. Built-in support for SQL ([mozStorage](/en-US/docs/Storage)) and XML datasources is also provided. A full description of the new features available for templates [is available](https://wiki.mozilla.org/XUL:Template_Features_in_1.9). ([Firefox bug 285631](https://bugzil.la/285631))
### Other template improvements
- Relational conditions have been added to allow for more precise control over what results match a rule. This allows, for example, matching of results that start or end with certain strings, or that are before or after other values.
- A flag, `dont-recurse`, has been added to prevent recursion from happening such that only one level of results are generated
- APIs have been added to the template builder to retrieve a result object representing an output item.
- The XUL sort service is more robust and [sorts](/en-US/docs/XUL/Template_Guide/Sorting_Results) both content and non-content trees better. It also allows sorting of non-template built content. ([Firefox bug 335122](https://bugzil.la/335122))
### See also
- [Firefox 3 for developers](/en-US/docs/Mozilla/Firefox/Releases/3)
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases/3 | data/mdn-content/files/en-us/mozilla/firefox/releases/3/site_compatibility/index.md | ---
title: Site compatibility for Firefox 3
slug: Mozilla/Firefox/Releases/3/Site_compatibility
page-type: guide
---
{{FirefoxSidebar}}
This page tries to give an overview of the changes between [Gecko](/en-US/Gecko) 1.8 and Gecko 1.9, that could possibly affect websites in their behavior or rendering.
See also [Firefox 3 for developers](/en-US/Firefox_3_for_developers).
## Events
### Capturing load event listeners
In Gecko 1.8, it was not possible to set capturing load event listeners on images. In Gecko 1.9, this has been fixed by [Firefox bug 234455](https://bugzil.la/234455). But this can cause problems on websites that incorrectly have their event listeners set to capture the load event. See the discussion in [Webkit bug 335251](https://bugzil.la/335251). To fix this problem, the problematic page in question should not set a capturing load event listener.
For example, this:
```bash
window.addEventListener('load', yourFunction, true);
```
should be changed into this:
```bash
window.addEventListener('load', yourFunction, false);
```
For an explanation of how event capture works, see [DOM Level 2 Event capture](https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-capture)
### `preventBubble` has been removed
In Gecko 1.8, the `preventBubble` method existed on events to prevent events from bubbling upwards. In Gecko 1.9 this method has been removed. Instead, you should use the standard [stopPropagation()](/en-US/docs/Web/API/Event/stopPropagation), which also works fine in Gecko 1.8. The patch in [Firefox bug 330494](https://bugzil.la/330494) made this happen. See also [Webkit bug 105280](https://bugzil.la/105280).
### A few other old event APIs are no longer supported
[`window.captureEvents`](/en-US/docs/Web/API/Window/captureEvents), [`window.releaseEvents`](/en-US/docs/Web/API/Window/releaseEvents) and [`window.routeEvent`](/en-US/docs/Web/API/Window/routeEvent) are now considered deprecated since Gecko 1.9.
## DOM
### `WRONG_DOCUMENT_ERR`
Nodes from external documents should be cloned using [`document.importNode()`](/en-US/docs/Web/API/Document/importNode) (or adopted using [`document.adoptNode()`](/en-US/docs/Web/API/Document/adoptNode)) before they can be inserted into the current document. For more on the [`Node.ownerDocument`](/en-US/docs/Web/API/Node/ownerDocument) issues, see the [W3C DOM FAQ](https://www.w3.org/DOM/faq.html#ownerdoc).
Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for improved future compatibility.
## Ranges
### `intersectsNode` has been removed
In Gecko 1.8 the function `intersectsNode` code be used to test if a node intersected a range. However the return values from this function were confusing and rarely useful and has therefore been removed in Gecko 1.9. Instead use the more precise and standard function [compareBoundaryPoints](/en-US/docs/Web/API/Range/compareBoundaryPoints). The patch in [Firefox bug 358073](https://bugzil.la/358073) removed this function.
See the documentation for [intersectsNode](/en-US/docs/Web/API/Range/intersectsNode) for how to use `compareBoundaryPoints` instead.
### `compareNode` has been removed
In Gecko 1.8 the function `compareNode` code be used to test how a node intersected a range. However the return values from this function were confusing and rarely useful and has therefore been removed in Gecko 1.9. Instead use the more precise and standard function [compareBoundaryPoints](/en-US/docs/Web/API/Range/compareBoundaryPoints). The patch in [Firefox bug 358073](https://bugzil.la/358073) removed this function.
See the documentation for [compareNode](/en-US/docs/Web/API/Range/compareNode) for how to use `compareBoundaryPoints` instead.
## HTML
### Many bugs in the `<object>` have been fixed
`object` and `embed` elements no longer need a `type` attribute to render. Changing the `src` attribute (of `<embed>`) or the `data` attribute (of `<object>`) via JavaScript now works correctly. The Content-Type header sent by the server (if any) now takes precedence over the `type` attribute of an `<object>` element as per the HTML specification (this is not the case for `embed`).
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases/3 | data/mdn-content/files/en-us/mozilla/firefox/releases/3/notable_bugs_fixed/index.md | ---
title: Notable bugs fixed in Firefox 3
slug: Mozilla/Firefox/Releases/3/Notable_bugs_fixed
page-type: guide
---
{{FirefoxSidebar}}
This article offers a list of important bug fixes offered by Firefox 3 that are not necessarily obvious in the documentation.
- if an error occurs parsing an overlay, the overlay is not applied. Parse errors are logged to the error console. ([Firefox bug 335755](https://bugzil.la/335755))
- bug fixed where `<menupopup>` elements can be placed inside a binding when attached to a menu or menu-like element. ([Firefox bug 345896](https://bugzil.la/345896))
- the button's `dlgType` property now works properly. ([Firefox bug 308591](https://bugzil.la/308591))
- the `canBubble` argument to {{ Domxref("event.initEvent") }} now works properly so that events can be fired which don't bubble. ([Firefox bug 330190](https://bugzil.la/330190))
- the `DOMAttrModified` event now handles namespaced attributes properly. ([Firefox bug 362391](https://bugzil.la/362391))
- XML processing instructions, such as `<?xml-stylesheet ?>`, are now added to a XUL document's DOM. This means {{ Domxref("Node.firstChild", "document.firstChild") }} isn't guaranteed to be the root element, use {{ Domxref("document.documentElement") }} instead. Also, `<?xml-stylesheet ?>` and `<?xul-overlay ?>` processing instructions now have no effect outside the document prolog. ([Firefox bug 319654](https://bugzil.la/319654))
- [`getElementsByAttributeNS()`](/en-US/docs/Mozilla/Tech/XUL/Method/getElementsByAttributeNS) functions have been added to XUL elements and documents. ([Firefox bug 239976](https://bugzil.la/239976))
- event listeners are maintained when moving or removing an element from a XUL document. ([Firefox bug 286619](https://bugzil.la/286619))
- mutation events are now fired for non-displayed documents. ([Firefox bug 201236](https://bugzil.la/201236))
- various issues with elements drawing in the wrong order are fixed. ([Firefox bug 317375](https://bugzil.la/317375))
- [`getElementsByTagName()`](/en-US/docs/Web/API/Element/getElementsByTagName) has been fixed to work correctly on subtrees that have elements with namespace prefixes in their tag names ([Firefox bug 206053](https://bugzil.la/206053)).
- The `DOMNodeInserted` and `DOMNodeRemoved` events now properly apply to the correct nodes ([Firefox bug 367164](https://bugzil.la/367164)).
- `\d`, one of special characters in regular expressions, has been fixed to match only Basic Latin alphabet digits (equivalent to `[0-9]`). ([Firefox bug 378738](https://bugzil.la/378738))
- The image-sniffing-services category allows for image decoders implemented as extensions to correctly decode images sent with incorrect mime-types. ([Firefox bug 391667](https://bugzil.la/391667))
- Right-clicks on form controls no longer brings up a context menu by default ([Firefox bug 404536](https://bugzil.la/404536). See [Offering a context menu for form controls](/en-US/docs/Offering%20a%20context%20menu%20for%20form%20controls) to learn how to enable this on a case-by-case basis.
### See also
- [Firefox 3 for developers](/en-US/docs/Mozilla/Firefox/Releases/3)
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases | data/mdn-content/files/en-us/mozilla/firefox/releases/8/index.md | ---
title: Firefox 8 for developers
slug: Mozilla/Firefox/Releases/8
page-type: firefox-release-notes
---
{{FirefoxSidebar}}
Firefox 8 was released on November 8, 2011. This article provides information both for [web developers](#changes_for_web_developers) and for add-on and [Mozilla project developers](#changes_for_mozilla_and_add-on_developers) to help take full advantage of the features of this release.
## Changes for web developers
### HTML
- The {{ domxref("HTMLImageElement") }} `crossOrigin` property has been added and the [`crossorigin`](/en-US/docs/Web/HTML/Element/img#crossorigin) attribute has been added to the {{ HTMLElement("img") }} element. (see [Firefox bug 664299](https://bugzil.la/664299))
- The {{ domxref("HTMLSelectElement","","add()") }} method now supports either an item or index of an item that the new item should be inserted before. Previously it only supported an item. (see [Firefox bug 666200](https://bugzil.la/666200))
- The `HTMLIsIndexElement` constructor has been removed. No elements have implemented this interface since before Firefox 4.
- The HTML5 "context menu" feature (`contextmenu` attribute), which lets you add custom element specific items to native context menu, is now supported (the implementation is still experimental awaiting changes in the specification; see [Firefox bug 617528](https://bugzil.la/617528)).
- Support for the {{ domxref("HTMLElement.accessKeyLabel") }} attribute has been added to all elements.
- The {{ HTMLElement("input") }} and {{ HTMLElement("textarea") }} elements now support the `selectionDirection` attribute, and their `setSelectionRange()` methods have been updated to support optionally specifying a direction.
- Most elements now get a focus ring drawn around them if they've been made focusable by using the `tabindex` attribute and the user then focuses the element.
- In a set of nested {{ HTMLElement("label") }} elements click events do no longer trigger multiple \<label> elements, which caused Firefox to stop responding in the past (see [Firefox bug 646157](https://bugzil.la/646157)).
### DOM
- The {{ domxref("Element.insertAdjacentHTML","insertAdjacentHTML") }} method has been implemented.
- `BlobBuilder` now has a `getFile()` method that returns the content of the blob as a file.
- The {{ domxref("FileReaderSync") }} interface (part of the FileAPI) has been implemented.
- Event handling in nested {{ HTMLElement("label") }}s has been fixed.
- You can now use {{ domxref("window.postMessage()") }} to pass {{ domxref("File") }} and {{ domxref("FileList") }} objects between windows.
- When editing {{ domxref("HTMLelement.contenteditable", "contenteditable") }} areas, exiting a heading by pressing return, or exiting list editing mode by pressing return twice, now returns to paragraph entry mode (that is, paragraphs inside {{ HTMLElement("p") }} blocks) instead of separating lines by {{ HTMLElement("br") }} elements.
- Fixed a bug that prevents justification from taking effect properly when applied to the first line in a {{ domxref("HTMLelement.contenteditable", "contenteditable") }} area.
- Fixed a bug that caused pressing delete or backspace at the beginning of a {{ domxref("HTMLelement.contenteditable", "contenteditable") }} area to affect the previous `contenteditable` block if one is present.
- {{ domxref("Document.getSelection()") }} now returns the same `Selection` object as {{ domxref("window.getSelection()") }}, instead of _stringifying_ it.
- The HTML5 `selectionDirection` property makes it possible to define the direction of the selection in an editable text.
- {{ domxref("HTMLMediaElement") }} now have a `seekable` property that return a {{ domxref("TimeRanges") }} object.
- The {{ domxref("HTMLMediaElement") }}`.preload` attribute now correctly reflects as an _enumerated value_.
- [`crossOrigin` property](/en-US/docs/Web/HTML/Attributes/crossorigin) defaults to "Anonymous" when an invalid value is used.
- {{ domxref("navigator.cookieEnabled") }} now returns correct information when the default cookie setting is overridden on a per-site basis.
### JavaScript
- [`RegExp.exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) and [`RegExp.test()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) called with no arguments now match against the string "undefined".
- [`String.search()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) and [`String.match()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) called with no arguments or `undefined` now match against the empty string and thus match every string.
- Support for watchlists has been implemented with the new (non-standard) `watch()` and `unwatch()` methods.
### CSS
- {{ cssxref("resolution") }} now accepts {{cssxref("<number>")}}, not just {{cssxref("<integer>")}} values as per the specification.
- Hyphenation rules have been added for many new languages when using {{ cssxref("hyphens") }}.
- Handling of {{ cssxref("background-size") }} has been revised to more closely match the specification.
- In the past, {{ cssxref("text-decoration") }} in quirks mode had line thickness and position adjusted on descendant text to match the descendant. Now standards mode and quirks mode rendering are more similar.
- Horizontal positioning for elements has been brought more in line with the specification in many cases. Documentation for this is forthcoming, but for now, see [Firefox bug 682780](https://bugzil.la/682780), comment 23 for details.
- [SVG images are now scaled properly](/en-US/docs/Web/CSS/Scaling_of_SVG_backgrounds) when used as background images.
### Network
- Double quotes are no longer accepted as a delimiter for {{ RFC("2231") }} or {{ RFC("5987") }} encoding, as per those RFCs.
- MIME header field parser (`Content-Disposition`) now requires "=" in parameters.
- Scripts are no longer downloaded when JavaScript is disabled.
- SSL 2.0 is no longer supported.
### WebSockets
- The [`WebSocket`](/en-US/docs/Web/API/WebSocket) object's [`send()`](/en-US/docs/Web/API/WebSocket/send) method no longer incorrectly returns a Boolean value.
- The [`WebSocket`](/en-US/docs/Web/API/WebSocket) object's [`close()`](/en-US/docs/Web/API/WebSocket/close) method now matches the current draft of the standard, and close events now properly use the [`CloseEvent`](/en-US/docs/Web/API/CloseEvent) interface.
- The [`WebSocket`](/en-US/docs/Web/API/WebSocket) object's `extensions` attribute is now supported.
- The WebSocket constructor now supports an array of protocols as well as a single protocol string.
- Mixed content is not allowed with WebSockets; that is, you can no longer open a connection to a non-secure WebSocket server from secure content.
- Connection errors with WebSockets now trigger the `onerror` handler.
- [WebSocket](/en-US/docs/Web/API/WebSockets_API) API has been updated to the latest draft of the specification (see [Firefox bug 674890](https://bugzil.la/674890), [Firefox bug 674527](https://bugzil.la/674527), and [Firefox bug 674716](https://bugzil.la/674716)).
- The deflate-stream extension to WebSockets has been disabled; it has been deprecated, and was breaking compatibility with some sites.
### WebGL
- [Cross-domain textures](/en-US/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL#cross-domain_textures) can now be allowed with CORS approval.
- Cross-process rendering with Direct2D/Direct3D 10.
### MathML
- Support for the `displaystyle` attribute on the top-level {{ MathMLElement("math") }} element has been added.
- The interpretation of negative row numbers for the `align` attribute on {{ MathMLElement("mtable") }} has been corrected.
### Developer tools
- The [`console`](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html#the-console-object) object has a new `dir()` method, which displays an interactive list of the properties on a specified object.
## Changes for Mozilla and add-on developers
See [Updating add-ons for Firefox 8](/en-US/docs/Mozilla/Firefox/Releases/8/Updating_add-ons) for a guide to changes you're likely to have to make your add-ons compatible with Firefox 8.
> **Note:** Firefox 8 requires that binary components be recompiled, as do all major releases of Firefox.
### XPCOM
- `Components.utils`
- : The new methods `Components.utils.createObjectIn()` and `Components.utils.makeObjectPropsNormal()` have been created to make it easier to create objects in specific compartments.
#### Other XPCOM-related changes
- You can now instantiate DOM {{ domxref("File") }} objects from component code by doing new File, instead of having to instantiate an `nsIDOMFile` directly.
- The `nsTPtrArray` array type has been removed. Its functionality is now all available on `nsTArray`, which now offers the `SafeElementAt()` method when instantiated using a pointer type.
### Workers
It is no longer possible to access XPCOM objects from ChromeWorkers. XPConnect has been disabled in worker contexts as of [Firefox bug 649537](https://bugzil.la/649537).
### XUL
- A bug in {{ domxref("document.execCommand()") }} that occurred when calling it on the value of `contentDocument` has been fixed. Since Firefox 3, this has resulted in errors instead of working correctly.
- Bootstrapped add-ons can now load chrome using a `chrome.manifest` file.
- XUL images now shrink down with the same ratio in both directions when specifying maximum sizes.
### Changes to the build system
- The following build configuration options have been removed:
- `--enable-timeline`
- `--disable-storage`
- `--necko-disk-cache`
- When compiling IDL files to headers, the header file `jspubtd.h` is automatically included when needed. Manual inclusions of `jspubtd.h` and/or `jsapi.h` in IDL files that use jsval or \[implicit_jscontext] are no longer necessary.
### Chrome registration
- The `platformversion` flag can be used in the chrome.manifest to specify Gecko version compatibility.
### Interface changes
- The `mozIJSSubScriptLoader.loadSubScript()` method now loads scripts from the startup cache when possible.
- The `ownerWindow` attribute has been removed from the `nsIAccessNode` interface.
- The `nsIDOMStorageWindow` interface has been merged into the `nsIDOMWindow` interface.
- All members of the `nsIDOMWindowInternal` interface have been moved into the `nsIDOMWindow` interface. The interface itself (with no members) remains available for compatibility until Firefox 9.
- In order to improve performance, callback handling for asynchronous Places database updates has been changed. See the new `mozIVisitInfoCallback.handleResult()` and `mozIVisitInfoCallback.handleError()` methods, which replace the old single method for both error and success condition handling.
- The `KIND_MAPPED` attribute of `nsIMemoryReporter` has been deprecated in favor of `KIND_NONHEAP`, new unit types `UNITS_COUNT_CUMULATIVE` and `UNITS_PERCENTAGE` have been added.
- The `nsIMemoryReporterManager` interface has a new `explicit` attribute, which reports the total size of explicit memory allocations.
- The `nsIMemoryReporterManager` interface has a new `resident` attribute, which reports the amount of physical memory used.
- The `nsINetworkLinkService` interface has a new attribute, `linkType`. This attribute provides the type of network connection in use. All Operating Systems currently return `LINK_TYPE_UNKNOWN`. Android support was backed out due to perceived security concerns.
- The `nsISelection2` interface has been merged into the `nsISelectionPrivate` interface.
- The `nsISelection3` interface has been merged into the `nsISelection` interface.
- The `nsISessionStartup` attribute state is now a `jsval` instead of a string, for performance reasons.
- The `nsIDocShell` attribute `isActive` is now `false` for minimized windows.
- The `nsIDownloadHistory.addDownload()` method now saves the target where the download is saved on the local file system.
#### Removed interfaces
The following interfaces were implementation details that are no longer needed:
- `nsITimelineService`
- `nsIDOMHTMLIsIndexElement`
The `nsIWorkerFactory` interface has been removed as well. Workers can still be created using the `Worker` and `ChromeWorker` constructors.
### Other changes
- When a window is minimized, un-minimized, or switches between full screen and windowed mode, it receives a `sizemodechange` event.
- You can now [use the `extensions.autoDisableScopes` preference](https://extensionworkshop.com/documentation/publish/signing-and-distribution-overview/#preventing_automatic_install_from_specific_locations) to disable automatic installation of add-ons from specific add-on install locations.
- The new `mozSyntheticDocument` property on {{ domxref("Document") }} objects lets you determine whether a document is synthetic (that is, something like a standalone image, video, or audio file) rather than a full, standard DOM document. This can be useful, for example, if you want to present different user interface in this situation (such as adding contextual items differently depending on this case).
- You can now specify a filter when opening `about:config`; for example, "about:config?filter=sessionstore" will show only session storage related preferences.
## See also
- [Firefox 7 for developers](/en-US/docs/Mozilla/Firefox/Releases/7)
- [Firefox 6 for developers](/en-US/docs/Mozilla/Firefox/Releases/6)
- [Firefox 5 for developers](/en-US/docs/Mozilla/Firefox/Releases/5)
- [Firefox 4 for developers](/en-US/docs/Mozilla/Firefox/Releases/4)
- [Firefox 3.6 for developers](/en-US/docs/Mozilla/Firefox/Releases/3.6)
- [Firefox 3.5 for developers](/en-US/docs/Mozilla/Firefox/Releases/3.5)
- [Firefox 3 for developers](/en-US/docs/Mozilla/Firefox/Releases/3)
- [Firefox 2 for developers](/en-US/docs/Mozilla/Firefox/Releases/2)
- [Firefox 1.5 for developers](/en-US/docs/Mozilla/Firefox/Releases/1.5)
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases/8 | data/mdn-content/files/en-us/mozilla/firefox/releases/8/updating_add-ons/index.md | ---
title: Updating add-ons for Firefox 8
slug: Mozilla/Firefox/Releases/8/Updating_add-ons
page-type: guide
---
{{FirefoxSidebar}}
This article provides information on steps you need to take in order to update your existing add-on for compatibility with Firefox 8. See [Firefox 8 for developers](/en-US/docs/Mozilla/Firefox/Releases/8) for a complete list of everything that changed in Firefox 8.
## Do you need to do anything at all?
If your add-on is distributed on [addons.mozilla.org](https://addons.mozilla.org/en-US/firefox/) (AMO), it's been checked by an automated compatibility verification tool. Add-ons that don't use APIs that changed in Firefox 8, and have no binary components (which [need to be recompiled for every major Firefox release](/en-US/docs/Mozilla/Developer_guide/Interface_Compatibility#binary_interfaces)), have automatically been updated on AMO to indicate that they work in Firefox 8.
So you should start by visiting AMO and looking to see if your add-on needs any work done at all.
> **Note:** You should still test your add-on on Firefox 8, even if it's been automatically upgraded. There are edge cases that may not be automatically detected.
Once you've confirmed that you need to make changes, come on back to this page and read on.
## Development process note
It's worth noting that during startup, Firefox 8 now checks for third-party add-ons on its first startup, and presents a user interface letting users decide whether or not to enable them. If you drop your add-on into the profile directory in order to test it, Firefox won't enable it automatically on the first startup, but will show this interface instead.
You can avoid this by setting the preference `extensions.autoDisableScopes` to 14. This should only be done for development and testing purposes.
## Interfaces have been merged
As part of our ongoing effort to streamline Gecko's internals, a few interfaces have been merged together:
- `nsIDOMWindowInternal` has been merged into `nsIDOMWindow`. The `nsIDOMWindowInternal` interface still exists, but is empty, and will be removed entirely in Firefox 9. You should update any code that relies on the existence of `nsIDOMWindowInternal` to look for `nsIDOMWindow` instead.
- All of the sub-interfaces of `nsISelection` have been merged into the base `nsISelection` interface. If by some chance you were previously looking for `nsISelection2` or `nsISelection3`, you should update your code.
## Date handling improved
Now that the JavaScript [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object can parse ISO 8601 dates, the [`ISO8601DateUtils.jsm`](/en-US/docs/JavaScript_code_modules/ISO8601DateUtils.jsm) code module has been removed. If you were using this code module, you should update your code to use the methods on `Date` instead.
## DOM changes
There have been a couple of changes in the DOM that impact add-ons:
### Selection changes
In the past, {{ domxref("Document.getSelection()") }} was returning a stringified version of the selection instead of the {{ domxref("Selection") }} object itself. This was non-standard behavior, and has been corrected.
### Potential name conflicts
When the DOM File API was added, a new global called {{ domxref("File") }} was added; this can conflict with objects in your scripts. If you have any globals called `File`, you should rename them.
Similarly, a new global, {{ domxref("ChromeWorker") }}, was introduced to support allowing Workers to be used from chrome code. If by some chance you have any globals with this name, you should rename them.
## Security changes
Support for SSL 2.0 has been removed. This shouldn't affect any current add-ons. However, for reference, some very old code was removed, as well as support for the preferences `security.enable_ssl2` (which is false by default), and all preferences starting with "`security.ssl2.`"
## See also
- [Firefox 8 for developers](/en-US/docs/Mozilla/Firefox/Releases/8)
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases | data/mdn-content/files/en-us/mozilla/firefox/releases/55/index.md | ---
title: Firefox 55 for developers
slug: Mozilla/Firefox/Releases/55
page-type: firefox-release-notes
---
{{FirefoxSidebar}}
Firefox 55 was released on August 8, 2017. This article lists key changes that are useful for web developers.
## Changes for Web developers
### Developer Tools
- Added filtering of network requests by column values and other properties ([Firefox bug 1041895](https://bugzil.la/1041895), [Firefox bug 1354508](https://bugzil.la/1354508), [Firefox bug 1354507](https://bugzil.la/1354507)) and by using regular expressions ([Firefox bug 1354495](https://bugzil.la/1354495)).
- Made it possible to show and hide columns within the [Network Monitor](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/index.html) ([Firefox bug 862855](https://bugzil.la/862855)).
- Added remote IP ([Firefox bug 1344523](https://bugzil.la/1344523)), protocol ([Firefox bug 1345489](https://bugzil.la/1345489)), scheme ([Firefox bug 1356867](https://bugzil.la/1356867)), cookies and set cookies columns ([Firefox bug 1356869](https://bugzil.la/1356869)) to Network Monitor.
- The {{HTTPHeader("SourceMap")}} HTTP header is now supported (prior versions supported the deprecated `X-SourceMap` header, see [Firefox bug 1346936](https://bugzil.la/1346936)).
### HTML
- Elements on which [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes#contenteditable) has been set to `true` now use {{htmlelement("div")}} elements to separate different lines of text, to give Firefox parity with other modern browsers ([Firefox bug 1297414](https://bugzil.la/1297414)). See [Differences in markup generation](/en-US/docs/Web/HTML/Global_attributes/contenteditable#differences_in_markup_generation) for more details.
- Enable `dom.forms.datetime` by default on Nightly ([Firefox bug 1366188](https://bugzil.la/1366188)).
### CSS
- Exposed the {{cssxref("transform-box")}} property by default ([Firefox bug 1208550](https://bugzil.la/1208550)).
- Implemented the `frames()` timing function ([Firefox bug 1248340](https://bugzil.la/1248340)).
- Implemented the {{cssxref("text-justify")}} property ([Firefox bug 1343512](https://bugzil.la/1343512), [Firefox bug 276079](https://bugzil.la/276079)).
- \[css-grid] {{cssxref("fit-content")}} unexpectedly reserves space for full clamp size in {{cssxref("repeat", "repeat()")}} ([Firefox bug 1359060](https://bugzil.la/1359060)).
- The {{cssxref("float")}} / {{cssxref("clear")}} logical values β `inline-start` and `inline-end` β which were previously implemented but preffed off in release channels, are now available in all channels by default ([Firefox bug 1253919](https://bugzil.la/1253919)).
- The `layout.css.variables.enabled` preference has been removed completely meaning that the [CSS variables](/en-US/docs/Web/CSS/Using_CSS_custom_properties) feature is enabled all the time and can no longer be disabled ([Firefox bug 1312328](https://bugzil.la/1312328)).
- Implemented the proprietary `-moz-context-properties` property ([Firefox bug 1058040](https://bugzil.la/1058040)).
- Zero (0) angle value without degree unit is not correctly interpreted in {{cssxref("gradient/linear-gradient")}} ([Firefox bug 1363292](https://bugzil.la/1363292)).
- The {{cssxref("::cue")}} pseudo-element is now supported; it matches on text cues presented within a media element ([Firefox bug 1318542](https://bugzil.la/1318542)).
### SVG
- The {{svgelement("radialGradient")}} {{ SVGAttr("fr") }} attribute has been implemented ([Firefox bug 1240275](https://bugzil.la/1240275)).
### JavaScript
- The {{jsxref("SharedArrayBuffer")}} and {{jsxref("Atomics")}} objects are now enabled by default. See [A Taste of JavaScript's New Parallel Primitives](https://hacks.mozilla.org/2016/05/a-taste-of-javascripts-new-parallel-primitives/) for an introduction to JavaScript Shared Memory and Atomics.
- The rest operator (`...`) is now supported in [object destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and the spread operator (`...`) now works in [object literals](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_object_literals) (Stage 3 ECMAScript proposal: [Object Rest/Spread Properties](https://github.com/tc39/proposal-object-rest-spread), [Firefox bug 1339395](https://bugzil.la/1339395)).
- [Async generator methods](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions#async_generator_methods) are now supported ([Firefox bug 1353693](https://bugzil.la/1353693)).
- The {{jsxref("String.prototype.toLocaleLowerCase()")}} and {{jsxref("String.prototype.toLocaleUpperCase()")}} methods now support an optional `locale` parameter to specify a language tag for locale-specific case mappings ([Firefox bug 1318403](https://bugzil.la/1318403)).
- The {{jsxref("Intl/Collator", "Intl.Collator")}} object now supports the `caseFirst` option ([Firefox bug 866473](https://bugzil.la/866473)).
- The [Intl API](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) now uses the browser's default locale instead of the operating system's default locale when no locale setting is provided ([Firefox bug 1346674](https://bugzil.la/1346674)).
- [Template call sites objects](/en-US/docs/Web/JavaScript/Reference/Template_literals) are now canonicalized per realm, based upon their list of raw strings ([Firefox bug 1108941](https://bugzil.la/1108941)).
- {{jsxref("TypedArray")}} constructors (like {{jsxref("Int8Array")}}, {{jsxref("Float32Array")}}, etc.) have been updated to ES2017. They now use the `ToIndex` operation and allow constructors without arguments, which return zero-length typed arrays ([Firefox bug 1317383](https://bugzil.la/1317383)).
### APIs
#### New APIs
- The [Collaborative Scheduling of Background Tasks API](/en-US/docs/Web/API/Background_Tasks_API) (also known as the **Background Tasks API** or the `requestIdleCallback` API) is now enabled by default after being available behind a preference since Firefox 53. This API lets you schedule tasks to be executed when the browser determines that there's free time available before the next repaint occurs, so that your code can make use of that time without causing visible performance lag ([Firefox bug 1314959](https://bugzil.la/1314959)).
- The [WebVR 1.1 API](/en-US/docs/Web/API/WebVR_API) is now turned on by default on Windows (and is available on macOS in Nightly). This API exposes virtual reality devices β for example head-mounted displays like the Oculus Rift or HTC Vive β to web apps, enabling developers to translate position and movement information from the display into movement around a 3D scene, and present content into such displays.
- The [Intersection Observer API](/en-US/docs/Web/API/Intersection_Observer_API) β which provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's [viewport](/en-US/docs/Glossary/Viewport) β has been added ([Firefox bug 1321865](https://bugzil.la/1321865)).
#### DOM
- The {{domxref("Window")}} properties {{domxref("Window.scrollX", "scrollX")}} and {{domxref("Window.scrollY", "scrollY")}} (as well as their aliases `pageXOffset` and `pageYOffset` have been updated to be subpixel precise. Instead of returning an integer, these now return a floating-point value which more accurately describes the scroll position on subpixel-precise displays ([Firefox bug 1151421](https://bugzil.la/1151421)). If need be, you can use {{jsxref("Math.round()")}} to convert them into integers.
- {{domxref("MediaQueryList")}} (and other related features) have been updated to match the latest spec. See [Firefox bug 1354441](https://bugzil.la/1354441), and also see {{domxref("MediaQueryList")}} and {{domxref("MediaQueryListEvent")}}.
- Methods of the {{domxref("DOMTokenList")}} that modify the list value now automatically trim whitespace and remove duplicate tokens ([Firefox bug 869788](https://bugzil.la/869788), also see [Trimming of whitespace and removal of duplicates](/en-US/docs/Web/API/DOMTokenList#trimming_of_whitespace_and_removal_of_duplicates)).
- The {{domxref("HTMLInputElement")}}'s `maxLength` property can now be dynamically altered with JavaScript after the equivalent HTML has been created ([Firefox bug 1352799](https://bugzil.la/1352799)).
- The {{domxref("URL.URL", "URL()")}} constructor can no longer accept a `DOMString` as its base (2nd parameter) β it only accepts a `USVString`. It can still use an existing {{domxref("URL")}} object for the base, which stringifies itself to the object's `href` attribute ([Firefox bug 1368950](https://bugzil.la/1368950)).
#### DOM events
- The event types supported by the {{domxref("Document.createEvent()")}} method have been updated as per the latest DOM spec ([Firefox bug 1251198](https://bugzil.la/1251198)).
- The {{domxref("MessageEvent.origin")}} property value is now of type `USVString`, not `DOMString`, and the {{domxref("MessageEvent.source")}} property now takes a `MessageEventSource` value (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) ([Firefox bug 1311324](https://bugzil.la/1311324)).
- The pinch-to-zoom gesture has now been mapped to the {{domxref("Element/wheel_event","wheel")}} event plus the + `Ctrl` key. This mapping was implemented to allow developers to implement simple zooming functionality using the pinch-to-zoom gesture on mobile screens/trackpads (mousewheel + `Ctrl` commonly zooms) ([Firefox bug 1052253](https://bugzil.la/1052253)).
#### Selection API
- The [Selection API](/en-US/docs/Web/API/Selection) has been updated so that it has parity with other browsers in terms of how editing hosts are given focus when the selection moves inside them ([Firefox bug 1318312](https://bugzil.la/1318312)). See [Behavior of Selection API in terms of editing host focus changes](/en-US/docs/Web/API/Selection#behavior_of_selection_api_in_terms_of_editing_host_focus_changes) for more details.
- The {{domxref("Selection")}} API has been updated to match some recent spec changes ([Firefox bug 1359371](https://bugzil.la/1359371)):
- The {{domxref("Selection.collapse", "collapse()")}} and {{domxref("Selection.extend", "extend()")}} methods' `offset` parameter is now optional.
- The {{domxref("Selection.collapse", "collapse()")}} method's `node` parameter is now nullable.
- The {{domxref("Selection.containsNode", "containsNode()")}} method's `partialContainment` parameter is now optional.
- The {{domxref("Selection.deleteFromDocument", "deleteFromDocument()")}} method has been added.
- Also in the {{domxref("Selection")}} API, `Selection.empty()` and `Selection.setPosition()` have been added as aliases of {{domxref("Selection.removeAllRanges()")}} and {{domxref("Selection.collapse()")}}, for web compat and WebKit/Blink parity reasons ([Firefox bug 1359387](https://bugzil.la/1359387)).
- The {{domxref("StorageManager.persist()")}} and {{domxref("StorageManager.persisted()")}} methods of the [Storage API](/en-US/docs/Web/API/Storage_API) have been implemented and exposed to `Window` contexts ([Firefox bug 1286717](https://bugzil.la/1286717)).
#### Workers
- Workers and shared workers can now be created with an identifying `name` property. See the {{domxref("Worker.Worker", "Worker()")}} and {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructors, and the {{domxref("DedicatedWorkerGlobalScope")}} and {{domxref("SharedWorkerGlobalScope")}} interfaces. ([Firefox bug 1364297](https://bugzil.la/1364297)).
- {{domxref("setTimeout()")}} and {{domxref("setInterval()")}} are now subject to minimum interval throttling for tracking scripts in background tabs β see [Throttling of tracking timeout scripts](/en-US/docs/Web/API/setTimeout#throttling_of_tracking_timeout_scripts) ([Firefox bug 1355311](https://bugzil.la/1355311)).
#### Service Workers/Push
- Messages sent to service worker contexts (e.g. as the event object of {{domxref("ServiceWorkerGlobalScope.message_event","onmessage")}} are now represented by {{domxref("MessageEvent")}} objects, for consistency with other web messaging features.
- The {{domxref("PushManager.subscribe()")}} method now accepts {{jsxref("ArrayBuffer")}}s and Base64-encoded strings as `applicationServerKey` values ([Firefox bug 1337348](https://bugzil.la/1337348)).
#### Web Audio API
- A non-standard constructor (which accepted a string enum value indicating the purpose for which the context would be used) for {{domxref("AudioContext")}} interface was causing errors to be thrown when the `options` parameter was provided. We have removed the non-standard constructor. However, please note that the `options` parameter is not yet supported in Firefox and is currently ignored ([Firefox bug 1361475](https://bugzil.la/1361475)).
#### WebRTC
- {{domxref("mediaDevices.getUserMedia", "getUserMedia()")}} now provides a stereo audio stream by default if the source device provides stereo sound; support to specifically request mono input will come in [Firefox 56](/en-US/docs/Mozilla/Firefox/Releases/56). This only works on desktop at this time; mobile Firefox does not currently support stereo audio input sources ([Firefox bug 971528](https://bugzil.la/971528)).
- The `getUserMedia()` [media capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints) `autoGainControl` and `noiseSuppression` now match the spec; formerly they were `moz`-prefixed ([Firefox bug 1366415](https://bugzil.la/1366415)).
- When called with an empty constraints set, `getUserMedia()` was incorrectly returning `NotSupportedError` instead of `TypeError`. This has been fixed ([Firefox bug 1349480](https://bugzil.la/1349480)).
- The following new WebRTC statistics are available: `framesEncoded`, `pliCount`, `nackCount`, and `firCount` ([Firefox bug 1348657](https://bugzil.la/1348657)).
- The `RTCInboundRTPStreamStats` dictionary field formerly called `mozRtt` has been renamed to `roundTripTime` to match the specification; in addition, its behavior has been adjusted to match the standard: it contains a double-precision floating point value which estimates the round-trip time based on the RTCP timestamps in the RTCP Receiver Report, measured in seconds (following the algorithm described in {{RFC(3550, "", "6.4.1")}}). ([Firefox bug 1344970](https://bugzil.la/1344970)). However, please be aware that _this property is moving_ to a different dictionary (`RTCRemoteInboundRTPStreamStats`) soon ([Firefox bug 1380555](https://bugzil.la/1380555)).
- The `RTCRTPStreamStats` dictionary now includes the fields `firCount`, `pliCount`, and `nackCount`. These return low-level information that can be used to determine how reliable the connection is ([Firefox bug 1348657](https://bugzil.la/1348657)).
- The `RTCOutboundRTPStreamStats` dictionary now includes the field `framesEncoded`, which reports the number of frames that have been successfully encoded for the stream; with this information, you can compute the frame rate ([Firefox bug 1348657](https://bugzil.la/1348657)).
- On Android, there's now a [pref](https://bugzil.la/1265755#c36) to turn on hardware video encoding to improve video call performance and save on battery. To be enabled by default in [Firefox 56](/en-US/docs/Mozilla/Firefox/Releases/56) ([Firefox bug 1265755](https://bugzil.la/1265755)).
#### Encrypted Media Extensions API
- Firefox currently allows Encrypted Media Extensions to be used in insecure contexts, despite this not being allowed in the specification. This will be changed in the near future, and starting in Firefox 55, deprecation warnings are output to the [web console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html) when this is done. ([Firefox bug 1361000](https://bugzil.la/1361000)).
- Firefox currently doesn't require that at least one `MediaKeySystemCapabilities` object be included in the `suggestedConfigurations` parameter passed into {{domxref("Navigator.requestMediaKeySystemAccess()")}}, which the specification does mandate. Starting in Firefox 55, a warning is output to the web console when any audio or video configuration is specified without specifying supported codecs. Soon, failure to include a valid configuration for one or more of audio and video will throw an exception [Firefox bug 1368683](https://bugzil.la/1368683)).
#### WebGL
- The {{domxref("WEBGL_compressed_texture_s3tc_srgb")}} extension is now available to [WebGL](/en-US/docs/Web/API/WebGL_API) and [WebGL2](/en-US/docs/Web/API/WebGL2RenderingContext) contexts ([Firefox bug 1325113](https://bugzil.la/1325113)).
### Security
- The {{domxref("Geolocation")}} API is now available only to [secure contexts](/en-US/docs/Web/Security/Secure_Contexts) ([Firefox bug 1072859](https://bugzil.la/1072859)).
- The {{domxref("Storage API")}} is now available only to [secure contexts](/en-US/docs/Web/Security/Secure_Contexts) ([Firefox bug 1268804](https://bugzil.la/1268804)).
- The loading of mixed content is now allowed on localhost ([Firefox bug 903966](https://bugzil.la/903966)).
- Loading of remote JAR files has been disabled again ([Firefox bug 1329336](https://bugzil.la/1329336)).
### Plugins
- Flash content is now "click-to-activate" ([Firefox bug 1317856](https://bugzil.la/1317856)). This was immediately put into effect for all users of Nightly, and 50% of beta users. For Firefox 55 release version, the plan is to activate this for 5% of users 2 weeks after release, 25% of users 4 weeks after release, and 100% of users 6 weeks after release ([Firefox bug 1365714](https://bugzil.la/1365714)).
- Flash and other plugins can no longer be loaded from any URL scheme except for `http://` and `https://` ([Firefox bug 1335475](https://bugzil.la/1335475)).
### Other
- Firefox on Linux can now be made to run in headless mode using the `-headless` flag (see [Firefox bug 1356681](https://bugzil.la/1356681)).
## Removals from the web platform
### HTML
- The `xml:base` attribute can no longer be used to set the base URL for paths appearing in the [`style`](/en-US/docs/Web/HTML/Global_attributes#style) attribute, for example β
`<div xml:base="https://example.com/" style="background:url(picture.jpg)"></div>` ([Firefox bug 1350521](https://bugzil.la/1350521)).
- The {{htmlelement("style")}} element's [`scoped`](/en-US/docs/Web/HTML/Element/style#scoped) attribute has been hidden behind a pref (`layout.css.scoped-style.enabled`) in content documents in Firefox 55+, as no other browsers support it.
- Support for the obscure `MSThemeCompatible` value of the {{htmlelement("meta")}} element's [`http-equiv`](/en-US/docs/Web/HTML/Element/meta#http-equiv) attribute has been removed from Gecko. No other modern browsers support it, and it was causing compatibility problems ([Firefox bug 966240](https://bugzil.la/966240)).
### CSS
- The proprietary `:-moz-bound-element` pseudo-class has been removed ([Firefox bug 1350147](https://bugzil.la/1350147)).
- The proprietary `-moz-anchor-decoration` value of {{cssxref("text-decoration-line")}} has been removed ([Firefox bug 1355734](https://bugzil.la/1355734)).
### APIs
- The `UIEvent.isChar` property has never been supported by any browser but Firefox, and it has never been fully implemented except on macOS. For that reason, it was removed in Firefox 55 to align with other browsers.
- The proprietary Firefox OS Device Storage API has been removed from the platform ([Firefox bug 1299500](https://bugzil.la/1299500)).
- The `aShowDialog` parameter of the non-standard {{domxref("Window.find()")}} method (which could be specified to open up a "Find" dialog in the browser) has been removed ([Firefox bug 1348409](https://bugzil.la/1348409)).
- The `HTMLFormElement.requestAutoComplete()` method has been removed (see {{domxref("HTMLFormElement")}}) ([Firefox bug 1270740](https://bugzil.la/1270740)).
- The non-standard, Mozilla-specific, WebRTC offer options `mozDontOfferDataChannel` and `mozBundleOnly` have been removed from the `RTCOfferOptions` dictionary and are no longer supported by {{domxref("RTCPeerConnection.createOffer()")}} ([Firefox bug 1196974](https://bugzil.la/1196974)).
- Support for the proprietary Firefox OS `Audio Channels API` has been removed from {{domxref("HTMLMediaElement")}} and {{domxref("AudioContext")}} ([Firefox bug 1358061](https://bugzil.la/1358061)).
### SVG
- The `SVGZoomEvent` and `SVGZoomEvents` interfaces have been removed from the SVG2 spec and Gecko, along with the `onzoom <svg>` attribute ([Firefox bug 1314388](https://bugzil.la/1314388)).
## Changes for add-on and Mozilla developers
### WebExtensions
- [contextMenus.create()'s command property enables you to open browser action popups, page action popups, and sidebars from the context menu.](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/create)
- [proxy API](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy)
- [chrome_settings_overrides key enables you to override the browser's homepage.](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_settings_overrides)
- browser_style property enables you to have browser-like styling for [browser action popups](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action), [sidebars](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action), and [options pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui).
- [permissions API](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/permissions)
## Older versions
{{Firefox_for_developers(54)}}
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases | data/mdn-content/files/en-us/mozilla/firefox/releases/64/index.md | ---
title: Firefox 64 for developers
slug: Mozilla/Firefox/Releases/64
page-type: firefox-release-notes
---
{{FirefoxSidebar}}
This article provides information about the changes in Firefox 64 that will affect developers. Firefox 64 was released on December 11, 2018.
## Changes for web developers
### Developer tools
- The [Accessibility info-bar](https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/index.html#highlighting-of-ui-items) has been enhanced to include information about the color contrast ratio of text or images on the page ([Firefox bug 1473037](https://bugzil.la/1473037)).
- [Responsive Design Mode](https://firefox-source-docs.mozilla.org/devtools-user/responsive_design_mode/index.html) device selection is now saved between sessions ([Firefox bug 1248619](https://bugzil.la/1248619)).
- Resources that are potentially affected by [Tracking Protection](/en-US/docs/Web/Privacy/Firefox_tracking_protection) are now indicated in the [Network Monitor](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/index.html) ([Firefox bug 1333994](https://bugzil.la/1333994)).
- The [Web Console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html) got improvements around entering and evaluating code:
- [Autocomplete](https://firefox-source-docs.mozilla.org/devtools-user/web_console/the_command_line_interpreter/index.html#autocomplete) for Console expressions is now case-insensitive ([Firefox bug 672733](https://bugzil.la/672733)).
- You can now step through the [Console expression history](https://firefox-source-docs.mozilla.org/devtools-user/web_console/the_command_line_interpreter/index.html#command-history) with bash-like reverse search ([Firefox bug 1024913](https://bugzil.la/1024913)).
- [Evaluated code](https://firefox-source-docs.mozilla.org/devtools-user/web_console/the_command_line_interpreter/index.html) in the Console is now syntax-highlighted in both the input and output ([Firefox bug 1463669](https://bugzil.la/1463669)).
- Stepping in the [JavaScript Debugger](https://firefox-source-docs.mozilla.org/devtools-user/debugger/index.html) also had some improvements:
- [Stepping out](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/step_through_code/index.html) of a function in the Debugger now skips the return value ([Firefox bug 923975](https://bugzil.la/923975)).
#### Removals
- The Developer Tools GCLI has been removed ([Firefox bug 1429421](https://bugzil.la/1429421)).
### HTML
_No changes._
### CSS
- [CSS Scrollbars](/en-US/docs/Web/CSS/CSS_scrollbars_styling) spec functionality has been enabled by default ([Firefox bug 1492012](https://bugzil.la/1492012)).
- Interaction Media Features implemented, including [`pointer:coarse`](/en-US/docs/Web/CSS/@media/pointer) ([Firefox bug 1035774](https://bugzil.la/1035774)). For [`any-pointer`](/en-US/docs/Web/CSS/@media/any-pointer) and [`any-hover`](/en-US/docs/Web/CSS/@media/any-hover) implementation, see [Firefox bug 1483111](https://bugzil.la/1483111).
- The [`prefers-reduced-motion`](/en-US/docs/Web/CSS/@media/prefers-reduced-motion) media feature is now supported in Firefox for Android ([Firefox bug 1478505](https://bugzil.la/1478505)).
- CSS {{cssxref("<gradient>")}} values now support multi-position color stop syntax, e.g. `yellow 25%, yellow 50%` can now be written `yellow 25% 50%` ([Firefox bug 1352643](https://bugzil.la/1352643)).
- The {{cssxref("text-transform")}} property now accepts the `full-size-kana` value ([Firefox bug 1498148](https://bugzil.la/1498148)).
- Support added for {{cssxref("appearance", "-webkit-appearance")}} to alleviate associated web compat issues ([Firefox bug 1368555](https://bugzil.la/1368555)).
- Closely associated with the above update, we've also removed most of the Firefox-specific `-moz-appearance` values ([Firefox bug 1496720](https://bugzil.la/1496720)).
- {{cssxref("display")}}: `list-item` is now supported on {{htmlelement("legend")}} elements ([Firefox bug 1486602](https://bugzil.la/1486602)).
- SVG `path()`s, as usable in {{cssxref("offset-path")}}, are now animatable ([Firefox bug 1486094](https://bugzil.la/1486094)).
- If a selector chain or group includes a `-webkit-`prefixed pseudo-element, that pseudo-element no longer invalidates it (see [Firefox bug 1424106](https://bugzil.la/1424106) for the details, and [Firefox bug 1486325](https://bugzil.la/1486325) for enabling this feature).
#### Removals
- The non-standard `-moz-box` and `-moz-inline-box` {{CSSxRef("display")}} values have been hidden from web content ([Firefox bug 1496961](https://bugzil.la/1496961)).
- The non-standard `::-moz-tree` [pseudo-element](/en-US/docs/Web/CSS/Pseudo-elements) has been hidden from web content ([Firefox bug 1496961](https://bugzil.la/1496961)).
- The `layout.css.filters.enabled` preference has been removed; [CSS filters](/en-US/docs/Web/CSS/CSS_filter_effects) can no longer be disabled ([Firefox bug 1408841](https://bugzil.la/1408841)).
- A previous change β to swap the values of the 2-value {{cssxref("overflow")}} syntax so block is specified first and inline second ([Firefox bug 1481866](https://bugzil.la/1481866)) β has been reverted ([Firefox bug 1492567](https://bugzil.la/1492567)). See [Bug 1481866 comment 14](https://bugzil.la/1481866#c14) for why.
### SVG
_No changes._
### JavaScript
- The TC39 [Well-formed JSON.stringify](https://github.com/tc39/proposal-well-formed-stringify) proposal has been implemented, to prevent {{jsxref("JSON.stringify")}} from returning ill-formed Unicode strings ([Firefox bug 1469021](https://bugzil.la/1469021)).
- Proxied functions can now be passed to {{jsxref("Function.prototype.toString")}}`.call()` ([Firefox bug 1440468](https://bugzil.la/1440468)).
- In the [`WebAssembly.Global()`](/en-US/docs/WebAssembly/JavaScript_interface/Global) constructor, if no value is specified a typed 0 value is used. This is specified by the [`DefaultValue` algorithm](https://webassembly.github.io/spec/js-api/#defaultvalue) ([Firefox bug 1490286](https://bugzil.la/1490286)).
### APIs
#### DOM
- A number of changes related to the {{domxref("Fullscreen_API", "Fullscreen API", "", "1")}} have been implemented:
- The API has been unprefixed ([Firefox bug 1269276](https://bugzil.la/1269276)).
- The {{domxref("Element.requestFullscreen()")}} and {{domxref("Document.exitFullscreen()")}} methods both now return a {{jsxref("Promise")}}, which is resolved when the mode change is complete ([Firefox bug 1188256](https://bugzil.la/1188256) and [Firefox bug 1491212](https://bugzil.la/1491212)).
- Previously, {{domxref("Element/fullscreenchange_event", "fullscreenchange")}} and {{domxref("Element/fullscreenerror_event", "fullscreenerror")}} events were dispatched to the {{domxref("Document")}} first, then the {{domxref("Element")}}. This has been reversed so that the element gets the event first. This matches the latest specification as well as the behavior of Google Chrome ([Firefox bug 1375319](https://bugzil.la/1375319)).
- The {{domxref("WebVR_API", "WebVR API", "", "1")}} (1.1) is now re-enabled in macOS ([Firefox bug 1476091](https://bugzil.la/1476091)).
- {{domxref("Window.screenLeft")}} and {{domxref("Window.screenTop")}} have been implemented, as aliases of {{domxref("Window.screenX")}} and {{domxref("Window.screenY")}} ([Firefox bug 1498860](https://bugzil.la/1498860)).
- The {{domxref("XMLHttpRequest.getAllResponseHeaders()")}} method now returns header names all in lowercase, as per spec ([Firefox bug 1398718](https://bugzil.la/1398718)).
- The legacy `HTMLAllCollection` interface has been updated as per recent [spec updates](https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#htmlallcollection) ([Firefox bug 1398354](https://bugzil.la/1398354)).
- {{domxref("Navigator.buildID")}} now returns a fixed timestamp as a privacy measure ([Firefox bug 583181](https://bugzil.la/583181)).
- The following {{domxref("Document.execCommand()")}} UI feature commands have been disabled by default ([Firefox bug 1490641](https://bugzil.la/1490641):
- `enableObjectResizing`
- `enableInlineTableEditing`
- `enableAbsolutePositionEditor`
#### Service workers
- The {{domxref("ServiceWorkerContainer.startMessages()")}} method has been implemented ([Firefox bug 1263734](https://bugzil.la/1263734)).
#### Media, Web Audio, and WebRTC
- The {{domxref("PannerNode.refDistance")}}, {{domxref("PannerNode.maxDistance")}}, {{domxref("PannerNode.rolloffFactor")}}, and {{domxref("PannerNode.coneOuterGain")}} properties now correctly throw exceptions when set to values outside their accepted ranges ([Firefox bug 1487963](https://bugzil.la/1487963)).
- `RTCRtpEncodingParameters` settings changed via {{domxref("RTCRtpSender.setParameters()")}} used to not update if the changes were made during a call. They will now update live, without renegotiation ([Firefox bug 1253499](https://bugzil.la/1253499)).
- {{domxref("RTCIceCandidateStats.relayProtocol")}} has been implemented β this is the standardized version of `RTCIceCandidateStats.mozLocalTransport`, which has now been deprecated ([Firefox bug 1435789](https://bugzil.la/1435789)).
- Automatic Gain Control (AGC) is now enabled by default; this can be changed using the preference `media.getusermedia.agc_enabled` ([Firefox bug 1496714](https://bugzil.la/1496714)).
#### Removals
- The {{domxref("Window.event")}} property, added in Firefox 63 to aid with web compat issues, has been put behind a pref (`dom.window.event.enabled`) and disabled by default in release versions for now due to other issues that have been uncovered ([Firefox bug 1493869](https://bugzil.la/1493869)). Note that this was actually done late in the Firefox 63 release cycle, but we are mentioning it here just in case.
- The `LocalMediaStream` interface and its `stop()` method have been removed ([Firefox bug 1258143](https://bugzil.la/1258143)). This method is no longer available with the deprecation of `LocalMediaStream`. See the [Stopping a video stream](/en-US/docs/Web/API/MediaStreamTrack/stop#stopping_a_video_stream) section to learn how to stop an entire stream.
- The `AudioStreamTrack` and `VideoStreamTrack` interfaces have been removed, as both have been deprecated for some time ([Firefox bug 1377146](https://bugzil.la/1377146)). Their functionality has been merged into {{domxref("MediaStreamTrack")}}; tracks are now identified by the value of their {{domxref("MediaStreamTrack.kind", "kind")}} property, such as `audio` or `video`.
### Security
- The Symantec CA Distrust plan has been implemented (see [Firefox bug 1409257](https://bugzil.la/1409257); see also the [Mozilla's Plan for Symantec Roots](https://groups.google.com/forum/#!topic/mozilla.dev.security.policy/FLHRT79e3XE/discussion) discussion for more details).
- {{httpheader("Referrer-Policy")}} can now be used to govern resources fetched via stylesheets ([Firefox bug 1330487](https://bugzil.la/1330487)) β see [Integration with CSS](/en-US/docs/Web/HTTP/Headers/Referrer-Policy#integration_with_css) for more information.
### Plugins
_No changes._
### WebDriver conformance (Marionette)
#### API changes
- Deprecated command end-points without the `Marionette:`, `L10n:`, or `Addon:` prefix (including `singeTap`) have been removed ([Firefox bug 1504478](https://bugzil.la/1504478), [Firefox bug 1504940](https://bugzil.la/1504940)).
#### Bug fixes
- Synthesized `Shift` key events by using `WebDriver:PerformActions` didn't result in capitalized letters ([Firefox bug 1405370](https://bugzil.la/1405370)).
- `WebDriver:Navigate` could cause an infinite hang if the tab's underlying content process is changed multiple times during that navigation ([Firefox bug 1504807](https://bugzil.la/1504807)).
- To improve the performance, and to reduce the memory footprint of Firefox the default page to be loaded for a new tab or window is no longer `about:newtab` but `about:blank` ([Firefox bug 1506643](https://bugzil.la/1506643)).
- The content blocking introduction panel, which was shown on various web pages and caused element interactions to fail is disabled by default now ([Firefox bug 1488826](https://bugzil.la/1488826)).
## Changes for add-on developers
### API changes
#### Menus
- A new API, `{{WebExtAPIRef("menus.overrideContext()")}}`, can be called from the `contextmenu` DOM event to set a custom context menu in extension pages. This API allows extensions to hide all default Firefox menu items in favor of providing a custom context menu UI. This context menu can consist of multiple top-level menu items from the extension, and may optionally include tab or bookmark context menu items from other extensions. See [this blog post](https://blog.mozilla.org/addons/2018/11/08/extensions-in-firefox-64/#cm) for more details.
- `{{WebExtAPIRef("menus.overrideContext()")}}` was implemented in ([Firefox bug 1280347](https://bugzil.la/1280347)).
- The `showDefaults: false` option, which can be used to hide the default context menu options, was implemented in ([Firefox bug 1367160](https://bugzil.la/1367160)).
- `documentURLPatterns` can now be used to match a `moz-extension://` document URL, even if `{{WebExtAPIRef("menus.overrideContext()")}}` is used. This way, it can reliably be used to restrict custom menu items to certain documents ([Firefox bug 1498896](https://bugzil.la/1498896)).
- You can now restrict where context menus can appear in an add-on using the new `viewTypes` property in {{WebExtAPIRef("menus.create()")}} and {{WebExtAPIRef("menus.update()")}} ([Firefox bug 1416839](https://bugzil.la/1416839)).
- {{WebExtAPIRef("menus.update()")}} can now be used to update the icon of an existing menu item ([Firefox bug 1414566](https://bugzil.la/1414566)).
- Extensions can now detect which mouse button was used when a menu item was clicked β this can be found using the new `button` property of {{WebExtAPIRef("menus.OnClickData")}} ([Firefox bug 1469148](https://bugzil.la/1469148)).
#### Windows
- The {{WebExtAPIRef("windows.create()")}} method now has a new option available β `cookieStoreId` β which specifies the `CookieStoreId` to use for all tabs that were created when the window is opened ([Firefox bug 1393570](https://bugzil.la/1393570)).
#### Privacy
- The {{WebExtAPIRef("privacy.websites")}} `cookieConfig` property is an object that can accept a `behavior` property β this property can now take a new value, `reject_trackers`, which instructs the extension to reject tracking cookies ([Firefox bug 1493057](https://bugzil.la/1493057)).
#### devtools.panels API
- The [`devtools.panels.elements`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/panels/elements) `Sidebar.setPage()` method is now supported ([Firefox bug 1398734](https://bugzil.la/1398734)).
### Manifest changes
- The new `pinned` property of the [`page_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action) manifest key enables extensions to control whether their page actions should be pinned to the location bar on install or not ([Firefox bug 1494135](https://bugzil.la/1494135)).
- In native manifests on Windows, the 32-bit registry view ([Wow6432Node)](https://en.wikipedia.org/wiki/WoW64#Registry_and_file_system) will be checked first for registry keys, followed by the "native" registry view; you should use whichever is appropriate for your application ([Firefox bug 1494709](https://bugzil.la/1494709)).
- The [`chrome_settings_overrides`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_settings_overrides) field's `search_provider` object can now include new properties β `suggest_url` and `suggest_url_post_params` ([Firefox bug 1486819](https://bugzil.la/1486819)), and `search_url_post_params`.
## See also
- Hacks release post: [Firefox 64 Released](https://hacks.mozilla.org/2018/12/firefox-64-released/)
## Older versions
{{Firefox_for_developers(63)}}
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases | data/mdn-content/files/en-us/mozilla/firefox/releases/93/index.md | ---
title: Firefox 93 for developers
slug: Mozilla/Firefox/Releases/93
page-type: firefox-release-notes
---
{{FirefoxSidebar}}
This article provides information about the changes in Firefox 93 that will affect developers. Firefox 93 was released on October 5, 2021.
> **Note:** See also [Lots to see in Firefox 93](https://hacks.mozilla.org/2021/10/lots-to-see-in-firefox-93/) on Mozilla Hacks.
## Changes for web developers
### HTML
- The ARIA [`meter`](/en-US/docs/Web/Accessibility/ARIA/Roles/meter_role) role has been implemented ([Firefox bug 1727616](https://bugzil.la/1727616)).
- The UI for [`<input type="datetime-local">`](/en-US/docs/Web/HTML/Element/input/datetime-local) has been implemented. ([Firefox bug 1283388](https://bugzil.la/1283388)).
### CSS
- The `small-caps` keyword is now supported for the {{cssxref("font-synthesis")}} property ([Firefox bug 1706080](https://bugzil.la/1706080)).
### JavaScript
- [Class `static` initialization blocks](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks) are now supported, allowing more flexible initialization of {{jsxref("Classes/static", "static")}} properties ([Firefox bug 1725689](https://bugzil.la/1725689)).
- The properties `imageOrientation` and `premultiplyAlpha` can be passed to the method {{domxref("createImageBitmap()")}} using the `options` object ([Firefox bug 1367251](https://bugzil.la/1367251)).
- {{jsxref("Intl.supportedValuesOf()")}} is now supported, allowing code to enumerate values supported by an implementation, This might be used, for example, to download a polyfill for just the missing category of values ([Firefox bug 1670033](https://bugzil.la/1670033)).
### HTTP
- The SHA-256 algorithm is now supported for [HTTP Authentication](/en-US/docs/Web/HTTP/Authentication) using digests. This allows much more secure authentication than previously available using the MD5 algorithm ([Firefox bug 472823](https://bugzil.la/472823)).
- The default HTTP {{HTTPHeader("ACCEPT")}} header for _images_ changed to: `image/avif,image/webp,*/*` (following addition of support for the [AVIF](/en-US/docs/Web/Media/Formats/Image_types#avif_image) image format). ([Firefox bug 1682995](https://bugzil.la/1682995)).
### APIs
- {{domxref("ElementInternals.shadowRoot")}} and {{domxref("HTMLElement.attachInternals")}} are now supported ([Firefox bug 1723521](https://bugzil.la/1723521)).
- The value `device-pixel-content-box` is now supported for {{domxref("ResizeObserver.Observe()")}} ([Firefox bug 1587973](https://bugzil.la/1587973)).
- The {{domxref("reportError()")}} global function is now supported, allowing scripts to report errors to the console or global event handlers, emulating an uncaught JavaScript exception ([Firefox bug 1722448](https://bugzil.la/1722448)).
#### Events
- The {{domxref("Element.securitypolicyviolation_event","onsecuritypolicyviolation")}} global event handler property is now supported.
This can be used to assign a handler for processing [`securitypolicyviolation`](/en-US/docs/Web/API/Element/securitypolicyviolation_event) events fired when there is a [Content Security Policy](/en-US/docs/Web/HTTP/CSP) violation ([Firefox bug 1727302](https://bugzil.la/1727302)).
- The `onslotchange` event handler property is now supported on {{domxref("HTMLSlotElement")}} and {{domxref("ShadowRoot")}}.
This can be used to assign a handler for processing [`slotchange`](/en-US/docs/Web/API/HTMLSlotElement/slotchange_event) events, which are fired on {{HTMLElement("slot")}} elements when the node(s) contained in the slot change ([Firefox bug 1501983](https://bugzil.la/1501983)).
#### Removals
- {{domxref("KeyboardEvent.initKeyEvent()")}} has been moved behind the preference `dom.keyboardevent.init_key_event.enabled` and is disabled by default.
The method is not present in any current specification or supported in other current browsers ([Firefox bug 1717760](https://bugzil.la/1717760)).
### WebDriver conformance (Marionette)
- Fixed a bug which caused `WebDriver:Print` to fail for large documents ([Firefox bug 1721982](https://bugzil.la/1721982)).
## Changes for add-on developers
- Sidebars are now included in {{WebExtAPIRef("extension.getViews")}} when `windowId` is specified ([Firefox bug 1612390](https://bugzil.la/1612390)).
## Other
- Support for [AVIF](/en-US/docs/Web/Media/Formats/Image_types#avif_image) images is now enabled by default ([Firefox bug 1682995](https://bugzil.la/1682995)).
This format has excellent compression and no patent restrictions (it was developed by the [Alliance for Open Media](https://aomedia.org/)).
Firefox can display still images, with colorspace support for both full and limited range colors, and image transforms for mirroring and rotation.
The preference [image.avif.compliance_strictness](/en-US/docs/Mozilla/Firefox/Experimental_features#avif_compliance_strictness) can be used to adjust the compliance strictness with the specification. Animated images are not supported.
## Older versions
{{Firefox_for_developers(92)}}
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases | data/mdn-content/files/en-us/mozilla/firefox/releases/102/index.md | ---
title: Firefox 102 for developers
slug: Mozilla/Firefox/Releases/102
page-type: firefox-release-notes
---
{{FirefoxSidebar}}
This article provides information about the changes in Firefox 102 that will affect developers. Firefox 102 was released on June 28, 2022.
## Changes for web developers
### HTML
No notable changes.
### CSS
The [`update`](/en-US/docs/Web/CSS/@media/update) media feature that can be used to query the ability of the output device to modify the appearance of content after it is rendered is now available by default ([Firefox bug 1422312](https://bugzil.la/1422312)).
### JavaScript
No notable changes.
### APIs
- The non-standard interfaces `IDBMutableFile`, `IDBFileHandle`, `IDBFileRequest`, and the method `IDBDatabase.createMutableFile()` have been disabled by default in preparation for removal in a future release ([Firefox bug 1764771](https://bugzil.la/1764771)).
- [Transform streams](/en-US/docs/Web/API/TransformStream) are now supported, allowing you to pipe from {{domxref("ReadableStream")}} to a {{domxref("WritableStream")}}, executing a transformation on the chunks.
The update includes the new interfaces [`TransformStream`](/en-US/docs/Web/API/TransformStream) and [`TransformStreamDefaultController`](/en-US/docs/Web/API/TransformStreamDefaultController) and the method [`ReadableStream.pipeThrough()`](/en-US/docs/Web/API/ReadableStream/pipeThrough) ([Firefox bug 1767507](https://bugzil.la/1767507)).
- [Readable byte streams](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams) are now supported, allowing efficient zero-byte transfer of data from an underlying byte source to a consumer (bypassing the stream's internal queues).
The new interfaces are {{domxref("ReadableStreamBYOBReader")}}, {{domxref("ReadableByteStreamController")}} and {{domxref("ReadableStreamBYOBRequest")}} ([Firefox bug 1767342](https://bugzil.la/1767342)).
### Security
- Support of the [`wasm-unsafe-eval`](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_webassembly_execution) CSP policy directive has been implemented.
A document with a CSP that restricts scripts will no longer load and execute WebAssembly unless the CSP uses `'wasm-unsafe-eval'` or the existing `'unsafe-eval'` keyword ([Firefox bug 1740263](https://bugzil.la/1740263)).
#### DOM
- The Firefox-only property {{domxref("Window.sidebar")}} has been moved behind a preference (and permanently removed in version 119) ([Firefox bug 1768486](https://bugzil.la/1768486)).
### WebDriver conformance
#### WebDriver BiDi
- There are some improvements to Webdriver BiDi's `browsingContext.navigate`
- Fixed edge cases where the navigation could incorrectly timeout ([Firefox bug 1766217](https://bugzil.la/1766217)).
- Added support for hash changes ([Firefox bug 1763127](https://bugzil.la/1763127)).
- Added support navigation to error pages ([Firefox bug 1763124](https://bugzil.la/1763124)).
#### Marionette
- Allow marionette to connect to a windowless instance of Firefox ([Firefox bug 1726465](https://bugzil.la/1726465)).
- Fixed issue where `WebDriver:Navigate` with a PageLoadStrategy of "none" returns before navigation has started ([Firefox bug 1754132](https://bugzil.la/1754132)).
- Fixed a potential race condition in `WebDriver:SwitchToWindow` when switching to a different tab ([Firefox bug 1749666](https://bugzil.la/1749666)).
## Changes for add-on developers
- The {{WebExtAPIRef("scripting")}} API, which provides features to execute script, insert and remove CSS, and manage the registration of content scripts is available to Manifest V2 extensions ([Firefox bug 1766615](https://bugzil.la/1766615)).
- The `nonPersistentCookies` option of the {{WebExtAPIRef("privacy.websites")}} `cookieConfig` property has been deprecated ([Firefox bug 1754924](https://bugzil.la/1754924)).
- Manifest V3 [preview](https://blog.mozilla.org/addons/2022/06/08/manifest-v3-firefox-developer-preview-how-to-get-involved/) features:
- With the introduction of support for the 'wasm-unsafe-eval' CSP keyword in Firefox ([Firefox bug 1740263](https://bugzil.la/1740263)), Manifest V3 extensions are now required to specify this keyword in the [content_security_policy](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy) manifest key to use [WebAssembly](/en-US/docs/WebAssembly). For backwards-compatibility, Manifest V2 extensions can still use WebAssembly without the keyword ([Firefox bug 1766027](https://bugzil.la/1766027)).
## Older versions
{{Firefox_for_developers(101)}}
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases | data/mdn-content/files/en-us/mozilla/firefox/releases/5/index.md | ---
title: Firefox 5 for developers
slug: Mozilla/Firefox/Releases/5
page-type: firefox-release-notes
---
{{FirefoxSidebar}}
Firefox 5, based on Gecko 5.0, was released on June 21, 2011. This article provides links to information about the changes that affect developers in this release.
## Changes for web developers
### HTML
- All HTML elements now have the {{ domxref("HTMLElement/accessKey", "accessKey") }} attribute, as well as the {{ domxref("element.blur()", "blur()") }}, {{ domxref("element.click()", "click()") }}, and {{ domxref("element.focus()", "focus()") }} methods. These are specified in the {{ domxref("HTMLElement") }} interface.
- In order to comply with the HTML5 specification, support for the UTF-7 and UTF-32 [character sets](/en-US/docs/Character_Sets_Supported_by_Gecko) has been removed.
- When in quirks mode, empty {{ HTMLElement("map") }}s are no longer skipped over in favor of non-empty ones when matching. See the [Gecko notes](/en-US/docs/Web/HTML/Element/map#gecko_notes) on the {{ HTMLElement("map") }} element for details.
- Firefox mobile on Android now supports WOFF fonts for {{ cssxref("@font-face") }}.
- WebGL [no longer loads textures from domains other than the originating domain](/en-US/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL#cross-domain_textures), as a security measure. [HTTP access control](/en-US/docs/Web/HTTP_access_control) support should be coming sometime in the future to make this possible more securely.
#### Canvas improvements
- The {{ HTMLElement("canvas") }} 2D drawing context now supports specifying an `ImageData` object as the input to the `createImageData()` method; this [creates a new `ImageData` object](/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas#creating_an_imagedata_object) initialized with the same dimensions as the specified object, but still with all pixels preset to transparent black. This was documented as implemented already but was not.
- Specifying non-finite values when adding color stops through a call to the {{ domxref("CanvasGradient") }} method `addColorStop()` now correctly throws `INDEX_SIZE_ERR` instead of `SYNTAX_ERR`.
- The {{ domxref("HTMLCanvasElement") }} method `toDataURL()` now correctly lower-cases the specified MIME type before matching.
- `getImageData()` now correctly accepts rectangles that extend beyond the bounds of the canvas; pixels outside the canvas are returned as transparent black.
- `drawImage()` and `createImageData()` now handle negative arguments in accordance with the specification, by flipping the rectangle around the appropriate axis. **We need an article about [CSS sizing](https://drafts.csswg.org/css-images-3/) and how this works.**
- Specifying non-finite values when calling `createImageData()` now properly throws a `NOT_SUPPORTED_ERR` exception.
- `createImageData()` and `getImageData()` now correctly return at least one pixel's worth of image data if a rectangle smaller than one pixel is specified.
- Specifying a negative radius when calling `createRadialGradient()` now correctly throws `INDEX_SIZE_ERR`.
- Specifying a `null` or `undefined` image when calling `createPattern()` or `drawImage()` now correctly throws a `TYPE_MISMATCH_ERR` exception.
- Specifying invalid values for `globalAlpha` no longer throws a `SYNTAX_ERR` exception; these are now correctly silently ignored.
- Specifying invalid values when calling `translate()`, `transform()`, `rect()`, `clearRect()`, `fillRect()`, `strokeRect()`, `lineTo()`, `moveTo()`, `quadraticCurveTo()`, or `arc()` no longer throws an exception; these calls are now correctly silently ignored.
- Setting the value of `shadowOffsetX`, `shadowOffsetY`, or `shadowBlur` to an invalid value is now silently ignored.
- Setting the value of `rotate` or `scale` to an invalid value is now silently ignored.
### CSS
- [CSS animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations)
- : Support for CSS animations has been added, using the `-moz-` prefix for now.
### DOM
- The {{ domxref("selection") }} object's [`modify()`](/en-US/docs/Web/API/Selection/modify) method has been changed so that the "word" selection granularity no longer includes trailing spaces; this makes it more consistent across platforms and matches the behavior of WebKit's implementation.
- The {{ domxref("setTimeout()") }} method now clamps to send no more than one timeout per second in inactive tabs. In addition, it now clamps nested timeouts to the smallest value allowed by the HTML5 specification: 4 ms (instead of the 10 ms it used to clamp to).
- Similarly, the {{ domxref("setInterval()") }} method now clamps to no more than one interval per second in inactive tabs.
- [`XMLHttpRequest`](/en-US/docs/Web/API/XMLHttpRequest) now [supports the `loadend` event](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest#detecting_any_load_end_condition) for progress listeners. This is sent after any transfer is finished (that is, after the `abort`, `error`, or `load` event). You can use this to handle any tasks that need to be performed regardless of success or failure of a transfer.
- The {{ domxref("Blob") }} and, by extension, the {{ domxref("File") }} objects' `slice()` method has been removed and replaced with a new, proposed syntax that makes it more consistent with [`Array.slice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) and [`String.slice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods in JavaScript. This method is named `mozSlice()` for now.
- The value of {{ domxref("window.navigator.language") }} is now determined by looking at the value of the `Accept-Language` [HTTP header](/en-US/docs/Web/HTTP/Headers).
- The {{ domxref("Element.prefix") }} property is now read only, as required by the DOM specification.
- The {{ domxref("HTMLVideoElement") }} now supports experimental properties to get information about video paint statistics like frame rates.
### JavaScript
- Regular expressions are no longer callable as if they were functions; this change has been made in concert with the WebKit team to ensure compatibility (see [Webkit bug 28285](https://webkit.org/b/28285). This feature had existed for a long time but was never documented (at least, not here on MDC).
- The [`Function.prototype.isGenerator()`](/en-US/docs/JavaScript/Reference/Global_Objects/Function/isGenerator) method is now supported; this lets you determine if a function is a [generator](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators#generator_functions).
- The following [reserved words](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords) were previously only treated as reserved when in strict mode; now they're always treated as reserved: `class`, `enum`, `export`, `extends`, `import`, and `super`.
- DOM documents created in chrome code may no longer be exposed to sandboxed scripts.
- The JSON parser has been re-written for improved speed and compliance. This includes a fix for [Firefox bug 572279](https://bugzil.la/572279).
### SVG
- The {{ SVGAttr("class") }} SVG attribute can now be animated.
- The following SVG-related DOM interfaces representing lists of objects are now indexable and can be accessed like arrays; in addition, they have a `length` property indicating the number of items in the lists: {{ domxref("SVGLengthList") }}, {{ domxref("SVGNumberList") }}, {{ domxref("SVGPathSegList") }}, and {{ domxref("SVGPointList") }}.
### HTTP
- Firefox no longer sends the `Keep-Alive` HTTP header; we weren't formatting it correctly, and it was redundant since we were also sending the {{ httpheader("Connection") }} or {{ httpheader("Proxy-Connection") }} header with the value "keep-alive" anyway.
- The HTTP transaction model has been updated to be more intelligent about reusing connections in the persistent connection pool; instead of treating the pool as a [FIFO](https://en.wikipedia.org/wiki/FIFO) queue, Necko now attempts to sort the pool with connections with the largest [congestion window](https://en.wikipedia.org/wiki/Congestion_window) (CWND) first. This can reduce the round-trip time (RTT) of HTTP transactions by avoiding the need to grow connections' windows in many cases.
- Firefox now handles the `Content-Disposition` HTTP response header more effectively if both the `filename` and `filename*` parameters are provided; it looks through all provided names, using the `filename*` parameter if one is available, even if a `filename` parameter is included first. Previously, the first matching parameter would be used, thereby preventing a more appropriate name from being used. See [Firefox bug 588781](https://bugzil.la/588781).
### MathML
- Support for [embellished operators](https://www.w3.org/TR/MathML3/chapter3.html#id.3.2.5.7.3)
### Developer tools
- The [Web Console's `Console` object](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html#the-console-object) now has a `debug()` method, which is an alias for its `log()` method; this improves compatibility with certain existing sites.
## Changes for Mozilla and add-on developers
For a guide to updating your add-on for Firefox 5, please see [Updating add-ons for Firefox 5](/en-US/docs/Mozilla/Firefox/Updating_add-ons_for_Firefox_5).
> **Note:** Firefox 5 requires that binary components be recompiled, as do all major releases of Firefox. See [Binary Interfaces](/en-US/docs/Mozilla/Developer_guide/Interface_Compatibility#binary_interfaces) for details.
### Changes to JavaScript code modules
#### New JavaScript code modules
- The [`Dict.jsm`](/en-US/docs/JavaScript_code_modules/Dict.jsm) code module was added; it provides an API for dictionaries of key/value pairs.
#### NetUtil.jsm
- The `asyncFetch()` method now supports specifying the input source as an `nsIInputStream`.
### Interface changes
- The `nsIHttpChannelInternal` interface has new attributes providing access to information about the channels' endpoints' addresses and ports. This information is provided primarily for debugging purposes.
- The {{ HTMLElement("canvas") }} element's [`width`](/en-US/docs/Web/HTML/Element/canvas#width) and [`height`](/en-US/docs/Web/HTML/Element/canvas#height) attributes are now reflected in IDL as unsigned integers instead of signed (see [`HTMLCanvasElement`](/en-US/docs/Web/API/HTMLCanvasElement)).
- The `nsIAppStartup2` and `nsIAppStartup_MOZILLA_2_0` interfaces have been merged into the `nsIAppStartup` interface.
- The `nsIDocShell_MOZILLA_2_0_BRANCH` interface has been merged into the `nsIDocShell` interface.
- The `nsIFocusManager_MOZILLA_2_0_BRANCH` interface has been merged into the `nsIFocusManager` interface.
- The `nsIHTMLEditor_MOZILLA_2_0_BRANCH` interface has been merged into the `nsIHTMLEditor` interface.
#### New interfaces
- `nsIDOMAnimationEvent` added. {{domxref("AnimationEvent")}}
#### Removed interfaces
The following interfaces were implementation details that are no longer needed:
- `nsICiter` (see [Firefox bug 633066](https://bugzil.la/633066))
- `nsIDOM3Document` (see [Firefox bug 639849](https://bugzil.la/639849))
- `nsIFIXptrEvaluator`
- `nsISelectElement` (see [Firefox bug 619996](https://bugzil.la/619996))
### Debugging aids
- The new [`DebugOnly<T>`](/en-US/Namespace/Mozilla/DebugOnly%3CT%3E) helper makes it possible to declare variables only for `DEBUG` builds.
### JavaScript API (SpiderMonkey)
- [`JS_DoubleToInt32()`](/en-US/docs/SpiderMonkey/JSAPI_Reference/JS_DoubleToInt32) and [`JS_DoubleToUint32()`](/en-US/docs/SpiderMonkey/JSAPI_Reference/JS_DoubleToUint32) have been added, for converting [`jsdouble`](/en-US/docs/SpiderMonkey/JSAPI_Reference/jsdouble) values into C integers and unsigned integers.
### Build system changes
- You can now build Firefox without a `mozconfig` file; the [`--enable-application` setting](https://firefox-source-docs.mozilla.org/setup/configuring_build_options.html#choose_an_application) now defaults to "browser". After pulling or downloading the code, you can `configure && make` (or `make -f client.mk`) to build Firefox.
## See also
{{Firefox_for_developers('4')}}
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases/5 | data/mdn-content/files/en-us/mozilla/firefox/releases/5/updating_add-ons/index.md | ---
title: Updating add-ons for Firefox 5
slug: Mozilla/Firefox/Releases/5/Updating_add-ons
page-type: guide
---
{{FirefoxSidebar}}
This article provides an overview of the changes you may need to make to your add-ons in order for them to work properly in Firefox 5. You can find a complete list of developer-related changes in Firefox 5 in [Firefox 5 for developers](/en-US/docs/Mozilla/Firefox/Releases/5).
## Do you need to do anything at all?
If your add-on is distributed on [addons.mozilla.org](https://addons.mozilla.org/en-US/firefox/) (AMO), it's been checked by an automated compatibility verification tool. Add-ons that don't use APIs that changed in Firefox 5, and have no binary components (which need to be recompiled for every major Firefox release), have automatically been updated on AMO to indicate that they work in Firefox 5.
So you should start by visiting AMO and looking to see if your add-on needs any work done at all.
> **Note:** You should still test your add-on on Firefox 5, even if it's been automatically upgraded. There are edge cases that may not be automatically detected.
Once you've confirmed that you need to make changes, come on back to this page and read on.
## User interface related changes
Due to the short development cycle (even for our rapid release cycle; Firefox 5 was on an extra-short schedule for timing reasons), there are very few UI related changes in Firefox 5.
### Determining the UI language
In the past, the {{ domxref("Navigator.language", "window.navigator.language") }} DOM property reflected the language of Firefox's user interface. This is no longer the case; instead, it reflects the value of the `Accept-Language` header for the current document. If you need to detect the UI language, you should instead look at the value of the `general.useragent.locale` preference.
## DOM changes
The behaviors of {{ domxref("setTimeout()") }} and {{ domxref("setInterval()") }} have changed; the minimum allowed time has changed, and [varies depending on the situation](/en-US/docs/Web/API/setTimeout#minimum_delay_and_timeout_nesting). In addition, timeouts and intervals are clamped to one per second in inactive tabs (that is, tabs the user isn't currently looking at).
## JavaScript changes
The following keywords are now reserved in JavaScript, even when you're not in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode):
- `class`
- `enum`
- `export`
- `extends`
- `import`
- `super`
Don't use those keywords anywhere in your code, even as object property names.
> **Note:** This is one of those things that AMO's automatically upgrade tool may not always catch, so check your code for these if your add-on was automatically upgraded but is still not working properly.
## Interface changes
Instantiating certain services, including the `nsICertOverrideService`, at startup can make Firefox unusable ([Firefox bug 650858](https://bugzil.la/650858). This happens only if you try to instantiate a service before the `load` event is fired.
To fix this, move your instantiation of these services into your `load` event handler:
```js
var MyObject = {
comp: null,
init() {
this.comp = Components.classes["β¦"].getService(/* β¦ */);
},
// β¦
};
window.addEventListener(
"load",
function () {
MyObject.init();
},
false,
);
```
An even better solution, of course, is to follow performance best practices and to not instantiate services until you need to use them.
## See also
- [Firefox 5 for developers](/en-US/docs/Mozilla/Firefox/Releases/5)
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases | data/mdn-content/files/en-us/mozilla/firefox/releases/87/index.md | ---
title: Firefox 87 for developers
slug: Mozilla/Firefox/Releases/87
page-type: firefox-release-notes
---
{{FirefoxSidebar}}
This article provides information about the changes in Firefox 87 that will affect developers. Firefox 87 was released on March 23, 2021.
> **Note:** See also [In March, we see Firefox 87](https://hacks.mozilla.org/2021/03/in-march-we-see-firefox-87/) on Mozilla Hacks.
## Changes for web developers
### Developer Tools
- Developers can now use the [Page Inspector](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_and_edit_css/index.html#view-media-rules-for-prefers-color-scheme) to simulate {{cssxref("@media/prefers-color-scheme", "prefers-color-scheme")}} media queries, without having to change the operating system to light or dark mode ([Firefox bug 1679408](https://bugzil.la/1679408) and [Firefox bug 1692272](https://bugzil.la/1692272)).
- Developers can now use the [Page Inspector](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_and_edit_css/index.html#viewing-common-pseudo-classes) to toggle the {{cssxref(":target")}} pseudo-class for the currently selected element in addition to the pseudo-classes that were previously supported: {{cssxref(":hover")}}, {{cssxref(":active")}} and {{cssxref(":focus")}}, {{cssxref(":focus-within")}}, {{cssxref(":focus-visible")}}, and {{cssxref(":visited")}} ([Firefox bug 1689899](https://bugzil.la/1689899)).
- Firefox 87 sees a number of [Page Inspector](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_and_edit_css/index.html#rule-display) improvements and bug fixes related to inactive CSS rules:
- The {{cssxref("table-layout")}} property is now marked as inactive for non-table elements ([Firefox bug 1551571](https://bugzil.la/1551571)).
- The {{cssxref("scroll-padding")}} properties (shorthand and longhand) are now marked as inactive for non-scrollable elements ([Firefox bug 1551577](https://bugzil.la/1551577)).
- The {{cssxref("text-overflow")}} property was previously incorrectly marked as inactive for some {{cssxref("overflow")}} values ([Firefox bug 1671457](https://bugzil.la/1671457)).
### HTML
_No changes._
### CSS
- Some languages have digraphs that are always capitalized together, for example `IJ` in Dutch. The {{cssxref("::first-letter")}} pseudo-element now respects these digraphs and treats them as a single unit ([Firefox bug 92176](https://bugzil.la/92176)).
- The {{HTMLElement("link")}} element is no longer matched by {{cssxref(":link")}}, {{cssxref(":visited")}}, or {{cssxref(":any-link")}}. This aligns the behavior in Firefox to existing behavior in Chrome and to a recent spec change ([Firefox bug 1687538](https://bugzil.la/1687538)).
#### Removals
- The following Firefox-specific theme-related media features have been disabled for use in web pages ([Firefox bug 787521](https://bugzil.la/787521)):
- `-moz-mac-graphite-theme`
- `-moz-mac-lion-theme`
- `-moz-maemo-classic`
- `-moz-windows-classic`
- `-moz-windows-compositor`
- `-moz-windows-default-theme`
- `-moz-windows-theme`
- `-moz-scrollbar-end-backward`
- `-moz-scrollbar-end-forward`
- `-moz-scrollbar-start-backward`
- `-moz-scrollbar-start-forward`
- `-moz-scrollbar-thumb-proportional`
- `-moz-menubar-drag`
- The non-standard values of {{cssxref("caption-side")}} (`left`, `right`, `top-outside`, and `bottom-outside`) have been removed and placed behind the `layout.css.caption-side-non-standard.enabled` flag ([Firefox bug 1688695](https://bugzil.la/1688695)).
### JavaScript
_No changes._
### HTTP
- Some enterprise authentication services require that TLS client certificates be [sent in CORS preflight requests](/en-US/docs/Web/HTTP/CORS#preflight_requests_and_credentials). Users of these services can enable this (non-specification compliant) behavior using the `network.cors_preflight.allow_client_cert` preference ([Firefox bug 1511151](https://bugzil.la/1511151)).
- The default [`Referrer-Policy`](/en-US/docs/Web/HTTP/Headers/Referrer-Policy) has been changed to [`strict-origin-when-cross-origin`](/en-US/docs/Web/HTTP/Headers/Referrer-Policy#strict-origin-when-cross-origin) (from `no-referrer-when-downgrade`), reducing the risk of leaking referrer information in cross-origin requests ([Firefox bug 1589074](https://bugzil.la/1589074)).
- [`Content-Length`](/en-US/docs/Web/HTTP/Headers/Content-Length) has been added to the list of [CORS-safelisted response headers](/en-US/docs/Glossary/CORS-safelisted_response_header) ([Firefox bug 1460299](https://bugzil.la/1460299)).
### Security
_No changes._
### APIs
#### DOM
- The {{domxref("Element.beforeinput_event", "beforeinput")}} event and {{domxref('InputEvent.getTargetRanges()', 'getTargetRanges()')}} method are now enabled by default. They allow web apps to override text edit behavior before the browser modifies the DOM tree, and provide more control over input events to improve performance. The global `beforeinput` event is sent to an {{HTMLElement("input")}} element β or any element whose [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes#contenteditable) attribute is set to `true` β immediately before the element's value changes. The `getTargetRanges()` method of the {{domxref("InputEvent")}} interface returns an array of static ranges that will be affected by a change to the DOM if the input event is not canceled.
### WebDriver conformance (Marionette)
- The work of rewriting Marionette to support Fission (site-isolation) has been finished, so the old Marionette implementation has been removed. The `marionette.actors.enabled` preference, which toggled between the new and old implementations, has therefore also been removed ([Firefox bug 1669172](https://bugzil.la/1669172)).
- WebDriver commands following a call to `WebDriver:SwitchToFrame` will no longer fail with a "no such window" error if the frame's content hasn't yet finished loading ([Firefox bug 1691348](https://bugzil.la/1691348)).
- After a [cross-group page navigation](https://firefox-source-docs.mozilla.org/dom/navigation/nav_replace.html#cross-group-navigations), accessing a previously-retrieved element will now always raise a "stale element" error; there is no longer a chance that this action will lead to a "no such element" error ([Firefox bug 1690308](https://bugzil.la/1690308)).
- `Addon:Uninstall` now raises an `unknown error` when the id of the add-on to uninstall is unknown ([Firefox bug 1693022](https://bugzil.la/1693022)).
## Changes for add-on developers
- [nativeMessaging](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging) is now an [optional permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) ([Firefox bug 1630415](https://bugzil.la/1630415)).
- Added support for querying and setting color management related features with {{WebExtAPIRef("browserSettings.colorManagement")}} ([Firefox bug 1719688](https://bugzil.la/1719688)) and ([Firefox bug 1714428](https://bugzil.la/1714428)).
## Older versions
{{Firefox_for_developers(86)}}
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases | data/mdn-content/files/en-us/mozilla/firefox/releases/84/index.md | ---
title: Firefox 84 for developers
slug: Mozilla/Firefox/Releases/84
page-type: firefox-release-notes
---
{{FirefoxSidebar}}
This article provides information about the changes in Firefox 84 that will affect developers. Firefox 84 was released on December 15, 2020.
> **Note:** See also [And now for β¦ Firefox 84](https://hacks.mozilla.org/2020/12/and-now-for-firefox-84/) on Mozilla Hacks.
## Changes for web developers
### Developer Tools
- The Firefox [Accessibility Inspector](https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/index.html) now supports displaying the [keyboard tab order](https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/index.html#show-web-page-tabbing-order) on a web page. This provides a better high-level overview of how the page will be navigated using the keyboard than tabbing through the links ([Firefox bug 1654956](https://bugzil.la/1654956)).
### HTML
_No changes._
### CSS
- We've added support for complex selectors to the {{cssxref(":not")}} pseudo-class ([Firefox bug 933562](https://bugzil.la/933562)).
#### Removals
- We've removed the proprietary `-moz-default-appearance` property values `scrollbar-small` (`scrollbar-width: thin` is used instead) and `scrollbar` (macOS only; `scrollbar-horizontal` and `scrollbar-vertical` are used instead) ([Firefox bug 1673132](https://bugzil.la/1673132)).
### JavaScript
- Custom date/time formats specified as options to the [`Intl.DateTimeFormat()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) can now include `fractionalSecondDigits` β the number of digits used to represent fractions of a second ([Firefox bug 1645107](https://bugzil.la/1645107)).
### HTTP
_No changes._
### Security
- Firefox now ensures that `localhost` URLs β such as `http://localhost/` and `http://dev.localhost/` β refer to the local host's loopback interface (e.g. `http://127.0.0.1`). As a result, resources loaded from `localhost` are now assumed to have been delivered securely (see [Secure contexts](/en-US/docs/Web/Security/Secure_Contexts)), and also will not be treated as [mixed content](/en-US/docs/Web/Security/Mixed_content) ([Firefox bug 1220810](https://bugzil.la/1220810), [Firefox bug 1488740](https://bugzil.la/1488740)).
### APIs
- We've added support for the {{domxref('PerformancePaintTiming')}} interface of the Paint Timing API ([Firefox bug 1518999](https://bugzil.la/1518999)).
- The {{domxref('Navigator.registerProtocolHandler()')}} method now only accepts two parameters: `scheme` and `url`. `title` has been removed ([Firefox bug 1631464](https://bugzil.la/1631464)).
#### Media, WebRTC, and Web Audio
- The {{domxref('MediaRecorder.start()')}} method now throws an `InvalidModificationError` if the number of tracks on the stream being recorded has changed ([Firefox bug 1581139](https://bugzil.la/1581139)).
#### Removals
- The application cache has been removed β developers should use the [Service Worker API](/en-US/docs/Web/API/Service_Worker_API) instead ([Firefox bug 1619673](https://bugzil.la/1619673)).
### WebAssembly
_No changes._
### WebDriver conformance (Marionette)
- Added chrome scope support for `WebDriver:PerformActions` and `WebDriver:ReleaseActions` ([Firefox bug 1365886](https://bugzil.la/1365886)).
- The new Fission-compatible API has been enabled by default now. To revert to the former API the `marionette.actors.enabled` preference has to be set to `false` ([Firefox bug 1669169](https://bugzil.la/1669169)).
- Fixed `WebDriver:SwitchToWindow` to always switch back to the top-level browsing context ([Firefox bug 1305822](https://bugzil.la/1305822)).
- Improved browsing context checks for `WebDriver:SwitchToParentFrame` ([Firefox bug 1671622](https://bugzil.la/1671622)).
- Fixed a hang for `WebDriver:Back` encountered when the currently-selected [`<iframe>`](/en-US/docs/Web/HTML/Element/iframe) gets unloaded ([Firefox bug 1672758](https://bugzil.la/1672758)).
#### Known bugs
- After page navigation, accessing a previously-retrieved element might not always raise a "stale element" error, and can also lead to a "no such element" error. To prevent this, set the `marionette.actors.enabled` preference to `false` ([Firefox bug 1684827](https://bugzil.la/1684827)).
## Changes for add-on developers
- The [`browsingData.remove()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browsingData/remove) API now supports removing a subset of data types by `cookieStoreId`.
## Older versions
{{Firefox_for_developers(83)}}
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases | data/mdn-content/files/en-us/mozilla/firefox/releases/109/index.md | ---
title: Firefox 109 for developers
slug: Mozilla/Firefox/Releases/109
page-type: firefox-release-notes
---
{{FirefoxSidebar}}
This article provides information about the changes in Firefox 109 that will affect developers. Firefox 109 was released on January 17, 2023.
## Changes for web developers
### HTML
- The {{HTMLElement("input/range", "range")}} element supports the [`list`](/en-US/docs/Web/HTML/Element/input/range#list) attribute, which links via an id to a {{HTMLElement("datalist")}} to allow Firefox to display tick marks along the range.
### CSS
- The [`<system-color>`](/en-US/docs/Web/CSS/system-color) CSS data type now supports the values [`Mark`](/en-US/docs/Web/CSS/system-color#mark), [`MarkText`](/en-US/docs/Web/CSS/system-color#marktext), and [`ButtonBorder`](/en-US/docs/Web/CSS/system-color#buttonborder) ([Firefox bug 1638052](https://bugzil.la/1638052)).
### JavaScript
No notable changes.
### SVG
#### Removals
- `SVGGraphicsElement.getTransformToElement()` has been removed.
This follows its removal from the SVG2 specification in 2015, and from other major browsers.
([Firefox bug 1803790](https://bugzil.la/1803790)).
- The `SVGGraphicsElement.nearestViewportElement` and `SVGGraphicsElement.farthestViewportElement` attributes have been disabled by default in nightly and early beta builds (behind preference `svg.nearestAndFarthestViewportElement.enabled`).
[`SVGElement.viewportElement`](/en-US/docs/Web/API/SVGElement#svgelement.viewportelement) can be used as an alternative to `SVGGraphicsElement.nearestViewportElement`.
They have been removed from the SVG2 specification and are likely to be removed entirely from Firefox in a future release.
([Firefox bug 1133174](https://bugzil.la/1133174)).
### HTTP
- The `'unsafe-hashes'` value for {{HTTPHeader("Content-Security-Policy")}} source directives is now supported.
For more information, see [CSP unsafe-hashes](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_hashes) ([Firefox bug 1343950](https://bugzil.la/1343950)).
### APIs
#### DOM
- The `scrollend` events are now supported, which indicate that the user has completed scrolling in {{domxref("Element")}} and {{domxref("Document")}} objects.
For more information, see [Element: `scrollend` event](/en-US/docs/Web/API/Element/scrollend_event) and [Document: `scrollend` event](/en-US/docs/Web/API/Document/scrollend_event) ([Firefox bug 1797013](https://bugzil.la/1797013), [Firefox bug 1803435](https://bugzil.la/1803435)).
### WebDriver conformance (WebDriver BiDi, Marionette)
#### WebDriver BiDi
- The connection details for WebDriver BiDi are now written to `WebDriverBiDiServer.json` instead of `WebDriverBiDiActivePort`, which contains both the port (`ws_port`) and the host (`ws_host`). This file is located in the Firefox profile folder ([Firefox bug 1792875](https://bugzil.la/1792875)).
- Added support for subscribing / unsubscribing to individual `contexts` when using `session.subscribe` and `session.unsubscribe` ([Firefox bug 1723102](https://bugzil.la/1723102)).
- Added support for serializing `Node` objects ([Firefox bug 1770731](https://bugzil.la/1770731)).
- Fixed the `columnNumber` for `exceptions` and `stackTraces` to be 0-based ([Firefox bug 1796073](https://bugzil.la/1796073)).
#### Marionette
- Fixed a bug where `WebDriver:NewWindow` and `WebDriver:SwitchToWindow` were not focusing the new window properly ([Firefox bug 1798655](https://bugzil.la/1798655)).
- Fixed a bug where `WebDriver:FindElement` (and similar commands) would fail if the Firefox window was occluded by other applications on Windows ([Firefox bug 1802473](https://bugzil.la/1802473)).
## Changes for add-on developers
- Manifest V3 is now supported with the ability to sign and release Manifest V3 extensions on AMO. See the [Manifest v3 signing available November 21 on Firefox Nightly](https://blog.mozilla.org/addons/2022/11/17/manifest-v3-signing-available-november-21-on-firefox-nightly/) blog post for more information. The following preview features are now fully available:
- The {{WebExtAPIRef("scripting")}} API, although this has been available to Manifest V2 extensions from Firefox 102.
- The {{WebExtAPIRef("action")}} API, and [`"action"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/action) manifest key and [`_execute_action` special shortcut](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/commands#special_shortcuts) in the manifest `commands` key.
- The [`"host_permissions"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/host_permissions) manifest key.
- The default [Content Security Policy (CSP)](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy) for Manifest V3 extensions has been updated to [include `upgrade-insecure-requests`](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy#upgrade_insecure_network_requests_in_manifest_v3). This means that, by default, all network requests are upgraded to use `https:`. Extensions that need to use `http:` can do so by overriding the default CSP using the [`content_security_policy`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy) manifest.json key ([Firefox bug 1797086](https://bugzil.la/1797086)).
- The property `secretKeyLength` has been added to {{WebExtAPIRef("webRequest.SecurityInfo")}}. This property provides the length in bits of the secret key in the security properties of a web request ([Firefox bug 1778473](https://bugzil.la/1778473)).
- With the introduction of the [extensions button](https://support.mozilla.org/en-US/kb/extensions-button), the default value of `default_area` in the [`action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/action) and [`browser_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) manifest keys has changed from `"navbar"` to `"menupanel"` ([Firefox bug 1799947](https://bugzil.la/1799947)).
- Support for {{WebExtAPIRef("omnibox.onDeleteSuggestion")}} and the `deletable` property in {{WebExtAPIRef("omnibox.SuggestResult")}}, enabling extensions to react to a user deleting an address bar search result ([Firefox bug 1799947](https://bugzil.la/1799947)).
## Older versions
{{Firefox_for_developers(108)}}
| 0 |
data/mdn-content/files/en-us/mozilla/firefox/releases | data/mdn-content/files/en-us/mozilla/firefox/releases/74/index.md | ---
title: Firefox 74 for developers
slug: Mozilla/Firefox/Releases/74
page-type: firefox-release-notes
---
{{FirefoxSidebar}}
This article provides information about the changes in Firefox 74 that will affect developers. Firefox 74 was released on March 10, 2020.
## Changes for web developers
### Developer tools
#### Web console
- The `$x()` [web console helper](https://firefox-source-docs.mozilla.org/devtools-user/web_console/helpers/index.html)'s third argument (result type) now accepts simple string values as well as [`XPathResult` constants](/en-US/docs/Web/API/XPathResult#constants) ([bug 1602591](https://bugzil.la/1602591)).
- Freshly landed support for the optional chaining operator "?." which can also be used with Console's autocomplete ([bug 1594009](https://bugzil.la/1594009)).
- The Debugger can now inspect and debug [nested workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) ([bug 1590766](https://bugzil.la/1590766))
### HTML
_No changes._
### CSS
- [`text-underline-position`](/en-US/docs/Web/CSS/text-underline-position) is now enabled by default ([bug 1606997](https://bugzil.la/1606997)).
- The [`text-underline-offset`](/en-US/docs/Web/CSS/text-underline-offset) and [`text-decoration-thickness`](/en-US/docs/Web/CSS/text-decoration-thickness) properties now accept percentage values ([bug 1607534](https://bugzil.la/1607534)).
- The `auto` value of the {{cssxref("outline-style")}} property has been enabled by default ([Firefox bug 1031664](https://bugzil.la/1031664)).
#### Removals
- The `-moz-` prefixed-[Multiple-column layout](/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout) properties have been removed ([Firefox bug 1308636](https://bugzil.la/1308636)).
### SVG
_No changes._
### JavaScript
- The [Optional chaining operator](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) has been implemented ([Firefox bug 1566143](https://bugzil.la/1566143)).
- When a JavaScript URL (`javascript:`) is evaluated and the result is a string, this string is parsed to create an HTML document, which is then presented. Previously, this document's URL (as reported by the [`document.location`](/en-US/docs/Web/API/Document/location) property, for example) was the originating `javascript:` URL; it is now correctly the URL of the document the `javascript:` URL was evaluated in ([Firefox bug 836567](https://bugzil.la/836567)).
#### Removals
- The `Object.toSource()` method and the global function `uneval()` are no longer available for use by web content or extensions ([bug 1565170](https://bugzil.la/1565170)).
### APIs
#### DOM
- The {{domxref("IDBTransaction.commit()")}} method has been implemented ([Firefox bug 1497007](https://bugzil.la/1497007)).
#### DOM events
- Firefox 74 now supports the {{domxref("WorkerGlobalScope.languagechange_event", "languagechange_event")}} event and its companion event handler property, `onlanguagechange`, which is triggered when the user changes their preferred language ([Firefox bug 1154779](https://bugzil.la/1154779)). This was previously listed in our [compatibility database](https://github.com/mdn/browser-compat-data) as supported from Firefox 3.5, but this was in error.
#### Canvas and WebGL
- The {{domxref("TextMetrics")}} interface has been extended to contain four more properties measuring the actual bounding box β [`actualBoundingBoxLeft`](/en-US/docs/Web/API/TextMetrics/actualBoundingBoxLeft), [`actualBoundingBoxRight`](/en-US/docs/Web/API/TextMetrics/actualBoundingBoxRight), [`actualBoundingBoxAscent`](/en-US/docs/Web/API/TextMetrics/actualBoundingBoxAscent), and [`actualBoundingBoxDescent`](/en-US/docs/Web/API/TextMetrics/actualBoundingBoxDescent). Text metrics can be retrieved using the {{domxref("CanvasRenderingContext2D.measureText()")}} method ([Firefox bug 1102584](https://bugzil.la/1102584)).
#### Removals
- The non-standard `IDBDatabase.mozCreateFileHandle()` method has been removed, in favor of the (also non-standard) `IDBDatabase.createMutableFile()` method ([Firefox bug 1024312](https://bugzil.la/1024312)).
- The non-standard `IDBMutableFile.getFile()` method has been removed ([Firefox bug 1607791](https://bugzil.la/1607791)).
- The non-standard {{domxref("HTMLCanvasElement")}} method `mozGetAsFile()` has been removed, after being deprecated several years ago ([Firefox bug 1588980](https://bugzil.la/1588980)).
- The {{domxref("FetchEvent")}} property {{domxref("FetchEvent.isReload", "isReload")}} has been removed, from both Firefox and the specification ([Firefox bug 1264175](https://bugzil.la/1264175)).
### HTTP
- The [`Cross-Origin-Resource-Policy`](/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy) header is now enabled by default ([bug 1602363](https://bugzil.la/1602363)).
### Security
- TLS 1.0 and 1.1 support has been removed from Firefox; you'll need to make sure your web server supports TLS 1.2 or 1.3 going forward. From now on, Firefox will return a [Secure Connection Failed](https://support.mozilla.org/en-US/kb/secure-connection-failed-firefox-did-not-connect) error when connecting to servers using the older TLS versions ([Firefox bug 1606734](https://bugzil.la/1606734)).
- Starting in Firefox 74, when a site delegates permission to access a resource to embedded content in an {{HTMLElement("iframe")}} using the [`allow`](/en-US/docs/Web/HTML/Element/iframe#allow) attribute, and the embedded page requests permission to use that resource, the parent page prompts the user for permission to use the resource and share it with the embedded domain, rather than both the outer and inner pages prompting the user for permission. If the outer page doesn't have the permission requested by the `allow` attribute, the `<iframe>` is immediately denied access without prompting the user [Firefox bug 1483631](https://bugzil.la/1483631).
### Plugins
_No changes._
### WebDriver conformance (Marionette)
- Added `WebDriver:Print` to print the current page as a PDF document ([Firefox bug 1604506](https://bugzil.la/1604506)).
- `Webdriver:TakeScreenshot` now always captures the top-level browsing context and not the currently-selected browsing context, if no element to capture has been specified ([Firefox bug 1398087](https://bugzil.la/1398087), [Firefox bug 1606794](https://bugzil.la/1606794)).
- Using `Webdriver:TakeScreenshot`'s `full` argument causes the complete page to be captured ([Firefox bug 1571424](https://bugzil.la/1571424)).
## Changes for add-on developers
### API changes
- Shortcut keys can now be unassigned in {{WebExtAPIRef("Commands.update")}} by passing an empty value of `shortcut` [Firefox bug 1475043](https://bugzil.la/1475043).
- `urlclassification`s are now returned as part of the `details` in each event of {{WebExtAPIRef("webrequest")}}, providing information on whether a request is classified as fingerprinting or tracking [Firefox bug 1589494](https://bugzil.la/1589494).
### Manifest changes
_No changes._
## See also
- Hacks blog post: [Security means more with Firefox 74](https://hacks.mozilla.org/2020/03/security-means-more-with-firefox-74-2/)
## Older versions
{{Firefox_for_developers(73)}}
| 0 |
data/mdn-content/files/en-us/mozilla | data/mdn-content/files/en-us/mozilla/add-ons/index.md | ---
title: Add-ons
slug: Mozilla/Add-ons
page-type: landing-page
---
{{AddonSidebarMain}}
Add-ons allow developers to extend and modify the functionality of Firefox. They are written using standard Web technologies - JavaScript, HTML, and CSS - plus some dedicated JavaScript APIs.
Among other things, an add-on could:
- Change the appearance or content of particular websites
- Modify the Firefox user interface
- Add new features to Firefox
There are several types of add-ons, but the most common type are extensions.
## Developing extensions
In the past, there were several toolsets for developing Firefox extensions, but as of November 2017, extensions must be built using [WebExtensions APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions). Other toolsets, such as overlay add-ons, bootstrapped add-ons, and the Add-on SDK, are no longer supported.
Extensions written using WebExtensions APIs for Firefox are designed to be cross-browser compatible. In most cases, it will run in Chrome, Edge, and Opera with few if any changes. They are also fully compatible with multiprocess Firefox. You can see [the APIs currently supported in Firefox and other browsers](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs).
### Extension Workshop
The [Firefox Extension Workshop](https://extensionworkshop.com) can help you develop extensions for Firefox and give your users simple, yet powerful ways to customize their browsing experience. You'll find:
- [Overview of the Firefox extension features](https://extensionworkshop.com/#about)
- [Tools and processes for developing and testing](https://extensionworkshop.com/documentation/develop/)
- [How to publish your extension on addons.mozilla.org or distribute it yourself](https://extensionworkshop.com/documentation/publish/)
- [How to manage your published extension](https://extensionworkshop.com/documentation/manage/)
- [An enterprise guide for developing and using extensions](https://extensionworkshop.com/documentation/enterprise/)
- [How to develop themes for Firefox](https://extensionworkshop.com/documentation/themes/)
- [Firefox developer communities](https://extensionworkshop.com/community/)
### Extensions for Firefox for Android
In 2020, Mozilla will release a new Firefox for Android experience. This new, high-performance browser for Android has been rebuilt from the ground up using GeckoView, Mozilla's mobile browser engine. We are currently building support for the WebExtensions API on GeckoView.
### Migrate an existing extension
If you maintain a legacy extension, such as an XUL overlay, bootstrapped, or Add-on SDK-based extension, you can still port it to use WebExtension APIs. There are some [porting resources on Firefox Extension Workshop](https://extensionworkshop.com/documentation/develop/porting-a-legacy-firefox-extension/), our site for Firefox-specific development resources.
For more information about transition support, please visit our [wiki page.](https://wiki.mozilla.org/Add-ons/developer/communication)
## Publishing add-ons
[Addons.mozilla.org](https://addons.mozilla.org), commonly known as "AMO," is Mozilla's official site for developers to list add-ons, and for users to discover them. By uploading your add-on to AMO, you can participate in our community of users and creators and find an audience for your add-on.
You are not required to list your add-on on AMO, but your add-on must be signed by Mozilla else users will not be able to install it.
For an overview for the process of publishing your add-on see [Signing and distributing your add-on](https://extensionworkshop.com/documentation/publish/signing-and-distribution-overview/).
## Other types of add-ons
In addition to extensions, there are a few other add-on types that allow users to customize Firefox. Those add-ons include:
- [User dictionaries](https://support.mozilla.org/en-US/kb/how-do-i-use-firefox-spell-checker) let you spell-check in different languages.
- [Language packs](https://support.mozilla.org/en-US/kb/use-firefox-another-language) let you have more languages available for the user interface of Firefox.
## Contact us
Check out the [contact us](/en-US/docs/Mozilla/Add-ons/Contact_us) page for details on how to get help, keep up to date with add-ons news, and give us feedback.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons | data/mdn-content/files/en-us/mozilla/add-ons/contact_us/index.md | ---
title: Contact us
slug: Mozilla/Add-ons/Contact_us
page-type: guide
---
{{AddonSidebar}}
Use the links below to get help, to keep up to date with add-ons news, and to give us feedback.
### Add-ons forum
Use the [Add-ons Discourse forum](https://discourse.mozilla.org/c/add-ons/35) to discuss all aspects of add-on development and to request help.
### Mailing lists
The **dev-addons mailing list** was retired on December 1, 2020. You can view the [dev-addons archives](https://mail.mozilla.org/pipermail/dev-addons/) to see past discussions about the WebExtensions API and addons.mozilla.org.
### Chat
[Matrix](https://matrix.org/) is an open, lightweight protocol for decentralized, real-time communications. For information on how to join Mozilla's Matrix instance, refer to the [Matrix page on MozillaWiki](https://wiki.mozilla.org/Matrix).
- [Add-ons](https://chat.mozilla.org/#/room/#addons:mozilla.org) (support for extensions, themes, and the WebExtensions API)
- [AMO](https://chat.mozilla.org/#/room/#amo:mozilla.org) (discussion around addons.mozilla.org)
### Report problems
#### Security vulnerabilities
If you discover an add-on security vulnerability, even if the add-on is not hosted on a Mozilla site, please notify us. We will work with the developer to correct the issue. Please report security vulnerabilities [confidentially](https://www.mozilla.org/en-US/about/governance/policies/security-group/bugs/) in [Bugzilla](https://bugzilla.mozilla.org/enter_bug.cgi?product=addons.mozilla.org&component=Add-on%20Security&maketemplate=Add-on%20Security%20Bug&bit-23=1&rep_platform=All&op_sys=All)or by emailing <[email protected]>.
#### Bugs on addons.mozilla.org (AMO)
If you find a problem with the site, we'd love to fix it. Please [file a bug report](https://github.com/mozilla/addons/issues/new) and include as much detail as possible.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/index.md | ---
title: Browser extensions
slug: Mozilla/Add-ons/WebExtensions
page-type: landing-page
---
{{AddonSidebar}}
Extensions, or add-ons, can modify and enhance the capability of a browser. Extensions for Firefox are built using the WebExtensions API cross-browser technology.
The technology for extensions in Firefox is, to a large extent, compatible with the [extension API](https://developer.chrome.com/docs/extensions/reference/) supported by Chromium-based browsers (such as Google Chrome, Microsoft Edge, Opera, Vivaldi). In most cases, extensions written for Chromium-based browsers run in Firefox with [just a few changes](https://extensionworkshop.com/documentation/develop/porting-a-google-chrome-extension/).
## Key resources
- Guides
- : Whether you're just beginning or looking for more advanced advice, learn about how extensions work and use the WebExtensions API from our extensive range of [tutorials and guides](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_are_WebExtensions).
- References
- : Get comprehensive details about the methods, properties, types, and events of the [WebExtensions APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs) and full details about the [manifest keys](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json).
- Firefox workflow
- : Discover how to build and publish extensions for Firefox: get the lowdown on developer tools, publication and distribution, and porting on [Extension Workshop](https://extensionworkshop.com/).
> **Note:** If you have ideas or questions or need help, you can reach us on the [community forum](https://discourse.mozilla.org/c/add-ons/35) or in the [Add-ons Room](https://matrix.to/#/!CuzZVoCbeoDHsxMCVJ:mozilla.org?via=mozilla.org&via=matrix.org&via=humanoids.be) on [Matrix](https://wiki.mozilla.org/Matrix).
## Get started
Discover [what extensions can do](/en-US/docs/Mozilla/Add-ons/WebExtensions/What_are_WebExtensions) before building [your first extension.](/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension) Learn about the [anatomy of an extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension) and get an overview of the [extension development and publication workflow, Firefox style](/en-US/docs/Mozilla/Add-ons/WebExtensions/Firefox_workflow_overview). Explore a little deeper with a comprehensive selection of [example extensions](/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples) that you can run right in Firefox.
## Concepts
Get detailed information on the concept that underpin extensions [from an overview of the JavaScript API](/en-US/docs/Mozilla/Add-ons/WebExtensions/API), through [content scripts,](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) [match patterns](/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns), [working with files](/en-US/docs/Mozilla/Add-ons/WebExtensions/Working_with_files), [internationalization](/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization), and [content security policy](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy), to more advanced subjects such as [native messaging](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging), [using the devtools APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools), and [native manifests](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_manifests).
## User interface
Discover all the [user interface](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface) components you can use in your extensions, with coding examples and tips.
## How to
From patterns you'll regularly use such as [work with the Tabs API](/en-US/docs/Mozilla/Add-ons/WebExtensions/Working_with_the_Tabs_API) and [adding a button to the toolbar](/en-US/docs/Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar) to more advanced topics such as [intercepting HTTP requests](/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests) and [working with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities), you'll find a range of tutorials to get you started.
## Firefox workflow
When you are ready to create your extension for Firefox or port your Chrome extension, head over to [Extension Workshop](https://extensionworkshop.com/). It has details on:
- The Firefox workflow, such as [temporarily installing extensions during development](https://extensionworkshop.com/documentation/develop/temporary-installation-in-firefox/), [debugging](https://extensionworkshop.com/documentation/develop/debugging/), [request the right permissions](https://extensionworkshop.com/documentation/develop/request-the-right-permissions/), and more.
- The [web-ext](https://extensionworkshop.com/documentation/develop/getting-started-with-web-ext/) developer tool.
- [Porting a Google Chrome extension](https://extensionworkshop.com/documentation/develop/porting-a-google-chrome-extension/), [differences between desktop and Android](https://extensionworkshop.com/documentation/develop/differences-between-desktop-and-android-extensions/), and more.
- [Publishing and distribution overview](https://extensionworkshop.com/documentation/publish/), [promoting your extension](https://extensionworkshop.com/documentation/publish/promoting-your-extension/), the [extension lifecycle best practices](https://extensionworkshop.com/documentation/manage/), and more.
## Reference
### JavaScript APIs
Get comprehensive details about the methods, properties, types, and events for all the [JavaScript APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/API). There is also detailed information about the compatibility of each API with the major browsers. Most reference pages also include coding examples and links to the extension examples that use the API.
### Manifest keys
Get full details about the [manifest keys](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json), including all their properties and settings. There's also detailed information on the [compatibility](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_compatibility_for_manifest.json) of each key with the major browsers.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/work_with_the_cookies_api/index.md | ---
title: Work with the Cookies API
slug: Mozilla/Add-ons/WebExtensions/Work_with_the_Cookies_API
page-type: guide
---
{{AddonSidebar}}
With the Cookies API your extensions have access to capabilities similar to those used by websites to store and read cookies. The API's features give extensions the ability to store information on a site-by-site basis. So, as we shall see in the example, you could store details of a user's choice of background color for a site. Then, when the user revisits the site, your extension can use the API's ability to get details about cookies and read them to recover the user's choice and apply it to the website.
> **Note:** The behavior of cookies can be controlled using the {{WebExtAPIRef("privacy.websites")}} `cookieConfig` property. This property controls whether and how cookies are accepted or whether all cookies are treated as session cookies.
## Permissions
To use the Cookies API you need to request both the `"cookies"` permission and [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the protocols, domains, or websites you want to access or use `"<all_urls>"` to access any protocol and domain. The way in which you define your host permission string affects your extension's ability to read, write, and delete cookies.
<table>
<colgroup>
<col />
<col />
<col />
<col />
<col />
</colgroup>
<tbody>
<tr>
<td rowspan="2"><p>Host permission string</p></td>
<td colspan="2"><p>Read</p></td>
<td colspan="2"><p>Write/Delete</p></td>
</tr>
<tr>
<td><p>Secure</p></td>
<td><p>Non-secure</p></td>
<td><p>Secure</p></td>
<td><p>Non-secure</p></td>
</tr>
<tr>
<td>
<p><code>"http://*.example.com/"</code></p>
</td>
<td><p>No</p></td>
<td><p>Main and sub domains, with any path</p></td>
<td><p>Main and sub domains, with any path</p></td>
<td><p>Main and sub domains, with any path</p></td>
</tr>
<tr>
<td>
<p><code>"https://www.example.com/"</code></p>
</td>
<td>
<p>www.example.com or .example.com with any path, but no subdomains</p>
</td>
<td>
<p>www.example.com or .example.com with any path, but no subdomains</p>
</td>
<td>
<p>www.example.com or .example.com with any path, but no subdomains</p>
</td>
<td>
<p>www.example.com or .example.com with any path, but no subdomains</p>
</td>
</tr>
<tr>
<td>
<p><code>"*://*.example.com/"</code></p>
</td>
<td><p>Main and sub domains, with any path</p></td>
<td><p>Main and sub domains, with any path</p></td>
<td><p>Main and sub domains, with any path</p></td>
<td><p>Main and sub domains, with any path</p></td>
</tr>
<tr>
<td>
<p><code>"<all_urls>"</code></p>
</td>
<td><p>Any domain with any path</p></td>
<td><p>Any domain with any path</p></td>
<td><p>Any domain with any path</p></td>
<td><p>Any domain with any path</p></td>
</tr>
</tbody>
</table>
## Cookie stores
Firefox provides three types of cookie store:
- The default store, which stores cookies from normal browsing.
- Private browsing mode stores, which stores cookies created during a private browsing session. These stores and any cookies they contain are removed when the related private browsing window closes.
> **Note:**
> Only visible if {{WebExtAPIRef("extension.isAllowedIncognitoAccess()")}} returns true. Safari doesn't support access to private cookies.
- Container tabs stores, which stores cookies for each contextual identity in Firefox. Contextual identities enable a user to maintain multiple identities within one browser window. This is useful if, for example, you've a company and personal email account on Gmail. With contextual identities, you can open one tab against a personal identity and a second tab against a business identity. Each tab can then sign into Google mail with a different username, and the two accounts can be used side-by-side. For more information, see [Security/Contextual Identity Project/Containers](https://wiki.mozilla.org/Security/Contextual_Identity_Project/Containers) in the Mozilla wiki.
You can find out what cookie stores are available using {{WebExtAPIRef("cookies.getAllCookieStores")}}, which returns an object containing the ID of each cookie store and a list of the IDs of the tabs using each cookie store.
## Example walkthrough
The example extension [cookie-bg-picker](https://github.com/mdn/webextensions-examples/tree/main/cookie-bg-picker) allows its user to pick a color and icon that are applied to the background of a site's web pages. These choices are saved on a per-site basis using {{WebExtAPIRef("cookies.set")}}. When a page from the site is opened, {{WebExtAPIRef("cookies.get")}} reads any earlier choice, and the extension applies it to the web page. A reset option removes the background icon and color from the site as well as the cookie, using {{WebExtAPIRef("cookies.remove")}}. It also uses {{WebExtAPIRef("cookies.onChanged")}} to listen for changes to cookies, sending details of the change to the console.
This video shows the extension in action:
{{EmbedYouTube("_rlp3eYqEMA")}}
This example also uses the Tabs and Runtime APIs, but we'll discuss those features only in passing.
### manifest.json
The key feature of the [manifest.json](https://github.com/mdn/webextensions-examples/blob/main/cookie-bg-picker/manifest.json) file relating to the use of the Cookies API is the permissions request:
```json
"permissions": [
"tabs",
"cookies",
"<all_urls>"
],
```
Here, the extension requests permission to use the Cookies API (`"cookies"`) with all websites (`"<all_urls>"`). This enables the extension to save the background color icon choice for any website.
### Scriptsβbgpicker.js
The extension's UI uses a toolbar button ({{WebExtAPIRef("browserAction")}}) implemented with [bgpicker.html](https://github.com/mdn/webextensions-examples/blob/main/cookie-bg-picker/popup/bgpicker.html) that calls [bgpicker.js](https://github.com/mdn/webextensions-examples/blob/main/cookie-bg-picker/popup/bgpicker.js). Together these allow the user to select the icon and enter the color they want to apply as the site background. They also provide the option to clear those settings.
[bgpicker.js](https://github.com/mdn/webextensions-examples/blob/main/cookie-bg-picker/popup/bgpicker.js) handles the selection of icon or entry of a color for the background in separate functions.
To handle the icon buttons the script first gathers all the class names used for the buttons in the HTML file:
```js
let bgBtns = document.querySelectorAll(".bg-container button");
```
It then loops through all the buttons assigning them their image and creating an onclick listener for each button:
```js
for (let i = 0; i < bgBtns.length; i++) {
let imgName = bgBtns[i].getAttribute('class');
let bgImg = 'url(\'images/' + imgName + '.png\')';
bgBtns[i].style.backgroundImage = bgImg;
bgBtns[i].onclick = (e) => {
```
When a button is clicked, its corresponding listener function gets the button class name and then the icon path which it passes to the page's content script ([updatebg.js](https://github.com/mdn/webextensions-examples/blob/main/cookie-bg-picker/content_scripts/updatebg.js)) using a message. The content script then applies the icon to the web page's background. Meanwhile, [bgpicker.js](https://github.com/mdn/webextensions-examples/blob/main/cookie-bg-picker/popup/bgpicker.js) stores the details of the icon applied to the background in a cookie:
```js
cookieVal.image = fullURL;
browser.cookies.set({
url: tabs[0].url,
name: "bgpicker",
value: JSON.stringify(cookieVal),
});
```
The color setting is handled in a similar way, triggered by a listener on the color input field. When a color is entered the active tab is discovered and the color selection details sent, using a message, to the page's content script to be applied to the web page background. Then the color selection is added to the cookie:
```js
cookieVal.color = currColor;
browser.cookies.set({
url: tabs[0].url,
name: "bgpicker",
value: JSON.stringify(cookieVal)
```
When the user clicks the reset button, which has been assigned to the variable reset:
```js
let reset = document.querySelector(".color-reset button");
```
`reset.onclick` first finds the active tab. Then, using the tab's ID it passes a message to the page's content script ([updatebg.js](https://github.com/mdn/webextensions-examples/blob/main/cookie-bg-picker/content_scripts/updatebg.js)) to get it to remove the icon and color from the page. The function then clears the cookie values (so the old values aren't carried forward and written onto a cookie created for a new icon or color selection on the same page) before removing the cookie:
```js
cookieVal = { image : '',
color : '' };
browser.cookies.remove({
url: tabs[0].url,
name: "bgpicker"
```
Also, so you can see what is going on with the cookies, the script reports on all changes to cookies in the console:
```js
browser.cookies.onChanged.addListener((changeInfo) => {
console.log(`Cookie changed:\n
* Cookie: ${JSON.stringify(changeInfo.cookie)}\n
* Cause: ${changeInfo.cause}\n
* Removed: ${changeInfo.removed}`);
});
```
### Scriptsβbackground.js
A background script ([background.js](https://github.com/mdn/webextensions-examples/blob/main/cookie-bg-picker/background_scripts/background.js)) provides for the possibility that the user has chosen a background icon and color for the website in an earlier session. The script listens for changes in the active tab, either the user switching between tabs or changing the URL of the page displayed in the tab. When either of these events happen, `cookieUpdate()` is called. `cookieUpdate()` in turn uses `getActiveTab()` to get the active tab ID. The function can then check whether a cookie for the extension exists, using the tab's URL:
```js
let gettingCookies = browser.cookies.get({
url: tabs[0].url,
name: "bgpicker",
});
```
If the `"bgpicker"` cookie exists for the website, the details of the icon and color selected earlier are retrieved and passed to the content script [updatebg.js](https://github.com/mdn/webextensions-examples/blob/main/cookie-bg-picker/content_scripts/updatebg.js) using messages:
```js
gettingCookies.then((cookie) => {
if (cookie) {
let cookieVal = JSON.parse(cookie.value);
browser.tabs.sendMessage(tabs[0].id, { image: cookieVal.image });
browser.tabs.sendMessage(tabs[0].id, { color: cookieVal.color });
}
});
```
## Other features
In addition to the APIs mentioned so far, the Cookies API also offers {{WebExtAPIRef("cookies.getAll")}}. This function takes the details object to specify filters for the selected cookies and returns an array of {{WebExtAPIRef("cookies.Cookie")}} objects that match the filter criteria.
## Learn more
If you want to learn more about the Cookies API, check out:
- [Cookies API reference](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies).
- [List-cookies](https://github.com/mdn/webextensions-examples/tree/main/list-cookies) example.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.md | ---
title: Anatomy of an extension
slug: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension
page-type: guide
---
{{AddonSidebar}}
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](#background_scripts_2)
- : Scripts that respond to browser events.
- Icons
- : For the extension and any buttons it might define.
- [Sidebars, popups, and options pages](#sidebars_popups_and_options_pages_2)
- : HTML documents that provide content for various user interface components.
- [Content scripts](#content_scripts_2)
- : JavaScript included with your extension, that you will inject into web pages.
- [Web-accessible resources](#web_accessible_resources)
- : Make packaged content accessible to web pages and content scripts.

See the [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) reference page for all the details.
Along with those already listed in the manifest, an extension may also include additional [Extension pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/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](/en-US/docs/Mozilla/Add-ons/WebExtensions/API) in the script, if you have requested the necessary [permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions).
See the [background scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/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](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars)
- : A pane that is displayed at the left-hand side of the browser window, next to the web page.
- [Popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups)
- : A dialog that you can display when the user clicks on a [toolbar button](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button) or [address bar button](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions)
- [Options](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages)
- : 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`](/en-US/docs/Mozilla/Add-ons/WebExtensions/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](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/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 {{WebExtAPIRef("windows.create()")}} or {{WebExtAPIRef("tabs.create()")}}.
See [Extension pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/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 {{HTMLElement("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](/en-US/docs/Mozilla/Add-ons/WebExtensions/API).
- [Exchange messages with their background scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#communicating_with_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()`](/en-US/docs/Web/API/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](/en-US/docs/Mozilla/Add-ons/WebExtensions/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`](/en-US/docs/Web/HTML/Element/img) tags which reference the images via the `src` attribute.
To learn more, see the documentation for the [`"web_accessible_resources"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources) `manifest.json` key.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/safely_inserting_external_content_into_a_page/index.md | ---
title: Safely insert external content into a page
short-title: Insert external content
slug: Mozilla/Add-ons/WebExtensions/Safely_inserting_external_content_into_a_page
page-type: guide
---
{{AddonSidebar}}
There are times when you might want or need to include content from an external source in your extension. But, there is the risk that the source may have malicious scripts embedded in itβadded by either the developer of the source or by a malicious third-party.
Take an RSS reader as an example. You don't know what RSS feeds your extension will open and have no control over the content of those RSS feeds. So, it's possible the user could subscribe to a feed where, for example, a feed item's title includes a script. This could be something as simple as including JavaScript code within `<script></script>` tags. If you were to extract the title, assume it was plain text, and add it to the DOM of a page created by your extension, your user now has an unknown script running in their browser. Therefore, care needs to be taken to avoid evaluating arbitrary text as HTML.
You also need to remember that extensions have privileged contexts, for example in background scripts and content scripts. In the worst case, an embedded script could run in one of these contexts, a situation known as privilege escalation. This situation can leave a user's browser open to remote attack by enabling the website that injected the code to access critical user data, such as passwords, browser history, or browsing behavior.
This article examines how to work safely with remote data and add it to a DOM.
## Working with arbitrary strings
When working with strings, there are a couple of recommended options to safely add them to a page: the standard DOM node creation methods or jQuery.
### DOM node creation methods
A lightweight approach to inserting strings into a page is to use the native DOM manipulation methods: [`document.createElement`](/en-US/docs/Web/API/Document/createElement), [`Element.setAttribute`](/en-US/docs/Web/API/Element/setAttribute), and [`Node.textContent`](/en-US/docs/Web/API/Node/textContent). The safe approach is to create the nodes separately and assign their content using textContent:
```js example-good
let data = JSON.parse(responseText);
let div = document.createElement("div");
div.className = data.className;
div.textContent = `Your favorite color is now ${data.color}`;
addonElement.appendChild(div);
```
This approach is safe because the use of `.textContent` automatically escapes any remote HTML in `data.color`.
However, beware, you can use native methods that aren't safe. Take the following code:
```js example-bad
let data = JSON.parse(responseText);
addonElement.innerHTML = `<div class='${data.className}'>Your favorite color is now ${data.color}</div>`;
```
Here, the contents of `data.className` or `data.color` could contain HTML that can close the tag early, insert arbitrary further HTML content, then open another tag.
### jQuery
When using jQuery, functions such as `attr()` and `text()` escape content as it's added to a DOM. So, the "favorite color" example from above, implemented in jQuery, would look like this:
```js example-good
let node = $("</div>");
node.addClass(data.className);
node.text(`Your favorite color is now ${data.color}`);
```
## Working with HTML content
When working with externally sourced content that you know is HTML, sanitizing the HTML is essential before it's added to a page. Best practice for sanitizing HTML is to use an HTML sanitization library or a template engine with HTML sanitization features. In this section, we look at some suitable tools and how to use them.
### HTML sanitization
An HTML sanitization library strips anything that could lead to script execution from HTML, so you can safely inject complete sets of HTML nodes from a remote source into your DOM. [DOMPurify](https://github.com/cure53/DOMPurify), which has been reviewed by various security experts, is a suitable library for this task in extensions.
For production use, [DOMPurify](https://github.com/cure53/DOMPurify) comes as a minified version: purify.min.js. You can use this script in the way that best suits your extension. For example, you could add it as a content script:
```json
"content_scripts": [
{
"matches" : ["<all_urls>"],
"js": ["purify.min.js", "myinjectionscript.js"]
}
]
```
Then, in myinjectionscript.js you can read the external HTML, sanitize it, and add it to a page's DOM:
```js
let elem = document.createElement("div");
let cleanHTML = DOMPurify.sanitize(externalHTML);
elem.innerHTML = cleanHTML;
```
You can use any method to add the sanitized HTML to your DOM, for example jQuery's `.html()` function. Remember though that the `SAFE_FOR_JQUERY` flag needs to be used in this case:
```js
let elem = $("<div/>");
let cleanHTML = DOMPurify.sanitize(externalHTML, { SAFE_FOR_JQUERY: true });
elem.html(cleanHTML);
```
### Template engines
Another common pattern is to create a local HTML template for a page and use remote values to fill in the blanks. While this approach is generally acceptable, care should be taken to avoid use of constructs that would allow the insertion of executable code. This can happen when the templating engine uses constructs that insert raw HTML into the document. If the variable used to insert raw HTML is of a remote source, it is subject to the same security risk mentioned in the introduction.
For example, when using [mustache templates](https://mustache.github.io/) you must use the double mustache, `\{{variable}}`, which escapes any HTML. Use of the triple mustache, `\{\{{variable}}}`, must be avoided as this injects a raw HTML string and could add executable code to your template. [Handlebars](https://handlebarsjs.com/) works in a similar way, with variables in double handlebars, `\{{variable}}`, being escaped. Whereas, variables in triple handlebars are left raw and must be avoided. Also, if you create a Handlebars helper using `Handlebars.SafeString` use `Handlebars.escapeExpression()` to escape any dynamic parameters passed to the helper. This is a requirement because the resulting variable from `Handlebars.SafeString` is considered safe and it isn't escaped when inserted with double handlebars.
There are similar constructs in other templating systems that need to be approached with the same level of care.
## Additional reading
For more information on this subject, see the following articles:
- [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://owasp.org/www-community/xss-filter-evasion-cheatsheet)
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/what_next/index.md | ---
title: What next?
slug: Mozilla/Add-ons/WebExtensions/What_next
page-type: guide
---
{{AddonSidebar}}
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](https://extensionworkshop.com), 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](#the_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](https://extensionworkshop.com/documentation/develop/browser-extension-development-tools/)
## 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_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](https://extensionworkshop.com/documentation/publish/source-code-submission/)
## 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](https://extensionworkshop.com/documentation/publish/firefox-add-on-distribution-agreement/)
[Learn more about signing on Extension Workshop](https://extensionworkshop.com/documentation/publish/signing-and-distribution-overview/)
## 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](https://extensionworkshop.com/documentation/publish/add-on-policies/)
## 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](https://extensionworkshop.com/documentation/publish/recommended-extensions/)
## 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](/en-US/docs/Mozilla/Add-ons/WebExtensions/API).
- A guide to the [user interface components](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface) 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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs).
- A full reference guide to the [Manifest keys](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json).
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](https://extensionworkshop.com/#about)
- [details of the tools and processes for developing and testing](https://extensionworkshop.com/documentation/develop/)
- [how to publish your extension on addons.mozilla.org or distribute it yourself](https://extensionworkshop.com/documentation/publish/)
- [how to manage your published extension](https://extensionworkshop.com/documentation/manage/)
- [an enterprise guide for developing and using extensions](https://extensionworkshop.com/documentation/enterprise/)
- [how to develop themes for Firefox](https://extensionworkshop.com/documentation/themes/)
- [details about the Firefox developer communities](https://extensionworkshop.com/community/)
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/developing_webextensions_for_thunderbird/index.md | ---
title: Developing WebExtensions for Thunderbird
slug: Mozilla/Add-ons/WebExtensions/Developing_WebExtensions_for_Thunderbird
page-type: guide
---
{{AddonSidebar}}
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](https://webextension-api.thunderbird.net/en/latest/) 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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_compatibility_for_manifest.json) and [browser support for JavaScript APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs) for details.
## See also
- [Introduction to Thunderbird Add-On development](https://developer.thunderbird.net/add-ons/about-add-ons)
- [Thunderbird specific WebExtension API documentation](https://webextension-api.thunderbird.net/en/latest/)
- [Browser support for JavaScript APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs)
- [Browser compatibility for manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_compatibility_for_manifest.json)
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/interact_with_the_clipboard/index.md | ---
title: Interact with the clipboard
slug: Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard
page-type: guide
browser-compat:
- api.Clipboard
- webextensions.api.clipboard
---
{{AddonSidebar}}
Working with the clipboard in extensions is transitioning from the Web API {{domxref("Document.execCommand()","document.execCommand")}} method (which is deprecated) to the {{domxref("Clipboard", "navigator.clipboard")}} method.
> **Note:** The {{domxref("Clipboard", "navigator.clipboard")}} API is a recent addition to the specification and may not be fully implemented in all browsers. This article describes some limitations, but be sure to review the compatibility tables for each method before using them to ensure that the API supports your needs.
The difference between the two APIs is that {{domxref("Document.execCommand()","document.execCommand")}} this is analogous to the keyboard copy, cut, and paste actions β exchanging data between a webpage and clipboard β whereas {{domxref("Clipboard", "navigator.clipboard")}} writes and reads arbitrary data to and from the clipboard.
{{domxref("Clipboard", "navigator.clipboard")}} provide separate methods to read or write:
- text content, using {{domxref("Clipboard.readText", "navigator.clipboard.readText()")}} and {{domxref("Clipboard.writeText", "navigator.clipboard.writeText()")}}.
- images, rich text, HTML, and other rich content, using {{domxref("Clipboard.read", "navigator.clipboard.read()")}} and {{domxref("Clipboard.write", "navigator.clipboard.write()")}}.
However, while {{domxref("Clipboard.readText", "navigator.clipboard.readText()")}} and {{domxref("Clipboard.writeText", "navigator.clipboard.writeText()")}} work on all browsers, {{domxref("Clipboard.read", "navigator.clipboard.read()")}} and {{domxref("Clipboard.write", "navigator.clipboard.write()")}} do not. For example, on Firefox at the time of writing, {{domxref("Clipboard.read", "navigator.clipboard.read()")}} and {{domxref("Clipboard.write", "navigator.clipboard.write()")}} are not fully implemented, such that to:
- work with images use {{WebExtAPIRef("clipboard.setImageData","browser.clipboard.setImageData()")}} to write images to the clipboard and {{domxref("Document.execCommand()","document.execCommand("paste")")}} to paste images to a webpage.
- write rich content (such as, HTML, rich text including images, etc.) to the clipboard, use {{domxref("Document.execCommand()","document.execCommand("copy")")}} or {{domxref("Document.execCommand()","document.execCommand("cut")")}}. Then, either {{domxref("Clipboard.read","navigator.clipboard.read()")}} (recommended) or {{domxref("Document.execCommand()","document.execCommand("paste")")}} to read the content from the clipboard.
## Writing to the clipboard
This section describes the options for writing data to the clipboard.
### Using the Clipboard API
The Clipboard API writes arbitrary data to the clipboard from your extension. Using the API requires the permission `"clipboardRead"` or `"clipboardWrite"` in your `manifest.json` file. As the API is only available to [Secure Contexts](/en-US/docs/Web/Security/Secure_Contexts), it cannot be used from a content script running on `http:`-pages, only `https:`-pages.
For page scripts, the `"clipboard-write"` permission needs to be requested using the Web API {{domxref("Permissions", "navigator.permissions")}}. You can check for that permission using {{domxref("Permissions.query", "navigator.permissions.query()")}}:
```js
navigator.permissions.query({ name: "clipboard-write" }).then((result) => {
if (result.state === "granted" || result.state === "prompt") {
/* write to the clipboard now */
}
});
```
> **Note:** The `clipboard-write` permission name is not supported in Firefox, only Chromium browsers.
This function takes a string and writes it to the clipboard:
```js
function updateClipboard(newClip) {
navigator.clipboard.writeText(newClip).then(
() => {
/* clipboard successfully set */
},
() => {
/* clipboard write failed */
},
);
}
```
### Using execCommand()
The `"cut"` and `"copy"` commands of the {{domxref("Document.execCommand", "document.execCommand()")}} method are used to replace the clipboard's content with the selected material. These commands can be used without any special permission in short-lived event handlers for a user action (for example, a click handler).
For example, suppose you've got a popup that includes the following HTML:
```html
<input id="input" type="text" /> <button id="copy">Copy</button>
```
To make the `"copy"` button copy the contents of the {{HTMLElement("input")}} element, you can use code like this:
```js
function copy() {
let copyText = document.querySelector("#input");
copyText.select();
document.execCommand("copy");
}
document.querySelector("#copy").addEventListener("click", copy);
```
Because the `execCommand()` call is inside a click event handler, you don't need any special permissions.
However, let's say that instead you trigger the copy from an alarm:
```js
function copy() {
let copyText = document.querySelector("#input");
copyText.select();
document.execCommand("copy");
}
browser.alarms.create({
delayInMinutes: 0.1,
});
browser.alarms.onAlarm.addListener(copy);
```
Depending on the browser, this may not work. On Firefox, it will not work, and you'll see a message like this in your console:
`document.execCommand('cut'/'copy') was denied because it was not called from inside a short running user-generated event handler.`
To enable this use case, you need to ask for the `"clipboardWrite"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). So: `"clipboardWrite"` enables you to write to the clipboard outside a short-lived event handler for a user action.
> **Note:**{{domxref("Document.execCommand", "document.execCommand()")}} does not work on input fields of `type="hidden"`, with the HTML5 attribute `"hidden"`, or any matching CSS rule using `"display: none;"`. So, to add a "copy to clipboard" button to a `span`, `div`, or `p` tag, you need to use a workaround, such as setting the input's position to absolute and moving it out of the viewport.
### Browser-specific considerations
The clipboard and other APIs involved here are evolving rapidly, so there are variations among browsers in how they work.
In Chrome:
- You don't need `"clipboardWrite"`, even to write to the clipboard outside a user-generated event handler.
In Firefox:
- {{domxref("Clipboard.write", "navigator.clipboard.write()")}} is not supported.
See the [browser compatibility tables](#browser_compatibility) for more information.
## Reading from the clipboard
This section describes the options for reading or pasting data from the clipboard.
### Using the Clipboard API
The Clipboard API's {{domxref("Clipboard.readText", "navigator.clipboard.readText()")}} and {{domxref("Clipboard.read", "navigator.clipboard.read()")}} methods let you read arbitrary text or binary data from the clipboard in [secure contexts](/en-US/docs/Web/Security/Secure_Contexts). This lets you access the data in the clipboard without pasting it into an editable element.
Once you have the `"clipboard-read"` permission from the [Permissions API](/en-US/docs/Web/API/Permissions_API), you can read from the clipboard easily. For example, this snippet of code fetches the text from the clipboard and replaces the contents of the element with the ID `"outbox"` with that text.
```js
navigator.clipboard
.readText()
.then((clipText) => (document.getElementById("outbox").innerText = clipText));
```
### Using execCommand()
To use {{domxref("Document.execCommand()","document.execCommand("paste")")}} your extension needs the `"clipboardRead"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). This is the case even if you're using the `"paste"` command from within a user-generated event handler, such as {{domxref("Element/click_event", "click")}} or {{domxref("Element/keypress_event", "keypress")}}.
Consider HTML that includes something like this:
```html
<textarea id="output"></textarea> <button id="paste">Paste</button>
```
To set the content of the {{HTMLElement("textarea")}} element with the ID `"output"` from the clipboard when the user clicks the `"paste"` {{HTMLElement("button")}}, you can use code like this:
```js
function paste() {
let pasteText = document.querySelector("#output");
pasteText.focus();
document.execCommand("paste");
console.log(pasteText.textContent);
}
document.querySelector("#paste").addEventListener("click", paste);
```
### Browser-specific considerations
Firefox supports the `"clipboardRead"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) from version 54 but only supports pasting into elements in [content editable mode](/en-US/docs/Web/HTML/Global_attributes/contenteditable), which for content scripts only works with a {{HTMLElement("textarea")}}. For background scripts, any element can be set to content editable mode.
## Browser compatibility
{{Compat}}
## See also
- [Clipboard API](/en-US/docs/Web/API/Clipboard_API)
- [Permissions API](/en-US/docs/Web/API/Permissions_API)
- [Make content editable](/en-US/docs/Web/HTML/Global_attributes#contenteditable)
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/differences_between_api_implementations/index.md | ---
title: Differences between API implementations
slug: Mozilla/Add-ons/WebExtensions/Differences_between_API_implementations
page-type: guide
---
{{AddonSidebar}}
The browser extensions API is an [emerging standard](https://browserext.github.io/browserext/). As a result, while it is supported by most major browsers β including Firefox, Chrome, Edge, and Opera β there are differences between the various implementations. This means some changes may be necessary to implement your extension for multiple browsers.
Among the various browsers supporting the extensions API, Firefox is the most compliant with the emerging standard and, therefore, is your best place to start when developing browser extensions.
The differences between browsers' API implementations fall into four areas: namespace, asynchronous event handling, API coverage, and manifest keys.
## Namespace
You reference all extensions API functions using a namespace. For example, `browser.alarms.create({delayInMinutes});` creates an alarm in Firefox that goes off after the time specified in `delayInMinutes`.
There are two API namespaces in use:
- `chrome` used in Chrome, Edge, and Opera.
- `browser` used in Firefox and Safari.
## Asynchronous event handling
JavaScript provides several ways to handle asynchronous events. The proposed extensions API standard is to use promises. The promises approach offers significant advantages when dealing with chained asynchronous event calls.
Firefox and Safari implement promises for the extensions API. All other browsers use callbacks. In Manifest V3, Chrome, Edge, and Opera provided for [promises](https://developer.chrome.com/docs/extensions/mv3/intro/mv3-overview/#promises) on most appropriate methods. (cf. [Chrome bug 328932](https://crbug.com/328932))
If you are unfamiliar with how JavaScript can handle asynchronous events or promises, look at [Getting to know asynchronous JavaScript: Callbacks, Promises and Async/Await](https://medium.com/codebuddies/getting-to-know-asynchronous-javascript-callbacks-promises-and-async-await-17e0673281ee) or the MDN [Using promises](/en-US/docs/Web/JavaScript/Guide/Using_promises) page.
## API coverage
The differences in the extensions API function implementations among the browsers fall into three broad categories:
- Lack of support for an entire function.
- Variations in the support for features within a function. For example, at the time of writing, Firefox doesn't support the [`notification`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications) function method [`onButtonClicked`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications/onButtonClicked), while Firefox is the only browser that supports [`onShown`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications/onShown).
- Proprietary functions supporting browser-specific features. For example, at the time of writing, containers is a Firefox-specific feature supported by the [`contextualIdentities`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/contextualIdentities) function.
## Manifest keys
The differences in the supported [`manifest.json` keys](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) among the browsers fall broadly into two categories:
- Extension information attributes. For example, at the time of writing, Firefox and Opera include the [`developer`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/developer) key (in addition to the [`author`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/author) key) to record details about the extension developer.
- Extension features. For example, at the time of writing, only Firefox supports the [`protocol_handlers`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/protocol_handlers) key (which registers web-based protocol handlers, applications that know how to handle particular types of links).
## More information
You can find more detailed information about the differences in the supported browser extensions API features in:
- [Chrome incompatibilities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities)
- [Browser support for JavaScript APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs)
- [Browser compatibility for manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_compatibility_for_manifest.json)
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/content_security_policy/index.md | ---
title: Content Security Policy
slug: Mozilla/Add-ons/WebExtensions/Content_Security_Policy
page-type: guide
---
{{AddonSidebar}}
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>](/en-US/docs/Web/HTML/Element/script) and disallows potentially unsafe practices such as using [`eval()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](/en-US/docs/Web/HTTP/CSP) (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()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](#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`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy).
## Default content security policy
The default content security policy for extensions using Manifest V2 is:
```plain
"script-src 'self'; object-src 'self';"
```
While for extensions using Manifest V3, the default content security policy is:
```plain
"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`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/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.](#location_of_script_and_object_resources)
- [The extension is not allowed to evaluate strings as JavaScript.](#eval_and_friends)
- [Inline JavaScript is not executed.](#inline_javascript)
- [WebAssembly cannot be used by default.](#webassembly)
- [Insecure network requests are upgraded in Manifest V3.](#upgrade_insecure_network_requests_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 {{CSP("script-src")}} to secure sources only, which covers [\<script>](/en-US/docs/Web/HTML/Element/script) resources, [ES6 modules](/en-US/docs/Web/JavaScript/Guide/Modules) and [web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers). In browsers that support obsolete [plugins](/en-US/docs/Glossary/Plugin), the {{CSP("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)](https://github.com/w3c/webextensions/issues/204)).
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`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/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](https://extensionworkshop.com/documentation/develop/build-a-secure-extension/).
### 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](/en-US/docs/Web/API/Document/DOMContentLoaded_event) or [load](/en-US/docs/Web/API/Window/load_event) instead.
### WebAssembly
Extensions wishing to use [WebAssembly](/en-US/docs/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`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/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](https://bugzil.la/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 {{CSP("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](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/host_permissions) 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`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy) manifest.json key with a policy that excludes the `upgrade-insecure-requests` directive. However, to comply with the [security requirements](https://extensionworkshop.com/documentation/publish/add-on-policies/#security-compliance-and-blocking) 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](https://bugzil.la/1581611#c10)).
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](https://crbug.com/896041)).
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/extending_the_developer_tools/index.md | ---
title: Extend the developer tools
slug: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools
page-type: guide
---
{{AddonSidebar}}
> **Note:** This page describes the devtools APIs in Firefox 55. Although the APIs are based on the [Chrome devtools APIs](https://developer.chrome.com/docs/extensions/mv3/devtools/), Firefox does not implement all those features; therefore, not all features are documented here. To see which features are missing, refer to [Limitations of the devtools APIs](#limitations_of_the_devtools_apis).
You can use WebExtensions APIs to extend the browser's built-in developer tools. To create a devtools extension, include the "[devtools_page](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page)" key in your [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file:
```json
"devtools_page": "devtools/devtools-page.html"
```
The value of this key is a URL pointing to an HTML file bundled with your extension, a special extension page called the devtools page. The URL must be relative to the manifest.json file.
This manifest key implicitly sets the `"devtools"` permission, which triggers [an install-time permission warning about devtools](https://support.mozilla.org/en-US/kb/permission-request-messages-firefox-extensions#w_extend-developer-tools-to-access-your-data-in-open-tabs). To avoid this warning, mark the feature as optional by listing the `"devtools"` permission in the [`optional_permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) manifest key. Setting the optional permission can be particularly helpful when introducing devtools features in an update, as it prevents the extension from being disabled (in Chrome) or blocked from updating (in Firefox).
## The devtools page
The devtools page is loaded when the browser devtools are opened, and unloaded when it is closed. Note that because the devtools window is associated with a single tab, it's quite possible for more than one devtools window - hence more than one devtools page - to exist at the same time.
The devtools page doesn't have any visible DOM, but can include JavaScript sources using [`<script>`](/en-US/docs/Web/HTML/Element/script) tags. The sources must be bundled with the extension itself. The sources get access to:
- The normal DOM APIs accessible through the global [`window`](/en-US/docs/Web/API/Window) object
- The same [WebExtension APIs as in Content Scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#webextension_apis)
- The devtools APIs:
- [`devtools.inspectedWindow`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/inspectedWindow)
- [`devtools.network`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/network)
- [`devtools.panels`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/panels)
Note that the devtools page does not get access to any other WebExtension APIs, and the background page doesn't get access to the devtools APIs. Instead, the devtools page and the background page must communicate using the `runtime` messaging APIs. Here's an example:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>DevTools Extension</title>
</head>
<body>
<script src="devtools.js"></script>
</body>
</html>
```
The `devtools.js` file will hold the actual code creating your dev tools extensions.
## Creating panels
The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".
Using the `devtools.panels.create()` API, you can create your own panel in the devtools window:
```js
browser.devtools.panels
.create(
"My Panel", // title
"/icons/star.png", // icon
"/devtools/panel/panel.html", // content
)
.then((newPanel) => {
newPanel.onShown.addListener(initialisePanel);
newPanel.onHidden.addListener(unInitialisePanel);
});
```
This takes three mandatory arguments: the panel's title, icon, and content. It returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves to a `devtools.panels.ExtensionPanel` object representing the new panel.
## Interacting with the target window
The developer tools are always attached to a particular browser tab. This is referred to as the "target" for the developer tools, or the "inspected window". You can interact with the inspected window using the [`devtools.inspectedWindow`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/inspectedWindow) API.
### Running code in the target window
The [`devtools.inspectedWindow.eval()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/inspectedWindow/eval) provides one way to run code in the inspected window.
This is somewhat like using {{WebExtAPIRef("tabs.executeScript()")}} to inject a content script, but with one important difference:
- unlike content scripts, scripts loaded using `devtools.inspectedWindow.eval()` **do not** get [a "clean view of the DOM"](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#dom_access): that is, they can see changes to the page made by page scripts.
> **Note:** A clean view of the DOM is a security feature, intended to help prevent hostile pages from tricking extensions by redefining the behavior of native DOM functions. This means you need to be very careful using eval(), and should use a normal content script if you can.
Scripts loaded using `devtools.inspectedWindow.eval()` also don't see any JavaScript variables defined by content scripts.
### Working with content scripts
A devtools document doesn't have direct access to {{WebExtAPIRef("tabs.executeScript()")}}, so if you need to inject a content script, the devtools document must send a message to the background script asking it to inject the script. The [`devtools.inspectedWindow.tabId`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/inspectedWindow/tabId) provides the ID of the target tab: the devtools document can pass this to the background script, and the background script can in turn pass it into {{WebExtAPIRef("tabs.executeScript()")}}:
```js
// devtools-panel.js
const scriptToAttach = "document.body.innerHTML = 'Hi from the devtools';";
window.addEventListener("click", () => {
browser.runtime.sendMessage({
tabId: browser.devtools.inspectedWindow.tabId,
script: scriptToAttach,
});
});
```
```js
// background.js
function handleMessage(request, sender, sendResponse) {
browser.tabs.executeScript(request.tabId, {
code: request.script,
});
}
browser.runtime.onMessage.addListener(handleMessage);
```
If you need to exchange messages between the content scripts running in the target window and a devtools document, it's a good idea to use the {{WebExtAPIRef("runtime.connect()")}} and {{WebExtAPIRef("runtime.onConnect")}} to set up a connection between the background page and the devtools document. The background page can then maintain a mapping between tab IDs and {{WebExtAPIRef("runtime.Port")}} objects, and use this to route messages between the two scopes.

## Limitations of the devtools APIs
These APIs are based on the Chrome devtools APIs, but many features are still missing, compared with Chrome. This section lists the features that are still not implemented, as of Firefox 54. Note that the devtools APIs are under active development and we expect to add support for most of them in future releases.
### devtools.inspectedWindow
The following are not supported:
- `inspectedWindow.getResources()`
- `inspectedWindow.onResourceAdded`
- `inspectedWindow.onResourceContentCommitted`
None of the options to `inspectedWindow.eval()` are supported.
Scripts injected using `inspectedWindow.eval()` can't use all the Console's command-line helper functions, but `$0` and `inspect()` are both supported (starting from Firefox 55).
### devtools.panels
The following are not supported:
- `panels.elements`
- `panels.sources`
- `panels.setOpenResourceHandler()`
- `panels.openResource()`
- `panels.ExtensionPanel.createStatusBarButton()`
- `panels.Button`
- `panels.ElementsPanel`
- `panels.SourcesPanel`
## Examples
The [webextensions-examples](https://github.com/mdn/webextensions-examples) repo on GitHub, contains several examples of extensions that use devtools panels:
- [devtools-panels](https://github.com/mdn/webextensions-examples/tree/main/devtools-panels) use devtools panels:
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/what_are_webextensions/index.md | ---
title: What are extensions?
slug: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions
page-type: guide
---
{{AddonSidebar}}
> **Note:** If you are already familiar with the basic concepts of browser extensions, skip this section to [see how extension files are put together](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension). Then, use the [reference documentation](/en-US/docs/Mozilla/Add-ons/WebExtensions#reference) to start building your extension. Visit [Firefox Extension Workshop](https://extensionworkshop.com/?utm_source=developer.mozilla.org&utm_medium=documentation&utm_campaign=your-first-extension) to learn more about the workflow for testing, publishing, and extensions for Firefox.
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.

Examples: [Amazon Assistant for Firefox](https://addons.mozilla.org/en-US/firefox/addon/amazon-browser-bar/), [OneNote Web Clipper](https://addons.mozilla.org/en-US/firefox/addon/onenote-clipper/), and [Grammarly for Firefox](https://addons.mozilla.org/en-US/firefox/addon/grammarly-1/).
**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](https://extensionworkshop.com/documentation/themes/) do.

Examples: [MyWeb New Tab](https://chrome.google.com/webstore/detail/myweb-new-tab/cnbiadnhebmicjcbpgajglfemclnlagh), [Tabliss](https://addons.mozilla.org/en-US/firefox/addon/tabliss/), and [VivaldiFox](https://addons.mozilla.org/en-US/firefox/addon/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.

Examples: [uBlock Origin](https://addons.mozilla.org/en-US/firefox/addon/ublock-origin/), [Reader](https://addons.mozilla.org/en-US/firefox/addon/reader/), and [Toolbox for Google Play Storeβ’](https://addons.mozilla.org/en-US/firefox/addon/toolbox-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](/en-US/docs/Mozilla/Add-ons/WebExtensions) 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.

Examples: [Swimlanes for Trello](https://addons.mozilla.org/en-US/firefox/addon/swimlanes-for-trello/) and [Tomato Clock](https://addons.mozilla.org/en-US/firefox/addon/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](https://addons.mozilla.org/en-US/firefox/addon/solitaire-spider-freecell/), and [2048 Prime](https://addons.mozilla.org/en-US/firefox/addon/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.

Examples: [Web Developer](https://addons.mozilla.org/en-US/firefox/addon/web-developer/), [Web React Developer Tools](https://addons.mozilla.org/en-US/firefox/addon/react-devtools/), and [aXe Developer Tools](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/).
Extensions for Firefox are built using the [WebExtensions APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions), a cross-browser system for developing extensions. To a large extent, the API is compatible with the [extension API](https://developer.chrome.com/docs/extensions/reference/) 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](https://extensionworkshop.com/documentation/develop/porting-a-google-chrome-extension/).
If you have ideas or questions, you can reach us on the [Add-ons Discourse](https://discourse.mozilla.org/c/add-ons/35) or in the [Add-ons room](https://chat.mozilla.org/#/room/#addons:mozilla.org) on [Matrix](https://wiki.mozilla.org/Matrix).
## What's next?
- Walk through the development of a simple extension in [Your first extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension).
- Learn about the structure of an extension in [Anatomy of an extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension).
- Try out some example extensions in [Example extensions](/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples).
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/index.md | ---
title: JavaScript APIs
slug: Mozilla/Add-ons/WebExtensions/API
page-type: landing-page
---
{{AddonSidebar}}
JavaScript APIs for WebExtensions can be used inside the extension's [background scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#background_scripts) and in any other documents bundled with the extension, including [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button) or [page action](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions) popups, [sidebars](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars), [options pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages), or [new tab pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_url_overrides). A few of these APIs can also be accessed by an extension's [content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#content_scripts). (See the [list in the content script guide](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#webextension_apis).)
To use the more powerful APIs, you need to [request permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) 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 {{JSxRef("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](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs) and [Chrome incompatibilities](/en-US/docs/Mozilla/Add-ons/WebExtensions/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](https://extensionworkshop.com/documentation/develop/debugging/#developer-tools-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:

## JavaScript API listing
See below for a complete list of JavaScript APIs:
{{LandingPageListSubpages}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contentscripts/index.md | ---
title: contentScripts
slug: Mozilla/Add-ons/WebExtensions/API/contentScripts
page-type: webextension-api
browser-compat: webextensions.api.contentScripts
---
{{AddonSidebar}}
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 {{WebExtAPIRef("scripting.registerContentScripts()")}} to register scripts.
This API is very similar to the [`"content_scripts"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/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 {{WebExtAPIRef("contentScripts.register()")}} passing in an object defining the scripts to register, the URL patterns, and other options. This returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is resolved with a {{WebExtAPIRef("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](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for any patterns it passes to `register()`.
## Types
- {{WebExtAPIRef("contentScripts.RegisteredContentScript")}}
- : An object of this type is returned by the {{WebExtAPIRef("contentScripts.register()")}} function. It represents the content scripts that were registered by that call, and can be used to unregister the content script.
## Functions
- {{WebExtAPIRef("contentScripts.register()")}}
- : Registers the given content scripts.
## Browser compatibility
{{Compat}}
{{WebExtExamples("h2")}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contentscripts | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contentscripts/registeredcontentscript/index.md | ---
title: contentScripts.RegisteredContentScript
slug: Mozilla/Add-ons/WebExtensions/API/contentScripts/RegisteredContentScript
page-type: webextension-api-type
browser-compat: webextensions.api.contentScripts.RegisteredContentScript
---
{{AddonSidebar}}
A `RegisteredContentScript` is returned by a call to {{WebExtAPIRef("contentScripts.register()")}} and represents the content scripts registered in that call.
It defines a single function {{WebExtAPIRef("contentScripts.RegisteredContentScript.unregister", "unregister()")}}, which can be used to unregister the content scripts.
> **Note:** If this object is destroyed (for example because it goes out of scope) then the content scripts will be unregistered automatically, so you should keep a reference to this object for as long as you want the content scripts to stay registered.
## Methods
- {{WebExtAPIRef("contentScripts.RegisteredContentScript.unregister","unregister()")}}
- : Unregisters the content scripts represented by this object.
## Browser compatibility
{{Compat}}
## Examples
This code toggles a registered content script on a browser action click:
```js
let registered = null;
async function register() {
registered = await browser.contentScripts.register({
matches: ["*://*.org/*"],
js: [
{
code: "document.body.innerHTML = '<h1>This page has been eaten<h1>'",
},
],
runAt: "document_idle",
});
}
function toggle() {
if (registered) {
registered.unregister();
registered = null;
} else {
register();
}
}
browser.browserAction.onClicked.addListener(toggle);
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contentscripts/registeredcontentscript | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contentscripts/registeredcontentscript/unregister/index.md | ---
title: contentScripts.RegisteredContentScript.unregister()
slug: Mozilla/Add-ons/WebExtensions/API/contentScripts/RegisteredContentScript/unregister
page-type: webextension-api-function
browser-compat: webextensions.api.contentScripts.RegisteredContentScript.unregister
---
{{AddonSidebar}}
Unregisters the content scripts represented by this `RegisteredContentScript` object.
## Syntax
```js-nolint
registered.unregister()
```
### Parameters
None.
### Return value
None.
## Browser compatibility
{{Compat}}
## Examples
This code toggles a registered content script on a browser action click:
```js
let registered = null;
async function register() {
registered = await browser.contentScripts.register({
matches: ["*://*.org/*"],
js: [
{
code: "document.body.innerHTML = '<h1>This page has been eaten<h1>'",
},
],
runAt: "document_idle",
});
}
function toggle() {
if (registered) {
registered.unregister();
registered = null;
} else {
register();
}
}
browser.browserAction.onClicked.addListener(toggle);
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contentscripts | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/contentscripts/register/index.md | ---
title: contentScripts.register()
slug: Mozilla/Add-ons/WebExtensions/API/contentScripts/register
page-type: webextension-api-function
browser-compat: webextensions.api.contentScripts.register
---
{{AddonSidebar}}
Use this function to register one or more content scripts.
It accepts one parameter, which is an object with similar properties to the objects given in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) manifest key (but note that `content_scripts` is an array of objects, while the argument to `register()` is a single object).
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let registering = browser.contentScripts.register(
contentScriptOptions // object
)
```
### Parameters
- `contentScriptOptions`
- : `object`. A `RegisteredContentScriptOptions` object representing the content scripts to register. It has similar syntax to the objects in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) manifest key array. The differences are:
- property names use {{Glossary("camel_case", "camel case")}}, rather than underscores ({{Glossary("snake_case", "snake case")}}) β for example, `excludeMatches`, not `exclude_matches`.
- the `js` and `css` properties allow you to register strings as well as URLs, so their syntax has to distinguish these types.
The `RegisteredContentScriptOptions` object has the following properties:
- `allFrames` {{optional_inline}}
- : Same as `all_frames` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key.
- `cookieStoreId` {{optional_inline}}
- : A string or array of strings. Registers the content script in the tabs that belong to one or more cookie store IDs. This enables scripts to be registered for all default or non-contextual identity tabs, private browsing tabs (if the [extension is enabled in private browsing](https://support.mozilla.org/en-US/kb/extensions-private-browsing)), the tabs of a [contextual identity](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities), or a combination of these. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information.
- `css` {{optional_inline}}
- : An array of objects. Each object has either a property named `file`, which is a URL starting at the extension's manifest.json and pointing to a CSS file to register, or a property named `code`, which is some CSS code to register.
- `excludeGlobs` {{optional_inline}}
- : Same as `exclude_globs` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key.
- `excludeMatches` {{optional_inline}}
- : Same as `exclude_matches` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key.
- `includeGlobs` {{optional_inline}}
- : Same as `include_globs` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key.
- `js` {{optional_inline}}
- : An array of objects. Each object has either a property named `file`, which is a URL starting at the extension's manifest.json and pointing to a JavaScript file to register, or a property named `code`, which is some JavaScript code to register.
- `matchAboutBlank` {{optional_inline}}
- : Same as `match_about_blank` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key.
- `matches`
- : Same as `matches` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key.
- `runAt` {{optional_inline}}
- : Same as `run_at` in the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef("contentScripts.RegisteredContentScript")}} object that you can use to unregister the content scripts.
Currently, content scripts are unregistered when the related extension page (from which the content scripts were registered) is unloaded, so you should register a content script from an extension page that persists at least as long as you want the content scripts to stay registered.
## Browser compatibility
{{Compat}}
## Examples
This example registers the `defaultCode` content script for all `.org` URLs:
```js
const defaultHosts = "*://*.org/*";
const defaultCode =
"document.body.innerHTML = '<h1>This page has been eaten<h1>'";
async function register(hosts, code) {
return await browser.contentScripts.register({
matches: [hosts],
js: [{ code }],
runAt: "document_idle",
});
}
let registered = register(defaultHosts, defaultCode);
```
This code registers the JS file at content_scripts/example.js:
```js
const scriptObj = await browser.contentScripts.register({
js: [{ file: "/content_scripts/example.js" }],
matches: ["<all_urls>"],
allFrames: true,
runAt: "document_start",
});
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox/index.md | ---
title: omnibox
slug: Mozilla/Add-ons/WebExtensions/API/omnibox
page-type: webextension-api
browser-compat: webextensions.api.omnibox
---
{{AddonSidebar}}
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](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/omnibox)" key in its [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/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 {{WebExtAPIRef("omnibox.onInputStarted")}} event.
3. Optionally, the extension can call {{WebExtAPIRef("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 {{WebExtAPIRef("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 {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, this suggestion is displayed first in the drop-down.
5. If the user accepts a suggestion, the extension gets an {{WebExtAPIRef("omnibox.onInputEntered")}} event. The event listener is passed the accepted suggestion.
6. If the user deletes a suggestion, the extension gets an {{WebExtAPIRef("omnibox.onDeleteSuggestion")}} event.
7. If the user dismisses the drop-down, the extension gets an {{WebExtAPIRef("omnibox.onInputCancelled")}} event.
## Types
- {{WebExtAPIRef("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.
- {{WebExtAPIRef("omnibox.SuggestResult")}}
- : An object representing a suggestion to add to the address bar drop-down.
## Functions
- {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}
- : Defines the first suggestion displayed in the drop-down when the user enters your extension's keyword followed by a space.
## Events
- {{WebExtAPIRef("omnibox.onDeleteSuggestion")}}
- : Fired whenever the user deletes a suggestion.
- {{WebExtAPIRef("omnibox.onInputStarted")}}
- : Fired when the user focuses the address bar and types your extension's omnibox keyword, followed by a space.
- {{WebExtAPIRef("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.
- {{WebExtAPIRef("omnibox.onInputEntered")}}
- : Fired when the user accepts one of your extension's suggestions.
- {{WebExtAPIRef("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.
{{WebExtExamples("h2")}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.omnibox`](https://developer.chrome.com/docs/extensions/reference/omnibox/) API.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox/oninputcancelled/index.md | ---
title: omnibox.onInputCancelled
slug: Mozilla/Add-ons/WebExtensions/API/omnibox/onInputCancelled
page-type: webextension-api-event
browser-compat: webextensions.api.omnibox.onInputCancelled
---
{{AddonSidebar}}
Fired when the user has cancelled their interaction with your extension (for example, by clicking outside the address bar).
## Syntax
```js-nolint
browser.omnibox.onInputCancelled.addListener(listener)
browser.omnibox.onInputCancelled.removeListener(listener)
browser.omnibox.onInputCancelled.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
The listener function is passed no parameters.
## Browser compatibility
{{Compat}}
## Examples
```js
browser.omnibox.onInputCancelled.addListener(() => {
console.log("The user cancelled the session.");
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.omnibox`](https://developer.chrome.com/docs/extensions/reference/omnibox/) API.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox/oninputentereddisposition/index.md | ---
title: omnibox.OnInputEnteredDisposition
slug: Mozilla/Add-ons/WebExtensions/API/omnibox/OnInputEnteredDisposition
page-type: webextension-api-type
browser-compat: webextensions.api.omnibox.OnInputEnteredDisposition
---
{{AddonSidebar}}
The **`omnibox.OnInputEnteredDisposition`** type describes how the extension should handle a user selection from the suggestions in the address bar's drop-down list.
It's passed into the {{WebExtAPIRef("omnibox.onInputEntered")}} event listener, along with the selection itself.
## Type
Values of this type are strings. They may take any one of the following values:
- "currentTab"
- : Open the selection in the current tab.
- "newForegroundTab"
- : Open the selection in a new tab, and bring this new tab into the foreground.
- "newBackgroundTab"
- : Open the selection in a new background tab, keeping the current tab in the foreground.
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.omnibox`](https://developer.chrome.com/docs/extensions/reference/omnibox/) API.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox/oninputchanged/index.md | ---
title: omnibox.onInputChanged
slug: Mozilla/Add-ons/WebExtensions/API/omnibox/onInputChanged
page-type: webextension-api-event
browser-compat: webextensions.api.omnibox.onInputChanged
---
{{AddonSidebar}}
Fired whenever the user changes their input, after they have started interacting with your extension by entering its keyword in the address bar and then pressing the space key.
This is the event you'll use to populate the address bar's drop-down list with suggestions. The event listener is passed:
- the current user input (not including the keyword itself or the space after it)
- a function which the listener can call with an array of {{WebExtAPIRef("omnibox.SuggestResult")}} objects, one for each suggestion. Only the first six suggestions will be displayed.
## Syntax
```js-nolint
browser.omnibox.onInputChanged.addListener(listener)
browser.omnibox.onInputChanged.removeListener(listener)
browser.omnibox.onInputChanged.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
The listener function is passed two parameters: a string `text`, and the function `suggest`.
### Parameters
- `text`
- : `String`. The current user input in the address bar, not including the extension's keyword itself or the space after the keyword. Use this to decide which suggestions to display in the drop-down list.
- `suggest`
- : `Function`. A function that the event listener can call to supply suggestions for the address bar's drop-down list. The function expects to receive an array of {{WebExtAPIRef("omnibox.SuggestResult")}} objects, one for each suggestion. Only the first six suggestions will be displayed.
## Browser compatibility
{{Compat}}
## Examples
This example interprets the user's input as a CSS property name and populates the drop-down list with one {{WebExtAPIRef("omnibox.SuggestResult")}} object for each CSS property matching the input. The `description` property of `SuggestResult` is the full name of the property, and the `content` is the MDN page for that property.
The example also listens to {{WebExtAPIRef("omnibox.onInputEntered")}}, and opens the MDN page corresponding to the selection, according to the {{WebExtAPIRef("omnibox.OnInputEnteredDisposition")}} argument.
```js
browser.omnibox.setDefaultSuggestion({
description: "Type the name of a CSS property",
});
/*
Very short list of a few CSS properties.
*/
const props = [
"animation",
"background",
"border",
"box-shadow",
"color",
"display",
"flex",
"flex",
"float",
"font",
"grid",
"margin",
"opacity",
"overflow",
"padding",
"position",
"transform",
"transition",
];
const baseURL = "https://developer.mozilla.org/en-US/docs/Web/CSS/";
/*
Return an array of SuggestResult objects,
one for each CSS property that matches the user's input.
*/
function getMatchingProperties(input) {
const result = [];
for (const prop of props) {
if (prop.startsWith(input)) {
console.log(prop);
const suggestion = {
content: `${baseURL}${prop}`,
description: prop,
};
result.push(suggestion);
} else if (result.length !== 0) {
return result;
}
}
return result;
}
browser.omnibox.onInputChanged.addListener((input, suggest) => {
suggest(getMatchingProperties(input));
});
browser.omnibox.onInputEntered.addListener((url, disposition) => {
switch (disposition) {
case "currentTab":
browser.tabs.update({ url });
break;
case "newForegroundTab":
browser.tabs.create({ url });
break;
case "newBackgroundTab":
browser.tabs.create({ url, active: false });
break;
}
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.omnibox`](https://developer.chrome.com/docs/extensions/reference/omnibox/) API.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox/oninputentered/index.md | ---
title: omnibox.onInputEntered
slug: Mozilla/Add-ons/WebExtensions/API/omnibox/onInputEntered
page-type: webextension-api-event
browser-compat: webextensions.api.omnibox.onInputEntered
---
{{AddonSidebar}}
Fired when the user has selected one of the suggestions your extension has added to the address bar's drop-down list.
Use this event to handle the user's selection, generally by opening the corresponding page. The event listener is passed:
- the user's selection
- a {{WebExtAPIRef("omnibox.OnInputEnteredDisposition")}}: use this to determine whether to open the new page in the current tab, in a new foreground tab, or in a new background tab.
## Syntax
```js-nolint
browser.omnibox.onInputEntered.addListener(listener)
browser.omnibox.onInputEntered.removeListener(listener)
browser.omnibox.onInputEntered.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
The listener function will be passed two parameters: a string `text`, and an {{WebExtAPIRef("omnibox.OnInputEnteredDisposition")}}.
### Parameters
- `text`
- : `String`. This is the value of the `content` property of the {{WebExtAPIRef("omnibox.SuggestResult")}} object that the user selected.
- `disposition`
- : {{WebExtAPIRef("omnibox.OnInputEnteredDisposition", "OnInputEnteredDisposition")}}. A {{WebExtAPIRef("omnibox.OnInputEnteredDisposition")}} enumeration, indicating whether the extension should open the page in the current tab, in a new foreground tab, or in a new background tab.
## Browser compatibility
{{Compat}}
## Examples
This example interprets the user's input as a CSS property name and populates the drop-down list with one {{WebExtAPIRef("omnibox.SuggestResult")}} object for each CSS property matching the input. The `description` property of `SuggestResult` is the full name of the property, and the `content` is the MDN page for that property.
The example also listens to {{WebExtAPIRef("omnibox.onInputEntered")}}, and opens the MDN page corresponding to the selection, according to the {{WebExtAPIRef("omnibox.OnInputEnteredDisposition")}} argument.
```js
browser.omnibox.setDefaultSuggestion({
description: "Type the name of a CSS property",
});
/*
Very short list of a few CSS properties.
*/
const props = [
"animation",
"background",
"border",
"box-shadow",
"color",
"display",
"flex",
"flex",
"float",
"font",
"grid",
"margin",
"opacity",
"overflow",
"padding",
"position",
"transform",
"transition",
];
const baseURL = "https://developer.mozilla.org/en-US/docs/Web/CSS/";
/*
Return an array of SuggestResult objects,
one for each CSS property that matches the user's input.
*/
function getMatchingProperties(input) {
const result = [];
for (const prop of props) {
if (prop.startsWith(input)) {
console.log(prop);
const suggestion = {
content: `${baseURL}${prop}`,
description: prop,
};
result.push(suggestion);
} else if (result.length !== 0) {
return result;
}
}
return result;
}
browser.omnibox.onInputChanged.addListener((input, suggest) => {
suggest(getMatchingProperties(input));
});
browser.omnibox.onInputEntered.addListener((url, disposition) => {
switch (disposition) {
case "currentTab":
browser.tabs.update({ url });
break;
case "newForegroundTab":
browser.tabs.create({ url });
break;
case "newBackgroundTab":
browser.tabs.create({ url, active: false });
break;
}
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.omnibox`](https://developer.chrome.com/docs/extensions/reference/omnibox/) API.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox/ondeletesuggestion/index.md | ---
title: omnibox.onDeleteSuggestion
slug: Mozilla/Add-ons/WebExtensions/API/omnibox/onDeleteSuggestion
page-type: webextension-api-event
browser-compat: webextensions.api.omnibox.onDeleteSuggestion
---
{{AddonSidebar}}
Fired whenever the user deletes a suggestion.
A suggestion can be deleted when {{WebExtAPIRef("omnibox.SuggestResult","SuggestResult")}}`.deletable` is set to true.
## Syntax
```js-nolint
browser.omnibox.onDeleteSuggestion.addListener(listener)
browser.omnibox.onDeleteSuggestion.removeListener(listener)
browser.omnibox.onDeleteSuggestion.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `text`
- : `string`. The description of the deleted suggestion.
## Examples
This example prints the deleted suggestion to the console:
```js
function logDeletedSuggestion(text) {
console.log(`The user deleted: ${text}`);
}
browser.omnibox.onDeleteSuggestion.addListener(logDeletedSuggestion);
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.omnibox`](https://developer.chrome.com/docs/extensions/reference/omnibox/) API.
>
> Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox/oninputstarted/index.md | ---
title: omnibox.onInputStarted
slug: Mozilla/Add-ons/WebExtensions/API/omnibox/onInputStarted
page-type: webextension-api-event
browser-compat: webextensions.api.omnibox.onInputStarted
---
{{AddonSidebar}}
Fired when the user starts interacting with your extension by entering its keyword in the address bar and then pressing the space key.
This will be sent before any {{WebExtAPIRef("omnibox.onInputChanged")}} events.
## Syntax
```js-nolint
browser.omnibox.onInputStarted.addListener(listener)
browser.omnibox.onInputStarted.removeListener(listener)
browser.omnibox.onInputStarted.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed no arguments.
## Browser compatibility
{{Compat}}
## Examples
```js
browser.omnibox.onInputStarted.addListener(() => {
console.log("User has started interacting with me.");
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.omnibox`](https://developer.chrome.com/docs/extensions/reference/omnibox/) API.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox/suggestresult/index.md | ---
title: omnibox.SuggestResult
slug: Mozilla/Add-ons/WebExtensions/API/omnibox/SuggestResult
page-type: webextension-api-type
browser-compat: webextensions.api.omnibox.SuggestResult
---
{{AddonSidebar}}
The **`omnibox.SuggestResult`** type defines a suggestion that the extension can add to the address bar's drop-down list.
The extension's {{WebExtAPIRef("omnibox.onInputChanged")}} event listener is passed a callback. To populate the address bar's drop-down list in response to the user's input, the extension can pass an array of `omnibox.SuggestResult` objects into this callback.
## Type
Values of this type are objects. They have the following properties:
- `content`
- : This is the value that will appear in the address bar itself when the user highlights this suggestion in the drop-down list. This is also the string sent to the {{WebExtAPIRef("omnibox.onInputEntered")}} event listener if the user selects this suggestion. If the string is the same as what the user has already typed, this entry will not appear in the drop-down list.
- `deletable`
- : Whether the suggest result can be deleted by the user.
- `description`
- : This is the string that's displayed in the address bar's drop-down list.
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.omnibox`](https://developer.chrome.com/docs/extensions/reference/omnibox/) API.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/omnibox/setdefaultsuggestion/index.md | ---
title: omnibox.setDefaultSuggestion()
slug: Mozilla/Add-ons/WebExtensions/API/omnibox/setDefaultSuggestion
page-type: webextension-api-function
browser-compat: webextensions.api.omnibox.setDefaultSuggestion
---
{{AddonSidebar}}
Set the default suggestion to appear in the address bar drop-down list when the user starts interacting with your extension.
Once the user has entered your keyword and started interacting with your extension, the default suggestion will always appear first in the drop-down list. Unlike the suggestions you supply in {{WebExtAPIRef("omnibox.onInputChanged")}}, this item can't be selected. Use it to provide the user with some guidance about what to type and what they can expect to see when they do.
## Syntax
```js-nolint
browser.omnibox.setDefaultSuggestion(
suggestion // object
)
```
### Parameters
- `suggestion`
- : `object`. An object containing a single string property `description`, which will be displayed as the first item in the drop-down when the user starts interacting with your extension.
### Return value
None.
## Browser compatibility
{{Compat}}
## Examples
```js
browser.omnibox.setDefaultSuggestion({
description: "Type the name of a CSS property",
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [chrome.omnibox](https://developer.chrome.com/docs/extensions/reference/omnibox/) API.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/index.md | ---
title: sessions
slug: Mozilla/Add-ons/WebExtensions/API/sessions
page-type: webextension-api
browser-compat: webextensions.api.sessions
---
{{AddonSidebar}}
Use the sessions API to list, and restore, tabs and windows that have been closed while the browser has been running.
The {{WebExtAPIRef("sessions.getRecentlyClosed()")}} function returns an array of {{WebExtAPIRef("tabs.Tab")}} and {{WebExtAPIRef("windows.Window")}} objects, representing tabs and windows that have been closed since the browser was running, up to the maximum defined in {{WebExtAPIRef("sessions.MAX_SESSION_RESULTS")}}.
You can then restore a window or tab using the {{WebExtAPIRef("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](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions).
## Types
- {{WebExtAPIRef("sessions.Filter")}}
- : Enables you to restrict the number of {{WebExtAPIRef("sessions.Session", "Session")}} objects returned by a call to {{WebExtAPIRef("sessions.getRecentlyClosed()")}}.
- {{WebExtAPIRef("sessions.Session")}}
- : Represents a tab or window that the user has closed in the current browsing session.
## Properties
- {{WebExtAPIRef("sessions.MAX_SESSION_RESULTS")}}
- : The maximum number of sessions that will be returned by a call to [`sessions.getRecentlyClosed()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/sessions/getRecentlyClosed).
## Functions
- {{WebExtAPIRef("sessions.forgetClosedTab()")}}
- : Removes a closed tab from the browser's list of recently closed tabs.
- {{WebExtAPIRef("sessions.forgetClosedWindow()")}}
- : Removes a closed window from the browser's list of recently closed windows.
- {{WebExtAPIRef("sessions.getRecentlyClosed()")}}
- : Returns an array of {{WebExtAPIRef("sessions.Session", "Session")}} objects, representing windows and tabs that were closed in the current browsing session (that is: the time since the browser was started).
- {{WebExtAPIRef("sessions.restore()")}}
- : Restores a closed tab or window.
- {{WebExtAPIRef("sessions.setTabValue()")}}
- : Store a key/value pair associated with a given tab.
- {{WebExtAPIRef("sessions.getTabValue()")}}
- : Retrieve a previously stored value for a given tab, given its key.
- {{WebExtAPIRef("sessions.removeTabValue()")}}
- : Remove a key/value pair from a given tab.
- {{WebExtAPIRef("sessions.setWindowValue()")}}
- : Store a key/value pair associated with a given window.
- {{WebExtAPIRef("sessions.getWindowValue()")}}
- : Retrieve a previously stored value for a given window, given its key.
- {{WebExtAPIRef("sessions.removeWindowValue()")}}
- : Remove a key/value pair from a given window.
## Events
- {{WebExtAPIRef("sessions.onChanged")}}
- : Fired when a tab or window is closed.
## Browser compatibility
{{Compat}}
{{WebExtExamples("h2")}}
> **Note:** This API is based on Chromium's [`chrome.sessions`](https://developer.chrome.com/docs/extensions/reference/sessions/) API.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/settabvalue/index.md | ---
title: sessions.setTabValue()
slug: Mozilla/Add-ons/WebExtensions/API/sessions/setTabValue
page-type: webextension-api-function
browser-compat: webextensions.api.sessions.setTabValue
---
{{AddonSidebar}}
Stores a key/value pair to associate with a given tab. You can subsequently retrieve this value using {{WebExtAPIRef("sessions.getTabValue")}}.
Note that this data will only be visible to the extension that set it, and not to any other extensions.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let storing = browser.sessions.setTabValue(
tabId, // integer
key, // string
value // string or object
)
```
### Parameters
- `tabId`
- : `integer`. ID of the tab with which you want to associate the data. Error is thrown if ID is invalid.
- `key`
- : `string`. Key that you can later use to retrieve this particular data value.
- `value`
- : `string` or `object`. If this is an object it is [stringified](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify), so object methods, for example, will be omitted. If a function is given here it will be stored as the value `null`.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be resolved with no arguments if the call succeeded. If the call failed (for example, because the tab ID could not be found) then the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
Set a value on the active tab when the user selects a menu item. Note that you'll need the "menus" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) to run this example:
```js
async function setOnActiveTab() {
let tabArray = await browser.tabs.query({
currentWindow: true,
active: true,
});
let tabId = tabArray[0].id;
await browser.sessions.setTabValue(tabId, "my-key", "my-value");
}
browser.menus.create({
id: "my-item",
title: "my item",
contexts: ["all"],
});
browser.menus.onClicked.addListener(setOnActiveTab);
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/max_session_results/index.md | ---
title: sessions.MAX_SESSION_RESULTS
slug: Mozilla/Add-ons/WebExtensions/API/sessions/MAX_SESSION_RESULTS
page-type: webextension-api-property
browser-compat: webextensions.api.sessions.MAX_SESSION_RESULTS
---
{{AddonSidebar}}
This value represents the maximum number of sessions that will be returned by a call to {{WebExtAPIRef("sessions.getRecentlyClosed()")}}. It is read-only for WebExtension code, and is set to 25.
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.sessions`](https://developer.chrome.com/docs/extensions/reference/sessions/) API.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/removewindowvalue/index.md | ---
title: sessions.removeWindowValue()
slug: Mozilla/Add-ons/WebExtensions/API/sessions/removeWindowValue
page-type: webextension-api-function
browser-compat: webextensions.api.sessions.removeWindowValue
---
{{AddonSidebar}}
Removes a value previously stored by a call to {{WebExtAPIRef("sessions.setWindowValue")}}.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let removing = browser.sessions.removeWindowValue(
windowId, // integer
key // string
)
```
### Parameters
- `windowId`
- : `integer`. ID of the window whose data you are trying to remove. Error is thrown if ID is invalid.
- `key`
- : `string`. Key identifying the particular value to remove. This needs to match the key previously given in {{WebExtAPIRef("sessions.setWindowValue")}}.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be resolved no arguments if the item was successfully removed. If the call failed (for example, because the window ID could not be found) then the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
This code adds two context menu items: one stores a value associated with the current window, the other one removes it:
```js
async function setOnActiveWindow() {
let currentWindow = await browser.windows.getLastFocused();
await browser.sessions.setWindowValue(currentWindow.id, "my-key", "my-value");
}
async function removeFromActiveWindow() {
let currentWindow = await browser.windows.getLastFocused();
await browser.sessions.removeWindowValue(currentWindow.id, "my-key");
}
browser.menus.create({
id: "add-my-item",
title: "add item",
contexts: ["all"],
});
browser.menus.create({
id: "remove-my-item",
title: "remove item",
contexts: ["all"],
});
browser.menus.onClicked.addListener((info) => {
if (info.menuItemId === "add-my-item") {
setOnActiveWindow();
} else {
removeFromActiveWindow();
}
});
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/onchanged/index.md | ---
title: sessions.onChanged
slug: Mozilla/Add-ons/WebExtensions/API/sessions/onChanged
page-type: webextension-api-event
browser-compat: webextensions.api.sessions.onChanged
---
{{AddonSidebar}}
Fired whenever the list of closed tabs or windows changes.
## Syntax
```js-nolint
browser.sessions.onChanged.addListener(listener)
browser.sessions.onChanged.removeListener(listener)
browser.sessions.onChanged.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. It's passed no parameters.
## Browser compatibility
{{Compat}}
## Examples
This very annoying extension listens for `onChanged`, then immediately restores the most recently closed session, thus making it impossible to close windows or tabs:
```js
function restoreSession(sessionInfos) {
if (!sessionInfos.length) {
console.log("No sessions found");
return;
}
let sessionInfo = sessionInfos[0];
if (sessionInfo.tab) {
browser.sessions.restore(sessionInfo.tab.sessionId);
} else {
browser.sessions.restore(sessionInfo.window.sessionId);
}
}
function onError(error) {
console.log(error);
}
function restoreMostRecent() {
let gettingSessions = browser.sessions.getRecentlyClosed({
maxResults: 1,
});
gettingSessions.then(restoreSession, onError);
}
browser.sessions.onChanged.addListener(restoreMostRecent);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.sessions`](https://developer.chrome.com/docs/extensions/reference/sessions/) API.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/removetabvalue/index.md | ---
title: sessions.removeTabValue()
slug: Mozilla/Add-ons/WebExtensions/API/sessions/removeTabValue
page-type: webextension-api-function
browser-compat: webextensions.api.sessions.removeTabValue
---
{{AddonSidebar}}
Removes a value previously stored by a call to {{WebExtAPIRef("sessions.setTabValue")}}.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let removing = browser.sessions.removeTabValue(
tabId, // integer
key // string
)
```
### Parameters
- `tabId`
- : `integer`. ID of the tab whose data you are trying to remove. Error is thrown if ID is invalid.
- `key`
- : `string`. Key identifying the particular value to remove. This needs to match the key previously given in {{WebExtAPIRef("sessions.setTabValue")}}.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be resolved no arguments if the item was successfully removed. If the call failed (for example, because the tab ID could not be found) then the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
This code adds two context menu items: one stores a value associated with the current tab, the other one removes it:
```js
async function setOnActiveTab() {
let tabArray = await browser.tabs.query({
currentWindow: true,
active: true,
});
let tabId = tabArray[0].id;
await browser.sessions.setTabValue(tabId, "my-key", "my-value");
}
async function removeFromActiveTab() {
let tabArray = await browser.tabs.query({
currentWindow: true,
active: true,
});
let tabId = tabArray[0].id;
await browser.sessions.removeTabValue(tabId, "my-key");
}
browser.menus.create({
id: "add-my-item",
title: "add item",
contexts: ["all"],
});
browser.menus.create({
id: "remove-my-item",
title: "remove item",
contexts: ["all"],
});
browser.menus.onClicked.addListener((info) => {
if (info.menuItemId === "add-my-item") {
setOnActiveTab();
} else {
removeFromActiveTab();
}
});
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/session/index.md | ---
title: sessions.Session
slug: Mozilla/Add-ons/WebExtensions/API/sessions/Session
page-type: webextension-api-type
browser-compat: webextensions.api.sessions.Session
---
{{AddonSidebar}}
The `Session` object represents a tab or window that the user has closed in the current browsing session.
Sessions are represented as {{WebExtAPIRef("tabs.Tab", "Tab")}} objects if the tab was closed but its window was not closed: for example, because the user clicked the "Close tab" button, and this tab was not the only tab in its window.
Sessions are represented as {{WebExtAPIRef("windows.Window", "Window")}} objects if the window was closed: for example, because the user clicked the "Close window" button, or closed the only tab open in a window.
Note that different browsers might have a different idea of when a session is a Tab and when it is a Window. For example:
- In Chrome a session is recorded as a Window if the user closes a window that contained more than one tab. If the user closed a window that contained only one tab, this is recorded as a Tab.
- In Firefox, a session is recorded as a Window if the user closes a window (or a tab that was the last tab in the window), and a Tab if the user closes a tab that wasn't the last tab in its window.
The Tab object for a tab that is open will not have a `sessionId`. When the tab is closed, it will have a `sessionId` but will not have a tab `id`. If the tab is restored, it will get a new tab `id` and will lose the `sessionId`.
## Type
Values of this type are objects. They contain the following properties:
- `lastModified`
- : `number`. The time the tab or window was closed, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
- `tab` {{optional_inline}}
- : `object`. If the object represents a closed tab, then this property is present and will be a {{WebExtAPIRef("tabs.Tab")}} object. This will contain `url`, `title`, and `favIconUrl` only if the extension has the "tabs" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) to access the tab's URL.
- `window` {{optional_inline}}
- : `object`. If the object represents a closed window, then this property is present and will be a {{WebExtAPIRef("windows.Window")}} object.
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.sessions`](https://developer.chrome.com/docs/extensions/reference/sessions/) API.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/gettabvalue/index.md | ---
title: sessions.getTabValue()
slug: Mozilla/Add-ons/WebExtensions/API/sessions/getTabValue
page-type: webextension-api-function
browser-compat: webextensions.api.sessions.getTabValue
---
{{AddonSidebar}}
Retrieves a value previously stored by a call to {{WebExtAPIRef("sessions.setTabValue")}}.
You can retrieve a value from a tab even over a close/restore cycle: meaning that if you set a value, then the user closes the tab, then restores the tab using the browser's "restore tab" feature (for example, by pressing Control+Shift+T), then you will be able to retrieve the value from the restored tab. Note, though, that a restored tab does not get the same ID as the original, so the ID you pass into `getTabValue()` will be different from the ID you passed into `setTabValue()`, even though they both refer to the same tab.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let retrieving = browser.sessions.getTabValue(
tabId, // integer
key // string
)
```
### Parameters
- `tabId`
- : `integer`. ID of the tab whose data you are trying to retrieve. Error is thrown if ID is invalid.
- `key`
- : `string`. Key identifying the particular value to retrieve. This needs to match the key previously given in {{WebExtAPIRef("sessions.setTabValue")}}.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be resolved with the value if it exists, or `undefined` if it does not exist. If the call failed (for example, because the tab ID could not be found) then the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
Log the value of "my-key" for all newly created tabs (this will include any tabs that have been restored):
```js
function onGetResolved(r) {
console.log(`success: ${r}`);
}
function onGetRejected(e) {
console.log(`error: ${e}`);
}
browser.tabs.onCreated.addListener((tab) => {
browser.sessions
.getTabValue(tab.id, "my-key")
.then(onGetResolved, onGetRejected);
});
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/restore/index.md | ---
title: sessions.restore()
slug: Mozilla/Add-ons/WebExtensions/API/sessions/restore
page-type: webextension-api-function
browser-compat: webextensions.api.sessions.restore
---
{{AddonSidebar}}
Restores a closed tab or window. Restoring doesn't just reopen the tab or window: it also restores the tab's navigation history so the back/forward buttons will work. Restoring a window will restore all the tabs that the window contained when it was closed.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let restoringSession = browser.sessions.restore(
sessionId // string
)
```
### Parameters
- `sessionId`
- : `string`. A string containing the session ID for the window or tab to restore. This can be found in the `sessionId` property of the {{WebExtAPIRef("tabs.Tab", "Tab")}} or {{WebExtAPIRef("windows.Window", "Window")}} object in the {{WebExtAPIRef("sessions.Session", "Session")}} returned from {{WebExtAPIRef("sessions.getRecentlyClosed()")}}.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). This will be fulfilled with a {{WebExtAPIRef("sessions.Session", "Session")}} object representing the session that was restored.
## Browser compatibility
{{Compat}}
## Examples
This restores the single most recently-closed session, whether it's a window or tab:
```js
function restoreMostRecent(sessionInfos) {
if (!sessionInfos.length) {
console.log("No sessions found");
return;
}
let sessionInfo = sessionInfos[0];
if (sessionInfo.tab) {
browser.sessions.restore(sessionInfo.tab.sessionId);
} else {
browser.sessions.restore(sessionInfo.window.sessionId);
}
}
function onError(error) {
console.log(error);
}
browser.browserAction.onClicked.addListener(() => {
let gettingSessions = browser.sessions.getRecentlyClosed({
maxResults: 1,
});
gettingSessions.then(restoreMostRecent, onError);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.sessions`](https://developer.chrome.com/docs/extensions/reference/sessions/) API.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
## Known issues
[Bug 1538119](https://bugzil.la/1538119) - Duplicate sessionId in browser.sessions.getRecentlyClosed() after "Restore previous session"
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/forgetclosedtab/index.md | ---
title: sessions.forgetClosedTab()
slug: Mozilla/Add-ons/WebExtensions/API/sessions/forgetClosedTab
page-type: webextension-api-function
browser-compat: webextensions.api.sessions.forgetClosedTab
---
{{AddonSidebar}}
Removes a closed tab from the browser's list of recently closed tabs. Note that the sites visited by that tab are not removed from the browser's history. Use the {{WebExtAPIRef("browsingData")}} or {{WebExtAPIRef("history")}} APIs to remove history.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let forgettingTab = browser.sessions.forgetClosedTab(
windowId, // integer
sessionId // string
)
```
### Parameters
- `windowId`
- : `Integer`. The ID of the window that hosted the tab you want to forget.
- `sessionId`
- : `String`. The ID of the session you want to forget.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). This will be fulfilled with no arguments when the session has been removed.
If an error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
This code forgets the single most recently-closed session, whether it's a tab or a window:
```js
function forgetMostRecent(sessionInfos) {
if (!sessionInfos.length) {
console.log("No sessions found");
return;
}
let sessionInfo = sessionInfos[0];
if (sessionInfo.tab) {
browser.sessions.forgetClosedTab(
sessionInfo.tab.windowId,
sessionInfo.tab.sessionId,
);
} else {
browser.sessions.forgetClosedWindow(sessionInfo.window.sessionId);
}
}
function onError(error) {
console.log(error);
}
browser.sessions
.getRecentlyClosed({ maxResults: 1 })
.then(forgetMostRecent, onError);
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/getrecentlyclosed/index.md | ---
title: sessions.getRecentlyClosed()
slug: Mozilla/Add-ons/WebExtensions/API/sessions/getRecentlyClosed
page-type: webextension-api-function
browser-compat: webextensions.api.sessions.getRecentlyClosed
---
{{AddonSidebar}}
Returns an array of {{WebExtAPIRef("sessions.Session", "Session")}} objects, representing windows and tabs that were closed in the current browsing session (that is: the time since the browser was started).
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingSessions = browser.sessions.getRecentlyClosed(
filter // optional object
)
```
### Parameters
- `filter` {{optional_inline}}
- : `object`. A {{WebExtAPIRef("sessions.Filter")}} object that limits the set of sessions returned.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). This will be fulfilled with an array of {{WebExtAPIRef("sessions.Session", "Session")}} objects, one for each of the most recently closed tabs or windows in the current browsing session, up to {{WebExtAPIRef("sessions.MAX_SESSION_RESULTS")}} or the number included in the `filter` argument, whichever is smaller. The array is given in the reverse of the order in which tabs or windows were closed, so the most recently closed will be at index 0.
If an error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
This code restores the single most recently-closed session, whether it's a tab or a window:
```js
function restoreMostRecent(sessionInfos) {
if (!sessionInfos.length) {
console.log("No sessions found");
return;
}
let sessionInfo = sessionInfos[0];
if (sessionInfo.tab) {
browser.sessions.restore(sessionInfo.tab.sessionId);
} else {
browser.sessions.restore(sessionInfo.window.sessionId);
}
}
function onError(error) {
console.log(error);
}
browser.browserAction.onClicked.addListener(() => {
let gettingSessions = browser.sessions.getRecentlyClosed({
maxResults: 1,
});
gettingSessions.then(restoreMostRecent, onError);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.sessions`](https://developer.chrome.com/docs/extensions/reference/sessions/) API.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/forgetclosedwindow/index.md | ---
title: sessions.forgetClosedWindow()
slug: Mozilla/Add-ons/WebExtensions/API/sessions/forgetClosedWindow
page-type: webextension-api-function
browser-compat: webextensions.api.sessions.forgetClosedWindow
---
{{AddonSidebar}}
Removes a closed window from the browser's list of recently closed windows. Note that the sites visited by that window are not removed from the browser's history. Use the {{WebExtAPIRef("browsingData")}} or {{WebExtAPIRef("history")}} APIs to remove history.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let forgettingWindow = browser.sessions.forgetClosedWindow(
sessionId // string
)
```
### Parameters
- `sessionId`
- : `String`. The ID of the session you want to forget.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). This will be fulfilled with no arguments when the session has been removed.
If an error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
This code forgets the single most recently-closed session, whether it's a tab or a window:
```js
function forgetMostRecent(sessionInfos) {
if (!sessionInfos.length) {
console.log("No sessions found");
return;
}
let sessionInfo = sessionInfos[0];
if (sessionInfo.tab) {
browser.sessions.forgetClosedTab(
sessionInfo.tab.windowId,
sessionInfo.tab.sessionId,
);
} else {
browser.sessions.forgetClosedWindow(sessionInfo.window.sessionId);
}
}
function onError(error) {
console.log(error);
}
browser.sessions
.getRecentlyClosed({ maxResults: 1 })
.then(forgetMostRecent, onError);
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/getwindowvalue/index.md | ---
title: sessions.getWindowValue()
slug: Mozilla/Add-ons/WebExtensions/API/sessions/getWindowValue
page-type: webextension-api-function
browser-compat: webextensions.api.sessions.getWindowValue
---
{{AddonSidebar}}
Retrieves a value previously stored by a call to {{WebExtAPIRef("sessions.setWindowValue")}}.
You can retrieve a value from a window even over a close/restore cycle: meaning that if you set a value, then the user closes the window, then restores the window using the browser's "restore window" feature (for example, by pressing Control+Shift+N), then you will be able to retrieve the value from the restored window. Note, though, that a restored window does not get the same ID as the original, so the ID you pass into `getWindowValue()` will be different from the ID you passed into `setWindowValue()`, even though they both refer to the same window.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let retrieving = browser.sessions.getWindowValue(
windowId, // integer
key // string
)
```
### Parameters
- `windowId`
- : `integer`. ID of the window whose data you are trying to retrieve. Error is thrown if ID is invalid.
- `key`
- : `string`. Key identifying the particular value to retrieve. This needs to match the key previously given in {{WebExtAPIRef("sessions.setWindowValue")}}.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be resolved with the value if it exists, or `undefined` if it does not exist. If the call failed (for example, because the window ID could not be found) then the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
Log the value of "my-key" for all newly created windows (this will include any windows that have been restored):
```js
function onGetResolved(r) {
console.log(`success: ${r}`);
}
function onGetRejected(e) {
console.log(`error: ${e}`);
}
browser.windows.onCreated.addListener((window) => {
browser.sessions
.getWindowValue(window.id, "my-key")
.then(onGetResolved, onGetRejected);
});
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/filter/index.md | ---
title: sessions.Filter
slug: Mozilla/Add-ons/WebExtensions/API/sessions/Filter
page-type: webextension-api-type
browser-compat: webextensions.api.sessions.Filter
---
{{AddonSidebar}}
The `Filter` object enables you to restrict the number of {{WebExtAPIRef("sessions.Session", "Session")}} objects returned by a call to {{WebExtAPIRef("sessions.getRecentlyClosed()")}}.
## Type
Values of this type are objects. They contain the following properties:
- `maxResults` {{optional_inline}}
- : `number`. The maximum number of results to return.
## Browser compatibility
{{Compat}}
## Examples
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.sessions`](https://developer.chrome.com/docs/extensions/reference/sessions/) API.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/sessions/setwindowvalue/index.md | ---
title: sessions.setWindowValue()
slug: Mozilla/Add-ons/WebExtensions/API/sessions/setWindowValue
page-type: webextension-api-function
browser-compat: webextensions.api.sessions.setWindowValue
---
{{AddonSidebar}}
Stores a key/value pair to associate with a given window. You can subsequently retrieve this value using {{WebExtAPIRef("sessions.getWindowValue")}}.
Note that this data will only be visible to the extension that set it, and not to any other extensions.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let storing = browser.sessions.setWindowValue(
windowId, // integer
key, // string
value // string or object
)
```
### Parameters
- `windowId`
- : `integer`. ID of the window with which you want to associate the data. Error is thrown if ID is invalid.
- `key`
- : `string`. Key that you can later use to retrieve this particular data value.
- `value`
- : `string` or `object`. If this is an object it is [stringified](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify), so object methods, for example, will be omitted. If a function is given here it will be stored as the value `null`.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be resolved with no arguments if the call succeeded. If the call failed (for example, because the window ID could not be found) then the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
Set a value on the active window when the user selects a menu item. Note that you'll need the "menus" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) to run this example:
```js
async function setOnActiveWindow() {
let currentWindow = await browser.windows.getLastFocused();
await browser.sessions.setWindowValue(currentWindow.id, "my-key", "my-value");
}
browser.menus.create({
id: "my-item",
title: "my item",
contexts: ["all"],
});
browser.menus.onClicked.addListener(setOnActiveWindow);
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/index.md | ---
title: windows
slug: Mozilla/Add-ons/WebExtensions/API/windows
page-type: webextension-api
browser-compat: webextensions.api.windows
---
{{AddonSidebar}}
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
- {{WebExtAPIRef("windows.WindowType")}}
- : The type of browser window this is.
- {{WebExtAPIRef("windows.WindowState")}}
- : The state of this browser window.
- {{WebExtAPIRef("windows.Window")}}
- : Contains information about a browser window.
- {{WebExtAPIRef("windows.CreateType")}}
- : Specifies the type of browser window to create.
## Constants
- {{WebExtAPIRef("windows.WINDOW_ID_NONE")}}
- : The `windowId` value that represents the absence of a browser window.
- {{WebExtAPIRef("windows.WINDOW_ID_CURRENT")}}
- : A value that can be used in place of a `windowId` in some APIs to represent the current window.
## Methods
- {{WebExtAPIRef("windows.get()")}}
- : Gets details about a window, given its ID.
- {{WebExtAPIRef("windows.getCurrent()")}}
- : Gets the current window.
- {{WebExtAPIRef("windows.getLastFocused()")}}
- : Gets the window that was most recently focused β typically the window 'on top'.
- {{WebExtAPIRef("windows.getAll()")}}
- : Gets all windows.
- {{WebExtAPIRef("windows.create()")}}
- : Creates a new window.
- {{WebExtAPIRef("windows.update()")}}
- : Updates the properties of a window. Use this to move, resize, and (un)focus a window, etc.
- {{WebExtAPIRef("windows.remove()")}}
- : Closes a window, and all its tabs.
## Events
- {{WebExtAPIRef("windows.onCreated")}}
- : Fired when a window is created.
- {{WebExtAPIRef("windows.onRemoved")}}
- : Fired when a window is closed.
- {{WebExtAPIRef("windows.onFocusChanged")}}
- : Fired when the currently focused window changes.
## Browser compatibility
{{Compat}}
{{WebExtExamples("h2")}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/windowtype/index.md | ---
title: windows.WindowType
slug: Mozilla/Add-ons/WebExtensions/API/windows/WindowType
page-type: webextension-api-type
browser-compat: webextensions.api.windows.WindowType
---
{{AddonSidebar}}
The type of browser window this is.
## Type
Values of this type are `strings`. Possible values are:
- `"normal"`
- `"popup"`
- `"panel"`
- `"devtools"`
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#type-WindowType) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/windowstate/index.md | ---
title: windows.WindowState
slug: Mozilla/Add-ons/WebExtensions/API/windows/WindowState
page-type: webextension-api-type
browser-compat: webextensions.api.windows.WindowState
---
{{AddonSidebar}}
The state of this browser window.
## Type
Values of this type are `strings`. Possible values are:
- `"normal"`
- : The window is at the default size or user-selected size.
- `"minimized"`
- : The window is only visible as an icon in the taskbar or .
- `"maximized"`
- : The window fills the screen on which it is displayed not including any screen areas reserved by the operating system.
- `"fullscreen"`
- : The window is running as a full screen application or content in a tab is using the [Fullscreen API](/en-US/docs/Web/API/Fullscreen_API)
- `"docked"`
- : A docked window occupies a fixed position relative to other windows owned by the same application.
macOS compatibility: Beginning in macOS 10.10, the default maximizing behavior for windows changed to run applications as full screen applications instead of "zoomed" windows. `fullscreen` refers to both the browser running as a full screen application and when content in a tab uses the Fullscreen API.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#type-WindowState) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/remove/index.md | ---
title: windows.remove()
slug: Mozilla/Add-ons/WebExtensions/API/windows/remove
page-type: webextension-api-function
browser-compat: webextensions.api.windows.remove
---
{{AddonSidebar}}
Closes a window and all the tabs inside it, given the window's ID.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let removing = browser.windows.remove(
windowId // integer
)
```
### Parameters
- `windowId`
- : `integer`. ID of the window to close.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with no arguments when the window has been closed. If any error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
When the user clicks a browser action's icon, close the window in which the icon was clicked:
```js
function onRemoved() {
console.log(`Removed window`);
}
function onError(error) {
console.error(`Error:`, error);
}
browser.browserAction.onClicked.addListener((tab) => {
let removing = browser.windows.remove(tab.windowId);
removing.then(onRemoved, onError);
});
```
Close the current, e.g. popup, window when the user clicks a button on the page:
```js
// in a script loaded by the page in the window
document.querySelector("#close").addEventListener(async ({ button }) => {
try {
if (button) return; // not a left click
const windowId = (await browser.windows.getCurrent()).id;
await browser.windows.remove(windowId);
// this point will never be reached, since the window is gone
} catch (error) {
console.error("Closing failed:", error);
}
});
```
In Firefox, the same could be achieved with the `.allowScriptsToClose` window creation property and `window.close()`.
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#method-remove) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/get/index.md | ---
title: windows.get()
slug: Mozilla/Add-ons/WebExtensions/API/windows/get
page-type: webextension-api-function
browser-compat: webextensions.api.windows.get
---
{{AddonSidebar}}
Gets details about a window, given its ID. The details are passed into a callback.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let getting = browser.windows.get(
windowId, // integer
getInfo // optional object
)
```
### Parameters
- `windowId`
- : `integer`. The ID of the window object you want returned.
- `getInfo` {{optional_inline}}
- : `object`. Contains options to filter the type of window.
- `populate` {{optional_inline}}
- : `boolean`. If `true`, the {{WebExtAPIRef('windows.Window')}} object will have a `tabs` property that contains a list of {{WebExtAPIRef('tabs.Tab')}} objects representing the tabs open in the window. The `Tab` objects only contain the `url`, `title` and `favIconUrl` properties if the extension's manifest file includes the `"tabs"` permission or a matching [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions).
- `windowTypes` {{optional_inline}}
- : `array` of {{WebExtAPIRef('windows.WindowType')}} objects. If set, the {{WebExtAPIRef('windows.Window')}} returned will be filtered based on its type. If unset the default filter is set to `['normal', 'panel', 'popup']`, with `'panel'` window types limited to the extension's own windows.
> **Note:** If supplied, the `windowTypes` component of `getInfo` is ignored. The use of `windowTypes` has been deprecated as of Firefox 62.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('windows.Window')}} object containing the details of the window. If any error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
This example gets the current window and logs the URLs of the tabs it contains. Note that you'll need the "tabs" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or matching [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) to access tab URLs.
> **Note:** This example is a bit unrealistic: in this situation you would more probably use {{WebExtAPIRef("windows.getCurrent()")}}.
```js
function logTabs(windowInfo) {
for (const tabInfo of windowInfo.tabs) {
console.log(tabInfo.url);
}
}
function onError(error) {
console.error(`Error: ${error}`);
}
browser.browserAction.onClicked.addListener((tab) => {
browser.windows.get(tab.windowId, { populate: true }).then(logTabs, onError);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#method-get) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/create/index.md | ---
title: windows.create()
slug: Mozilla/Add-ons/WebExtensions/API/windows/create
page-type: webextension-api-function
browser-compat: webextensions.api.windows.create
---
{{AddonSidebar}}
Creates a new window.
When you create the window, you can:
- Load one or more new tabs into the window.
- Move a tab from an existing window into the new window.
- Set the size and position of the window.
- Create a "panel" style window, which in this context means a window without any of the normal browser UI (address bar, toolbar, etc.).
- Set various properties of the window, such as whether it is focused or private.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let creating = browser.windows.create(
createData // optional object
)
```
### Parameters
- `createData` {{optional_inline}}
- : `object`.
- `allowScriptsToClose` {{optional_inline}}
- : `boolean`. When the window is opened, it will contain a single tab, or more than one tab if `url` is given and includes an array containing more than one URL. By default scripts running in these pages are not allowed to close their tab using [`window.close()`](/en-US/docs/Web/API/Window/close). If you include `allowScriptsToClose` and set it to `true`, then this default behavior is changed, so scripts can close their tabs. Note that:
- this only applies to the tabs that were opened when the window was created. If the user opens more tabs in this window, then scripts will not be able to close those new tabs.
- if the URL(s) given in `url` point to [extension pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages) (that is, they are pages included with this extension and loaded with the "moz-extension:" protocol) then scripts _are_ by default allowed to close those tabs.
- `cookieStoreId` {{optional_inline}}
- : `integer`. If present, specifies the `CookieStoreId` for all the tabs created when the window is opened. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information on using `cookieStoreId`.
- `focused` {{optional_inline}}
- : `boolean`. If `true`, the new window will be focused. If `false`, the new window will be opened in the background and the currently focused window will stay focused. Defaults to `true`.
- `height` {{optional_inline}}
- : `integer`. The height in pixels of the new window, including the frame. If not specified defaults to a natural height.
- `incognito` {{optional_inline}}
- : `boolean`. Whether the new window should be an incognito (private) window. Note that if you specify `incognito` and `tabId`, the ID must refer to a private tab β that is, you can't move a non-private tab to a private window.
- `left` {{optional_inline}}
- : `integer`. The number of pixels to position the new window from the left edge of the screen. If not specified, the new window is offset naturally from the last focused window. This value is ignored for panels. (In Firefox, this value currently is ignored for popups (bug 1271047) but can be set using browser.windows.update().)
- `state` {{optional_inline}}
- : A {{WebExtAPIRef('windows.WindowState')}} value. The initial state of the window. The `minimized`, `maximized` and, `fullscreen` states cannot be combined with `left`, `top`, `width`, or `height`.
- `tabId` {{optional_inline}}
- : `integer`. If included, moves a tab of the specified ID from an existing window into the new window.
- `titlePreface` {{optional_inline}}
- : `string`. Use this to add a string to the beginning of the browser window's title. Depending on the underlying operating system, this might not work on browser windows that don't have a title (such as about:blank in Firefox).
- `top` {{optional_inline}}
- : `integer`. The number of pixels to position the new window from the top edge of the screen. If not specified, the new window is offset naturally from the last focused window. This value is ignored for panels. (In Firefox, this value currently is ignored for popups (bug 1271047) but can be set using browser.windows.update().)
- `type` {{optional_inline}}
- : A {{WebExtAPIRef('windows.CreateType')}} value. Specifies what type of browser window to create. Specify `panel` or `popup` here to open a window without any of the normal browser UI (address bar, toolbar, etc.).
- `url` {{optional_inline}}
- : `string` or `array` of `string`s. A URL or array of URLs to open as tabs in the window. Fully-qualified URLs must include a scheme (i.e. `http://www.google.com`, not `www.google.com`). Relative URLs will be relative to the current page within the extension. Defaults to the New Tab Page.
- `width` {{optional_inline}}
- : `integer`. The width in pixels of the new window, including the frame. If not specified defaults to a natural width.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('windows.Window')}} object containing the details of the new window. This `Window` object will always have its `tabs` property set, unlike the `Window` objects returned from {{WebExtAPIRef("windows.get()")}} and similar APIs, which only contain `tabs` if the `populate` option is passed. If any error occurs, the promise will be rejected with an error message.
## Examples
Open a window containing two tabs:
```js
function onCreated(windowInfo) {
console.log(`Created window: ${windowInfo.id}`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
browser.browserAction.onClicked.addListener((tab) => {
let creating = browser.windows.create({
url: ["https://developer.mozilla.org", "https://addons.mozilla.org"],
});
creating.then(onCreated, onError);
});
```
Open a window when the user clicks a browser action, and move the currently active tab into it:
```js
function onCreated(windowInfo) {
console.log(`Created window: ${windowInfo.id}`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
browser.browserAction.onClicked.addListener((tab) => {
let creating = browser.windows.create({
tabId: tab.id,
});
creating.then(onCreated, onError);
});
```
Open a small panel-style window, and load a locally-packaged file into it:
```js
function onCreated(windowInfo) {
console.log(`Created window: ${windowInfo.id}`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
browser.browserAction.onClicked.addListener((tab) => {
let popupURL = browser.extension.getURL("popup/popup.html");
let creating = browser.windows.create({
url: popupURL,
type: "popup",
height: 200,
width: 200,
});
creating.then(onCreated, onError);
});
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#method-create) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
## See also
- {{domxref("Window.open()","window.open")}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/window_id_current/index.md | ---
title: windows.WINDOW_ID_CURRENT
slug: Mozilla/Add-ons/WebExtensions/API/windows/WINDOW_ID_CURRENT
page-type: webextension-api-property
browser-compat: webextensions.api.windows.WINDOW_ID_CURRENT
---
{{AddonSidebar}}
`browser.windows.WINDOW_ID_CURRENT` is a value that can be used as a `windowId` parameter in some APIs to represent the current window.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#property-WINDOW_ID_CURRENT) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/window_id_none/index.md | ---
title: windows.WINDOW_ID_NONE
slug: Mozilla/Add-ons/WebExtensions/API/windows/WINDOW_ID_NONE
page-type: webextension-api-property
browser-compat: webextensions.api.windows.WINDOW_ID_NONE
---
{{AddonSidebar}}
The `windowId` value that represents the absence of a browser window.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#property-WINDOW_ID_NONE) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/getlastfocused/index.md | ---
title: windows.getLastFocused()
slug: Mozilla/Add-ons/WebExtensions/API/windows/getLastFocused
page-type: webextension-api-function
browser-compat: webextensions.api.windows.getLastFocused
---
{{AddonSidebar}}
Gets the window that was most recently focused β typically the window 'on top'.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingWindow = browser.windows.getLastFocused(
getInfo // optional object
)
```
### Parameters
- `getInfo` {{optional_inline}}
- : `object`.
- `populate` {{optional_inline}}
- : `boolean`. If `true`, the {{WebExtAPIRef('windows.Window')}} object will have a `tabs` property that contains a list of {{WebExtAPIRef('tabs.Tab')}} objects representing the tabs in the window. The `Tab` objects only contain the `url`, `title` and `favIconUrl` properties if the extension's manifest file includes the `"tabs"` permission or [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) matching the tab's URL.
- `windowTypes` {{optional_inline}}
- : An `array` of {{WebExtAPIRef('windows.WindowType')}} objects. If set, the {{WebExtAPIRef('windows.Window')}} returned will be filtered based on its type. If unset the default filter is set to `['normal', 'panel', 'popup']`, with `'panel'` window types limited to the extension's own windows.
> **Note:** If supplied, the `windowTypes` component of `getInfo` is ignored. The use of `windowTypes` has been deprecated as of Firefox 62.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('windows.Window')}} object containing the details of the last focused window. If any error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
Get the last focused window, and log the tabs it contains. Note that you'll need the "tabs" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or matching [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) to access tab URLs.
```js
function logTabs(windowInfo) {
for (const tabInfo of windowInfo.tabs) {
console.log(tabInfo.url);
}
}
function onError(error) {
console.error(`Error: ${error}`);
}
browser.browserAction.onClicked.addListener((tab) => {
browser.windows.getLastFocused({ populate: true }).then(logTabs, onError);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#method-getLastFocused) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/oncreated/index.md | ---
title: windows.onCreated
slug: Mozilla/Add-ons/WebExtensions/API/windows/onCreated
page-type: webextension-api-event
browser-compat: webextensions.api.windows.onCreated
---
{{AddonSidebar}}
Fired when a window is created.
## Syntax
```js-nolint
browser.windows.onCreated.addListener(listener)
browser.windows.onCreated.removeListener(listener)
browser.windows.onCreated.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether a `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `window`
- : A {{WebExtAPIRef('windows.Window')}} object containing details of the window that was created.
## Browser compatibility
{{Compat}}
## Examples
Log the IDs of new windows as they are created:
```js
browser.windows.onCreated.addListener((window) => {
console.log(`New window: ${window.id}`);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#event-onCreated) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/update/index.md | ---
title: windows.update()
slug: Mozilla/Add-ons/WebExtensions/API/windows/update
page-type: webextension-api-function
browser-compat: webextensions.api.windows.update
---
{{AddonSidebar}}
Updates the properties of a window. Use this to move, resize, and (un)focus a window, etc.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let updating = browser.windows.update(
windowId, // integer
updateInfo // object
)
```
### Parameters
- `windowId`
- : `integer`. ID of the window to update.
- `updateInfo`
- : `object`. Object containing the properties to update.
- `drawAttention` {{optional_inline}}
- : `boolean`. If `true`, causes the window to be displayed in a manner that draws the user's attention to the window, without changing the focused window. The effect lasts until the user changes focus to the window. This option has no effect if the window already has focus. Set to `false` to cancel a previous `drawAttention` request.
- `focused` {{optional_inline}}
- : `boolean`. If `true`, brings the window to the front. If false, brings the next window in the z-order to the front.
- `height` {{optional_inline}}
- : `integer`. The height to resize the window to in pixels. This value is ignored for panels.
- `left` {{optional_inline}}
- : `integer`. The offset from the left edge of the screen to move the window to in pixels. This value is ignored for panels.
- `state` {{optional_inline}}
- : {{WebExtAPIRef('windows.WindowState')}}. The new state of the window. The `minimized`, `maximized` and `fullscreen` states cannot be combined with `left`, `top`, `width` or `height`.
- `titlePreface` {{optional_inline}}
- : `string`. Use this to add a string to the beginning of the browser window's title. Depending on the underlying operating system, this might not work on browser windows that don't have a title (such as about:blank in Firefox).
- `top` {{optional_inline}}
- : `integer`. The offset from the top edge of the screen to move the window to in pixels. This value is ignored for panels.
- `width` {{optional_inline}}
- : `integer`. The width to resize the window to in pixels. This value is ignored for panels.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('windows.Window')}} object containing the details of the updated window. If any error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
When the user clicks a browser action's icon, move the window to the top left corner:
```js
function onUpdated(windowInfo) {
console.log(`Updated window: ${windowInfo.id}`);
}
function onError(error) {
console.log(`Error: ${error}`);
}
browser.browserAction.onClicked.addListener((tab) => {
let updating = browser.windows.update(tab.windowId, {
left: 0,
top: 0,
});
updating.then(onUpdated, onError);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#method-update) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/getcurrent/index.md | ---
title: windows.getCurrent()
slug: Mozilla/Add-ons/WebExtensions/API/windows/getCurrent
page-type: webextension-api-function
browser-compat: webextensions.api.windows.getCurrent
---
{{AddonSidebar}}
Gets the current browser window, passing its details into a callback.
The "current" window is not necessarily the same as the currently focused window. If this function is called from a background script, then it returns the currently focused window. But if it is called from a script whose document is associated with a particular browser window, then it returns that browser window. For example, if the browser is displaying a sidebar, then every browser window has its own instance of the sidebar document. If a script running in the sidebar document calls `getCurrent()`, then it will return that sidebar document's window.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingCurrent = browser.windows.getCurrent(
getInfo // optional object
)
```
### Parameters
- `getInfo` {{optional_inline}}
- : `object`.
- `populate` {{optional_inline}}
- : `boolean`. If true, the {{WebExtAPIRef('windows.Window')}} object will have a `tabs` property that contains a list of {{WebExtAPIRef('tabs.Tab')}} objects representing the tabs in the window. The `Tab` objects only contain the `url`, `title` and `favIconUrl` properties if the extension's manifest file includes the `"tabs"` permission or [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) that match the tab's URL.
- `windowTypes` {{deprecated_inline}} {{optional_inline}}
- : An `array` of `{{WebExtAPIRef('windows.WindowType')}}` objects. If set, the {{WebExtAPIRef('windows.Window')}} returned will be filtered based on its type. If unset the default filter is set to `['normal', 'panel', 'popup']`, with `'panel'` window types limited to the extension's own windows.
> **Note:** If supplied, the `windowTypes` component of `getInfo` is ignored. The use of `windowTypes` has been deprecated as of Firefox 62.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a [`windows.Window`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/windows/Window) object containing the details of the window. If any error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
When the user clicks a browser action's icon, this example gets the current window and logs the URLs of the tabs it contains. Note that you'll need the "tabs" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or matching [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) to access tab URLs.
```js
function logTabs(windowInfo) {
for (const tabInfo of windowInfo.tabs) {
console.log(tabInfo.url);
}
}
function onError(error) {
console.error(`Error: ${error}`);
}
browser.browserAction.onClicked.addListener((tab) => {
browser.windows.getCurrent({ populate: true }).then(logTabs, onError);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#method-getCurrent) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/createtype/index.md | ---
title: windows.CreateType
slug: Mozilla/Add-ons/WebExtensions/API/windows/CreateType
page-type: webextension-api-type
browser-compat: webextensions.api.windows.CreateType
---
{{AddonSidebar}}
Specifies the type of browser window to create.
## Type
Values of this type are `strings`. Possible values are:
- `"normal"`
- `"popup"`
- `"panel"`
- `"detached_panel"`
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#type-CreateType) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/getall/index.md | ---
title: windows.getAll()
slug: Mozilla/Add-ons/WebExtensions/API/windows/getAll
page-type: webextension-api-function
browser-compat: webextensions.api.windows.getAll
---
{{AddonSidebar}}
Gets information about all open windows, passing them into a callback.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingAll = browser.windows.getAll(
getInfo // optional object
)
```
### Parameters
- `getInfo` {{optional_inline}}
- : `object`. This controls what {{WebExtAPIRef('windows.Window')}} objects are retrieved.
- `populate` {{optional_inline}}
- : `boolean`. Defaults to `false`. If set to `true`, each {{WebExtAPIRef('windows.Window')}} object will have a `tabs` property that contains a list of {{WebExtAPIRef('tabs.Tab')}} objects representing the tabs in that window. The `Tab` objects will contain the `url`, `title` and `favIconUrl` properties only if the extension's manifest file includes the `"tabs"` permission or [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) that match the tab's URL.
- `windowTypes` {{optional_inline}}
- : An `array` of {{WebExtAPIRef('windows.WindowType')}} objects. If set, the {{WebExtAPIRef('windows.Window')}} objects returned will be filtered based on their type. If unset the default filter is set to `['normal', 'panel', 'popup']`, with `'panel'` window types limited to the extension's own windows.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an array of {{WebExtAPIRef('windows.Window')}} objects, representing all windows that match the given criteria. If any error occurs, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
Log the URLs for the tabs across all "normal" browser windows. Note that you'll need the "tabs" [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or matching [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) to access tab URLs.
```js
function logTabsForWindows(windowInfoArray) {
for (const windowInfo of windowInfoArray) {
console.log(`Window: ${windowInfo.id}`);
console.log(windowInfo.tabs.map((tab) => tab.url));
}
}
function onError(error) {
console.error(`Error: ${error}`);
}
browser.browserAction.onClicked.addListener((tab) => {
browser.windows
.getAll({
populate: true,
windowTypes: ["normal"],
})
.then(logTabsForWindows, onError);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#method-getAll) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/onremoved/index.md | ---
title: windows.onRemoved
slug: Mozilla/Add-ons/WebExtensions/API/windows/onRemoved
page-type: webextension-api-event
browser-compat: webextensions.api.windows.onRemoved
---
{{AddonSidebar}}
Fired when a window is closed.
## Syntax
```js-nolint
browser.windows.onRemoved.addListener(listener)
browser.windows.onRemoved.removeListener(listener)
browser.windows.onRemoved.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Checks whether a `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `windowId`
- : `integer`. ID of the window that was closed.
## Browser compatibility
{{Compat}}
## Examples
Log the IDs of windows as they are removed.
```js
browser.windows.onRemoved.addListener((windowId) => {
console.log(`Closed window: ${windowId}`);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#event-onRemoved) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/window/index.md | ---
title: windows.Window
slug: Mozilla/Add-ons/WebExtensions/API/windows/Window
page-type: webextension-api-type
browser-compat: webextensions.api.windows.Window
---
{{AddonSidebar}}
Information about a browser window.
## Type
Values of this type are `objects`. They contain the following properties:
- `alwaysOnTop`
- : `boolean`. Whether the window is set to be always on top.
- `focused`
- : `boolean`. Whether the window is currently the focused window.
- `height` {{optional_inline}}
- : `integer`. The height of the window, including the frame, in pixels.
- `id` {{optional_inline}}
- : `integer`. The ID of the window. Window IDs are unique within a browser session.
- `incognito`
- : `boolean`. Whether the window is incognito (private).
- `left` {{optional_inline}}
- : `integer`. The offset of the window from the left edge of the screen in pixels.
- `sessionId` {{optional_inline}}
- : `string`. The session ID used to uniquely identify a Window obtained from the {{WebExtAPIRef('sessions')}} API.
- `state` {{optional_inline}}
- : A {{WebExtAPIRef('windows.WindowState')}} value representing the state of this browser window β maximized, minimized, etc.
- `tabs` {{optional_inline}}
- : Array of {{WebExtAPIRef('tabs.Tab')}} objects representing the current tabs in the window.
- `title` {{optional_inline}}
- : The title of the browser window. Requires "tabs" permission or [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the active tab's URL. Read only.
- `top` {{optional_inline}}
- : `integer`. The offset of the window from the top edge of the screen in pixels.
- `type` {{optional_inline}}
- : A {{WebExtAPIRef('windows.WindowType')}} value representing the type of browser window this is β normal browser window, popup, etc.
- `width` {{optional_inline}}
- : `integer`. The width of the window, including the frame, in pixels.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#type-Window) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/windows/onfocuschanged/index.md | ---
title: windows.onFocusChanged
slug: Mozilla/Add-ons/WebExtensions/API/windows/onFocusChanged
page-type: webextension-api-event
browser-compat: webextensions.api.windows.onFocusChanged
---
{{AddonSidebar}}
Fired when the currently focused window changes. Will be {{WebExtAPIRef('windows.WINDOW_ID_NONE')}} if all browser windows have lost focus.
> **Note:** In Windows and some Linux window managers, WINDOW_ID_NONE will always be sent immediately preceding a switch from one browser window to another.
## Syntax
```js-nolint
browser.windows.onFocusChanged.addListener(listener)
browser.windows.onFocusChanged.removeListener(listener)
browser.windows.onFocusChanged.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether a `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `windowId`
- : `integer`. ID of the newly focused window.
## Browser compatibility
{{Compat}}
## Examples
Log focus changes:
```js
browser.windows.onFocusChanged.addListener((windowId) => {
console.log(`Newly focused window: ${windowId}`);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.windows`](https://developer.chrome.com/docs/extensions/reference/windows/#event-onFocusChanged) API. This documentation is derived from [`windows.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/windows.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/index.md | ---
title: cookies
slug: Mozilla/Add-ons/WebExtensions/API/cookies
page-type: webextension-api
browser-compat: webextensions.api.cookies
---
{{AddonSidebar}}
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](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) in its [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file, along with [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#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](/en-US/docs/Web/Privacy/State_Partitioning#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](/en-US/docs/Web/Privacy/State_Partitioning#status_of_partitioning_in_firefox), for details.
### Storage partitioning
When using [dynamic partitioning](/en-US/docs/Web/Privacy/State_Partitioning#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](/en-US/docs/Web/Privacy/State_Partitioning#status_of_partitioning_in_firefox), for implementation details.
Storage partitions are keyed by the schemeful URL of the top-level {{glossary("Site","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, {{WebExtAPIRef("cookies.get()")}}, {{WebExtAPIRef("cookies.getAll()")}}, {{WebExtAPIRef("cookies.set()")}}, and {{WebExtAPIRef("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. {{WebExtAPIRef("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 {{WebExtAPIRef("cookies.set()")}} and {{WebExtAPIRef("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 {{WebExtAPIRef("privacy.websites","firstPartyIsolate")}} setting in the {{WebExtAPIRef("privacy")}} API. Note that first-party isolation is enabled by default in [Tor Browser](https://www.torproject.org/).
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 {{WebExtAPIRef("cookies.get()")}}, {{WebExtAPIRef("cookies.getAll()")}}, {{WebExtAPIRef("cookies.set()")}} and {{WebExtAPIRef("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
- {{WebExtAPIRef("cookies.Cookie")}}
- : Represents information about an HTTP cookie.
- {{WebExtAPIRef("cookies.CookieStore")}}
- : Represents a cookie store in the browser.
- {{WebExtAPIRef("cookies.OnChangedCause")}}
- : Represents the reason a cookie changed.
- {{WebExtAPIRef("cookies.SameSiteStatus")}}
- : Represents the same-site status of the cookie.
## Methods
- {{WebExtAPIRef("cookies.get()")}}
- : Retrieves information about a single cookie.
- {{WebExtAPIRef("cookies.getAll()")}}
- : Retrieves all cookies that match a given set of filters.
- {{WebExtAPIRef("cookies.set()")}}
- : Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
- {{WebExtAPIRef("cookies.remove()")}}
- : Deletes a cookie by name.
- {{WebExtAPIRef("cookies.getAllCookieStores()")}}
- : Lists all existing cookie stores.
## Event handlers
- {{WebExtAPIRef("cookies.onChanged")}}
- : Fired when a cookie is set or removed.
## Browser compatibility
{{Compat}}
{{WebExtExamples("h2")}}
> **Note:** This API is based on Chromium's [`chrome.cookies`](https://developer.chrome.com/docs/extensions/reference/cookies/) API. This documentation is derived from [`cookies.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/cookies.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/remove/index.md | ---
title: cookies.remove()
slug: Mozilla/Add-ons/WebExtensions/API/cookies/remove
page-type: webextension-api-function
browser-compat: webextensions.api.cookies.remove
---
{{AddonSidebar}}
The **`remove()`** method of the {{WebExtAPIRef("cookies")}} API deletes a cookie, given its name and URL.
The call succeeds only if you include the "cookies" [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) in your [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file, as well as [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the given URL specified in its manifest.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let removing = browser.cookies.remove(
details // object
)
```
### Parameters
- `details`
- : An `object` containing information to identify the cookie to remove. It contains the following properties:
- `firstPartyDomain` {{optional_inline}}
- : A `string` representing the first-party domain with which the cookie to remove is associated. This property must be supplied if the browser has first-party isolation enabled. See [First-party isolation](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#first-party_isolation).
- `name`
- : A `string` representing the name of the cookie to remove.
- `partitionKey` {{optional_inline}}
- : An `object` representing the [storage partition](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#storage_partitioning) containing the cookie. Include this object to remove a cookie from partitioned storage. This object contains:
- `topLevelSite` {{optional_inline}}
- : A `string` representing the first-party URL of the top-level site storage partition containing the cookie.
- `storeId` {{optional_inline}}
- : A `string` representing the ID of the cookie store to find the cookie in. If unspecified, the cookie is looked for by default in the current execution context's cookie store.
- `url`
- : A `string` representing the URL associated with the cookie. If the extension does not have [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for this URL, the API call will fail.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('cookies.Cookie')}} object containing details about the cookie that's been removed. If a cookie matching the `details` parameter could not be found, the promise is fulfilled with `null`. If the call fails for any reason, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
This example tries to remove the cookie named "favorite-color", whose URL matches the URL of the document hosted by the currently active tab:
```js
function onRemoved(cookie) {
console.log(`Removed: ${cookie}`);
}
function onError(error) {
console.log(`Error removing cookie: ${error}`);
}
function removeCookie(tabs) {
let removing = browser.cookies.remove({
url: tabs[0].url,
name: "favorite-color",
});
removing.then(onRemoved, onError);
}
let getActive = browser.tabs.query({ active: true, currentWindow: true });
getActive.then(removeCookie);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.cookies`](https://developer.chrome.com/docs/extensions/reference/cookies/#method-remove) API. This documentation is derived from [`cookies.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/cookies.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/onchanged/index.md | ---
title: cookies.onChanged
slug: Mozilla/Add-ons/WebExtensions/API/cookies/onChanged
page-type: webextension-api-event
browser-compat: webextensions.api.cookies.onChanged
---
{{AddonSidebar}}
The `onChanged` event of the {{WebExtAPIRef("cookies")}} API fires when a cookie that the extension can access is set or removed.
> **Note:** When [storage partitioning](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#storage_partitioning) is active, `cookies.Cookie.partitionKey` contains the description of the cookie's storage partition. When modifying cookies, it's important to pass this value to {{WebExtAPIRef("cookies.set()")}} or {{WebExtAPIRef("cookies.remove()")}} to ensure the extension works with the correct cookie.
Note that updating a cookie's properties is implemented as a two step process:
1. First, the cookie to be updated is first removed entirely, generating a notification with a {{WebExtAPIRef("cookies.OnChangedCause")}} of `overwrite`.
2. Next, a new cookie is written with the updated values, generating a second notification with a {{WebExtAPIRef("cookies.OnChangedCause")}} of `explicit`.
## Syntax
```js-nolint
browser.cookies.onChanged.addListener(listener)
browser.cookies.onChanged.removeListener(listener)
browser.cookies.onChanged.hasListener(listener)
```
This API is also available as `browser.cookies.onChanged.*`.
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed these arguments:
- `changeInfo`
- : An `object` containing details of the change that occurred. Its properties are as follows:
- `removed`
- : A `boolean` that is set to `true` if a cookie was removed, and false if not.
- `cookie`
- : A {{WebExtAPIRef('cookies.Cookie')}} object containing information about the cookie that was set or removed.
- `cause`
- : A {{WebExtAPIRef('cookies.OnChangedCause')}} value representing the underlying reason behind the cookie's change.
## Browser compatibility
{{Compat}}
## Examples
This example listens for `onChanged` events and logs details from the `changeInfo` argument:
```js
browser.cookies.onChanged.addListener((changeInfo) => {
console.log(
`Cookie changed: \n` +
` * Cookie: ${JSON.stringify(changeInfo.cookie)}\n` +
` * Cause: ${changeInfo.cause}\n` +
` * Removed: ${changeInfo.removed}`,
);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.cookies`](https://developer.chrome.com/docs/extensions/reference/cookies/#event-onChanged) API. This documentation is derived from [`cookies.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/cookies.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/get/index.md | ---
title: cookies.get()
slug: Mozilla/Add-ons/WebExtensions/API/cookies/get
page-type: webextension-api-function
browser-compat: webextensions.api.cookies.get
---
{{AddonSidebar}}
The **`get()`** method of the {{WebExtAPIRef("cookies")}} API retrieves information about a single cookie, given its name and URL.
If more than one cookie with the same name exists for a given URL, the one with the longest path will be returned. For cookies with the same path length, the cookie with the earliest creation time will be returned. If no matching cookie could be found, `null` is returned.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let getting = browser.cookies.get(
details // object
)
```
### Parameters
- `details`
- : An `object` containing details that can be used to match a cookie to be retrieved. It can include the following properties:
- `firstPartyDomain` {{optional_inline}}
- : A `string` representing the first-party domain with which the cookie to retrieve is associated. This property must be supplied if the browser has first-party isolation enabled. See [First-party isolation](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#first-party_isolation).
- `name`
- : A `string` representing the name of the cookie to retrieve.
- `partitionKey` {{optional_inline}}
- : An `object` representing the [storage partition](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#storage_partitioning) containing the cookie. Include this object with `topLevelSite` to obtain a cookie from partitioned storage. Otherwise, returns the cookie from unpartitioned storage. This object contains:
- `topLevelSite` {{optional_inline}}
- : A `string` representing the first-party URL of the top-level site storage partition containing the cookie.
- `storeId` {{optional_inline}}
- : A `string` representing the ID of the {{WebExtAPIRef("cookies.CookieStore", "cookie store")}} in which to look for the cookie (as returned by {{WebExtAPIRef("cookies.getAllCookieStores()")}}). By default, the current execution context's cookie store will be used.
- `url`
- : A `string` representing the URL with which the cookie to retrieve is associated. This argument may be a full URL, in which case any data following the URL path (e.g. the query string) is ignored. If [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) for this URL are not specified in the extension's [manifest file](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json), the API call will fail.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('cookies.Cookie', 'Cookie')}} object containing details about the cookie, or `null` if the cookie was not found.
## Browser compatibility
{{Compat}}
## Examples
This example tries to get the cookie named "favorite-color", associated with the URL for the currently active tab:
```js
function logCookie(cookie) {
if (cookie) {
console.log(cookie.value);
}
}
function getCookie(tabs) {
let getting = browser.cookies.get({
url: tabs[0].url,
name: "favorite-color",
});
getting.then(logCookie);
}
let getActive = browser.tabs.query({
active: true,
currentWindow: true,
});
getActive.then(getCookie);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.cookies`](https://developer.chrome.com/docs/extensions/reference/cookies/#method-get) API. This documentation is derived from [`cookies.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/cookies.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/set/index.md | ---
title: cookies.set()
slug: Mozilla/Add-ons/WebExtensions/API/cookies/set
page-type: webextension-api-function
browser-compat: webextensions.api.cookies.set
---
{{AddonSidebar}}
The **`set()`** method of the {{WebExtAPIRef("cookies")}} API sets a cookie containing the specified cookie data. This method is equivalent to issuing an HTTP `Set-Cookie` header during a request to a given URL.
The call succeeds only if you include the "cookies" [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) in your [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file, as well as [host permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the given URL specified in its manifest. The given URL also needs the necessary permissions to create a cookie with the given parameters.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let setting = browser.cookies.set(
details // object
)
```
### Parameters
- `details`
- : An `object` containing the details of the cookie you wish to set. It can have the following properties:
- `domain` {{optional_inline}}
- : A `string` representing the domain of the cookie. If omitted, the cookie becomes a host-only cookie.
- `expirationDate` {{optional_inline}}
- : A `number` that represents the expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie.
- `firstPartyDomain` {{optional_inline}}
- : A `string` representing the first-party domain with which the cookie will be associated. This property must be supplied if the browser has first-party isolation enabled. See [First-party isolation](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#first-party_isolation).
- `httpOnly` {{optional_inline}}
- : A `boolean` that specifies whether the cookie should be marked as HttpOnly (`true`), or not (false). If omitted, it defaults to false.
- `name` {{optional_inline}}
- : A `string` representing the name of the cookie. If omitted, this is empty by default.
- `partitionKey` {{optional_inline}}
- : An `object` representing the [storage partition](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#storage_partitioning) to set the cookie in. Include this object to set a cookie in partitioned storage. This object contains:
- `topLevelSite` {{optional_inline}}
- : A `string` representing the first-party URL of the top-level site storage partition containing the cookie.
- `path` {{optional_inline}}
- : A `string` representing the path of the cookie. If omitted, this defaults to the path portion of the URL parameter.
- `sameSite` {{optional_inline}}
- : A {{WebExtAPIRef("cookies.SameSiteStatus")}} value that indicates the SameSite state of the cookie. If omitted, it defaults to 0, 'no_restriction'.
- `secure` {{optional_inline}}
- : A `boolean` that specifies whether the cookie should be marked as secure (`true`), or not (false). If omitted, it defaults to false.
- `storeId` {{optional_inline}}
- : A `string` representing the ID of the cookie store in which to set the cookie. If omitted, the cookie is set in the current execution context's cookie store by default.
- `url`
- : A `string` representing the request-URI to associate with the cookie. This value can affect the default domain and path values of the created cookie. If host permissions for this URL are not specified in the manifest file, the method call will fail.
- `value` {{optional_inline}}
- : A `string` representing the value of the cookie. If omitted, this is empty by default.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with a {{WebExtAPIRef('cookies.Cookie')}} object containing details about the cookie that's been set. If the call fails for any reason, the promise will be rejected with an error message.
## Browser compatibility
{{Compat}}
## Examples
This example sets a cookie for the document hosted by the currently active tab:
```js
let getActive = browser.tabs.query({ active: true, currentWindow: true });
getActive.then(setCookie);
function setCookie(tabs) {
browser.cookies.set({
url: tabs[0].url,
name: "favorite-color",
value: "red",
});
}
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.cookies`](https://developer.chrome.com/docs/extensions/reference/cookies/#method-set) API. This documentation is derived from [`cookies.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/cookies.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/cookie/index.md | ---
title: cookies.Cookie
slug: Mozilla/Add-ons/WebExtensions/API/cookies/Cookie
page-type: webextension-api-type
browser-compat: webextensions.api.cookies.Cookie
---
{{AddonSidebar}}
The `Cookie` type of the {{WebExtAPIRef("cookies")}} API represents information about an HTTP cookie.
## Type
Values of this type are objects, which can contain the following properties:
- `domain`
- : A `string` representing the domain the cookie belongs to (e.g. "www\.google.com", "example.com").
- `expirationDate` {{optional_inline}}
- : A `number` representing the expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies.
- `firstPartyDomain`
- : A `string` representing the first-party domain associated with the cookie. This will be an empty string if the cookie was set while first-party isolation was off. See [First-party isolation](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#first-party_isolation).
- `hostOnly`
- : A `boolean`, `true` if the cookie is a host-only cookie (i.e. the request's host must exactly match the domain of the cookie), or `false` otherwise.
- `httpOnly`
- : A `boolean`, `true` if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts), or `false` otherwise.
- `name`
- : A `string` representing the name of the cookie.
- `partitionKey` {{optional_inline}}
- : An `object` representing the description of the [storage partition](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#storage_partitioning) containing the cookie. This object is omitted (null) if the cookie is not in partitioned storage. This object contains the following properties:
- `topLevelSite`
- : A `string` representing the first-party URL of the cookie's storage partition, if the cookie is in storage that is partitioned by top-level site.
- `path`
- : A `string` representing the path of the cookie.
- `secure`
- : A `boolean`, `true` if the cookie is marked as secure (i.e. its scope is limited to secure channels, typically HTTPS), or `false` otherwise.
- `session`
- : A `boolean`, `true` if the cookie is a session cookie, or `false` if it is a persistent cookie with an expiration date.
- `sameSite`
- : A {{WebExtAPIRef("cookies.SameSiteStatus")}} value that indicates the SameSite state of the cookie.
- `storeId`
- : A `string` representing the ID of the cookie store containing this cookie, as provided by {{WebExtAPIRef("cookies.getAllCookieStores()")}}.
- `value`
- : A `string` representing the value of the cookie.
## Browser compatibility
{{Compat}}
## Examples
Most methods in the cookies API involve a `Cookie` object being used either as an input parameter or as part of the return value. For example, a call to {{WebExtAPIRef("cookies.getAll()")}} returns an array of `Cookie` objects.
In the example below we've asked for all cookies, then logged some of the values of each of the resulting `Cookie` objects:
```js
function logCookies(cookies) {
for (cookie of cookies) {
console.log(`Domain: ${cookie.domain}`);
console.log(`Name: ${cookie.name}`);
console.log(`Value: ${cookie.value}`);
console.log(`Persistent: ${!cookie.session}`);
}
}
let gettingAll = browser.cookies.getAll({});
gettingAll.then(logCookies);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.cookies`](https://developer.chrome.com/docs/extensions/reference/cookies/#type-Cookie) API. This documentation is derived from [`cookies.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/cookies.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/onchangedcause/index.md | ---
title: cookies.OnChangedCause
slug: Mozilla/Add-ons/WebExtensions/API/cookies/OnChangedCause
page-type: webextension-api-type
browser-compat: webextensions.api.cookies.OnChangedCause
---
{{AddonSidebar}}
The `OnChangedCause` type of the {{WebExtAPIRef("cookies")}} API represents the reason a cookie changed.
## Type
Values of this type are strings. Possible values are:
- `evicted`
- : A cookie has been automatically removed due to garbage collection.
- `expired`
- : A cookie has been automatically removed due to expiry.
- `explicit`
- : A cookie has been inserted or removed via an explicit call to {{WebExtAPIRef("cookies.remove()")}}.
- `expired_overwrite`
- : A cookie has been overwritten by a cookie with an already-expired expiration date.
- `overwrite`
- : A call to {{WebExtAPIRef("cookies.set()")}} overwrote this cookie with a different one.
## Browser compatibility
{{Compat}}
## Examples
You can listen to the {{WebExtAPIRef("cookies.onChanged")}} event to be notified when cookies change. The listener is passed a `changeInfo` object that contains a `cause` property, whose value is the `OnChangeCaused` string:
```js
browser.cookies.onChanged.addListener((changeInfo) => {
console.log(
`Cookie changed: \n` +
` * Cookie: ${JSON.stringify(changeInfo.cookie)}\n` +
` * Cause: ${changeInfo.cause}\n` +
` * Removed: ${changeInfo.removed}`,
);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.cookies`](https://developer.chrome.com/docs/extensions/reference/cookies/#type-OnChangedCause) API. This documentation is derived from [`cookies.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/cookies.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/cookiestore/index.md | ---
title: cookies.CookieStore
slug: Mozilla/Add-ons/WebExtensions/API/cookies/CookieStore
page-type: webextension-api-type
browser-compat: webextensions.api.cookies.CookieStore
---
{{AddonSidebar}}
The `CookieStore` type of the {{WebExtAPIRef("cookies")}} API represents a cookie store in the browser.
Windows in different browsing modes may use different cookie stores. For example, a private browsing/incognito mode window uses a separate cookie store from a non-incognito/private window. Also, a window may have several cookie stores when using [container tabs](https://wiki.mozilla.org/Security/Contextual_Identity_Project/Containers) in Firefox.
See [Work with the Cookies API](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_the_Cookies_API#cookie_stores) for more information about cookie stores.
## Type
Values of this type are objects, which can contain the following properties:
- `id`
- : A `string` representing the unique identifier for the cookie store.
- `incognito` {{optional_inline}}
- : A boolean value that indicates whether this is an incognito cookie store.
This property is not supported in Chrome or Safari. However, you can identify incognito cookie stores in Chrome because their `id` is always "1".
- `tabIds`
- : An `array` of `integers`, which identifies all of the browser tabs that share this cookie store.
## Browser compatibility
{{Compat}}
## Examples
In the following snippet, the {{WebExtAPIRef("cookies.getAllCookieStores()")}} method is used to retrieve all the cookie stores currently available in the browser, and print out each cookie store ID, and the tabs that currently share each cookie store.
```js
function logStores(cookieStores) {
for (const store of cookieStores) {
console.log(`Cookie store: ${store.id}\n Tab IDs: ${store.tabIds}`);
}
}
browser.cookies.getAllCookieStores().then(logStores);
```
The following code snippet gets all cookie stores and then logs the total number of stores and how many of those stores are incognito.
```js
browser.cookies.getAllCookieStores().then((stores) => {
const incognitoStores = stores.map((store) => store.incognito);
console.log(
`Of ${stores.length} cookie stores, ${incognitoStores.length} are incognito.`,
);
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.cookies`](https://developer.chrome.com/docs/extensions/reference/cookies/#type-CookieStore) API. This documentation is derived from [`cookies.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/cookies.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/getallcookiestores/index.md | ---
title: cookies.getAllCookieStores()
slug: Mozilla/Add-ons/WebExtensions/API/cookies/getAllCookieStores
page-type: webextension-api-function
browser-compat: webextensions.api.cookies.getAllCookieStores
---
{{AddonSidebar}}
The **`getAllCookieStores()`** method of the {{WebExtAPIRef("cookies")}} API returns a list of all cookie stores.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let gettingStores = browser.cookies.getAllCookieStores()
```
### Parameters
None.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an `array` of {{WebExtAPIRef('cookies.CookieStore')}} objects representing all the existing cookie stores.
## Browser compatibility
{{Compat}}
## Examples
In the following snippet, the `getAllCookieStores()` method is used to retrieve all the cookie stores currently available in the browser, and print out each cookie store ID, and the tabs that currently share each cookie store.
```js
function logStores(cookieStores) {
for (const store of cookieStores) {
console.log(`Cookie store: ${store.id}\n Tab IDs: ${store.tabIds}`);
}
}
browser.cookies.getAllCookieStores().then(logStores);
```
Each member of the `cookieStores` array is a {{WebExtAPIRef("cookies.CookieStore")}} object.
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.cookies`](https://developer.chrome.com/docs/extensions/reference/cookies/#method-getAllCookieStores) API. This documentation is derived from [`cookies.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/cookies.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/samesitestatus/index.md | ---
title: cookies.SameSiteStatus
slug: Mozilla/Add-ons/WebExtensions/API/cookies/SameSiteStatus
page-type: webextension-api-type
browser-compat: webextensions.api.cookies.SameSiteStatus
---
{{AddonSidebar}}
The `SameSiteStatus` type of the {{WebExtAPIRef("cookies")}} API represents information about the `SameSite` state of a cookie.
## Type
Values of this type are strings. Possible values are:
- `no_restriction`
- : Corresponds to a cookie set with `SameSite=None`.
- `lax`
- : Corresponds to a cookie set with `SameSite=Lax`.
- `strict`
- : Corresponds to a cookie set with `SameSite=Strict`.
- `unspecified`
- : Corresponds to a cookie set without the `SameSite` attribute. This state is not part of any SameSite standard, and is only supported by browsers that store this state internally. Other browsers map the absence of the SameSite flag to the default state (e.g. Lax). See the browser compatibility table for more details.
See [SameSite cookies](/en-US/docs/Web/HTTP/Cookies#samesite_cookies) for more information.
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/cookies/getall/index.md | ---
title: cookies.getAll()
slug: Mozilla/Add-ons/WebExtensions/API/cookies/getAll
page-type: webextension-api-function
browser-compat: webextensions.api.cookies.getAll
---
{{AddonSidebar}}
The **`getAll()`** method of the {{WebExtAPIRef("cookies")}} API retrieves all cookies from a single cookie store that match the given information.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
let getting = browser.cookies.getAll(
details // object
)
```
### Parameters
- `details`
- : An `object` containing details that can be used to match cookies to be retrieved. Included properties are as follows (see [Cookie type](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/Cookie#type) for more information on these):
- `domain` {{optional_inline}}
- : A `string` representing a domain that cookies must be associated with (they can be associated either with this exact domain or one of its subdomains).
- `firstPartyDomain` {{optional_inline}}
- : A `string` representing the first-party domain with which the cookie to retrieve is associated.
This property must be supplied if the browser has first-party isolation enabled. You can however pass `null` in this situation. If you do this, then cookies with any value for `firstPartyDomain`, as well as cookies which do not have `firstPartyDomain` set at all, will be included in the results. See [First-party isolation](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#first-party_isolation).
- `name` {{optional_inline}}
- : A `string` representing a name that the cookies should have.
- `partitionKey` {{optional_inline}}
- : An `object` defining which [storage partitions](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies#storage_partitioning) to return cookies from:
- if omitted, returns only cookies from unpartitioned storage.
- if included without `topLevelSite`, returns all cookies from partitioned and unpartitioned storage.
- if included with `topLevelSite` specified, returns cookies from the specified partition storage.
This object contains:
- `topLevelSite` {{optional_inline}}
- : A `string` representing the first-party URL of the top-level site storage partition containing the cookies.
- `path` {{optional_inline}}
- : A `string` representing a path β the cookies' path must be identical to this one.
- `secure` {{optional_inline}}
- : A `boolean` β filters cookies by their `secure` property, allowing you to filter secure cookies vs. non-secure cookies.
- `session` {{optional_inline}}
- : A `boolean` β filters the cookies by their `session` property, allowing you to filter session cookies vs. persistent cookies.
- `storeId` {{optional_inline}}
- : A `string` representing the cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used.
- `url` {{optional_inline}}
- : A `string` representing a URL that the retrieved cookies must be associated with.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be fulfilled with an array of `{{WebExtAPIRef('cookies.Cookie')}}` objects that match the properties given in the `details` parameter. Only unexpired cookies are returned. The cookies returned will be sorted by path length, longest to shortest. If multiple cookies have the same path length, those with the earliest creation time will be first.
## Browser compatibility
{{Compat}}
## Examples
In the following snippet, we are making a call to get all of the cookies the browser currently has stored that have a name of "favorite-color". When the result is returned, we are printing the value of each result to the console.
```js
function logCookies(cookies) {
for (const cookie of cookies) {
console.log(cookie.value);
}
}
browser.cookies
.getAll({
name: "favorite-color",
})
.then(logCookies);
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.cookies`](https://developer.chrome.com/docs/extensions/reference/cookies/#method-getAll) API. This documentation is derived from [`cookies.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/cookies.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/dom/index.md | ---
title: dom
slug: Mozilla/Add-ons/WebExtensions/API/dom
page-type: webextension-api
browser-compat: webextensions.api.dom
---
{{AddonSidebar}}
Access special extension only DOM features.
## Functions
- {{WebExtAPIRef("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`.
{{WebExtExamples("h2")}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/dom | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/dom/openorclosedshadowroot/index.md | ---
title: dom.openOrClosedShadowRoot()
slug: Mozilla/Add-ons/WebExtensions/API/dom/openOrClosedShadowRoot
page-type: webextension-api-function
browser-compat: webextensions.api.dom.openOrClosedShadowRoot
---
{{AddonSidebar}}
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`.
> **Note:** In Firefox, the equivalent property is `element.openOrClosedShadowRoot`. This read-only property represents the shadow root hosted by the element, regardless of whether its {{DOMxRef("ShadowRoot.mode", "mode")}} is `open` or `closed`.
>
> Use {{DOMxRef("Element.attachShadow()")}} to add a shadow root to an element.
## Syntax
```js-nolint
let shadowRoot = browser.dom.openOrClosedShadowRoot(
element, // HTMLElement
)
```
### Parameters
- `element`
- : `HTMLElement`. The host element.
### Return value
A {{DOMxRef("ShadowRoot")}} object instance, regardless of whether its
{{DOMxRef("ShadowRoot.mode", "mode")}} is set to `open` or
`closed`, or `null` if no shadow root is present.
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("Element.shadowRoot")}}
- [`chrome.dom.openOrClosedShadowRoot`](https://developer.chrome.com/docs/extensions/reference/dom/#method-openOrClosedShadowRoot)
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy/index.md | ---
title: proxy
slug: Mozilla/Add-ons/WebExtensions/API/proxy
page-type: webextension-api
browser-compat: webextensions.api.proxy
---
{{AddonSidebar}}
Use the proxy API to proxy web requests. You can use the {{WebExtAPIRef("proxy.onRequest")}} event listener to intercept web requests, and return an object that describes whether and how to proxy them.
The advantage of the {{WebExtAPIRef("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`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage) and networking APIs like [`dns`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/dns)).
Apart from this API, extensions can also use the [`browserSettings.proxyConfig`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy/settings) property to configure global proxy settings.
> **Note:** Chrome, Edge, and Opera have [an extension API also called "proxy"](https://developer.chrome.com/docs/extensions/reference/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](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions). Also, where you want to intercept requests, you also need [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the URLs of intercepted requests.
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"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings) key in your [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) to specify a minimum Firefox version. See [Securing the proxy API for Firefox add-ons](https://blog.mozilla.org/security/2021/10/25/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 {{WebExtAPIRef("webRequest.ResourceType")}} of `speculative`.
## Types
- {{WebExtAPIRef("proxy.ProxyInfo")}}
- : Describes a proxy.
- {{WebExtAPIRef("proxy.RequestDetails")}}
- : Contains information about a web request that the browser is about to make.
## Properties
- {{WebExtAPIRef("proxy.settings")}}
- : Get and set proxy settings.
## Events
- {{WebExtAPIRef("proxy.onError")}}
- : Fired when the system encounters an error running the PAC script or the `onRequest` listener.
- {{WebExtAPIRef("proxy.onRequest")}}
- : Fired when a web request is about to be made, giving the extension an opportunity to proxy it.
{{WebExtExamples("h2")}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy/proxyinfo/index.md | ---
title: proxy.ProxyInfo
slug: Mozilla/Add-ons/WebExtensions/API/proxy/ProxyInfo
page-type: webextension-api-type
browser-compat: webextensions.api.proxy.ProxyInfo
---
{{AddonSidebar}}
Contains information about a proxy. This object, or an array of these objects, is returned from the listener to {{WebExtAPIRef("proxy.onRequest")}}. It instructs the browser whether to proxy the request, and if so, which proxy to use.
## Type
Values of this type are objects. They contain the following properties:
- `type`
- : `string`. This describes whether to proxy at all, and if so, what kind of proxy to use. It may take one of the following values:
- `"direct"`: don't proxy the request. If this value is given, all other properties of this object are ignored. However, this setting doesn't override any [proxy set by the user](https://support.mozilla.org/en-US/kb/connection-settings-firefox). Use {{WebExtAPIRef("proxy.settings")}} to check whether a manual proxy is being used and, if necessary, monitor those settings for changes using [`BrowserSetting.onChange`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/types/BrowserSetting/onChange).
- `"http"`: HTTP proxy (or SSL CONNECT for HTTPS)
- `"https"`: HTTP proxying over TLS connection to proxy
- `"socks"`: SOCKS v5 proxy
- `"socks4"`: SOCKS v4 proxy
- `host`
- : `string`. The hostname of the proxy server. Mandatory unless `type` is `"direct"`.
- `port`
- : `number`. The port number of the proxy server. Mandatory unless `type` is `"direct"`.
- `username`
- : `string`. Username for the proxy service. This is usable with "socks". For HTTP proxy authorizations, use [`webRequest.onAuthRequired`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onAuthRequired).
- `password`
- : `string`. Password for the proxy service. This is usable with "socks". For HTTP proxy authorizations, use [`webRequest.onAuthRequired`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onAuthRequired).
- `proxyDNS`
- : `boolean`. If true, the proxy server is used to resolve certain DNS queries (only usable with `"socks4"` and `"socks"`). Defaults to `false`.
- `failoverTimeout`
- : `number`. Failover timeout in seconds. If the connection fails to connect the proxy server after this number of seconds, the next proxy server in the array returned from the `proxy.onRequest` listener will be used.
- `proxyAuthorizationHeader`
- : `string`. This string, if set to non-empty, is passed directly as a value to the {{httpheader("Proxy-Authorization")}} request header sent to HTTPS proxies as part of HTTPS and CONNECT requests. In other words, this can be used to directly authenticate to HTTPS proxies that allow (non-challenging) authentication.
For instance, if you want to send "username" and "password" for "basic" authentication, you can set the `proxyAuthorizationHeader` property to `Basic dXNlcm5hbWU6cGFzc3dvcmQ=`
- `connectionIsolationKey` {{optional_inline}}
- : `string`. An optional key used for additional isolation of this proxy connection. Applies to HTTPS proxies only.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy/settings/index.md | ---
title: proxy.settings
slug: Mozilla/Add-ons/WebExtensions/API/proxy/settings
page-type: webextension-api-property
browser-compat: webextensions.api.proxy.settings
---
{{AddonSidebar}}
A {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object that can be used to change the browser's proxy settings.
> **Note:** Changing proxy settings requires private browsing window access because proxy settings affect private and non-private windows. Whether an extension can access private browsing windows is under user control. For details, see [Extensions in Private Browsing](https://support.mozilla.org/en-US/kb/extensions-private-browsing). Your extension can check whether it can access private browsing windows using {{WebExtAPIRef("extension.isAllowedIncognitoAccess")}}. If your extension does not have private window permission, calls to `proxy.settings.set()` throw an exception.
The underlying value is an object with the properties listed below.
When setting this object, all properties are optional. Note that any properties that are omitted will be reset to their default value.
- `autoConfigUrl` {{optional_inline}}
- : `string`. A URL to use to configure the proxy.
- `autoLogin` {{optional_inline}}
- : `boolean`. Do not prompt for authentication if the password is saved. Defaults to `false`.
- `ftp` {{optional_inline}} {{Deprecated_Inline}}
- : `string`. The address of the FTP proxy. Can include a port.
- `http` {{optional_inline}}
- : `string`. The address of the HTTP proxy. Can include a port.
- `httpProxyAll` {{optional_inline}}
- : `boolean`. Use the HTTP proxy server for all protocols. Defaults to `false`.
- `passthrough` {{optional_inline}}
- : `string`. A comma-separated list of hosts which should not be proxied. Defaults to "localhost, 127.0.0.1".
- `proxyDNS` {{optional_inline}}
- : `boolean`. Proxy DNS when using SOCKS5. Defaults to `false`.
- `proxyType` {{optional_inline}}
- : `string`. The type of proxy to use. This may take any one of the following values: "none", "autoDetect", "system", "manual", "autoConfig". Defaults to "system".
- `socks` {{optional_inline}}
- : `string`. The address of the SOCKS proxy. Can include a port.
- `socksVersion` {{optional_inline}}
- : `integer`. The version of the SOCKS proxy. May be 4 or 5. Defaults to 5.
- `ssl` {{optional_inline}}
- : `string`. The address of the TLS/SSL proxy. Can include a port.
## Examples
```js
let proxySettings = {
proxyType: "manual",
http: "http://proxy.org:8080",
socksVersion: 4,
passthrough: ".example.org",
};
browser.proxy.settings.set({ value: proxySettings });
```
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy/onrequest/index.md | ---
title: proxy.onRequest
slug: Mozilla/Add-ons/WebExtensions/API/proxy/onRequest
page-type: webextension-api-event
browser-compat: webextensions.api.proxy.onRequest
---
{{AddonSidebar}}
Fired when a web request is about to be made, to give the extension an opportunity to proxy it.
This event is closely modeled on the events defined in the [`webRequest`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest) API. Like those events, its `addListener()` function takes three arguments:
- the listener that is called when the event is fired.
- a [`RequestFilter`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/RequestFilter) object controlling which requests cause the event to fire.
- an array of strings to control other aspects of the event's behavior.
The event is fired before any of the `webRequest` events for the same request.
When the event is fired, the listener is called with an object containing information about the request. The listener returns a {{WebExtAPIRef("proxy.ProxyInfo")}} object representing a proxy to use (or an array of {{WebExtAPIRef("proxy.ProxyInfo")}} objects, enabling the browser to fail over if a proxy is unreachable).
To use `proxy.onRequest`, an extension must have the "proxy" [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions) and the [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) for the URLs of the requests that it intercepts, which means that the match patterns in the `filter` argument must be a subset of the extension's host permissions.
## Syntax
```js-nolint
browser.proxy.onRequest.addListener(
listener, // function
filter, // object
extraInfoSpec // optional array of strings
)
browser.proxy.onRequest.removeListener(listener)
browser.proxy.onRequest.hasListener(listener)
```
Events have three functions:
- `addListener(listener, filter, extraInfoSpec)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function that is called when this event occurs. The function is passed a single argument, which is a {{WebExtAPIRef("proxy.RequestDetails")}} object containing details of the request.
The listener can return any of:
- a {{WebExtAPIRef("proxy.ProxyInfo")}} object.
- an array of {{WebExtAPIRef("proxy.ProxyInfo")}} objects.
- a `Promise` that resolves to a `ProxyInfo` object.
- a `Promise` that resolves to an array of `ProxyInfo` objects.
If the listener returns an array, or a Promise that resolves to an array, then all `ProxyInfo` objects after the first one represent failovers: if the proxy at position N in the array is not reachable when its `ProxyInfo.failoverTimeout` expires the browser will try the proxy at position N+1.
If there is an error specifying the {{WebExtAPIRef("proxy.ProxyInfo")}} objects, then {{WebExtAPIRef("proxy.onError")}} is called.
- `filter`
- : {{WebExtAPIRef('webRequest.RequestFilter')}}. A set of filters that restricts the events that are sent to the listener.
- `extraInfoSpec` {{optional_inline}}
- : `array` of `string`. Extra options for the event. Pass `"requestHeaders"` to include the request headers in the `details` object passed to the listener.
## Browser compatibility
{{Compat}}
## Examples
This code intercepts requests to `<all_urls>`, and proxies them if they are not for a top-level frame.
```js
function shouldProxyRequest(requestInfo) {
return requestInfo.parentFrameId !== -1;
}
function handleProxyRequest(requestInfo) {
if (shouldProxyRequest(requestInfo)) {
console.log(`Proxying: ${requestInfo.url}`);
return { type: "http", host: "127.0.0.1", port: 65535 };
}
return { type: "direct" };
}
browser.proxy.onRequest.addListener(handleProxyRequest, {
urls: ["<all_urls>"],
});
```
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy/requestdetails/index.md | ---
title: proxy.RequestDetails
slug: Mozilla/Add-ons/WebExtensions/API/proxy/RequestDetails
page-type: webextension-api-type
browser-compat: webextensions.api.proxy.RequestDetails
---
{{AddonSidebar}}
Contains information about a web request. An instance of this object is passed into the {{WebExtAPIRef("proxy.onRequest")}} listener.
## Type
Values of this type are objects. They contain the following properties:
- `cookieStoreId`
- : `string`. The cookie store ID of the current context. See [Work with contextual identities](/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities) for more information.
- `documentUrl`
- : `string`. URL of the page into which the requested resource will be loaded.
- `frameId`
- : `integer`. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.
- `fromCache`
- : `boolean`. Indicates if this response will be fetched from disk cache.
- `incognito`
- : `boolean`. `true` for private browsing requests.
- `method`
- : `string`. Standard HTTP method: for example, "GET" or "POST".
- `originUrl`
- : `string`. URL of the resource that triggered the request. Note that this may not be the same as the URL of the page into which the requested resource will be loaded. For example, if a document triggers a load in a different window through the [target attribute of a link](/en-US/docs/Web/HTML/Element/a#target), or a CSS document includes an image using the [`url()` functional notation](/en-US/docs/Web/CSS/url), then this is the URL of the original document or of the CSS document, respectively.
- `parentFrameId`
- : `integer`. ID of the frame that contains the frame that sent the request. Set to -1 if no parent frame exists.
- `requestId`
- : `string`. The ID of the request. Request IDs are unique within a browser session, so you can use an ID to identify different events associated with the same request.
- `requestHeaders` {{optional_inline}}
- : {{WebExtAPIRef('webRequest.HttpHeaders')}}. The HTTP request headers that will be sent with this request. Note that this is only included if the `"requestHeaders"` option was passed into `addListener()`.
- `tabId`
- : `integer`. ID of the tab in which the request takes place. Set to -1 if the request is not related to a tab.
- `thirdParty`
- : `boolean`. Indicates whether the request and its content window hierarchy is third party.
- `timeStamp`
- : `number`. The time when this event fired, in [milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time).
- `type`
- : {{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", or "stylesheet".
- `url`
- : `string`. Target of the request.
## Browser compatibility
{{Compat}}
{{WebExtExamples}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/proxy/onerror/index.md | ---
title: proxy.onError
slug: Mozilla/Add-ons/WebExtensions/API/proxy/onError
page-type: webextension-api-event
browser-compat: webextensions.api.proxy.onError
---
{{AddonSidebar}}
Fired when there is an error evaluating the PAC file or the `onRequest` listener.
The error can be triggered by throwing or returning an invalid value in the proxy.onRequest event handler.
## Syntax
```js-nolint
browser.proxy.onError.addListener(listener)
browser.proxy.onError.removeListener(listener)
browser.proxy.onError.hasListener(listener)
```
Events have three functions:
- `addListener(listener)`
- : Adds a listener to this event.
- `removeListener(listener)`
- : Stop listening to this event. The `listener` argument is the listener to remove.
- `hasListener(listener)`
- : Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.
## addListener syntax
### Parameters
- `listener`
- : The function called when this event occurs. The function is passed this argument:
- `newState`
- : `Object`. An [Error](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object representing the error.
{{WebExtExamples}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/clipboard/index.md | ---
title: clipboard
slug: Mozilla/Add-ons/WebExtensions/API/clipboard
page-type: webextension-api
browser-compat: webextensions.api.clipboard
---
{{AddonSidebar}}
The WebExtension `clipboard` API (which is different from the [standard Clipboard API](/en-US/docs/Web/API/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.
The WebExtension `clipboard` API exists primarily because the standard Clipboard API [doesn't support writing images to the clipboard](https://w3c.github.io/clipboard-apis/#writing-to-clipboard). The WebExtension `clipboard` API may be deprecated once the standard Clipboard API's support for non-text clipboard contents has entered general use.
Reading from the clipboard is not supported by this API, because the clipboard can already be read using the standard web platform APIs. See [Interacting with the clipboard](/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard#reading_from_the_clipboard).
This API is based on Chrome's [`clipboard`](https://developer.chrome.com/docs/extensions/reference/clipboard/) API, but that API is only available for Chrome apps, not extensions.
To use this API you need the `"clipboardWrite"` extension [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions).
## Functions
- {{WebExtAPIRef("clipboard.setImageData()")}}
- : Copy an image to the clipboard.
## Browser compatibility
{{WebExtExamples("h2")}}
{{Compat}}
> **Note:**
>
> This API is based on Chromium's [`chrome.clipboard`](https://developer.chrome.com/docs/extensions/reference/clipboard/) API.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/clipboard | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/clipboard/setimagedata/index.md | ---
title: clipboard.setImageData()
slug: Mozilla/Add-ons/WebExtensions/API/clipboard/setImageData
page-type: webextension-api-function
browser-compat: webextensions.api.clipboard.setImageData
---
{{AddonSidebar}}
Copies an image to the clipboard. The image is re-encoded before it is written to the clipboard. If the image is invalid, the clipboard is not modified.
The image is provided as an [`ArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing the encoded image. JPEG and PNG formats are supported.
Although this API is based on Chrome's [`clipboard.setImageData()`](https://developer.chrome.com/docs/extensions/reference/clipboard/) API, there are some differences:
- The Chrome API is only for apps, not extensions.
- This API requires only the `"clipboardWrite"` permission, while the Chrome version also requires the `"clipboard"` permission.
- Chrome's API uses callbacks, and this API only supports promises.
- This API does not support the `additionalItems` parameter.
This is an asynchronous function that returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
## Syntax
```js-nolint
browser.clipboard.setImageData(imageData, imageType)
```
### Parameters
- `imageData`
- : An [`ArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing the encoded image data to copy to the clipboard.
- `imageType`
- : A string indicating the type of image contained in `imageData`: `"png"` or `"jpeg"`.
### Return value
A [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will be resolved with no arguments if the operation succeeded, or rejected if there was an error (for example, because the data did not represent a valid image).
## Browser compatibility
{{Compat}}
## Examples
Copy a remote image:
```js
// requires:
// * the host permission for "https://cdn.mdn.mozilla.net/*"
// * the API permission "clipboardWrite"
fetch("https://cdn.mdn.mozilla.net/static/img/favicon144.png")
.then((response) => response.arrayBuffer())
.then((buffer) => browser.clipboard.setImageData(buffer, "png"));
```
Copy an image that was bundled with the extension:
```js
// requires the API permission "clipboardWrite"
fetch(browser.runtime.getURL("image.png"))
.then((response) => response.arrayBuffer())
.then((buffer) => browser.clipboard.setImageData(buffer, "png"));
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.clipboard`](https://developer.chrome.com/docs/extensions/reference/clipboard/) API.
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/privacy/index.md | ---
title: privacy
slug: Mozilla/Add-ons/WebExtensions/API/privacy
page-type: webextension-api
browser-compat: webextensions.api.privacy
---
{{AddonSidebar}}
Access and modify various privacy-related browser settings.
To use the privacy API, you must have the "privacy" [API permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions).
## Properties
- {{WebExtAPIRef("privacy.network")}}
- : Access and modify privacy settings relating to the network.
- {{WebExtAPIRef("privacy.services")}}
- : Access and modify privacy settings relating to the services provided by the browser or third parties.
- {{WebExtAPIRef("privacy.websites")}}
- : Access and modify privacy settings relating to the behavior of websites.
## Browser compatibility
{{Compat}}
{{WebExtExamples("h2")}}
> **Note:** This API is based on Chromium's [`chrome.privacy`](https://developer.chrome.com/docs/extensions/reference/privacy/) API.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/privacy | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/privacy/network/index.md | ---
title: privacy.network
slug: Mozilla/Add-ons/WebExtensions/API/privacy/network
page-type: webextension-api-property
browser-compat: webextensions.api.privacy.network
---
{{AddonSidebar}}
The {{WebExtAPIRef("privacy.network")}} property contains privacy-related network settings. Each property is a {{WebExtAPIRef("types.BrowserSetting")}} object.
Default values for these properties tend to vary across browsers.
## Properties
- `networkPredictionEnabled`
- : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is a boolean. If `true`, the browser attempts to speed up web browsing by pre-resolving DNS entries, prerendering sites (using, for example, `<link rel='prefetch' β¦>`), and preemptively opening TCP and TLS connections to servers.
- `peerConnectionEnabled`
- : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is a boolean. If `false`, the [`RTCPeerConnection`](/en-US/docs/Web/API/RTCPeerConnection) interface is disabled. Note that [`getUserMedia()`](/en-US/docs/Web/API/MediaDevices/getUserMedia) is _not_ affected by this setting.
- `webRTCIPHandlingPolicy`
- : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is a string. This setting allows users to specify the media performance/privacy tradeoffs which affect how WebRTC traffic will be routed and how much local address information is exposed. It may take any one of the following values, from least private to most private:
- `default`
- `default_public_and_private_interfaces`
- `default_public_interface_only`
- `disable_non_proxied_udp`
- `proxy_only` (only connections using TURN on a TCP connection through a proxy are allowed)
- `httpsOnlyMode`
- : This setting allows your extension to determine if a user has enabled
[HTTPS-Only mode](https://support.mozilla.org/kb/https-only-prefs). This property is read-only on all platforms. Its underlying value is a string that may take one of three values:
- `"always"`: HTTPS-Only mode is on.
- `"never"`: HTTPS-Only mode is off.
- `"private_browsing"`: HTTPS-Only mode is on in private browsing windows only.
- `globalPrivacyControl`
- : this setting allows your extension to determine if a user has enabled
[Global Privacy Control](/en-US/docs/Web/API/Navigator/globalPrivacyControl). This property is read-only on all platforms. Its underlying value is a boolean where `true` indicates that the browser sends Global Privacy Control signals and `false` indicates the browser does not send the signals.
## Browser compatibility
{{Compat}}
## Examples
Set the `webRTCIPHandlingPolicy` property:
```js
function onSet(result) {
if (result) {
console.log("success");
} else {
console.log("failure");
}
}
browser.browserAction.onClicked.addListener(() => {
let getting = browser.privacy.network.webRTCIPHandlingPolicy.get({});
getting.then((got) => {
console.log(got.value);
if (
got.levelOfControl === "controlled_by_this_extension" ||
got.levelOfControl === "controllable_by_this_extension"
) {
let setting = browser.privacy.network.webRTCIPHandlingPolicy.set({
value: "default_public_interface_only",
});
setting.then(onSet);
} else {
console.log("Not able to set webRTCIPHandlingPolicy");
}
});
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.privacy`](https://developer.chrome.com/docs/extensions/reference/privacy/) API. This documentation is derived from [`privacy.json`](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/privacy.json) in the Chromium code.
<!--
// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
| 0 |
data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/privacy | data/mdn-content/files/en-us/mozilla/add-ons/webextensions/api/privacy/services/index.md | ---
title: privacy.services
slug: Mozilla/Add-ons/WebExtensions/API/privacy/services
page-type: webextension-api-property
browser-compat: webextensions.api.privacy.services
---
{{AddonSidebar}}
The {{WebExtAPIRef("privacy.services")}} property contains privacy-related settings controlling services offered by the browser or by third parties. Each property is a {{WebExtAPIRef("types.BrowserSetting")}} object.
## Properties
- `passwordSavingEnabled`
- : A {{WebExtAPIRef("types.BrowserSetting")}} object whose underlying value is a boolean. If `true`, the browser's password manager will offer to store passwords when the user enters them. Defaults to `true`.
## Browser compatibility
{{Compat}}
## Examples
Disable the password manager if possible.
```js
function onSet(result) {
if (result) {
console.log("success");
} else {
console.log("failure");
}
}
let getting = browser.privacy.services.passwordSavingEnabled.get({});
getting.then((got) => {
console.log(got.value);
if (
got.levelOfControl === "controlled_by_this_extension" ||
got.levelOfControl === "controllable_by_this_extension"
) {
let setting = browser.privacy.services.passwordSavingEnabled.set({
value: false,
});
setting.then(onSet);
} else {
console.log("Not able to set passwordSavingEnabled");
}
});
```
{{WebExtExamples}}
> **Note:** This API is based on Chromium's [`chrome.privacy`](https://developer.chrome.com/docs/extensions/reference/privacy/) API.
| 0 |
Subsets and Splits