Reporting API - Web APIs

Reporting API
=============

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The Reporting API provides a generic reporting mechanism for web applications to use to make reports available based on various platform features (for example Content Security Policy, Permissions-Policy, or feature deprecation reports) in a consistent manner.

Concepts and usage
------------------

There are several different features and problems on the web platform that generate information useful to web developers when they are trying to fix bugs or improve their websites in other ways. Such information can include:

* Content Security Policy violations.
* Permissions-Policy violations.
* Deprecated feature usage (when you are using something that will stop working soon in browsers).
* Occurrence of crashes.
* Occurrence of user-agent interventions (when the browser blocks something your code is trying to do because it is deemed a security risk for example, or just plain annoying, like auto-playing audio).

The Reporting API's purpose is to provide a consistent reporting mechanism that can be used to make such information available to developers in the form of reports represented by JavaScript objects. There are a few ways to use it, which are detailed in the sections below.

### Origins and endpoints

Each unique origin you want to retrieve reports for can be given a series of endpoints, which are URLs that can receive given reports from a user agent.

The `Report-To` HTTP header is used to specify details about the different endpoints that a user-agent has available to it for delivering reports to. You can then retrieve reports by making a request to those URLs.

The endpoints are arranged into groups; an endpoint group can work together to provide load balancing (each endpoint will receive a specified proportion of report traffic) and safeguarding against failure (fallback endpoints can be specified to use if the primary ones fail).

**Note:** There is no absolute guarantee of report delivery — a report could still fail to be collected if a serious error occurs.

Reports sent to endpoints can be retrieved independently of the running of the websites they relate to, which is useful — a crash for example could bring down a website and stop anything running, but a report could still be obtained to give the developer some clues as to why it happened.

### Reporting observers

Reports can also be obtained via `ReportingObserver` objects created via JavaScript inside the website you are aiming to get reports on. This method is not as failsafe as the `Report-To` method described above — any page crash could stop you retrieving the reports — but it is easier to set up, and more flexible.

A `ReportingObserver` object is created using the `ReportingObserver()` constructor, which is passed two parameters:

* A callback function that has available as parameters the reports available in the observer's report queue, and a copy of the same `ReportingObserver` object, so observation can be controlled directly from inside the callback. The callback runs when observation starts
* An options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (`buffered: true`).

Methods are then available on the observer to start collecting reports (`ReportingObserver.observe()`), retrieve the reports currently in the report queue (`ReportingObserver.takeRecords()`), and disconnect the observer so it can no longer collect records (`ReportingObserver.disconnect()`).

### Generating reports via WebDriver

The Reporting API spec also defines a Generate Test Report WebDriver extension, which allows you to simulate report generation during automation. Reports generated via WebDriver are observed by any registered `ReportObserver` objects present in the loaded website. This is not yet documented.

Interfaces
----------

`CSPViolationReportBody`

Contains details of a Content Security Policy violation.

`DeprecationReportBody`

Contains details of deprecated web platform features that a website is using.

`InterventionReportBody`

Contains details of an intervention report, which is generated when a request made by the website has been denied by the browser; e.g. for security reasons.

`Report`

An object representing a single report.

`ReportingObserver`

An object that can be used to collect and access reports as they are generated.

Examples
--------

In our deprecation\_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page:

```js
const options = {
  types: ["deprecation"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  reportBtn.onclick = () => displayReports(reports);
}, options);
```

We then tell it to start observing reports using `ReportingObserver.observe()`; this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor:

```js
observer.observe();
```

Later on in the example we deliberately use the deprecated version of `MediaDevices.getUserMedia()`:

```js
if (navigator.mozGetUserMedia) {
  navigator.mozGetUserMedia(constraints, success, failure);
} else {
  navigator.getUserMedia(constraints, success, failure);
}
```

This causes a deprecation report to be generated; because of the event handler we set up inside the `ReportingObserver()` constructor, we can now click the button to display the report details.

![image of a jolly bearded man with various stats displayed below it about a deprecated feature](/en-US/docs/Web/API/Reporting_API/reporting_api_example.png)

**Note:** If you look at the complete source code, you'll notice that we actually call the deprecated `getUserMedia()` method twice. After the first time we call `ReportingObserver.takeRecords()`, which returns the first generated report and empties the queue. Because of this, when the button is pressed only the second report is listed.

Specifications
--------------

| Specification |
| --- |
| Reporting API # intro |

Browser compatibility
---------------------

Support is at an early stage right now. Firefox supports the JavaScript API and the `Report-To` header behind preferences:

* JavaScript API: `dom.reporting.enabled` (enabled in nightly only)
* HTTP header: `dom.reporting.header.enabled`

Chrome is also working on an implementation: information about Chrome implementation.

See also
--------

* Content Security Policy
* `Permissions-Policy`


RTCDTMFSender - Web APIs

RTCDTMFSender
=============

The **`RTCDTMFSender`** interface provides a mechanism for transmitting DTMF codes on a WebRTC `RTCPeerConnection`. You gain access to the connection's `RTCDTMFSender` through the `RTCRtpSender.dtmf` property on the audio track you wish to send DTMF with.

The primary purpose for WebRTC's DTMF support is to allow WebRTC-based communication clients to be connected to a public-switched telephone network (PSTN) or other legacy telephone service, including extant voice over IP (VoIP) services. For that reason, DTMF can't be used between two WebRTC-based devices, because there is no mechanism provided by WebRTC for receiving DTMF codes.

EventTarget

RTCDTMFSenderInstance properties
-------------------

`RTCDTMFSender.toneBuffer` Read only

A string which contains the list of DTMF tones currently in the queue to be transmitted (tones which have already been played are no longer included in the string). See `toneBuffer` for details on the format of the tone buffer.

Instance methods
----------------

`RTCDTMFSender.insertDTMF()`

Given a string describing a set of DTMF codes and, optionally, the duration of and inter-tone gap between the tones, `insertDTMF()` starts sending the specified tones. Calling `insertDTMF()` replaces any already-pending tones from the `toneBuffer`. You can abort sending queued tones by specifying an empty string (`""`) as the set of tones to play.

Events
------

Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

`tonechange`

The `tonechange` event is sent to the `RTCDTMFSender` instance's event handler to indicate that a tone has either started or stopped playing.

Example
-------

See the article Using DTMF with WebRTC for a full example.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # rtcdtmfsender |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API
* Using DTMF with WebRTC
* `RTCRtpSender.dtmf`
* `RTCPeerConnection`
* `RTCRtpSender`


HTMLFontElement - Web APIs

HTMLFontElement
===============

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Implements the document object model (DOM) representation of the font element. The HTML Font Element `<font>` defines the font size, font face and color of text.

EventTarget

Node

Element

HTMLElement

HTMLFontElementInstance properties
-------------------

*Inherits properties from its parent, `HTMLElement`.*

`HTMLFontElement.color`
Deprecated

A string that reflects the `color` HTML attribute, containing either a named color or a color specified in the hexadecimal #RRGGBB format.

`HTMLFontElement.face`
Deprecated

A string that reflects the `face` HTML attribute, containing a comma-separated list of one or more font names.

`HTMLFontElement.size`
Deprecated

A string that reflects the `size` HTML attribute, containing either a font size ranging from 1 to 7 or a number relative to the default value 3, for example -2 or +1.

Instance methods
----------------

*No specific method; inherits methods from its parent, `HTMLElement`.*

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmlfontelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The HTML element implementing this interface: `<font>`.


Geometry interfaces - Web APIs

Geometry interfaces
===================

**Geometry interfaces** is a CSS module that provides interfaces for working with 3D and 2D graphics — in particular, for working with points, rectangles, quadrilaterals and transformation matrices (for operations that translate/move, scale, rotate, skew/shear/slant, and flip graphics, as well as for multiplying/chaining and inverting/undoing those operations).

As a web developer, you don't always use the geometry interfaces directly, but instead use other features that rely on them behind the scenes: parts of CSS Transforms, the Canvas API, the WebXR Device API, and (more directly) `VideoFrame.visibleRect`, `Element.getClientRects()`, and `Element.getBoundingClientRect()`.

Interfaces
----------

`DOMMatrix`

Represents a transformation matrix, for operations that translate/move, scale, rotate, skew/shear/slant, and flip graphics, as well as for multiplying/chaining and inverting/undoing those operations.

`DOMMatrixReadOnly`

Read-only version of `DOMMatrix`.

`DOMPoint`

Represents a 2D or 3D point in a coordinate system; it includes values for the coordinates in up to three dimensions, as well as an optional perspective value.

`DOMPointReadOnly`

Read-only version of `DOMPoint`.

`DOMQuad`

Represents a collection of four `DOMPoint` objects defining the corners of a quadrilateral.

`DOMRect`

Represents the size and position of a rectangle.

`DOMRectReadOnly`

Read-only version of `DOMRect`.

Examples
--------

The `Path2D.addPath()` and `CanvasPattern.setTransform()` articles have examples that use some of the geometry interfaces.

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # DOMMatrix |
| Geometry Interfaces Module Level 1 # DOMPoint |
| Geometry Interfaces Module Level 1 # DOMQuad |
| Geometry Interfaces Module Level 1 # DOMRect |

Browser compatibility
---------------------

### api.DOMMatrix

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.DOMMatrixReadOnly

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.DOMPoint

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.DOMPointReadOnly

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.DOMQuad

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.DOMRect

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.DOMRectReadOnly

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Path2D.addPath()`
* `CanvasPattern.setTransform()`
* `CanvasRenderingContext2D.getTransform()`
* `CanvasRenderingContext2D.setTransform()`
* `CSSTransformValue.toMatrix()`
* `CSSTransformComponent.toMatrix()`
* `Element.getBoundingClientRect()`
* `Element.getClientRects()`
* `VideoFrame.visibleRect`
* `XRLightEstimate`
* `XRRigidTransform`


EXT_shader_texture_lod extension - Web APIs

EXT\_shader\_texture\_lod extension
===================================

The **`EXT_shader_texture_lod`** extension is part of the WebGL API and adds additional texture functions to the OpenGL ES Shading Language which provide the shader writer with explicit control of LOD (Level of detail).

WebGL extensions are available using the `WebGLRenderingContext.getExtension()` method. For more information, see also Using Extensions in the WebGL tutorial.

**Note:** This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. It requires GLSL `#version 300 es`.

GLSL built-in functions
-----------------------

The following new functions can be used in GLSL shader code, if this extension is enabled:

```cpp
vec4 texture2DLodEXT(sampler2D sampler, vec2 coord, float lod)
vec4 texture2DProjLodEXT(sampler2D sampler, vec3 coord, float lod)
vec4 texture2DProjLodEXT(sampler2D sampler, vec4 coord, float lod)
vec4 textureCubeLodEXT(samplerCube sampler, vec3 coord, float lod)
vec4 texture2DGradEXT(sampler2D sampler, vec2 P, vec2 dPdx, vec2 dPdy)
vec4 texture2DProjGradEXT(sampler2D sampler, vec3 P, vec2 dPdx, vec2 dPdy)
vec4 texture2DProjGradEXT(sampler2D sampler, vec4 P, vec2 dPdx, vec2 dPdy)
vec4 textureCubeGradEXT(samplerCube sampler, vec3 P, vec3 dPdx, vec3 dPdy)
```

Examples
--------

Enabling the extensions:

```js
gl.getExtension("EXT\_shader\_texture\_lod");
```

Shader code that avoids artifacts when wrapping texture coordinates:

```html
<script type="x-shader/x-fragment">
 #extension GL\_EXT\_shader\_texture\_lod : enable
 #extension GL\_OES\_standard\_derivatives : enable

 uniform sampler2D myTexture;
 varying vec2 texcoord;

 void main(){
 gl\_FragColor = texture2DGradEXT(myTexture, mod(texcoord, vec2(0.1, 0.5)),
 dFdx(texcoord), dFdy(texcoord));
 }
</script>
```

Specifications
--------------

| Specification |
| --- |
| WebGL EXT\_shader\_texture\_lod Khronos Ratified Extension Specification  |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `WebGLRenderingContext.getExtension()`
* `OES_standard_derivatives`


XPathResult - Web APIs

XPathResult
===========

The **`XPathResult`** interface represents the results generated by evaluating an XPath expression within the context of a given node.

Since XPath expressions can result in a variety of result types, this interface makes it possible to determine and handle the type and value of the result.

Instance properties
-------------------

`XPathResult.booleanValue` Read only

A `boolean` representing the value of the result if `resultType` is `BOOLEAN_TYPE`.

`XPathResult.invalidIteratorState` Read only

Signifies that the iterator has become invalid. It is `true` if `resultType` is `UNORDERED_NODE_ITERATOR_TYPE` or `ORDERED_NODE_ITERATOR_TYPE` and the document has been modified since this result was returned.

`XPathResult.numberValue` Read only

A `number` representing the value of the result if `resultType` is `NUMBER_TYPE`.

`XPathResult.resultType` Read only

A `number` code representing the type of the result, as defined by the type constants.

`XPathResult.singleNodeValue` Read only

A `Node` representing the value of the single node result, which may be `null`.

`XPathResult.snapshotLength` Read only

The number of nodes in the result snapshot.

`XPathResult.stringValue` Read only

A string representing the value of the result if `resultType` is `STRING_TYPE`.

Instance methods
----------------

`XPathResult.iterateNext()`

If the result is a node set, this method iterates over it and returns the next node from it or `null` if there are no more nodes.

`XPathResult.snapshotItem()`

Returns an item of the snapshot collection or `null` in case the index is not within the range of nodes. Unlike the iterator result, the snapshot does not become invalid, but may not correspond to the current document if it is mutated.

Constants
---------

| Result Type Defined Constant | Value | Description |
| --- | --- | --- |
| `ANY_TYPE` | `0` |
 A result set containing whatever type naturally results from evaluation
 of the expression. Note that if the result is a node-set then
 `UNORDERED_NODE_ITERATOR_TYPE` is always the resulting type.
  |
| `NUMBER_TYPE` | `1` |
 A result containing a single number. This is useful for example, in an
 XPath expression using the `count()` function.
  |
| `STRING_TYPE` | `2` | A result containing a single string. |
| `BOOLEAN_TYPE` | `3` |
 A result containing a single boolean value. This is useful for example,
 in an XPath expression using the `not()` function.
  |
| `UNORDERED_NODE_ITERATOR_TYPE` | `4` |
 A result node-set containing all the nodes matching the expression. The
 nodes may not necessarily be in the same order that they appear in the
 document.
  |
| `ORDERED_NODE_ITERATOR_TYPE` | `5` |
 A result node-set containing all the nodes matching the expression. The
 nodes in the result set are in the same order that they appear in the
 document.
  |
| `UNORDERED_NODE_SNAPSHOT_TYPE` | `6` |
 A result node-set containing snapshots of all the nodes matching the
 expression. The nodes may not necessarily be in the same order that they
 appear in the document.
  |
| `ORDERED_NODE_SNAPSHOT_TYPE` | `7` |
 A result node-set containing snapshots of all the nodes matching the
 expression. The nodes in the result set are in the same order that they
 appear in the document.
  |
| `ANY_UNORDERED_NODE_TYPE` | `8` |
 A result node-set containing any single node that matches the
 expression. The node is not necessarily the first node in the document
 that matches the expression.
  |
| `FIRST_ORDERED_NODE_TYPE` | `9` |
 A result node-set containing the first node in the document that matches
 the expression.
  |

Specifications
--------------

| Specification |
| --- |
| DOM Standard # interface-xpathresult |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Document.evaluate()`
* `XPathExpression`
* Dottoro Web Reference - XPathResult object


HTMLButtonElement - Web APIs

HTMLButtonElement
=================

The **`HTMLButtonElement`** interface provides properties and methods (beyond the regular `HTMLElement` interface it also has available to it by inheritance) for manipulating `<button>` elements.

EventTarget

Node

Element

HTMLElement

HTMLButtonElementInstance properties
-------------------

*Inherits properties from its parent, `HTMLElement`.*

`HTMLButtonElement.disabled`

A boolean value indicating whether or not the control is disabled, meaning that it does not accept any clicks.

`HTMLButtonElement.form` Read only

 An `HTMLFormElement` reflecting the form that this button is associated with. If the button is a descendant of a form element, then this attribute is a reference to that form's associated `HTMLFormElement`.
 If the button is not a descendant of a form element, then the attribute can be a reference to any `HTMLFormElement` element in the same document it is related to, or the `null` value if none matches.

`HTMLButtonElement.formAction`

A string reflecting the URI of a resource that processes information submitted by the button. If specified, this attribute overrides the `action` attribute of the `<form>` element that owns this element.

`HTMLButtonElement.formEnctype`

A string reflecting the type of content that is used to submit the form to the server. If specified, this attribute overrides the `enctype` attribute of the `<form>` element that owns this element.

`HTMLButtonElement.formMethod`

A string reflecting the HTTP method that the browser uses to submit the form. If specified, this attribute overrides the `method` attribute of the `<form>` element that owns this element.

`HTMLButtonElement.formNoValidate`

A boolean value indicating that the form is not to be validated when it is submitted. If specified, this attribute overrides the `novalidate` attribute of the `<form>` element that owns this element.

`HTMLButtonElement.formTarget`

A string reflecting a name or keyword indicating where to display the response received after submitting the form. If specified, this attribute overrides the `target` attribute of the `<form>` element that owns this element.

`HTMLButtonElement.labels` Read only

A `NodeList` that represents a list of `<label>` elements that are labels for this button.

`HTMLButtonElement.name`

A string representing the object's name when submitted with a form. If specified, it must not be the empty string.

`HTMLButtonElement.popoverTargetAction`

Gets and sets the action to be performed (`"hide"`, `"show"`, or `"toggle"`) on a popover element being controlled by a control button. It reflects the value of the `popovertargetaction` HTML attribute.

`HTMLButtonElement.popoverTargetElement`

Gets and sets the popover element to control via a button. The JavaScript equivalent of the `popovertarget` HTML attribute.

`HTMLButtonElement.type`

A string indicating the behavior of the button. This is an enumerated attribute with the following possible values:

* `submit`: The button submits the form. This is the default value if the attribute is not specified, or if it is dynamically changed to an empty or invalid value.
* `reset`: The button resets the form.
* `button`: The button does nothing.
* `menu`: The button displays a menu.
Experimental

`HTMLButtonElement.willValidate` Read only

A boolean value indicating whether the button is a candidate for constraint validation. It is `false` if any conditions bar it from constraint validation, including: its `type` property is `reset` or `button`; it has a `<datalist>` ancestor; or the `disabled` property is set to `true`.

`HTMLButtonElement.validationMessage` Read only

A string representing the localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints.

`HTMLButtonElement.validity` Read only

A `ValidityState` representing the validity states that this button is in.

`HTMLButtonElement.value`

A string representing the current form control value of the button.

Instance methods
----------------

*Inherits methods from its parent, `HTMLElement`*.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmlbuttonelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* HTML element implementing this interface: `<button>`


NavigateEvent - Web APIs

NavigateEvent
=============

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`NavigateEvent`** interface of the Navigation API is the event object for the `navigate` event, which fires when any type of navigation is initiated (this includes usage of History API features like `History.go()`). `NavigateEvent` provides access to information about that navigation, and allows developers to intercept and control the navigation handling.

Event

NavigateEventConstructor
-----------

`NavigateEvent()`
Experimental

Creates a new `NavigateEvent` object instance.

Instance properties
-------------------

*Inherits properties from its parent, `Event`.*

`canIntercept` Read only
Experimental

Returns `true` if the navigation can be intercepted, or `false` otherwise (e.g. you can't intercept a cross-origin navigation).

`destination` Read only
Experimental

Returns a `NavigationDestination` object representing the destination being navigated to.

`downloadRequest` Read only
Experimental

Returns the filename of the file requested for download, in the case of a download navigation (e.g. an `<a>` or `<area>` element with a `download` attribute), or `null` otherwise.

`formData` Read only
Experimental

Returns the `FormData` object representing the submitted data in the case of a `POST` form submission, or `null` otherwise.

`hashChange` Read only
Experimental

Returns `true` if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document), or `false` otherwise.

`info` Read only
Experimental

Returns the `info` data value passed by the initiating navigation operation (e.g. `Navigation.back()`, or `Navigation.navigate()`), or `undefined` if no `info` data was passed.

`navigationType` Read only
Experimental

Returns the type of the navigation — `push`, `reload`, `replace`, or `traverse`.

`signal` Read only
Experimental

Returns an `AbortSignal`, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one).

`userInitiated` Read only
Experimental

Returns `true` if the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons), or `false` otherwise.

Instance methods
----------------

*Inherits methods from its parent, `Event`.*

`intercept()`
Experimental

Intercepts this navigation, turning it into a same-document navigation to the `destination` URL. It can accept a handler function that defines what the navigation handling behavior should be, plus `focusReset` and `scroll` options to control behavior as desired.

`scroll()`
Experimental

Can be called to manually trigger the browser-driven scrolling behavior that occurs in response to the navigation, if you want it to happen before the navigation handling has completed.

Examples
--------

### Handling a navigation using `intercept()`

```js
navigation.addEventListener("navigate", (event) => {
  // Exit early if this navigation shouldn't be intercepted,
  // e.g. if the navigation is cross-origin, or a download request
  if (shouldNotIntercept(event)) return;

  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        // The URL has already changed, so show a placeholder while
        // fetching the new content, such as a spinner or loading page
        renderArticlePagePlaceholder();

        // Fetch the new content and display when ready
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);
      },
    });
  }
});
```

**Note:** Before the Navigation API was available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate `History.pushState()` call, then set up the page view based on the new URL. And this wouldn't handle all navigations — only user-initiated link clicks.

### Handling scrolling using `scroll()`

In this example of intercepting a navigation, the `handler()` function starts by fetching and rendering some article content, but then fetches and renders some secondary content afterwards. It makes sense to scroll the page to the main article content as soon as it is available so the user can interact with it, rather than waiting until the secondary content is also rendered. To achieve this, we have added a `scroll()` call between the two.

```js
navigation.addEventListener("navigate", (event) => {
  if (shouldNotIntercept(navigateEvent)) return;
  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);

        event.scroll();

        const secondaryContent = await getSecondaryContent(url.pathname);
        addSecondaryContent(secondaryContent);
      },
    });
  }
});
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # the-navigateevent-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


CacheStorage - Web APIs

CacheStorage
============

The **`CacheStorage`** interface represents the storage for `Cache` objects.

The interface:

* Provides a master directory of all the named caches that can be accessed by a `ServiceWorker` or other type of worker or `window` scope (you're not limited to only using it with service workers).
* Maintains a mapping of string names to corresponding `Cache` objects.

Use `CacheStorage.open()` to obtain a `Cache` instance.

Use `CacheStorage.match()` to check if a given `Request` is a key in any of the `Cache` objects that the `CacheStorage` object tracks.

You can access `CacheStorage` through the global `caches` property.

**Note:** `CacheStorage` always rejects with a `SecurityError` on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the future.) When testing on Firefox, you can get around this by checking the **Enable Service Workers over HTTP (when toolbox is open)** option in the Firefox Devtools options/gear menu. Furthermore, because `CacheStorage` requires file-system access, it may be unavailable in private mode in Firefox.

**Note:** `CacheStorage.match()` is a convenience method. Equivalent functionality to match a cache entry can be implemented by returning an array of cache names from `CacheStorage.keys()`, opening each cache with `CacheStorage.open()`, and matching the one you want with `Cache.match()`.

**Note:** This feature is available in Web Workers

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Instance methods
----------------

`CacheStorage.match()`

Checks if a given `Request` is a key in any of the `Cache` objects that the `CacheStorage` object tracks, and returns a `Promise` that resolves to that match.

`CacheStorage.has()`

Returns a `Promise` that resolves to `true` if a `Cache` object matching the `cacheName` exists.

`CacheStorage.open()`

Returns a `Promise` that resolves to the `Cache` object matching the `cacheName` (a new cache is created if it doesn't already exist.)

`CacheStorage.delete()`

Finds the `Cache` object matching the `cacheName`, and if found, deletes the `Cache` object and returns a `Promise` that resolves to `true`. If no `Cache` object is found, it resolves to `false`.

`CacheStorage.keys()`

Returns a `Promise` that will resolve with an array containing strings corresponding to all of the named `Cache` objects tracked by the `CacheStorage`. Use this method to iterate over a list of all the `Cache` objects.

Examples
--------

 This code snippet is from the MDN simple service worker example (see simple service worker running live.)
 This service worker script waits for an `InstallEvent` to fire, then runs `waitUntil` to handle the install process for the app. This consists of calling `CacheStorage.open` to create a new cache, then using `Cache.addAll` to add a series of assets to it.

In the second code block, we wait for a `FetchEvent` to fire. We construct a custom response like so:

1. Check whether a match for the request is found in the CacheStorage. If so, serve that.
2. If not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using `Cache.put` (`cache.put(event.request, response.clone())`.)
3. If this fails (e.g. because the network is down), return a fallback response.

Finally, return whatever the custom response ended up being equal to, using `FetchEvent.respondWith`.

```js
self.addEventListener("install", (event) => {
  event.waitUntil(
    caches
      .open("v1")
      .then((cache) =>
        cache.addAll([
          "/",
          "/index.html",
          "/style.css",
          "/app.js",
          "/image-list.js",
          "/star-wars-logo.jpg",
          "/gallery/bountyHunters.jpg",
          "/gallery/myLittleVader.jpg",
          "/gallery/snowTroopers.jpg",
        ]),
      ),
  );
});

self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      // caches.match() always resolves
      // but in case of success response will have value
      if (response !== undefined) {
        return response;
      } else {
        return fetch(event.request)
          .then((response) => {
            // response may be used only once
            // we need to save clone to put one copy in cache
            // and serve second one
            let responseClone = response.clone();

            caches.open("v1").then((cache) => {
              cache.put(event.request, responseClone);
            });
            return response;
          })
          .catch(() => caches.match("/gallery/myLittleVader.jpg"));
      }
    }),
  );
});
```

This snippet shows how the API can be used outside of a service worker context, and uses the `await` operator for much more readable code.

```js
// Try to get data from the cache, but fall back to fetching it live.
async function getData() {
  const cacheVersion = 1;
  const cacheName = `myapp-${cacheVersion}`;
  const url = "https://jsonplaceholder.typicode.com/todos/1";
  let cachedData = await getCachedData(cacheName, url);

  if (cachedData) {
    console.log("Retrieved cached data");
    return cachedData;
  }

  console.log("Fetching fresh data");

  const cacheStorage = await caches.open(cacheName);
  await cacheStorage.add(url);
  cachedData = await getCachedData(cacheName, url);
  await deleteOldCaches(cacheName);

  return cachedData;
}

// Get data from the cache.
async function getCachedData(cacheName, url) {
  const cacheStorage = await caches.open(cacheName);
  const cachedResponse = await cacheStorage.match(url);

  if (!cachedResponse || !cachedResponse.ok) {
    return false;
  }

  return await cachedResponse.json();
}

// Delete any old caches to respect user's disk space.
async function deleteOldCaches(currentCache) {
  const keys = await caches.keys();

  for (const key of keys) {
    const isOurCache = key.startsWith("myapp-");
    if (currentCache === key || !isOurCache) {
      continue;
    }
    caches.delete(key);
  }
}

try {
  const data = await getData();
  console.log({ data });
} catch (error) {
  console.error({ error });
}
```

Specifications
--------------

| Specification |
| --- |
| Service Workers # cachestorage-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using Service Workers
* `Cache`
* `caches`
* Private Browsing / Incognito modes


File System API - Web APIs

File System API
===============

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The File System API — with extensions provided via the File System Access API to access files on the device file system — allows read, write and file management capabilities.

Concepts and Usage
------------------

This API allows interaction with files on a user's local device, or on a user-accessible network file system. Core functionality of this API includes reading files, writing or saving files, and access to directory structure.

Most of the interaction with files and directories is accomplished through handles. A parent `FileSystemHandle` class helps define two child classes: `FileSystemFileHandle` and `FileSystemDirectoryHandle`, for files and directories respectively.

The handles represent a file or directory on the user's system. You can first gain access to them by showing the user a file or directory picker using methods such as `window.showOpenFilePicker()` and `window.showDirectoryPicker()`. Once these are called, the file picker presents itself and the user selects either a file or directory. Once this happens successfully, a handle is returned.

You can also gain access to file handles via:

* The `DataTransferItem.getAsFileSystemHandle()` method of the HTML Drag and Drop API.
* The File Handling API.

Each handle provides its own functionality and there are a few differences depending on which one you are using (see the interfaces section for specific details). You then can access file data, or information (including children) of the directory selected. This API opens up potential functionality the web has been lacking. Still, security has been of utmost concern when designing the API, and access to file/directory data is disallowed unless the user specifically permits it (note that this is not the case with the Origin private file system, because it is not visible to the user).

**Note:** The different exceptions that can be thrown when using the features of this API are listed on relevant pages as defined in the spec. However, the situation is made more complex by the interaction of the API and the underlying operating system. A proposal has been made to list the error mappings in the spec, which includes useful related information.

**Note:** Objects based on `FileSystemHandle` can also be serialized into an IndexedDB database instance, or transferred via `postMessage()`.

### Origin private file system

The origin private file system (OPFS) is a storage endpoint provided as part of the File System API, which is private to the origin of the page and not visible to the user like the regular file system. It provides access to a special kind of file that is highly optimized for performance and offers in-place write access to its content.

Read our Origin private file system for instructions on how to use it.

### Saving files

* In the case of the asynchronous handles, use the `FileSystemWritableFileStream` interface. Once the data you'd like to save is in a format of `Blob`, `String` object, string literal or `buffer`, you can open a stream and save the data to a file. This can be the existing file or a new file.
* In the case of the synchronous `FileSystemSyncAccessHandle`, you write changes to a file using the `write()` method. You can optionally also call `flush()` if you need the changes committed to disk at a specific time (otherwise you can leave the underlying operating system to handle this when it sees fit, which should be OK in most cases).
Interfaces
----------

`FileSystemHandle`

The **`FileSystemHandle`** interface is an object which represents an entry. Multiple handles can represent the same entry. For the most part you do not work with `FileSystemHandle` directly but rather its child interfaces `FileSystemFileHandle` and `FileSystemDirectoryHandle`.

`FileSystemFileHandle`

Provides a handle to a file system entry.

`FileSystemDirectoryHandle`

provides a handle to a file system directory.

`FileSystemSyncAccessHandle`

Provides a synchronous handle to a file system entry, which operates in-place on a single file on disk. The synchronous nature of the file reads and writes allows for higher performance for critical methods in contexts where asynchronous operations come with high overhead, e.g., WebAssembly. This class is only accessible inside dedicated Web Workers for files within the origin private file system.

`FileSystemWritableFileStream`

is a `WritableStream` object with additional convenience methods, which operates on a single file on disk.

Examples
--------

### Accessing files

The below code allows the user to choose a file from the file picker.

```js
async function getFile() {
  // Open file picker and destructure the result the first handle
  const [fileHandle] = await window.showOpenFilePicker();
  const file = await fileHandle.getFile();
  return file;
}
```

The following asynchronous function presents a file picker and once a file is chosen, uses the `getFile()` method to retrieve the contents.

```js
const pickerOpts = {
  types: [
    {
      description: "Images",
      accept: {
        "image/\*": [".png", ".gif", ".jpeg", ".jpg"],
      },
    },
  ],
  excludeAcceptAllOption: true,
  multiple: false,
};

async function getTheFile() {
  // Open file picker and destructure the result the first handle
  const [fileHandle] = await window.showOpenFilePicker(pickerOpts);

  // get file contents
  const fileData = await fileHandle.getFile();
}
```

### Accessing directories

The following example returns a directory handle with the specified name. If the directory does not exist, it is created.

```js
const dirName = "directoryToGetName";

// assuming we have a directory handle: 'currentDirHandle'
const subDir = currentDirHandle.getDirectoryHandle(dirName, { create: true });
```

The following asynchronous function uses `resolve()` to find the path to a chosen file, relative to a specified directory handle.

```js
async function returnPathDirectories(directoryHandle) {
  // Get a file handle by showing a file picker:
  const [handle] = await self.showOpenFilePicker();
  if (!handle) {
    // User cancelled, or otherwise failed to open a file.
    return;
  }

  // Check if handle exists inside our directory handle
  const relativePaths = await directoryHandle.resolve(handle);

  if (relativePaths === null) {
    // Not inside directory handle
  } else {
    // relativePaths is an array of names, giving the relative path

    for (const name of relativePaths) {
      // log each entry
      console.log(name);
    }
  }
}
```

### Writing to files

The following asynchronous function opens the save file picker, which returns a `FileSystemFileHandle` once a file is selected. A writable stream is then created using the `FileSystemFileHandle.createWritable()` method.

A user defined `Blob` is then written to the stream which is subsequently closed.

```js
async function saveFile() {
  // create a new handle
  const newHandle = await window.showSaveFilePicker();

  // create a FileSystemWritableFileStream to write to
  const writableStream = await newHandle.createWritable();

  // write our file
  await writableStream.write(imgBlob);

  // close the file and write the contents to disk.
  await writableStream.close();
}
```

The following show different examples of options that can be passed into the `write()` method.

```js
// just pass in the data (no options)
writableStream.write(data);

// writes the data to the stream from the determined position
writableStream.write({ type: "write", position, data });

// updates the current file cursor offset to the position specified
writableStream.write({ type: "seek", position });

// resizes the file to be size bytes long
writableStream.write({ type: "truncate", size });
```

### Synchronously reading and writing files in OPFS

This example synchronously reads and writes a file to the origin private file system.

The following asynchronous event handler function is contained inside a Web Worker. On receiving a message from the main thread it:

* Creates a synchronous file access handle.
* Gets the size of the file and creates an `ArrayBuffer` to contain it.
* Reads the file contents into the buffer.
* Encodes the message and writes it to the end of the file.
* Persists the changes to disk and closes the access handle.

```js
onmessage = async (e) => {
  // retrieve message sent to work from main script
  const message = e.data;

  // Get handle to draft file in OPFS
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // Get sync access handle
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // Get size of the file.
  const fileSize = accessHandle.getSize();
  // Read file content to a buffer.
  const buffer = new DataView(new ArrayBuffer(fileSize));
  const readBuffer = accessHandle.read(buffer, { at: 0 });

  // Write the message to the end of the file.
  const encoder = new TextEncoder();
  const encodedMessage = encoder.encode(message);
  const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });

  // Persist changes to disk.
  accessHandle.flush();

  // Always close FileSystemSyncAccessHandle if done.
  accessHandle.close();
};
```

**Note:** In earlier versions of the spec, `close()`, `flush()`, `getSize()`, and `truncate()` were unergonomically specified as asynchronous methods. This has now been amended, but some browsers still support the asynchronous versions.

Specifications
--------------

| Specification |
| --- |
| File System Standard # api-filesystemhandle |
| File System Standard # api-filesystemfilehandle |

Browser compatibility
---------------------

### api.FileSystemHandle

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.FileSystemFileHandle

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The File System Access API: simplifying access to local files on web.dev
* The origin private file system on web.dev


HTMLObjectElement - Web APIs

HTMLObjectElement
=================

The **`HTMLObjectElement`** interface provides special properties and methods (beyond those on the `HTMLElement` interface it also has available to it by inheritance) for manipulating the layout and presentation of `<object>` element, representing external resources.

EventTarget

Node

Element

HTMLElement

HTMLObjectElementInstance properties
-------------------

*Inherits properties from its parent, `HTMLElement`.*

`HTMLObjectElement.align`
Deprecated

A string representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`.

`HTMLObjectElement.archive`
Deprecated

A string that reflects the `archive` HTML attribute, containing a list of archives for resources for this object.

`HTMLObjectElement.border`
Deprecated

A string that reflects the `border` HTML attribute, specifying the width of a border around the object.

`HTMLObjectElement.code`
Deprecated

A string representing the name of an applet class file, containing either the applet's subclass, or the path to get to the class, including the class file itself.

`HTMLObjectElement.codeBase`
Deprecated

A string that reflects the `codebase` HTML attribute, specifying the base path to use to resolve relative URIs.

`HTMLObjectElement.codeType`
Deprecated

A string that reflects the `codetype` HTML attribute, specifying the content type of the data.

`HTMLObjectElement.contentDocument` Read only

Returns a `Document` representing the active document of the object element's nested browsing context, if any; otherwise `null`.

`HTMLObjectElement.contentWindow` Read only

Returns a WindowProxy representing the window proxy of the object element's nested browsing context, if any; otherwise `null`.

`HTMLObjectElement.data`

Returns a string that reflects the `data` HTML attribute, specifying the address of a resource's data.

`HTMLObjectElement.declare`
Deprecated

A boolean value that reflects the `declare` HTML attribute, indicating that this is a declaration, not an instantiation, of the object.

`HTMLObjectElement.form` Read only

Returns a `HTMLFormElement` representing the object element's form owner, or null if there isn't one.

`HTMLObjectElement.height`

Returns a string that reflects the `height` HTML attribute, specifying the displayed height of the resource in CSS pixels.

`HTMLObjectElement.hspace`
Deprecated

A `long` representing the horizontal space in pixels around the control.

`HTMLObjectElement.name`

Returns a string that reflects the `name` HTML attribute, specifying the name of the browsing context.

`HTMLObjectElement.standby`
Deprecated

A string that reflects the `standby` HTML attribute, specifying a message to display while the object loads.

`HTMLObjectElement.type`

A string that reflects the `type` HTML attribute, specifying the MIME type of the resource.

`HTMLObjectElement.useMap`

A string that reflects the `usemap` HTML attribute, specifying a `<map>` element to use.

`HTMLObjectElement.validationMessage` Read only

Returns a string representing a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints.

`HTMLObjectElement.validity` Read only

Returns a `ValidityState` with the validity states that this element is in.

`HTMLObjectElement.vspace`
Deprecated

A `long` representing the horizontal space in pixels around the control.

`HTMLObjectElement.width`

A string that reflects the `width` HTML attribute, specifying the displayed width of the resource in CSS pixels.

`HTMLObjectElement.willValidate` Read only

Returns a boolean value that indicates whether the element is a candidate for constraint validation. Always `false` for `HTMLObjectElement` objects.

Instance methods
----------------

*Inherits methods from its parent, `HTMLElement`.*

`HTMLObjectElement.checkValidity()`

Returns a boolean value that always is `true`, because `object` objects are never candidates for constraint validation.

`HTMLObjectElement.setCustomValidity()`

Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmlobjectelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The HTML element implementing this interface: `<object>`


BroadcastChannel - Web APIs

BroadcastChannel
================

Baseline 2022
-------------

Newly availableSince March 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`BroadcastChannel`** interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin. Messages are broadcasted via a `message` event fired at all `BroadcastChannel` objects listening to the channel, except the object that sent the message.

**Note:** This feature is available in Web Workers

EventTarget

BroadcastChannelConstructor
-----------

`BroadcastChannel()`

Creates an object linking to the named channel.

Instance properties
-------------------

*This interface also inherits properties from its parent, `EventTarget`.*

`BroadcastChannel.name` Read only

Returns a string, the name of the channel.

Instance methods
----------------

*This interface also inherits methods from its parent, `EventTarget`.*

`BroadcastChannel.postMessage()`

Sends the message, of any type of object, to each `BroadcastChannel` object listening to the same channel.

`BroadcastChannel.close()`

Closes the channel object, indicating it won't get any new messages, and allowing it to be, eventually, garbage collected.

Events
------

`message`

 Fired when a message arrives on the channel.
 Also available via the `onmessage` property.

`messageerror`

 Fired when a message arrives that can't be deserialized.
 Also available via the `onmessageerror` property.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # broadcasting-to-other-browsing-contexts |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Another, more heavyweight, way of communicating between browser contexts: `ServiceWorker`.
* Broadcast Channel API overview


WebTransport API - Web APIs

WebTransport API
================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **WebTransport API** provides a modern update to WebSockets, transmitting data between client and server using HTTP/3 Transport. WebTransport provides support for multiple streams, unidirectional streams, and out-of-order delivery. It enables reliable transport via streams and unreliable transport via UDP-like datagrams.

**Note:** This feature is available in Web Workers

Concepts and usage
------------------

HTTP/3 has been in progress since 2018. It is based on Google's QUIC protocol (which is itself based on UDP), and fixes several issues around the classic TCP protocol, on which HTTP and WebSockets are based.

These include:

**Head-of-line blocking**

HTTP/2 allows multiplexing, so a single connection can stream multiple resources simultaneously. However, if a single resource fails, all other resources on that connection are held up until any missing packets are retransmitted. With QUIC, only the failing resource is affected.

**Faster performance**

QUIC is more performant than TCP in many ways. QUIC can handle security features by itself, rather than handing responsibility off to other protocols like TLS — meaning fewer round trips. And streams provide better transport efficiency than the older packet mechanism. That can make a significant difference, especially on high-latency networks.

**Better network transitions**

QUIC uses a unique connection ID to handle the source and destination of each request — to ensure that packets are delivered correctly. This ID can persist between different networks, meaning that, for example, a download can continue interrupted if you switch from Wifi to a mobile network. HTTP/2, on the other hand, uses IP addresses as identifiers, so network transitions can be problematic.

**Unreliable transport**

HTTP/3 supports unreliable data transmission via datagrams.

The WebTransport API provides low-level access to two-way communication via HTTP/3, taking advantage of the above benefits, and supporting both reliable and unreliable data transmission.

### Initial connection

To open a connection to an HTTP/3 server, you pass its URL to the `WebTransport()` constructor. Note that the scheme needs to be HTTPS, and the port number needs to be explicitly specified. Once the `WebTransport.ready` promise fulfills, you can start using the connection.

Also note that you can respond to the connection closing by waiting for the `WebTransport.closed` promise to fulfill. Errors returned by WebTransport operations are of type `WebTransportError`, and contain additional data on top of the standard `DOMException` set.

```js
const url = "https://example.com:4999/wt";

async function initTransport(url) {
  // Initialize transport connection
  const transport = new WebTransport(url);

  // The connection can be used once ready fulfills
  await transport.ready;

  // ...
}

// ...

async function closeTransport(transport) {
  // Respond to connection closing
  try {
    await transport.closed;
    console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
  } catch (error) {
    console.error(`The HTTP/3 connection to ${url} closed due to ${error}.`);
  }
}
```

### Unreliable transmission via datagrams

"Unreliable" means that transmission of data is not guaranteed, nor is arrival in a specific order. This is fine in some situations and provides very fast delivery. For example, you might want to transmit regular game state updates where each message supersedes the last one that arrives, and order is not important.

Unreliable data transmission is handled via the `WebTransport.datagrams` property — this returns a `WebTransportDatagramDuplexStream` object containing everything you need to send datagrams to the server, and receive them back.

The `WebTransportDatagramDuplexStream.writable` property returns a `WritableStream` object that you can write data to using a writer, for transmission to the server:

```js
const writer = transport.datagrams.writable.getWriter();
const data1 = new Uint8Array([65, 66, 67]);
const data2 = new Uint8Array([68, 69, 70]);
writer.write(data1);
writer.write(data2);
```

The `WebTransportDatagramDuplexStream.readable` property returns a `ReadableStream` object that you can use to receive data from the server:

```js
async function readData() {
  const reader = transport.datagrams.readable.getReader();
  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break;
    }
    // value is a Uint8Array.
    console.log(value);
  }
}
```

### Reliable transmission via streams

"Reliable" means that transmission and order of data are guaranteed. That provides slower delivery (albeit faster than with WebSockets), and is needed in situations where reliability and ordering are important (such as chat applications, for example).

When using reliable transmission via streams you can also set the relative priority of different streams over the same transport.

### Unidirectional transmission

To open a unidirectional stream from a user agent, you use the `WebTransport.createUnidirectionalStream()` method to get a reference to a `WritableStream`. From this you can `get a writer` to allow data to be written to the stream and sent to the server.

```js
async function writeData() {
  const stream = await transport.createUnidirectionalStream();
  const writer = stream.writable.getWriter();
  const data1 = new Uint8Array([65, 66, 67]);
  const data2 = new Uint8Array([68, 69, 70]);
  writer.write(data1);
  writer.write(data2);

  try {
    await writer.close();
    console.log("All data has been sent.");
  } catch (error) {
    console.error(`An error occurred: ${error}`);
  }
}
```

Note also the use of the `WritableStreamDefaultWriter.close()` method to close the associated HTTP/3 connection once all data has been sent.

If the server opens a unidirectional stream to transmit data to the client, this can be accessed on the client via the `WebTransport.incomingUnidirectionalStreams` property, which returns a `ReadableStream` of `WebTransportReceiveStream` objects. These can be used to read `Uint8Array` instances sent by the server.

In this case, the first thing to do is set up a function to read a `WebTransportReceiveStream`. These objects inherit from the `ReadableStream` class, so can be used in just the same way:

```js
async function readData(receiveStream) {
  const reader = receiveStream.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    // value is a Uint8Array
    console.log(value);
  }
}
```

Next, call `WebTransport.incomingUnidirectionalStreams` and get a reference to the reader available on the `ReadableStream` it returns, and then use the reader to read the data from the server. Each chunk is a `WebTransportReceiveStream`, and we use the `readFrom()` set up earlier to read them:

```js
async function receiveUnidirectional() {
  const uds = transport.incomingUnidirectionalStreams;
  const reader = uds.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    // value is an instance of WebTransportReceiveStream
    await readData(value);
  }
}
```

#### Bidirectional transmission

 To open a bidirectional stream from a user agent, you use the `WebTransport.createBidirectionalStream()` method to get a reference to a `WebTransportBidirectionalStream`.
 This contains `readable` and `writable` properties returning references to `WebTransportReceiveStream` and `WebTransportSendStream` instances that can be used to read from and write to the server.

**Note:** `WebTransportBidirectionalStream` is similar to `WebTransportDatagramDuplexStream`, except that in that interface the `readable` and `writable` properties are `ReadableStream` and `WritableStream` respectively.

```js
async function setUpBidirectional() {
  const stream = await transport.createBidirectionalStream();
  // stream is a WebTransportBidirectionalStream
  // stream.readable is a WebTransportReceiveStream
  const readable = stream.readable;
  // stream.writable is a WebTransportSendStream
  const writable = stream.writable;

  ...
}
```

Reading from the `WebTransportReceiveStream` can then be done as follows:

```js
async function readData(readable) {
  const reader = readable.getReader();
  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break;
    }
    // value is a Uint8Array.
    console.log(value);
  }
}
```

And writing to the `WebTransportSendStream` can be done like this:

```js
async function writeData(writable) {
  const writer = writable.getWriter();
  const data1 = new Uint8Array([65, 66, 67]);
  const data2 = new Uint8Array([68, 69, 70]);
  writer.write(data1);
  writer.write(data2);
}
```

If the server opens a bidirectional stream to transmit data to and receive it from the client, this can be accessed via the `WebTransport.incomingBidirectionalStreams` property, which returns a `ReadableStream` of `WebTransportBidirectionalStream` objects. Each one can be used to read and write `Uint8Array` instances as shown above. However, as with the unidirectional example, you need an initial function to read the bidirectional stream in the first place:

```js
async function receiveBidirectional() {
  const bds = transport.incomingBidirectionalStreams;
  const reader = bds.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    // value is an instance of WebTransportBidirectionalStream
    await readData(value.readable);
    await writeData(value.writable);
  }
}
```

Interfaces
----------

`WebTransport`

Provides functionality to enable a user agent to connect to an HTTP/3 server, initiate reliable and unreliable transport in either or both directions, and close the connection once it is no longer needed.

`WebTransportBidirectionalStream`

Represents a bidirectional stream created by a server or a client that can be used for reliable transport. Provides access to a `ReadableStream` for reading incoming data, and a `WritableStream` for writing outgoing data.

`WebTransportDatagramDuplexStream`

Represents a duplex stream that can be used for unreliable transport of datagrams between client and server. Provides access to a `ReadableStream` for reading incoming datagrams, a `WritableStream` for writing outgoing datagrams, and various settings and statistics related to the stream.

`WebTransportError`

Represents an error related to the WebTransport API, which can arise from server errors, network connection problems, or client-initiated abort operations (for example, arising from a `WritableStream.abort()` call).

`WebTransportReceiveStream`

Provides streaming features for an incoming WebTransport unidirectional or bidirectional `WebTransport` stream.

`WebTransportSendStream`

Provides streaming features for an outgoing WebTransport unidirectional or bidirectional `WebTransport` stream.

Examples
--------

For complete examples, see:

* WebTransport over HTTP/3 client
* WebTransport (BYOB) Echo with WebCodecs in Worker
Specifications
--------------

| Specification |
| --- |
| WebTransport # web-transport |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using WebTransport
* WebSockets API
* Streams API
* WebTransport over HTTP/3


BlobEvent - Web APIs

BlobEvent
=========

The **`BlobEvent`** interface of the MediaStream Recording API represents events associated with a `Blob`. These blobs are typically, but not necessarily, associated with media content.

Event

BlobEventConstructor
-----------

`BlobEvent()`

Creates a `BlobEvent` event with the given parameters.

Instance properties
-------------------

*Inherits properties from its parent `Event`*.

`BlobEvent.data` Read only

A `Blob` representing the data associated with the event. The event was fired on the `EventTarget` because of something happening on that specific `Blob`.

`BlobEvent.timecode` Read only

A `DOMHighResTimeStamp` indicating the difference between the timestamp of the first chunk in data and the timestamp of the first chunk in the first BlobEvent produced by this recorder. Note that the timecode in the first produced BlobEvent does not need to be zero.

Instance methods
----------------

*No specific method; inherits methods from its parent `Event`.*

Specifications
--------------

| Specification |
| --- |
| MediaStream Recording # blobevent-section |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `Event` base interface.
* MediaStream Recording API: Sends `BlobEvent` objects each time a chunk of media is ready.
* Using the MediaStream Recording API


HTMLElement - Web APIs

HTMLElement
===========

The **`HTMLElement`** interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.

EventTarget

Node

Element

HTMLElementInstance properties
-------------------

*Also inherits properties from its parent, `Element`.*

`HTMLElement.accessKey`

A string representing the access key assigned to the element.

`HTMLElement.accessKeyLabel` Read only

Returns a string containing the element's assigned access key.

`HTMLElement.attributeStyleMap` Read only

A `StylePropertyMap` representing the declarations of the element's `style` attribute.

`HTMLElement.autofocus`

A boolean value reflecting the `autofocus` HTML global attribute, which indicates whether the control should be focused when the page loads, or when dialog or popover become shown if specified in an element inside `<dialog>` elements or elements whose popover attribute is set.

`HTMLElement.contentEditable`

A string, where a value of `true` means the element is editable and a value of `false` means it isn't.

`HTMLElement.dataset` Read only

Returns a `DOMStringMap` with which script can read and write the element's custom data attributes (`data-*`) .

`HTMLElement.dir`

A string, reflecting the `dir` global attribute, representing the directionality of the element. Possible values are `"ltr"`, `"rtl"`, and `"auto"`.

`HTMLElement.draggable`

A boolean value indicating if the element can be dragged.

`HTMLElement.editContext`
Experimental

Returns the `EditContext` associated with the element, or `null` if there isn't one.

`HTMLElement.enterKeyHint`

A string defining what action label (or icon) to present for the enter key on virtual keyboards.

`HTMLElement.hidden`

A string or boolean value reflecting the value of the element's `hidden` attribute.

`HTMLElement.inert`

A boolean value indicating whether the user agent must act as though the given node is absent for the purposes of user interaction events, in-page text searches ("find in page"), and text selection.

`HTMLElement.innerText`

 Represents the rendered text content of a node and its descendants.
 As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.
 As a setter, it replaces the content inside the selected element, converting any line breaks into `<br>` elements.

`HTMLElement.inputMode`

A string value reflecting the value of the element's `inputmode` attribute.

`HTMLElement.isContentEditable` Read only

Returns a boolean value indicating whether or not the content of the element can be edited.

`HTMLElement.lang`

A string representing the language of an element's attributes, text, and element contents.

`HTMLElement.nonce`

Returns the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed.

`HTMLElement.offsetHeight` Read only

Returns a `double` containing the height of an element, relative to the layout.

`HTMLElement.offsetLeft` Read only

Returns a `double`, the distance from this element's left border to its `offsetParent`'s left border.

`HTMLElement.offsetParent` Read only

An `Element` that is the element from which all offset calculations are currently computed.

`HTMLElement.offsetTop` Read only

Returns a `double`, the distance from this element's top border to its `offsetParent`'s top border.

`HTMLElement.offsetWidth` Read only

Returns a `double` containing the width of an element, relative to the layout.

`HTMLElement.outerText`

 Represents the rendered text content of a node and its descendants.
 As a getter, it is the same as `HTMLElement.innerText` (it represents the rendered text content of an element and its descendants).
 As a setter, it replaces the selected node and its contents with the given value, converting any line breaks into `<br>` elements.

`HTMLElement.popover`

Gets and sets an element's popover state via JavaScript (`"auto"` or `"manual"`), and can be used for feature detection. Reflects the value of the `popover` global HTML attribute.

`HTMLElement.spellcheck`

A boolean value that controls the spell-checking hint. It is available on all HTML elements, though it doesn't affect all of them.

`HTMLElement.style`

A `CSSStyleDeclaration` representing the declarations of the element's `style` attribute.

`HTMLElement.tabIndex`

A `long` representing the position of the element in the tabbing order.

`HTMLElement.title`

A string containing the text that appears in a popup box when mouse is over the element.

`HTMLElement.translate`

A boolean value representing the translation.

`HTMLElement.virtualKeyboardPolicy`
Experimental

A string indicating the on-screen virtual keyboard behavior on devices such as tablets, mobile phones, or other devices where a hardware keyboard may not be available, if the element's content is editable (for example, it is an `<input>` or `<textarea>` element, or an element with the `contenteditable` attribute set).

Instance methods
----------------

*Also inherits methods from its parent, `Element`.*

`HTMLElement.attachInternals()`

Returns an `ElementInternals` object, and enables a custom element to participate in HTML forms.

`HTMLElement.blur()`

Removes keyboard focus from the currently focused element.

`HTMLElement.click()`

Sends a mouse click event to the element.

`HTMLElement.focus()`

Makes the element the current keyboard focus.

`HTMLElement.hidePopover()`

Hides a popover element by removing it from the top layer and styling it with `display: none`.

`HTMLElement.showPopover()`

Shows a popover element by adding it to the top layer and removing `display: none;` from its styles.

`HTMLElement.togglePopover()`

Toggles a popover element between the hidden and showing states.

Events
------

Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

*Also, inherits events from its parent, `Element`.*

`cancel`

Fired for `<input>` and `<dialog>` elements when the user cancels the currently open dialog by closing it with the `Esc` key.

`change`

Fired when the `value` of an `<input>`, `<select>`, or `<textarea>` element has been changed and committed by the user. Unlike the `input` event, the `change` event is not necessarily fired for each alteration to an element's `value`.

`error`

Fired when a resource failed to load, or can't be used.

`load`

Fires for elements containing a resource when the resource has successfully loaded.

### Clipboard events

`copy`

Fired when the user initiates a copy action through the browser's user interface.

`cut`

Fired when the user initiates a cut action through the browser's user interface.

`paste`

Fired when the user initiates a paste action through the browser's user interface.

### Drag & drop events

`drag`

This event is fired when an element or text selection is being dragged.

`dragend`

This event is fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key).

`dragenter`

This event is fired when a dragged element or text selection enters a valid drop target.

`dragleave`

This event is fired when a dragged element or text selection leaves a valid drop target.

`dragover`

This event is fired continuously when an element or text selection is being dragged and the mouse pointer is over a valid drop target (every 50 ms WHEN mouse is not moving ELSE much faster between 5 ms (slow movement) and 1ms (fast movement) approximately. This firing pattern is different than `mouseover` ).

`dragstart`

This event is fired when the user starts dragging an element or text selection.

`drop`

This event is fired when an element or text selection is dropped on a valid drop target.

### Popover events

`beforetoggle`

Fired when the element is a popover, before it is hidden or shown.

`toggle`

Fired when the element is a popover, just after it is hidden or shown.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmlelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Element`


HTMLDListElement - Web APIs

HTMLDListElement
================

The **`HTMLDListElement`** interface provides special properties (beyond those of the regular `HTMLElement` interface it also has available to it by inheritance) for manipulating definition list (`<dl>`) elements.

EventTarget

Node

Element

HTMLElement

HTMLDListElementInstance properties
-------------------

*Inherits properties from its parent, `HTMLElement`.*

`HTMLDListElement.compact`
Deprecated

A boolean value indicating that spacing between list items should be reduced.

Instance methods
----------------

*No specific methods; inherits methods from its parent, `HTMLElement`.*

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmldlistelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The HTML element implementing this interface: `<dl>`


RelativeOrientationSensor - Web APIs

RelativeOrientationSensor
=========================

The **`RelativeOrientationSensor`** interface of the Sensor APIs describes the device's physical orientation without regard to the Earth's reference coordinate system.

To use this sensor, the user must grant permission to the `'accelerometer'`, and `'gyroscope'` device sensors through the Permissions API. In addition, this feature may be blocked by a Permissions Policy set on your server.

EventTarget

Sensor

OrientationSensor

RelativeOrientationSensorConstructor
-----------

`RelativeOrientationSensor()`

Creates a new `RelativeOrientationSensor` object.

Instance properties
-------------------

*No specific properties; inherits properties from its ancestors `OrientationSensor` and `Sensor`.*

Instance methods
----------------

*No specific methods; inherits methods from its ancestors `OrientationSensor` and `Sensor`.*

Events
------

*No specific events; inherits events from its ancestor, `Sensor`.*

Examples
--------

### Basic Example

The following example, which is loosely based on Intel's Orientation Phone demo, instantiates an `RelativeOrientationSensor` with a frequency of 60 times a second.

**Note:** The Intel demo this is based on uses the `AbsoluteOrientationSensor`. On each reading it uses `OrientationSensor.quaternion` to rotate a visual model of a phone.

```js
const options = { frequency: 60, referenceFrame: "device" };
const sensor = new RelativeOrientationSensor(options);

sensor.addEventListener("reading", () => {
  // model is a Three.js object instantiated elsewhere.
  model.quaternion.fromArray(sensor.quaternion).inverse();
});
sensor.addEventListener("error", (error) => {
  if (event.error.name === "NotReadableError") {
    console.log("Sensor is not available.");
  }
});
sensor.start();
```

### Permissions Example

Using orientation sensors requires requesting permissions for multiple device sensors. Because the `Permissions` interface uses promises, a good way to request permissions is to use `Promise.all`.

```js
const sensor = new RelativeOrientationSensor();
Promise.all([
  navigator.permissions.query({ name: "accelerometer" }),
  navigator.permissions.query({ name: "gyroscope" }),
]).then((results) => {
  if (results.every((result) => result.state === "granted")) {
    sensor.start();
    // ...
  } else {
    console.log("No permissions to use RelativeOrientationSensor.");
  }
});
```

Specifications
--------------

| Specification |
| --- |
| Orientation Sensor # relativeorientationsensor-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCSctpTransport - Web APIs

RTCSctpTransport
================

The **`RTCSctpTransport`** interface provides information which describes a Stream Control Transmission Protocol (**SCTP**) transport. This provides information about limitations of the transport, but also provides a way to access the underlying Datagram Transport Layer Security (**DTLS**) transport over which SCTP packets for all of an `RTCPeerConnection`'s data channels are sent and received.

You don't create `RTCSctpTransport` objects yourself; instead, you get access to the `RTCSctpTransport` for a given `RTCPeerConnection` through its **`sctp`** property.

Possibly the most useful property on this interface is its `maxMessageSize` property, which you can use to determine the upper limit on the size of messages you can send over a data channel on the peer connection.

EventTarget

RTCSctpTransportInstance properties
-------------------

*Also inherits properties from: `EventTarget`*.

`RTCSctpTransport.maxChannels` Read only

An integer value indicating the maximum number of `RTCDataChannel` objects that can be opened simultaneously.

`RTCSctpTransport.maxMessageSize` Read only

An integer value indicating the maximum size, in bytes, of a message which can be sent using the `RTCDataChannel.send()` method.

`RTCSctpTransport.state` Read only

A string enumerated value indicating the state of the SCTP transport.

`RTCSctpTransport.transport` Read only

An `RTCDtlsTransport` object representing the DTLS transport used for the transmission and receipt of data packets.

Events
------

Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

`statechange`

Sent when the `RTCSctpTransport.state` changes.

Instance methods
----------------

*This interface has no methods, but inherits methods from: `EventTarget`.*

Example
-------

TBD

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # rtcsctptransport-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC
* `RTCPeerConnection`
* `RTCPeerConnection.sctp`


SVGDescElement - Web APIs

SVGDescElement
==============

The **`SVGDescElement`** interface corresponds to the `<desc>` element.

EventTarget

Node

Element

SVGElement

SVGDescElementInstance properties
-------------------

*This interface also inherits properties from its parent, `SVGGeometryElement`.*

Instance methods
----------------

*This interface has no methods but inherits methods from its parent, `SVGGeometryElement`.*

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # InterfaceSVGDescElement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `<desc>`


USBIsochronousOutTransferResult - Web APIs

USBIsochronousOutTransferResult
===============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The `USBIsochronousOutTransferResult` interface of the WebUSB API provides the result from a call to the `isochronousTransferOut()` method of the `USBDevice` interface. It represents the result from requesting a transfer of data from the USB host to the USB device.

Constructor
-----------

`USBIsochronousOutTransferResult()`
Experimental

Creates a new `USBIsochronousOutTransferResult` object with the provided `packet` field.

Instance properties
-------------------

`USBIsochronousOutTransferResult.packets` Read only
Experimental

Returns an array of `USBIsochronousOutTransferPacket` objects containing the result of each request to send a packet to the device.

Specifications
--------------

| Specification |
| --- |
| WebUSB API # usbisochronousouttransferresult |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


WebVR API - Web APIs

WebVR API
=========

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

**Note:** WebVR API is replaced by WebXR API. WebVR was never ratified as a standard, was implemented and enabled by default in very few browsers and supported a small number of devices.

WebVR provides support for exposing 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. This has numerous, interesting applications, from virtual product tours and interactive training apps to immersive first-person games.

Concepts and usage
------------------

Any VR devices attached to your computer will be returned by the `Navigator.getVRDisplays()` method; each one will be represented by a `VRDisplay` object.

![Sketch of a person in a chair with wearing goggles labelled "Head mounted display (HMD)" facing a monitor with a webcam labelled "Position sensor"](/en-US/docs/Web/API/WebVR_API/hw-setup.png)

`VRDisplay` is the central interface in the WebVR API — via its properties and methods you can access functionality to:

* Retrieve useful information to allow us to identify the display, what capabilities it has, controllers associated with it, and more.
* Retrieve `frame data` for each frame of content you want to present in a display, and submit those frames for display at a consistent rate.
* Start and stop presenting to the display.

A typical (simple) WebVR app would work like so:

1. `Navigator.getVRDisplays()` is used to get a reference to your VR display.
2. `VRDisplay.requestPresent()` is used to start presenting to the VR display.
3. WebVR's dedicated `VRDisplay.requestAnimationFrame()` method is used to run the app's rendering loop at the correct refresh rate for the display.
4. Inside the rendering loop, you grab the data required to display the current frame (`VRDisplay.getFrameData()`), draw the displayed scene twice — once for the view in each eye, then submit the rendered view to the display to show to the user (`VRDisplay.submitFrame()`).

In addition, WebVR 1.1 adds a number of events on the `Window` object to allow JavaScript to respond to changes to the status of the display.

**Note:** You can find a lot more out about how the API works in our Using the WebVR API and WebVR Concepts articles.

### API availability

The WebVR API, which was never ratified as a web standard, has been deprecated in favor of the WebXR API, which is well on track toward finishing the standardization process. As such, you should try to update existing code to use the newer API instead. Generally the transition should be fairly painless.

Additionally, on some devices and/or browsers, WebVR requires that the page be loaded using a secure context, over an HTTPS connection. If the page is not fully secure, the WebVR methods and functions will not be available. You can easily test for this by checking to see if the `Navigator` method `getVRDisplays()` is `NULL`:

```js
if (!navigator.getVRDisplays) {
  console.error("WebVR is not available");
} else {
  /\* Use WebVR \*/
}
```

### Using controllers: Combining WebVR with the Gamepad API

Many WebVR hardware setups feature controllers that go along with the headset. These can be used in WebVR apps via the Gamepad API, and specifically the Gamepad Extensions API that adds API features for accessing controller pose, haptic actuators, and more.

**Note:** Our Using VR controllers with WebVR article explains the basics of how to use VR controllers with WebVR apps.

WebVR interfaces
----------------

`VRDisplay`

Represents any VR device supported by this API. It includes generic information such as device IDs and descriptions, as well as methods for starting to present a VR scene, retrieving eye parameters and display capabilities, and other important functionality.

`VRDisplayCapabilities`

Describes the capabilities of a `VRDisplay` — its features can be used to perform VR device capability tests, for example can it return position information.

`VRDisplayEvent`

Represents the event object of WebVR-related events (see the window object extensions listed below).

`VRFrameData`

Represents all the information needed to render a single frame of a VR scene; constructed by `VRDisplay.getFrameData()`.

`VRPose`

Represents the position state at a given timestamp (which includes orientation, position, velocity, and acceleration).

`VREyeParameters`

Provides access to all the information required to correctly render a scene for each given eye, including field of view information.

`VRFieldOfView`

Represents a field of view defined by 4 different degree values describing the view from a center point.

`VRLayerInit`

Represents a layer to be presented in a `VRDisplay`.

`VRStageParameters`

Represents the values describing the stage area for devices that support room-scale experiences.

### Extensions to other interfaces

The WebVR API extends the following APIs, adding the listed features.

#### Gamepad

`Gamepad.displayId` Read only

*Returns the `VRDisplay.displayId` of the associated `VRDisplay` — the `VRDisplay` that the gamepad is controlling the displayed scene of.*

#### Navigator

`Navigator.activeVRDisplays` Read only

Returns an array containing every `VRDisplay` object that is currently presenting (`VRDisplay.ispresenting` is `true`).

`Navigator.getVRDisplays()`

Returns a promise that resolves to an array of `VRDisplay` objects representing any available VR displays connected to the computer.

#### Window events

`vrdisplaypresentchange`

Fired when the presenting state of a VR display changes — i.e. goes from presenting to not presenting or vice versa.

`vrdisplayconnect`

Fired when a compatible VR display has been connected to the computer.

`vrdisplaydisconnect`

Fired when a compatible VR display has been disconnected from the computer.

`vrdisplayactivate`

Fired when a display is able to be presented to.

`vrdisplaydeactivate`

Fired when a display can no longer be presented to.

Examples
--------

You can find a number of examples at these locations:

* webvr-tests — very simple examples to accompany the MDN WebVR documentation.
* Carmel starter kit — nice simple, well-commented examples that go along with Carmel, Facebook's WebVR browser.
* WebVR.info samples — slightly more in-depth examples plus source code
* WebVR.rocks Firefox demos — showcase examples
* A-Frame homepage — examples showing A-Frame usage
Specifications
--------------

This API was specified in the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* A-Frame — Open source web framework for building VR experiences.
* webvr.info — Up-to-date information about WebVR, browser setup, and community.
* threejs-vr-boilerplate — A useful starter template for writing WebVR apps into.
* Web VR polyfill — JavaScript implementation of WebVR.
* Supermedium — A pure WebVR browser to easily access the best WebVR content.
* WebVR Directory — List of quality WebVR sites.


UIEvent - Web APIs

UIEvent
=======

The **`UIEvent`** interface represents simple user interface events.

`UIEvent` derives from `Event`. Although the `UIEvent.initUIEvent()` method is kept for backward compatibility, you should create a `UIEvent` object using the `UIEvent()` constructor.

Several interfaces are direct or indirect descendants of this one: `MouseEvent`, `TouchEvent`, `FocusEvent`, `KeyboardEvent`, `WheelEvent`, `InputEvent`, and `CompositionEvent`.

Event

UIEventConstructors
------------

`UIEvent()`

Creates a `UIEvent` object.

Instance properties
-------------------

*This interface also inherits properties of its parent, `Event`.*

`UIEvent.detail` Read only

Returns a `long` with details about the event, depending on the event type.

`UIEvent.sourceCapabilities`
Experimental
 Read only

Returns an instance of the `InputDeviceCapabilities` interface, which provides information about the physical device responsible for generating a touch event.

`UIEvent.view` Read only

Returns a WindowProxy that contains the view that generated the event.

`UIEvent.which`
Deprecated
 Read only

Returns the numeric `keyCode` of the key pressed, or the character code (`charCode`) for an alphanumeric key pressed.

Instance methods
----------------

*This interface also inherits methods of its parent, `Event`.*

`UIEvent.initUIEvent()`
Deprecated

Initializes a `UIEvent` object. If the event has already been dispatched, this method does nothing.

Specifications
--------------

| Specification |
| --- |
| UI Events # idl-uievent |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Introduction to events
* `Event`


Permissions API - Web APIs

Permissions API
===============

The **Permissions API** provides a consistent programmatic way to query the status of API permissions attributed to the current context. For example, the Permissions API can be used to determine if permission to access a particular API has been granted or denied, or requires specific user permission.

 Note that the permissions from this API effectively aggregate all security restrictions for the context, including any requirement for an API to be used in a secure context, Permissions-Policy restrictions applied to the document, and user prompts.
 So, for example, if an API is restricted by permissions policy, the returned permission would be `denied` and the user would not be prompted for access.

**Note:** This feature is available in Web Workers

Concepts and usage
------------------

 Historically different APIs handle their own permissions inconsistently — for example the Notifications API provided its own methods for requesting permissions and checking permission status, whereas the Geolocation API did not.
 The Permissions API provides the tools to allow developers to implement a consistent and better user experience for working with permissions.

The `permissions` property has been made available on the `Navigator` object, both in the standard browsing context and the worker context (`WorkerNavigator` — so permission checks are available inside workers), and returns a `Permissions` object that provides access to the Permissions API functionality.

Once you have this object you can then perform permission-related tasks, for example querying a permission using the `Permissions.query()` method to return a promise that resolves with the `PermissionStatus` for a specific API.

### Permission-aware APIs

 Not all APIs' permission statuses can be queried using the Permissions API.
 A non-exhaustive list of permission-aware APIs includes:

* Background Synchronization API: `background-sync` (should always be granted)
* Geolocation API: `geolocation`
* Local Font Access API: `local-fonts`
* Media Capture and Streams API: `microphone`, `camera`
* Notifications API: `notifications`
* Payment Handler API: `payment-handler`
* Push API: `push`
* Sensor APIs: `accelerometer`, `gyroscope`, `magnetometer`, `ambient-light-sensor`
* Storage Access API: `storage-access`, `top-level-storage-access`
* Storage API: `persistent-storage`
* Web MIDI API: `midi`
* Window Management API: `window-management`
Examples
--------

We have created a simple example called Location Finder. You can run the example live, or view the source code on GitHub.

Read more about how it works in our article Using the Permissions API.

Interfaces
----------

`Navigator.permissions` and `WorkerNavigator.permissions` Read only

Provides access to the `Permissions` object from the main context and worker context respectively.

`Permissions`

Provides the core Permission API functionality, such as methods for querying and revoking permissions.

`PermissionStatus`

Provides access to the current status of a permission, and an event handler to respond to changes in permission status.

Specifications
--------------

| Specification |
| --- |
| Permissions  |

Browser compatibility
---------------------

### api.Permissions

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.Navigator.permissions

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.WorkerNavigator.permissions

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Permissions API
* Using the Permissions API to Detect How Often Users Allow or Deny Camera Access
* `Notification.permission`
* Privacy, permissions, and information security