UI Events - Web APIs

UI Events
=========

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

The UI Events API defines a system for handling user interactions such as mouse and keyboard input. This includes:

* events that are fired on specific user actions such keypresses or mouse clicks. Most of these events fire on the `Element` interface, but the events relating to loading and unloading resources fire on the `Window` interface.
* event interfaces, which are passed into handlers for these events. These interfaces inherit from `Event` and provide extra information specific to the type of user interaction: for example, the `KeyboardEvent` is passed into a `keydown` event handler and provides information about the key that was pressed.
Interfaces
----------

`CompositionEvent`

Passed into handlers for composition events. Composition events enable a user to enter characters that might not be available on the physical keyboard.

`FocusEvent`

Passed into handlers for focus events, which are associated with elements receiving or losing focus.

`InputEvent`

Passed into handlers for input events, which are associated with the user entering some input; for example, using an `<input>` element.

`KeyboardEvent`

Passed into handlers for keyboard up/down events.

`MouseEvent`

Passed into event handlers for mouse events, including mouse move, mousing over and out, and mouse button up or down. Note that `auxclick`, `click`, and `dblclick` events are passed `PointerEvent` objects.

`MouseScrollEvent`
Deprecated

Deprecated, Firefox-only, non-standard interface for scroll events. Use `WheelEvent` instead.

`MutationEvent`
Deprecated

Passed into mutation event handlers, which were designed to allow notifications of changes to the DOM. Now deprecated: use `MutationObserver` instead.

`UIEvent`

A base from which other UI events inherit, and also the event interface passed into some events such as `load` and `unload`.

`WheelEvent`

Passed into the handler for the `wheel` event, which fires when the user rotates a mouse wheel or similar user interface component such as a touchpad.

Events
------

`abort`

Fired when loading a resource has been aborted (for example, because the user canceled it).

`auxclick`

Fired when the user clicks the non-primary pointer button.

`beforeinput`

Fired just before the DOM is about to be updated with some user input.

`blur`

Fired when an element has lost focus.

`click`

Fired when the user clicks the primary pointer button.

`compositionend`

Fired when a text composition system (such as a speech-to-text processor) has finished its session; for example, because the user has closed it.

`compositionstart`

Fired when the user has started a new session with a text composition system.

`compositionupdate`

Fired when a text composition system updates its text with a new character, reflected in an update to the `data` property of the `CompositionEvent`.

`contextmenu`

Fired just before a context menu is invoked.

`dblclick`

Fired when the user double-clicks the primary pointer button.

`error`

Fired when a resource fails to load or can't be processed (for example, if an image is invalid or a script has an error).

`focus`

Fired when an element has received focus.

`focusin`

Fired when an element is just about to receive focus.

`focusout`

Fired when an element is just about to lose focus.

`input`

Fired just after the DOM has been updated with some user input (for example, some text input).

`keydown`

Fired when the user has pressed a key.

`keypress`
Deprecated

Fired when the user has pressed a key, only if the key produces a character value. Use `keydown` instead.

`keyup`

Fired when the user has released a key.

`load`

Fired when the whole page has loaded, including all dependent resources such as stylesheets and images.

`mousedown`

Fired when the user presses a button on a mouse or other pointing device, while the pointer is over the element.

`mouseenter`

Fired when a mouse or other pointing device is moved inside the boundary of the element or one of its descendants.

`mouseleave`

Fired when a mouse or other pointing device is moved outside the boundary of the element and all of its descendants.

`mousemove`

Fired when a mouse or other pointing device is moved while over an element.

`mouseout`

Fired when a mouse or other pointing device is moved outside the boundary of the element.

`mouseover`

Fired when a mouse or other pointing device is moved over an element.

`mouseup`

Fired when the user releases a button on a mouse or other pointing device, while the pointer is over the element.

`unload`

Fired when the document or a child resource are being unloaded.

`wheel`

Fired when the user rotates a mouse wheel or similar user interface component such as a touchpad.

Examples
--------

### Mouse events

This example logs mouse events along with the X and Y coordinates at which the event was generated. Try moving the mouse into the yellow and red squares, and clicking or double-clicking.

#### HTML

```html
<div id="outer">
  <div id="inner"></div>
</div>

<div id="log">
  <pre id="contents"></pre>
  <button id="clear">Clear log</button>
</div>
```

#### CSS

```css
body {
  display: flex;
  gap: 1rem;
}

#outer {
  height: 200px;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: yellow;
}

#inner {
  height: 100px;
  width: 100px;
  background-color: red;
}

#contents {
  height: 150px;
  width: 250px;
  border: 1px solid black;
  padding: 0.5rem;
  overflow: scroll;
}
```

#### JavaScript

```js
const outer = document.querySelector("#outer");
const inner = document.querySelector("#inner");
const contents = document.querySelector("#contents");
const clear = document.querySelector("#clear");
let lines = 0;

outer.addEventListener("click", (event) => {
  log(event);
});

outer.addEventListener("dblclick", (event) => {
  log(event);
});

outer.addEventListener("mouseover", (event) => {
  log(event);
});

outer.addEventListener("mouseout", (event) => {
  log(event);
});

outer.addEventListener("mouseenter", (event) => {
  log(event);
});

outer.addEventListener("mouseleave", (event) => {
  log(event);
});

function log(event) {
  const prefix = `${String(lines++).padStart(3, "0")}: `;
  const line = `${event.type}(${event.clientX}, ${event.clientY})`;
  contents.textContent = `${contents.textContent}${prefix}${line}\n`;
  contents.scrollTop = contents.scrollHeight;
}

clear.addEventListener("click", () => {
  contents.textContent = "";
  lines = 0;
});
```

#### Result

### Keyboard and input events

This example logs `keydown`, `beforeinput` and, `input` events. Try typing into the text area. Note that keys like `Shift` produce `keydown` events but not `input` events.

#### HTML

```html
<textarea id="story" rows="5" cols="33"></textarea>

<div id="log">
  <pre id="contents"></pre>
  <button id="clear">Clear log</button>
</div>
```

#### CSS

```css
body {
  display: flex;
  gap: 1rem;
}

#story {
  padding: 0.5rem;
}

#contents {
  height: 150px;
  width: 250px;
  border: 1px solid black;
  padding: 0.5rem;
  overflow: scroll;
}
```

#### JavaScript

```js
const story = document.querySelector("#story");
const contents = document.querySelector("#contents");
const clear = document.querySelector("#clear");
let lines = 0;

story.addEventListener("keydown", (event) => {
  log(`${event.type}(${event.key})`);
});

story.addEventListener("beforeinput", (event) => {
  log(`${event.type}(${event.data})`);
});

story.addEventListener("input", (event) => {
  log(`${event.type}(${event.data})`);
});

function log(line) {
  const prefix = `${String(lines++).padStart(3, "0")}: `;
  contents.textContent = `${contents.textContent}${prefix}${line}\n`;
  contents.scrollTop = contents.scrollHeight;
}

clear.addEventListener("click", () => {
  contents.textContent = "";
  lines = 0;
});
```

#### Result

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

| Specification |
| --- |
| UI Events  |

See also
--------

* Pointer Events API
* Touch Events


TextTrack - Web APIs

TextTrack
=========

The `TextTrack` interface—part of the API for handling WebVTT (text tracks on media presentations)—describes and controls the text track associated with a particular `<track>` element.

EventTarget

TextTrackInstance properties
-------------------

*This interface also inherits properties from `EventTarget`.*

`TextTrack.activeCues` Read only

A `TextTrackCueList` object listing the currently active set of text track cues. Track cues are active if the current playback position of the media is between the cues' start and end times. Thus, for displayed cues such as captions or subtitles, the active cues are currently being displayed.

`TextTrack.cues` Read only

A `TextTrackCueList` which contains all of the track's cues.

`TextTrack.id` Read only

A string which identifies the track, if it has one. If it doesn't have an ID, then this value is an empty string (`""`). If the `TextTrack` is associated with a `<track>` element, then the track's ID matches the element's ID.

`TextTrack.inBandMetadataTrackDispatchType` Read only

Returns a string which indicates the track's in-band metadata track dispatch type.

`TextTrack.kind` Read only

Returns a string indicating what kind of text track the `TextTrack` describes. It must be one of the permitted values.

`TextTrack.label` Read only

A human-readable string which contains the text track's label, if one is present; otherwise, this is an empty string (`""`), in which case a custom label may need to be generated by your code using other attributes of the track, if the track's label needs to be exposed to the user.

`TextTrack.language` Read only

A string which specifies the text language in which the text track's contents is written. The value must adhere to the format specified in RFC 5646: Tags for Identifying Languages (also known as BCP 47), just like the HTML `lang` attribute. For example, this can be `"en-US"` for United States English or `"pt-BR"` for Brazilian Portuguese.

`TextTrack.mode`

A string specifying the track's current mode, which must be one of the permitted values. Changing this property's value changes the track's current mode to match. The default is `disabled`, unless the `<track>` element's `default` boolean attribute is set to `true` — in which case the default mode is `showing`.

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

*This interface also inherits methods from `EventTarget`.*

**Note:** The `TextTrackCue` interface is an abstract class used as the parent for other cue interfaces such as `VTTCue`. Therefore, when adding or removing a cue you will be passing in one of the cue types that inherit from `TextTrackCue`.

`TextTrack.addCue()`

Adds a cue (specified as a `TextTrackCue` object) to the track's list of cues.

`TextTrack.removeCue()`

Removes a cue (specified as a `TextTrackCue` object) from the track's list of cues.

Events
------

`cuechange`

 Fired when cues are entered and exited. A given text cue appears when the cue is entered and disappears when the cue is exited.
 Also available via the `oncuechange` property.

Example
-------

The following example adds a new `TextTrack` to a video, then sets it to display using `TextTrack.mode`.

```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
```

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

| Specification |
| --- |
| HTML Standard # texttrack |

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

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

See also
--------

* WebVTT
* `TextTrackCueList`
* `VTTCue`
* `<track>`
* `HTMLTrackElement`


CustomElementRegistry - Web APIs

CustomElementRegistry
=====================

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
The **`CustomElementRegistry`** interface provides methods for registering custom elements and querying registered elements. To get an instance of it, use the `window.customElements` property.

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

`CustomElementRegistry.define()`

Defines a new custom element.

`CustomElementRegistry.get()`

Returns the constructor for the named custom element, or `undefined` if the custom element is not defined.

`CustomElementRegistry.getName()`

Returns the name for the already-defined custom element, or `null` if the custom element is not defined.

`CustomElementRegistry.upgrade()`

Upgrades a custom element directly, even before it is connected to its shadow root.

`CustomElementRegistry.whenDefined()`

Returns an empty `Promise` that resolves when a custom element becomes defined with the given name. If such a custom element is already defined, the returned promise is immediately fulfilled.

Examples
--------

See the Examples section in our guide to using custom elements.

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

| Specification |
| --- |
| HTML Standard # custom-elements-api |

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

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


OES_texture_float_linear extension - Web APIs

OES\_texture\_float\_linear extension
=====================================

The **`OES_texture_float_linear`** extension is part of the WebGL API and allows linear filtering with floating-point pixel types for textures.

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

**Note:** This extension is available to both, WebGL1 and WebGL2 contexts.

Linear filtering
----------------

The `OES_texture_float` extension alone does not allow linear filtering with floating-point textures. This extension enables this ability.

With the help of this extension, you can now set the magnification or minification filter in the `WebGLRenderingContext.texParameter()` method to one of `gl.LINEAR`, `gl.LINEAR_MIPMAP_NEAREST`, `gl.NEAREST_MIPMAP_LINEAR`, or `gl.LINEAR_MIPMAP_LINEAR`, and use floating-point textures.

Examples
--------

```js
gl.getExtension("OES\_texture\_float");
gl.getExtension("OES\_texture\_float\_linear");

const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE\_2D, texture);

gl.texParameterf(gl.TEXTURE\_2D, gl.TEXTURE\_MAG\_FILTER, gl.LINEAR);
gl.texImage2D(gl.TEXTURE\_2D, 0, gl.RGBA, gl.RGBA, gl.FLOAT, image);
```

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

| Specification |
| --- |
| WebGL OES\_texture\_float\_linear 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()`
* `WebGLRenderingContext.texImage2D()`
* `WebGLRenderingContext.texSubImage2D()`
* `OES_texture_float`
* `OES_texture_half_float`
* `OES_texture_half_float_linear`


SensorErrorEvent - Web APIs

SensorErrorEvent
================

The **`SensorErrorEvent`** interface of the Sensor APIs provides information about errors thrown by a `Sensor` or derived interface.

Event

SensorErrorEventConstructor
-----------

`SensorErrorEvent()`

Creates a new `SensorErrorEvent` object.

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

`SensorErrorEvent.error` Read only

Returns the `DOMException` object passed in the event's constructor.

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

| Specification |
| --- |
| Generic Sensor API # the-sensor-error-event-interface |

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

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


EcKeyImportParams - Web APIs

EcKeyImportParams
=================

The **`EcKeyImportParams`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()` or `SubtleCrypto.unwrapKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as either of ECDSA or ECDH.

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

`name`

A string. This should be set to `ECDSA` or `ECDH`, depending on the algorithm you want to use.

`namedCurve`

A string representing the name of the elliptic curve to use. This may be any of the following names for NIST-approved curves:

* `P-256`
* `P-384`
* `P-521`

Examples
--------

See the examples for `SubtleCrypto.importKey()`.

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

| Specification |
| --- |
| Web Cryptography API # dfn-EcKeyImportParams |

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

Browsers that support the "ECDH" or "ECDSA" algorithms for the `SubtleCrypto.importKey()` or `SubtleCrypto.wrapKey()` methods will support this type.

See also
--------

* `SubtleCrypto.importKey()`.
* `SubtleCrypto.unwrapKey()`.


XRTransientInputHitTestSource - Web APIs

XRTransientInputHitTestSource
=============================

**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 **`XRTransientInputHitTestSource`** interface of the WebXR Device API handles transient input hit test subscriptions. You can get an `XRTransientInputHitTestSource` object by calling the `XRSession.requestHitTestSourceForTransientInput()`.

This object doesn't itself contain transient input hit test results, but it is used to compute hit tests for each `XRFrame` by calling `XRFrame.getHitTestResultsForTransientInput()`, which returns `XRTransientInputHitTestResult` objects.

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

None.

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

`XRTransientInputHitTestSource.cancel()`
Experimental

Unsubscribes from the transient input hit test.

Examples
--------

### Getting an `XRTransientInputHitTestSource` object for a session

Use the `XRSession.requestHitTestSourceForTransientInput()` method to get a transient input hit test source.

```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
  requiredFeatures: ["local", "hit-test"],
});

let transientHitTestSource = null;

xrSession
  .requestHitTestSourceForTransientInput({
    profile: "generic-touchscreen",
    offsetRay: new XRRay(),
  })
  .then((touchScreenHitTestSource) => {
    transientHitTestSource = touchScreenHitTestSource;
  });

// frame loop
function onXRFrame(time, xrFrame) {
  let hitTestResults = xrFrame.getHitTestResultsForTransientInput(
    transientHitTestSource,
  );

  // do things with the transient hit test results
}
```

### Unsubscribe from a transient input hit test

To unsubscribe from a transient input hit test source, use the `XRTransientInputHitTestSource.cancel()` method. Since the object will no longer be usable, you can clean up and set the `XRTransientInputHitTestSource` object to `null`.

```js
transientHitTestSource.cancel();
transientHitTestSource = null;
```

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

| Specification |
| --- |
| WebXR Hit Test Module # transient-input-hit-test-source-interface |

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

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

See also
--------

* `XRTransientInputHitTestResult`


CSSMathValue - Web APIs

CSSMathValue
============

The **`CSSMathValue`** interface of the CSS\_Object\_Model#css\_typed\_object\_model a base class for classes representing complex numeric values.

CSSStyleValue

CSSNumericValue

CSSMathValueInterfaces based on CSSMathValue
--------------------------------

Below is a list of interfaces based on the CSSMathValue interface.

* `CSSMathInvert`
* `CSSMathMax`
* `CSSMathMin`
* `CSSMathNegate`
* `CSSMathProduct`
* `CSSMathSum`
Instance properties
-------------------

`CSSMathValue.operator`

Indicates the operator that the current subtype represents.

Static methods
--------------

*The interface may also inherit methods from its parent interface, `CSSNumericValue`.*

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

*The interface may also inherit methods from its parent interface, `CSSNumericValue`.*

Event handlers
--------------

No

Examples
--------

We create an element with a `width` determined using a `calc()` function, then `console.log()` the `operator`.

```html
<div>has width</div>
```

We assign a `width` with a calculation

```css
div {
  width: calc(30% - 20px);
}
```

We add the JavaScript

```js
const styleMap = document.querySelector("div").computedStyleMap();

console.log(styleMap.get("width")); // CSSMathSum {values: CSSNumericArray, operator: "sum"}
console.log(styleMap.get("width").operator); // 'sum'
console.log(styleMap.get("width").values[1].value); // -20
```

The `CSSMathValue.operator` returns '`sum`' because `styleMap.get('width').values[1].value );` is `-20`: adding a negative number.

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

| Specification |
| --- |
| CSS Typed OM Level 1 # complex-numeric |

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

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


NodeIterator - Web APIs

NodeIterator
============

The **`NodeIterator`** interface represents an iterator to traverse nodes of a DOM subtree in document order.

Syntax
------

A `NodeIterator` can be created using the `Document.createNodeIterator()` method, as follows:

```js
const nodeIterator = document.createNodeIterator(root, whatToShow, filter);
```

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

*This interface doesn't inherit any property.*

`NodeIterator.root` Read only

 Returns a `Node` representing the root node, as specified when the
 `NodeIterator` was created.

`NodeIterator.whatToShow` Read only

 Returns an `unsigned long` bitmask that describes the types of `Node`
 to be matched. Non-matching nodes are skipped, but relevant child nodes may be included.

The possible bitmask values are constants from the `NodeFilter` interface:

| Constant | Numerical value | Description |
| --- | --- | --- |
| `NodeFilter.SHOW_ALL` | `4294967295` (that is the max value of `unsigned long`) | Shows all nodes. |
| `NodeFilter.SHOW_ATTRIBUTE`
Deprecated
 | `2` | Shows attribute `Attr` nodes. This is meaningful only when creating a `NodeIterator` with an `Attr` node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree. |
| `NodeFilter.SHOW_CDATA_SECTION`
Deprecated
 | `8` | Shows `CDATASection` nodes. |
| `NodeFilter.SHOW_COMMENT` | `128` | Shows `Comment` nodes. |
| `NodeFilter.SHOW_DOCUMENT` | `256` | Shows `Document` nodes. |
| `NodeFilter.SHOW_DOCUMENT_FRAGMENT` | `1024` | Shows `DocumentFragment` nodes. |
| `NodeFilter.SHOW_DOCUMENT_TYPE` | `512` | Shows `DocumentType` nodes. |
| `NodeFilter.SHOW_ELEMENT` | `1` | Shows `Element` nodes. |
| `NodeFilter.SHOW_ENTITY`
Deprecated
 | `32` | Legacy, no longer used. |
| `NodeFilter.SHOW_ENTITY_REFERENCE`
Deprecated
 | `16` | Legacy, no longer used. |
| `NodeFilter.SHOW_NOTATION`
Deprecated
 | `2048` | Legacy, no longer used. |
| `NodeFilter.SHOW_PROCESSING_INSTRUCTION` | `64` | Shows `ProcessingInstruction` nodes. |
| `NodeFilter.SHOW_TEXT` | `4` | Shows `Text` nodes. |

`NodeIterator.filter` Read only

Returns a `NodeFilter` used to select the relevant nodes.

`NodeIterator.referenceNode` Read only

Experimental

Returns the `Node` to which the iterator is anchored.

`NodeIterator.pointerBeforeReferenceNode` Read only

Returns a boolean indicating whether or not the `NodeIterator` is anchored *before* the `NodeIterator.referenceNode`. If `false`, it indicates that the iterator is anchored *after* the reference node.

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

*This interface doesn't inherit any method.*

`NodeIterator.detach()`
Deprecated

 This is a legacy method, and no longer has any effect. Previously it served to mark a
 `NodeIterator` as disposed, so it could be reclaimed by garbage collection.

`NodeIterator.previousNode()`

Returns the previous `Node` in the document, or `null` if there are none.

`NodeIterator.nextNode()`

Returns the next `Node` in the document, or `null` if there are none.

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

| Specification |
| --- |
| DOM Standard # interface-nodeiterator |

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

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

See also
--------

* The creator method: `Document.createNodeIterator()`.
* Related interface: `TreeWalker`


RTCIceTransport - Web APIs

RTCIceTransport
===============

 The **`RTCIceTransport`** interface provides access to information about the ICE transport layer over which the data is being sent and received.
 This is particularly useful if you need to access state information about the connection.

EventTarget

RTCIceTransportInstance properties
-------------------

*The `RTCIceTransport` interface inherits properties from its parent, `EventTarget`. It also offers the following properties:*

`component` Read only

The ICE component being used by the transport. The value is one of the strings from the `RTCIceTransport` enumerated type: `"RTP"` or `"RTSP"`.

`gatheringState` Read only

A string indicating which current gathering state of the ICE agent: `"new"`, `"gathering"`, or `"complete"`.

`role` Read only

Returns a string whose value is either `"controlling"` or `"controlled"`; this indicates whether the ICE agent is the one that makes the final decision as to the candidate pair to use or not.

`state` Read only

A string indicating what the current state of the ICE agent is. The value of `state` can be used to determine whether the ICE agent has made an initial connection using a viable candidate pair (`"connected"`), made its final selection of candidate pairs (`"completed"`), or in an error state (`"failed"`), among other states.

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

*Also includes methods from `EventTarget`, the parent interface.*

`getLocalCandidates()`

Returns an array of `RTCIceCandidate` objects, each describing one of the ICE candidates that have been gathered so far for the local device. These are the same candidates which have already been sent to the remote peer by sending an `icecandidate` event to the `RTCPeerConnection` for transmission.

`getLocalParameters()`

Returns a `RTCIceParameters` object describing the ICE parameters established by a call to the `RTCPeerConnection.setLocalDescription()` method. Returns `null` if parameters have not yet been received.

`getRemoteCandidates()`

Returns an array of `RTCIceCandidate` objects, one for each of the remote device's ICE candidates that have been received by the local end of the `RTCPeerConnection` and delivered to ICE by calling `addIceCandidate()`.

`getRemoteParameters()`

Returns a `RTCIceParameters` object containing the ICE parameters for the remote device, as set by a call to `RTCPeerConnection.setRemoteDescription()`. If `setRemoteDescription()` hasn't been called yet, the return value is `null`.

`getSelectedCandidatePair()`

Returns a `RTCIceCandidatePair` object that identifies the two candidates—one for each end of the connection—that have been selected so far. It's possible that a better pair will be found and selected later; if you need to keep up with this, watch for the `selectedcandidatepairchange` event. If no candidate pair has been selected yet, the return value is `null`.

Events
------

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

`gatheringstatechange`

 Sent to the `RTCIceTransport` object to indicate that the value of the `gatheringState` property has changed, indicating a change in this transport's ICE candidate negotiation process.
 Also available through the `ongatheringstatechange` event handler property.

`selectedcandidatepairchange`

 Sent to the `RTCIceTransport` when a new, better pair of candidates has been selected to describe the connectivity between the two peers. This occurs during negotiation or renegotiation, including after an ICE restart, which reuses the existing `RTCIceTransport` objects. The current candidate pair can be obtained using `getSelectedCandidatePair()`.
 Also available using the `onselectedcandidatepairchange` event handler property.

`statechange`

 Sent to the `RTCIceTransport` instance when the value of the `state` property has changed, indicating that the ICE gathering process has changed state.
 Also available through the `onstatechange` event handler property.

Examples
--------

tbd

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcicetransport |

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

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


KeyboardEvent - Web APIs

KeyboardEvent
=============

**`KeyboardEvent`** objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. The event type (`keydown`, `keypress`, or `keyup`) identifies what kind of keyboard activity occurred.

**Note:** `KeyboardEvent` events just indicate what interaction the user had with a key on the keyboard at a low level, providing no contextual meaning to that interaction. When you need to handle text input, use the `input` event instead. Keyboard events may not be fired if the user is using an alternate means of entering text, such as a handwriting system on a tablet or graphics tablet.

Event

UIEvent

KeyboardEventConstructor
-----------

`KeyboardEvent()`

Creates a new `KeyboardEvent` object.

Constants
---------

The `KeyboardEvent` interface defines the following constants.

### Keyboard locations

The following constants identify which part of the keyboard the key event originates from. They are accessed as `KeyboardEvent.DOM_KEY_LOCATION_STANDARD` and so forth.

Keyboard location identifiers| Constant | Value | Description |
| --- | --- | --- |
| `DOM_KEY_LOCATION_STANDARD` | 0x00 |
 The key described by the event is not identified as being located in a
 particular area of the keyboard; it is not located on the numeric
 keypad (unless it's the NumLock key), and for keys that are duplicated
 on the left and right sides of the keyboard, the key is, for whatever
 reason, not to be associated with that location.

 Examples include alphanumeric keys on the standard PC 101 US keyboard,
 the NumLock key, and the space bar.
  |
| `DOM_KEY_LOCATION_LEFT` | 0x01 |
 The key is one which may exist in multiple locations on the keyboard
 and, in this instance, is on the left side of the keyboard.

 Examples include the left Control key, the left Command key on a
 Macintosh keyboard, or the left Shift key.
  |
| `DOM_KEY_LOCATION_RIGHT` | 0x02 |
 The key is one which may exist in multiple positions on the keyboard
 and, in this case, is located on the right side of the keyboard.

 Examples include the right Shift key and the right Alt key (Option on
 a Mac keyboard).
  |
| `DOM_KEY_LOCATION_NUMPAD` | 0x03 |
 The key is located on the numeric keypad, or is a virtual key
 associated with the numeric keypad if there's more than one place the
 key could originate from. The NumLock key does not fall into this
 group and is always encoded with the location
 `DOM_KEY_LOCATION_STANDARD`.

 Examples include the digits on the numeric keypad, the keypad's Enter
 key, and the decimal point on the keypad.
  |

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

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`KeyboardEvent.altKey` Read only

Returns a boolean value that is `true` if the `Alt` (`Option` or `⌥` on macOS) key was active when the key event was generated.

`KeyboardEvent.code` Read only

Returns a string with the code value of the physical key represented by the event.

**Warning:** This ignores the user's keyboard layout, so that if the user presses the key at the "Y" position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return "KeyY", even if the user has a QWERTZ keyboard (which would mean the user expects a "Z" and all the other properties would indicate a "Z") or a Dvorak keyboard layout (where the user would expect an "F"). If you want to display the correct keystrokes to the user, you can use `Keyboard.getLayoutMap()`.

`KeyboardEvent.ctrlKey` Read only

Returns a boolean value that is `true` if the `Ctrl` key was active when the key event was generated.

`KeyboardEvent.isComposing` Read only

Returns a boolean value that is `true` if the event is fired between after `compositionstart` and before `compositionend`.

`KeyboardEvent.key` Read only

Returns a string representing the key value of the key represented by the event.

`KeyboardEvent.location` Read only

Returns a number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown above in Keyboard locations.

`KeyboardEvent.metaKey` Read only

Returns a boolean value that is `true` if the `Meta` key (on Mac keyboards, the `⌘ Command` key; on Windows keyboards, the Windows key (`⊞`)) was active when the key event was generated.

`KeyboardEvent.repeat` Read only

Returns a boolean value that is `true` if the key is being held down such that it is automatically repeating.

`KeyboardEvent.shiftKey` Read only

Returns a boolean value that is `true` if the `Shift` key was active when the key event was generated.

### Obsolete properties

`KeyboardEvent.charCode`
Deprecated
 Read only

Returns a number representing the Unicode reference number of the key; this property is used only by the `keypress` event. For keys whose `char` property contains multiple characters, this is the Unicode value of the first character in that property. In Firefox 26 this returns codes for printable characters.

**Warning:** This property is deprecated; you should use `KeyboardEvent.key` instead, if available.

`KeyboardEvent.keyCode`
Deprecated
 Read only

Returns a number representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key.

**Warning:** This property is deprecated; you should use `KeyboardEvent.key` instead, if available.

`KeyboardEvent.keyIdentifier`
Non-standard

Deprecated
 Read only

This property is non-standard and has been deprecated in favor of `KeyboardEvent.key`. It was part of an old version of DOM Level 3 Events.

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

*This interface also inherits methods of its parents, `UIEvent` and `Event`.*

`KeyboardEvent.getModifierState()`

Returns a boolean value indicating if a modifier key such as `Alt`, `Shift`, `Ctrl`, or `Meta`, was pressed when the event was created.

### Obsolete methods

`KeyboardEvent.initKeyEvent()`
Deprecated

Initializes a `KeyboardEvent` object. This was implemented only by Firefox, and is no longer supported even there; instead, you should use the `KeyboardEvent()` constructor.

`KeyboardEvent.initKeyboardEvent()`
Deprecated

Initializes a `KeyboardEvent` object. This is now deprecated. You should instead use the `KeyboardEvent()` constructor.

Events
------

The following events are based on the `KeyboardEvent` type. In the list below, each event links to the documentation for the `Element` handler for the event, which applies generally to all of the recipients, including `Element`, `Document`, and `Window`.

`keydown`

A key has been pressed.

`keyup`

A key has been released.

### Obsolete events

`keypress`
Deprecated

A key that normally produces a character value has been pressed. This event was highly device-dependent and is obsolete. You should not use it.

Usage notes
-----------

There are three types of keyboard events: `keydown`, `keypress`, and `keyup`. For most keys, Gecko dispatches a sequence of key events like this:

1. When the key is first pressed, the `keydown` event is sent.
2. If the key is not a modifier key, the `keypress` event is sent.
3. When the user releases the key, the `keyup` event is sent.
### Special cases

Some keys toggle the state of an indicator light; these include keys such as Caps Lock, Num Lock, and Scroll Lock. On Windows and Linux, these keys dispatch only the `keydown` and `keyup` events.

**Note:** On Linux, Firefox 12 and earlier also dispatched the `keypress` event for these keys.

However, a limitation of the macOS event model causes Caps Lock to dispatch only the `keydown` event. Num Lock was supported on some older laptop models (2007 models and older), but since then, macOS hasn't supported Num Lock even on external keyboards. On older MacBooks with a Num Lock key, that key doesn't generate any key events. Gecko does support the Scroll Lock key if an external keyboard which has an F14 key is connected. In certain older versions of Firefox, this key generated a `keypress` event; this inconsistent behavior was Firefox bug 602812.

### Auto-repeat handling

When a key is pressed and held down, it begins to auto-repeat. This results in a sequence of events similar to the following being dispatched:

1. `keydown`
2. `keypress`
3. `keydown`
4. `keypress`
5. <<repeating until the user releases the key>>
6. `keyup`

This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.

#### Auto-repeat on some GTK environments such as Ubuntu 9.4

In some GTK-based environments, auto-repeat dispatches a native key-up event automatically during auto-repeat, and there's no way for Gecko to know the difference between a repeated series of keypresses and an auto-repeat. On those platforms, then, an auto-repeat key will generate the following sequence of events:

1. `keydown`
2. `keypress`
3. `keyup`
4. `keydown`
5. `keypress`
6. `keyup`
7. <<repeating until the user releases the key>>
8. `keyup`

In these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.

Example
-------

```js
document.addEventListener(
  "keydown",
  (event) => {
    const keyName = event.key;

    if (keyName === "Control") {
      // do not alert when only Control key is pressed.
      return;
    }

    if (event.ctrlKey) {
      // Even though event.key is not 'Control' (e.g., 'a' is pressed),
      // event.ctrlKey may be true if Ctrl key is pressed at the same time.
      alert(`Combination of ctrlKey + ${keyName}`);
    } else {
      alert(`Key pressed ${keyName}`);
    }
  },
  false,
);

document.addEventListener(
  "keyup",
  (event) => {
    const keyName = event.key;

    // As the user releases the Ctrl key, the key is no longer active,
    // so event.ctrlKey is false.
    if (keyName === "Control") {
      alert("Control key was released");
    }
  },
  false,
);
```

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

| Specification |
| --- |
| UI Events # interface-keyboardevent |

The `KeyboardEvent` interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, `KeyboardEvent.initKeyEvent()` by Gecko browsers and the early DOM Events Level 3 version, `KeyboardEvent.initKeyboardEvent()` by others. Both have been superseded by the modern usage of a constructor: `KeyboardEvent()`.

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

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

### Compatibility notes

* As of Firefox 65, the `keypress` event is no longer fired for non-printable keys (Firefox bug 968056), except for the
 `Enter`
 key, and the
 `Shift`
 +
 `Enter`
 and
 `Ctrl`
 +
 `Enter`
 key combinations (these were kept for cross-browser compatibility purposes).
See also
--------

* `KeyboardEvent.code`.
* `KeyboardEvent.key`.
* `KeyboardEvent.getModifierState()`


HTMLPictureElement - Web APIs

HTMLPictureElement
==================

The **`HTMLPictureElement`** interface represents a `<picture>` HTML element. It doesn't implement specific properties or methods.

EventTarget

Node

Element

HTMLElement

HTMLPictureElementInstance properties
-------------------

*No specific property, but inherits properties from its parent, `HTMLElement`.*

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

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

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

| Specification |
| --- |
| HTML Standard # htmlpictureelement |

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

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

See also
--------

* The `<picture>` HTML element that implements it.
* The `HTMLImageElement` and `HTMLSourceElement` interfaces, often used in conjunction with a `<picture>` element.


HTMLUListElement - Web APIs

HTMLUListElement
================

The **`HTMLUListElement`** interface provides special properties (beyond those defined on the regular `HTMLElement` interface it also has available to it by inheritance) for manipulating unordered list (`<ul>`) elements.

EventTarget

Node

Element

HTMLElement

HTMLUListElementInstance properties
-------------------

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

`HTMLUListElement.type`
Deprecated

A string value reflecting the `type` and defining the kind of marker to be used to display. The values are browser dependent and have never been standardized.

`HTMLUListElement.compact`
Deprecated

A boolean value indicating that spacing between list items should be reduced. This property reflects the `compact` attribute only, it doesn't consider the `line-height` CSS property used for that behavior in modern pages.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlulistelement |

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: `<ul>`.


TrustedTypePolicy - Web APIs

TrustedTypePolicy
=================

The **`TrustedTypePolicy`** interface of the `Trusted Types API` defines a group of functions which create `TrustedType` objects.

A `TrustedTypePolicy` object is created by `TrustedTypePolicyFactory.createPolicy()` to define a policy for enforcing security rules on input. Therefore, `TrustedTypePolicy` has no constructor.

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

`TrustedTypePolicy.name` Read only

A string containing the name of the policy.

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

`TrustedTypePolicy.createHTML()`

Creates a `TrustedHTML` object.

`TrustedTypePolicy.createScript()`

Creates a `TrustedScript` object.

`TrustedTypePolicy.createScriptURL()`

Creates a `TrustedScriptURL` object.

Examples
--------

In the below example we create a policy that will create `TrustedHTML` objects using `TrustedTypePolicyFactory.createPolicy()`. We can then use `TrustedTypePolicy.createHTML` to create a sanitized HTML string to be inserted into the document.

The sanitized value can then be used with `Element.innerHTML` to ensure that no new HTML elements can be injected.

```html
<div id="myDiv"></div>
```

```js
const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {
  createHTML: (string) => string.replace(/>/g, "<"),
});

let el = document.getElementById("myDiv");
const escaped = escapeHTMLPolicy.createHTML("<img src=x onerror=alert(1)>");
console.log(escaped instanceof TrustedHTML); // true
el.innerHTML = escaped;
```

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

| Specification |
| --- |
| Trusted Types # trusted-type-policy |

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

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


VRFrameData - Web APIs

VRFrameData
===========

**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.

The **`VRFrameData`** interface of the WebVR API represents all the information needed to render a single frame of a VR scene; constructed by `VRDisplay.getFrameData()`.

**Note:** This interface was part of the old WebVR API. It has been superseded by the WebXR Device API.

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

`VRFrameData()`
Deprecated

Non-standard

Creates a `VRFrameData` object instance.

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

`VRFrameData.leftProjectionMatrix`
Deprecated
 Read only
Non-standard

A `Float32Array` representing a 4x4 matrix that describes the projection to be used for the left eye's rendering.

`VRFrameData.leftViewMatrix`
Deprecated
 Read only
Non-standard

A `Float32Array` representing a 4x4 matrix that describes the view transform to be used for the left eye's rendering.

`VRFrameData.pose`
Deprecated
 Read only
Non-standard

The `VRPose` of the `VRDisplay` at the current `VRFrameData.timestamp`.

`VRFrameData.rightProjectionMatrix`
Deprecated
 Read only
Non-standard

A `Float32Array` representing a 4x4 matrix that describes the projection to be used for the right eye's rendering.

`VRFrameData.rightViewMatrix`
Deprecated
 Read only
Non-standard

A `Float32Array` representing a 4x4 matrix that describes the view transform to be used for the right eye's rendering.

`VRFrameData.timestamp`
Deprecated
 Read only
Non-standard

A constantly increasing timestamp value representing the time a frame update occurred.

Examples
--------

See `VRDisplay.getFrameData()` for example code.

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

This interface was part of 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
--------

* WebVR API


CSSPageRule - Web APIs

CSSPageRule
===========

**`CSSPageRule`** represents a single CSS `@page` rule.

CSSRule

CSSGroupingRule

CSSPageRuleInstance properties
-------------------

*Inherits properties from its ancestor `CSSRule`.*

`CSSPageRule.selectorText`

Represents the text of the page selector associated with the at-rule.

`CSSPageRule.style` Read only

Returns the declaration block associated with the at-rule.

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

*Inherits methods from its ancestor `CSSRule`.*

Examples
--------

The stylesheet includes a single `@page` rule, therefore the first (and only) rule returned will be a `CSSPageRule`.

```css
@page {
  margin: 1cm;
}
```

```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); // a CSSPageRule
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # the-csspagerule-interface |

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

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


XMLSerializer - Web APIs

XMLSerializer
=============

The `XMLSerializer` interface provides the `serializeToString()` method to construct an XML string representing a DOM tree.

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

`XMLSerializer()`

Creates a new `XMLSerializer` object.

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

`serializeToString()`

Returns the serialized subtree of a string.

Examples
--------

### Serializing XML into a string

This example just serializes an entire document into a string containing XML.

```js
const s = new XMLSerializer();
const str = s.serializeToString(document);
saveXML(str);
```

This involves creating a new `XMLSerializer` object, then passing the `Document` to be serialized into `serializeToString()`, which returns the XML equivalent of the document. `saveXML()` represents a function that would then save the serialized string.

### Inserting nodes into a DOM based on XML

This example uses the `Element.insertAdjacentHTML()` method to insert a new DOM `Node` into the body of the `Document`, based on XML created by serializing an `Element` object.

**Note:** In the real world, you should usually instead call `importNode()` method to import the new node into the DOM, then call one of the following methods to add the node to the DOM tree:

* The `Element.append()`/`Element.prepend()` and `Document.append()`/`Document.prepend()` methods.
* The `Element.replaceWith` method (to replace an existing node with the new one)
* The `Element.insertAdjacentElement()` method.

Because `insertAdjacentHTML()` accepts a string and not a `Node` as its second parameter, `XMLSerializer` is used to first convert the node into a string.

```js
const inp = document.createElement("input");
const XMLS = new XMLSerializer();
const inp_xmls = XMLS.serializeToString(inp); // First convert DOM node into a string

// Insert the newly created node into the document's body
document.body.insertAdjacentHTML("afterbegin", inp_xmls);
```

The code creates a new `<input>` element by calling `Document.createElement()`, then serializes it into XML using `serializeToString()`.

Once that's done, `insertAdjacentHTML()` is used to insert the `<input>` element into the DOM.

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

| Specification |
| --- |
| DOM Parsing and Serialization # the-xmlserializer-interface |

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

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

See also
--------

* Parsing and serializing XML
* `DOMParser`


MIDIAccess - Web APIs

MIDIAccess
==========

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

The **`MIDIAccess`** interface of the Web MIDI API provides methods for listing MIDI input and output devices, and obtaining access to those devices.

EventTarget

MIDIAccessInstance properties
-------------------

`MIDIAccess.inputs` Read only

Returns an instance of `MIDIInputMap` which provides access to any available MIDI input ports.

`MIDIAccess.outputs` Read only

Returns an instance of `MIDIOutputMap` which provides access to any available MIDI output ports.

`MIDIAccess.sysexEnabled` Read only

A boolean attribute indicating whether system exclusive support is enabled on the current MIDIAccess instance.

### Events

`MIDIAccess.statechange_event`

Called whenever a new MIDI port is added or an existing port changes state.

Examples
--------

The `Navigator.requestMIDIAccess()` method returns a promise that resolves with a `MIDIAccess` object. Information about the input and output ports is returned.

When a port changes state, information about that port is printed to the console.

```js
navigator.requestMIDIAccess().then((access) => {
  // Get lists of available MIDI controllers
  const inputs = access.inputs.values();
  const outputs = access.outputs.values();

  access.onstatechange = (event) => {
    // Print information about the (dis)connected MIDI controller
    console.log(event.port.name, event.port.manufacturer, event.port.state);
  };
});
```

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

| Specification |
| --- |
| Web MIDI API # midiaccess-interface |

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

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


CSSMediaRule - Web APIs

CSSMediaRule
============

The **`CSSMediaRule`** interface represents a single CSS `@media` rule.

CSSRule

CSSGroupingRule

CSSConditionRule

CSSMediaRuleInstance properties
-------------------

*Inherits properties from its ancestors `CSSConditionRule`, `CSSGroupingRule`, and `CSSRule`.*

`CSSMediaRule.media` Read only

Returns a `MediaList` representing the intended destination medium for style information.

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

*No specific methods; inherits methods from its ancestors `CSSConditionRule`, `CSSGroupingRule`, and `CSSRule`.*

Examples
--------

 The CSS below includes a media query with one style rule.
 As this rule lives in the last stylesheet added to the document, it will be the first CSSRule returned by the last stylesheet in the document (`document.styleSheets[document.styleSheets.length-1].cssRules`).
 `myRules[0]` returns a `CSSMediaRule` object, from which we can get the `mediaText`.

```html
<p id="log"></p>
```

```css
@media (min-width: 500px) {
  body {
    color: blue;
  }
}
```

```js
const log = document.getElementById("log");
const myRules = document.styleSheets[document.styleSheets.length - 1].cssRules;
const mediaList = myRules[0]; // a CSSMediaRule representing the media query.
log.textContent += ` ${mediaList.media.mediaText}`;
```

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

| Specification |
| --- |
| CSS Conditional Rules Module Level 3 # the-cssmediarule-interface |

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

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


DeviceOrientationEvent - Web APIs

DeviceOrientationEvent
======================

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

The **`DeviceOrientationEvent`** interface of the Device Orientation Events provides web developers with information from the physical orientation of the device running the web page.

Event

DeviceOrientationEventConstructor
-----------

`DeviceOrientationEvent.DeviceOrientationEvent()`

Creates a new `DeviceOrientationEvent`.

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

`DeviceOrientationEvent.absolute` Read only

A boolean that indicates whether or not the device is providing orientation data absolutely.

`DeviceOrientationEvent.alpha` Read only

A number representing the motion of the device around the z axis, express in degrees with values ranging from 0 (inclusive) to 360 (exclusive).

`DeviceOrientationEvent.beta` Read only

A number representing the motion of the device around the x axis, express in degrees with values ranging from -180 (inclusive) to 180 (exclusive). This represents a front to back motion of the device.

`DeviceOrientationEvent.gamma` Read only

A number representing the motion of the device around the y axis, express in degrees with values ranging from -90 (inclusive) to 90 (exclusive). This represents a left to right motion of the device.

`DeviceOrientationEvent.webkitCompassHeading`
Non-standard
 Read only

A number represents the difference between the motion of the device around the z axis of the world system and the direction of the north, express in degrees with values ranging from 0 to 360.

`DeviceOrientationEvent.webkitCompassAccuracy`
Non-standard
 Read only

The accuracy of the compass means that the deviation is positive or negative. It's usually 10.

Example
-------

```js
window.addEventListener("deviceorientation", (event) => {
  console.log(`${event.alpha} : ${event.beta} : ${event.gamma}`);
});
```

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

| Specification |
| --- |
| DeviceOrientation Event Specification # deviceorientation |

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

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

See also
--------

* Detecting device orientation
* Orientation and motion data explained
* `DeviceMotionEvent`
* `devicemotion` event
* `deviceorientation` event
* `deviceorientationabsolute` event


SVGGlyphRefElement - Web APIs

SVGGlyphRefElement
==================

**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.

The **`SVGGlyphRefElement`** interface corresponds to the `<glyphRef>` elements.

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

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

`SVGGlyphRefElement.glyphRef`
Deprecated

A string corresponding to the `glyphRef` attribute of the given element.

`SVGGlyphRefElement.format`
Deprecated

A string corresponding to the `format` attribute of the given element.

`SVGGlyphRefElement.x`
Deprecated

A float corresponding to the `x` attribute of the given element.

`SVGGlyphRefElement.y`
Deprecated

A float corresponding to the `y` attribute of the given element.

`SVGGlyphRefElement.dx`
Deprecated

A float corresponding to the `dx` attribute of the given element.

`SVGGlyphRefElement.dy`
Deprecated

A float corresponding to the `dy` attribute of the given element.

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

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

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

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 1.1 (Second Edition) # InterfaceSVGGlyphRefElement |

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

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

See also
--------

* `<glyphRef>`


MediaStream - Web APIs

MediaStream
===========

The **`MediaStream`** interface of the Media Capture and Streams API represents a stream of media content. A stream consists of several **tracks**, such as video or audio tracks. Each track is specified as an instance of `MediaStreamTrack`.

You can obtain a `MediaStream` object either by using the constructor or by calling functions such as `MediaDevices.getUserMedia()`, `MediaDevices.getDisplayMedia()`, or `HTMLCanvasElement.captureStream()` and `HTMLMediaElement.captureStream()`.

EventTarget

MediaStreamConstructor
-----------

`MediaStream()`

Creates and returns a new `MediaStream` object. You can create an empty stream, a stream which is based upon an existing stream, or a stream that contains a specified list of tracks (specified as an array of `MediaStreamTrack` objects).

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

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

`MediaStream.active` Read only

A Boolean value that returns `true` if the `MediaStream` is active, or `false` otherwise.

`MediaStream.id` Read only

A string containing a 36-character universally unique identifier (UUID) for the object.

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

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

`MediaStream.addTrack()`

Stores a copy of the `MediaStreamTrack` given as argument. If the track has already been added to the `MediaStream` object, nothing happens.

`MediaStream.clone()`

Returns a clone of the `MediaStream` object. The clone will, however, have a unique value for `id`.

`MediaStream.getAudioTracks()`

Returns a list of the `MediaStreamTrack` objects stored in the `MediaStream` object that have their `kind` attribute set to `audio`. The order is not defined, and may not only vary from one browser to another, but also from one call to another.

`MediaStream.getTrackById()`

Returns the track whose ID corresponds to the one given in parameters, `trackid`. If no parameter is given, or if no track with that ID does exist, it returns `null`. If several tracks have the same ID, it returns the first one.

`MediaStream.getTracks()`

Returns a list of all `MediaStreamTrack` objects stored in the `MediaStream` object, regardless of the value of the `kind` attribute. The order is not defined, and may not only vary from one browser to another, but also from one call to another.

`MediaStream.getVideoTracks()`

Returns a list of the `MediaStreamTrack` objects stored in the `MediaStream` object that have their `kind` attribute set to `"video"`. The order is not defined, and may not only vary from one browser to another, but also from one call to another.

`MediaStream.removeTrack()`

Removes the `MediaStreamTrack` given as argument. If the track is not part of the `MediaStream` object, nothing happens.

Events
------

`addtrack`

Fired when a new `MediaStreamTrack` object is added.

`removetrack`

Fired when a `MediaStreamTrack` object has been removed.

`active`
Non-standard

Fired when the MediaStream is activated.

`inactive`
Non-standard

Fired when the MediaStream is inactivated.

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

| Specification |
| --- |
| Media Capture and Streams # mediastream |

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

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

See also
--------

* Using the MediaStream Recording API
* WebRTC API
* Web Audio API
* `MediaStreamTrack`


SVGHKernElement - Web APIs

SVGHKernElement
===============

**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.

The **`SVGHKernElement`** interface corresponds to the `<hkern>` elements.

Object-oriented access to the attributes of the `<hkern>` element via the SVG DOM is not possible.

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

*This interface has no properties but inherits properties from its parent, `SVGElement`.*

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

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

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

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 1.1 (Second Edition) # InterfaceSVGHKernElement |

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

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

See also
--------

* `<hkern>`


SecurityPolicyViolationEvent - Web APIs

SecurityPolicyViolationEvent
============================

The **`SecurityPolicyViolationEvent`** interface inherits from `Event`, and represents the event object of an event sent on a document or worker when its content security policy is violated.

Event

SecurityPolicyViolationEventConstructor
-----------

`SecurityPolicyViolationEvent()`

Creates a new `SecurityPolicyViolationEvent` object instance.

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

`SecurityPolicyViolationEvent.blockedURI` Read only

A string representing the URI of the resource that was blocked because it violates a policy.

`SecurityPolicyViolationEvent.columnNumber` Read only

The column number in the document or worker at which the violation occurred.

`SecurityPolicyViolationEvent.disposition` Read only

Indicates how the violated policy is configured to be treated by the user agent. This will be `"enforce"` or `"report"`.

`SecurityPolicyViolationEvent.documentURI` Read only

A string representing the URI of the document or worker in which the violation was found.

`SecurityPolicyViolationEvent.effectiveDirective` Read only

A string representing the directive whose enforcement uncovered the violation.

`SecurityPolicyViolationEvent.lineNumber` Read only

The line number in the document or worker at which the violation occurred.

`SecurityPolicyViolationEvent.originalPolicy` Read only

A string containing the policy whose enforcement uncovered the violation.

`SecurityPolicyViolationEvent.referrer` Read only

A string representing the URL for the referrer of the resources whose policy was violated, or `null`.

`SecurityPolicyViolationEvent.sample` Read only

A string representing a sample of the resource that caused the violation, usually the first 40 characters. This will only be populated if the resource is an inline script, event handler, or style — external resources causing a violation will not generate a sample.

`SecurityPolicyViolationEvent.sourceFile` Read only

If the violation occurred as a result of a script, this will be the URL of the script; otherwise, it will be `null`. Both `columnNumber` and `lineNumber` should have non-null values if this property is not `null`.

`SecurityPolicyViolationEvent.statusCode` Read only

A number representing the HTTP status code of the document or worker in which the violation occurred.

`SecurityPolicyViolationEvent.violatedDirective` Read only

A string representing the directive whose enforcement uncovered the violation.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.blockedURI);
  console.log(e.violatedDirective);
  console.log(e.originalPolicy);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # report-violation |

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

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

See also
--------

* Content Security Policy (CSP)


MIDIInputMap - Web APIs

MIDIInputMap
============

The **`MIDIInputMap`** read-only interface of the Web MIDI API provides the set of MIDI input ports that are currently available.

A `MIDIInputMap` instance is a read-only `Map`-like object, in which each key is the ID string for MIDI input, and the associated value is the corresponding `MIDIInput` object.

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

| Specification |
| --- |
| Web MIDI API # midiinputmap-interface |

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

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


HTMLOptionsCollection - Web APIs

HTMLOptionsCollection
=====================

The **`HTMLOptionsCollection`** interface represents a collection of `<option>` HTML elements (in document order) and offers methods and properties for selecting from the list as well as optionally altering its items. This object is returned only by the `options` property of select.

HTMLCollection

HTMLOptionsCollectionInstance properties
-------------------

`length`

`unsigned long`. As optionally allowed by the spec, this property isn't read-only. You can either remove options from the end by lowering the value, or add blank options at the end by raising the value. Mozilla allows this, while other implementations could potentially throw a DOMException.

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

*This interface inherits the methods of its parent, `HTMLCollection`.*

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

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

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

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

See also
--------

* HTMLCollection


VRPose - Web APIs

VRPose
======

**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.

The **`VRPose`** interface of the WebVR API represents the state of a VR sensor at a given timestamp (which includes orientation, position, velocity, and acceleration information).

**Note:** This interface was part of the old WebVR API. It has been superseded by the WebXR Device API.

This interface is accessible through the `VRDisplay.getPose()` and `VRDisplay.getFrameData()` methods. `VRDisplay.getPose()` is deprecated.

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

`VRPose.position`
Deprecated
 Read only
Non-standard

Returns the position of the `VRDisplay` at the current `VRFrameData.timestamp` as a 3D vector

`VRPose.linearVelocity`
Deprecated
 Read only
Non-standard

Returns the linear velocity of the `VRDisplay` at the current `VRFrameData.timestamp`, in meters per second.

`VRPose.linearAcceleration`
Deprecated
 Read only
Non-standard

Returns the linear acceleration of the `VRDisplay` at the current `VRFrameData.timestamp`, in meters per second per second.

`VRPose.orientation`
Deprecated
 Read only
Non-standard

Returns the orientation of the sensor at the current `VRFrameData.timestamp`, as a quarternion value.

`VRPose.angularVelocity`
Deprecated
 Read only
Non-standard

Returns the angular velocity of the `VRDisplay` at the current `VRFrameData.timestamp`, in radians per second.

`VRPose.angularAcceleration`
Deprecated
 Read only
Non-standard

Returns the angular acceleration of the `VRDisplay` at the current `VRFrameData.timestamp`, in meters per second per second.

Examples
--------

See `VRDisplay.getFrameData()` for example code.

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

This interface was part of 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
--------

* WebVR API


Performance - Web APIs

Performance
===========

The **`Performance`** interface provides access to performance-related information for the current page.

An object of this type can be obtained by calling `window.performance` or `self.performance` in workers. Note that Performance entries are per context. If you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa. See `self.performance` for which APIs are available in window and worker contexts.

EventTarget

PerformanceInstance properties
-------------------

*The `Performance` interface doesn't inherit any properties.*

`Performance.eventCounts` Read only

An `EventCounts` map containing the number of events which have been dispatched per event type.

`Performance.navigation` Read only
Deprecated

A legacy `PerformanceNavigation` object that provides useful context about the operations included in the times listed in `timing`, including whether the page was a load or a refresh, how many redirections occurred, and so forth.

`Performance.timing` Read only
Deprecated

A legacy `PerformanceTiming` object containing latency-related performance information.

`Performance.memory` Read only
Non-standard

Deprecated

A *non-standard* extension added in Chrome, this property provides an object with basic memory usage information. *You **should not use** this non-standard API.*

`Performance.timeOrigin` Read only

Returns the high resolution timestamp of the start time of the performance measurement.

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

*The `Performance` interface doesn't inherit any methods.*

`Performance.clearMarks()`

Removes the given *mark* from the browser's performance entry buffer.

`Performance.clearMeasures()`

Removes the given *measure* from the browser's performance entry buffer.

`Performance.clearResourceTimings()`

Removes all `performance entries` with a `entryType` of "`resource`" from the browser's performance data buffer.

`Performance.getEntries()`

Returns a list of `PerformanceEntry` objects based on the given *filter*.

`Performance.getEntriesByName()`

Returns a list of `PerformanceEntry` objects based on the given *name* and *entry type*.

`Performance.getEntriesByType()`

Returns a list of `PerformanceEntry` objects of the given *entry type*.

`Performance.mark()`

Creates a `timestamp` in the browser's *performance entry buffer* with the given name.

`Performance.measure()`

Creates a named `timestamp` in the browser's performance entry buffer between two specified marks (known as the *start mark* and *end mark*, respectively).

`Performance.measureUserAgentSpecificMemory()`
Experimental

Estimates the memory usage of a web application including all its iframes and workers.

`Performance.now()`

Returns a `DOMHighResTimeStamp` representing the number of milliseconds elapsed since a reference instant.

`Performance.setResourceTimingBufferSize()`

Sets the browser's resource timing buffer size to the specified number of "`resource`" `type` `performance entry` objects.

`Performance.toJSON()`

Returns a JSON representation of the `Performance` object.

Events
------

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

`resourcetimingbufferfull`

Fired when the browser's resource timing buffer is full.

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

| Specification |
| --- |
| High Resolution Time # sec-performance |
| Performance Timeline # extensions-to-the-performance-interface |
| Resource Timing # sec-extensions-performance-interface |
| User Timing # extensions-performance-interface |

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

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


BackgroundFetchEvent - Web APIs

BackgroundFetchEvent
====================

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
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`BackgroundFetchEvent`** interface of the Background Fetch API is the event type for background fetch events dispatched on the `service worker global scope`.

It is the event type passed to `onbackgroundfetchabort` and `onbackgroundfetchclick`.

Event

ExtendableEvent

BackgroundFetchEventConstructor
-----------

`BackgroundFetchEvent()`
Experimental

Creates a new `BackgroundFetchEvent` object. This constructor is not typically used, as the browser creates these objects itself and provides them to background fetch event callbacks.

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

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

`BackgroundFetchEvent.registration` Read only
Experimental

Returns the `BackgroundFetchRegistration` that the event was initialized to.

### Event handlers

None.

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

None.

Examples
--------

In this example, if the user clicks on the user interface displaying the download progress, a new window will open. The current `BackgroundFetchRegistration` is returned by calling `event.registration`.

```js
addEventListener("backgroundfetchclick", (event) => {
  const bgFetch = event.registration;

  if (bgFetch.result === "success") {
    clients.openWindow("/latest-podcasts");
  } else {
    clients.openWindow("/download-progress");
  }
});
```

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

| Specification |
| --- |
| Background Fetch # background-fetch-event |

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

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


NDEFRecord - Web APIs

NDEFRecord
==========

**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 **`NDEFRecord`** interface of the Web NFC API provides data that can be read from, or written to, compatible NFC devices, e.g. NFC tags supporting NDEF.

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

`NDEFRecord()`
Experimental

Returns a new `NDEFRecord`.

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

`NDEFRecord.recordType`
Experimental
 Read only

Returns the record type of the record. Records must have either a standardized well-known type name such as `"empty"`, `"text"`, `"url"`, `"smart-poster"`, `"absolute-url"`, `"mime"`, or `"unknown"` or else an external type name, which consists of a domain name and custom type name separated by a colon (":").

`NDEFRecord.mediaType`
Experimental
 Read only

Returns the MIME type of the record. This value will be `null` if `recordType` is not equal to `"mime"`.

`NDEFRecord.id`
Experimental
 Read only

Returns the record identifier, which is an absolute or relative URL used to identify the record.

**Note:** The uniqueness of the identifier is enforced only by the generator of the record.

`NDEFRecord.data`
Experimental
 Read only

Returns a `DataView` containing the raw bytes of the record's payload.

`NDEFRecord.encoding`
Experimental
 Read only

Returns the encoding of a textual payload, or `null` otherwise.

`NDEFRecord.lang`
Experimental
 Read only

Returns the language of a textual payload, or `null` if one was not supplied.

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

`NDEFRecord.toRecords()`
Experimental

Converts `NDEFRecord.data` to a sequence of records. This allows parsing the payloads of record types which may contain nested records, such as smart poster and external type records.

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

| Specification |
| --- |
| Web NFC API # dom-ndefrecord |

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

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


TextEncoderStream - Web APIs

TextEncoderStream
=================

The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. It is the streaming equivalent of `TextEncoder`.

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

`TextEncoderStream()`

Creates a new `TextEncoderStream` object.

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

`TextEncoderStream.encoding` Read only

Always returns "`utf-8`".

`TextEncoderStream.readable` Read only

Returns the `ReadableStream` instance controlled by this object.

`TextEncoderStream.writable` Read only

Returns the `WritableStream` instance controlled by this object.

Examples
--------

* Examples of streaming structured data and HTML
* An example of fetch request streams which uses `TextEncoderStream` to upload the data.
Specifications
--------------

| Specification |
| --- |
| Encoding Standard # interface-textencoderstream |

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

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

See also
--------

* `TextDecoderStream`
* Streams API Concepts
* Experimenting with the Streams API


CharacterData - Web APIs

CharacterData
=============

The **`CharacterData`** abstract interface represents a `Node` object that contains characters. This is an abstract interface, meaning there aren't any objects of type `CharacterData`: it is implemented by other interfaces like `Text`, `Comment`, `CDATASection`, or `ProcessingInstruction`, which aren't abstract.

EventTarget

Node

CharacterDataInstance properties
-------------------

*This interface also inherits properties from its parents, `Node` and `EventTarget`.*

`CharacterData.data`

A string representing the textual data contained in this object.

`CharacterData.length` Read only

Returns a number representing the size of the string contained in the object.

`CharacterData.nextElementSibling` Read only

Returns the first `Element` that *follows* this node, and is a sibling.

`CharacterData.previousElementSibling` Read only

Returns the first `Element` that *precedes* this node, and is a sibling.

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

*This interface also inherits methods from its parents, `Node` and `EventTarget`.*

`CharacterData.after()`

 Inserts a set of `Node` objects or strings in the children list of the
 `CharacterData`'s parent, just after the `CharacterData` object.

`CharacterData.appendData()`

Appends the given string to the `CharacterData.data` string; when this method returns, `data` contains the concatenated string.

`CharacterData.before()`

 Inserts a set of `Node` objects or strings in the children list of the
 `CharacterData`'s parent, just before the `CharacterData` object.

`CharacterData.deleteData()`

Removes the specified amount of characters, starting at the specified offset, from the `CharacterData.data` string; when this method returns, `data` contains the shortened string.

`CharacterData.insertData()`

Inserts the specified characters, at the specified offset, in the `CharacterData.data` string; when this method returns, `data` contains the modified string.

`CharacterData.remove()`

Removes the object from its parent children list.

`CharacterData.replaceData()`

Replaces the specified amount of characters, starting at the specified offset, with the specified string; when this method returns, `data` contains the modified string.

`CharacterData.replaceWith()`

Replaces the characters in the children list of its parent with a set of `Node` objects or strings.

`CharacterData.substringData()`

Returns a string containing the part of `CharacterData.data` of the specified length and starting at the specified offset.

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

| Specification |
| --- |
| DOM Standard # interface-characterdata |

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

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

See also
--------

* The DOM overview page.
* The concrete interfaces implemented it: `Text`, `CDATASection`, `ProcessingInstruction`, and `Comment`.


USBAlternateInterface - Web APIs

USBAlternateInterface
=====================

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 `USBAlternateInterface` interface of the WebUSB API provides information about a particular configuration of an interface provided by the USB device. An interface includes one or more alternate settings which can configure a set of endpoints based on the operating mode of the device.

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

`USBAlternateInterface()`
Experimental

Creates a new `USBAlternateInterface` object which will be populated with information about the alternate interface of the provided `USBInterface` with the given alternate setting number.

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

`USBAlternateInterface.alternateSetting` Read only
Experimental

Returns the alternate setting number of this interface. This is equal to the `bAlternateSetting` field of the interface descriptor defining this interface.

`USBAlternateInterface.interfaceClass` Read only
Experimental

Returns the class of this interface. This is equal to the `bInterfaceClass` field of the interface descriptor defining this interface. Standardized values for this field are defined by the USB Implementers Forum. A value of `0xFF` indicates a vendor-defined interface.

`USBAlternateInterface.interfaceSubclass` Read only
Experimental

Returns the subclass of this interface. This is equal to the `bInterfaceSubClass` field of the interface descriptor defining this interface. The meaning of this value depends on the `interfaceClass` field.

`USBAlternateInterface.interfaceProtocol` Read only
Experimental

Returns the protocol supported by this interface. This is equal to the `bInterfaceProtocol` field of the interface descriptor defining this interface. The meaning of this value depends on the `interfaceClass` and `interfaceSubclass` fields.

`USBAlternateInterface.interfaceName` Read only
Experimental

Returns the name of the interface, if one is provided by the device. This is the value of the string descriptor with the index specified by the `iInterface` field of the interface descriptor defining this interface.

`USBAlternateInterface.endpoints` Read only
Experimental

Returns an array containing instances of the `USBEndpoint` interface describing each of the endpoints that are part of this interface.

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

| Specification |
| --- |
| WebUSB API # usbalternateinterface |

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

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


PaymentManager - Web APIs

PaymentManager
==============

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

The **`PaymentManager`** interface of the Payment Handler API is used to manage various aspects of payment app functionality.

It is accessed via the `ServiceWorkerRegistration.paymentManager` property.

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

`userHint`
Experimental

Provides a hint for the browser to display along with the payment app's name and icon in the Payment Handler UI.

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

`enableDelegations()`
Experimental

Delegates responsibility for providing various parts of the required payment information to the payment app rather than collecting it from the browser (for example, via autofill).

Examples
--------

```js
navigator.serviceWorker.register("serviceworker.js").then((registration) => {
  registration.paymentManager.userHint = "Card number should be 16 digits";

  registration.paymentManager
    .enableDelegations(["shippingAddress", "payerName"])
    .then(() => {
      // ...
    });

  // ...
});
```

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

| Specification |
| --- |
| Payment Handler API # paymentmanager-interface |

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

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

See also
--------

* Payment Handler API
* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


HTMLInputElement - Web APIs

HTMLInputElement
================

The **`HTMLInputElement`** interface provides special properties and methods for manipulating the options, layout, and presentation of `<input>` elements.

EventTarget

Node

Element

HTMLElement

HTMLInputElementInstance properties
-------------------

*Also inherits properties from its parent interface, `HTMLElement`.*

Some properties only apply to input element types that support the corresponding attributes.

`align`
Deprecated

A string that represents the alignment of the element. *Use CSS instead.*

`defaultValue`

A string that represents the default value as originally specified in the HTML that created this object.

`dirName`

A string that represents the directionality of the element.

`incremental`
Non-standard

A boolean that represents the search event fire mode, if `true`, fires on every keypress, or on clicking the cancel button; otherwise fires when pressing `Enter`.

`labels` Read only

Returns a list of `<label>` elements that are labels for this element.

`list` Read only

Returns the element pointed to by the `list` attribute. The property may be `null` if no HTML element is found in the same tree.

`multiple`

A boolean that represents the element's `multiple` attribute, indicating whether more than one value is possible (e.g., multiple files).

`name`

A string that represents the element's `name` attribute, containing a name that identifies the element when submitting the form.

`popoverTargetAction`

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

`popoverTargetElement`

Gets and sets the popover element to control via an `<input>` element of `type="button"`. The JavaScript equivalent of the `popovertarget` HTML attribute.

`step`

A string that represents the element's `step` attribute, which works with `min` and `max` to limit the increments at which a numeric or date-time value can be set. It can be the string `any` or a positive floating point number. If this is not set to `any`, the control accepts only values at multiples of the step value greater than the minimum.

`type`

A string that represents the element's `type` attribute, indicating the type of control to display. For possible values, see the documentation for the `type` attribute.

`useMap`
Deprecated

A string that represents a client-side image map.

`value`

A string that represents the current value of the control. If the user enters a value different from the value expected, this may return an empty string.

`valueAsDate`

A `Date` that represents the value of the element, interpreted as a date, or `null` if conversion is not possible.

`valueAsNumber`

A number that represents the value of the element, interpreted as one of the following, in order: A time value, a number, or `NaN` if conversion is impossible.

### Instance properties related to the parent form

`form` Read only

Returns a reference to the parent `<form>` element.

`formAction`

A string that represents the element's `formaction` attribute, containing the URL of a program that processes information submitted by the element. This overrides the `action` attribute of the parent form.

`formEnctype`

A string that represents the element's `formenctype` attribute, containing the type of content that is used to submit the form to the server. This overrides the `enctype` attribute of the parent form.

`formMethod`

A string that represents the element's `formmethod` attribute, containing the HTTP method that the browser uses to submit the form. This overrides the `method` attribute of the parent form.

`formNoValidate`

A boolean that represents the element's `formnovalidate` attribute, indicating that the form is not to be validated when it is submitted. This overrides the `novalidate` attribute of the parent form.

`formTarget`

A string that represents the element's `formtarget` attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. This overrides the `target` attribute of the parent form.

### Instance properties that apply to any type of input element that is not hidden

`disabled`

A boolean that represents the element's `disabled` attribute, indicating that the control is not available for interaction. The input values will not be submitted with the form. See also `readonly`.

`required`

A boolean that represents the element's `required` attribute, indicating that the user must fill in a value before submitting a form.

`validationMessage` Read only

Returns 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. This value can be set by the `setCustomValidity()` method.

`validity` Read only

Returns the element's current validity state.

`willValidate` Read only

Returns whether the element is a candidate for constraint validation. It is `false` if any conditions bar it from constraint validation, including: its `type` is one of `hidden`, `reset` or `button`, it has a `<datalist>` ancestor or its `disabled` property is `true`.

### Instance properties that apply only to elements of type checkbox or radio

`checked`

A boolean that represents the current state of the element.

`defaultChecked`

A boolean that represents the default state of a radio button or checkbox as originally specified in HTML that created this object.

`indeterminate`

A boolean that represents whether the checkbox or radio button is in indeterminate state. For checkboxes, the effect is that the appearance of the checkbox is obscured/greyed in some way as to indicate its state is indeterminate (not checked but not unchecked). Does not affect the value of the `checked` attribute, and clicking the checkbox will set the value to false.

### Instance properties that apply only to elements of type image

`alt`

A string that represents the element's `alt` attribute, containing alternative text to use.

`height`

A string that represents the element's `height` attribute, which defines the height of the image displayed for the button.

`src`

A string that represents the element's `src` attribute, which specifies a URI for the location of an image to display on the graphical submit button.

`width`

A string that represents the element's `width` attribute, which defines the width of the image displayed for the button.

### Instance properties that apply only to elements of type file

`accept`

A string that represents the element's `accept` attribute, containing comma-separated list of file types that can be selected.

`files`

A `FileList` that represents the files selected for upload.

`webkitdirectory`

A boolean that represents the `webkitdirectory` attribute. If `true`, the file-system-picker interface only accepts directories instead of files.

`webkitEntries` Read only

Describes the currently selected files or directories.

### Instance properties that apply only to visible elements containing text or numbers

`autocomplete`

A string that represents the element's `autocomplete` attribute, indicating whether the value of the control can be automatically completed by the browser.

`capture`

A string that represents the element's `capture` attribute, indicating the media capture input method in file upload controls.

`max`

A string that represents the element's `max` attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum (`min` attribute) value.

`maxLength`

A number that represents the element's `maxlength` attribute, containing the maximum number of characters (in Unicode code points) that the value can have.

`min`

A string that represents the element's `min` attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum (`max` attribute) value.

`minLength`

A number that represents the element's `minlength` attribute, containing the minimum number of characters (in Unicode code points) that the value can have.

`pattern`

A string that represents the element's `pattern` attribute, containing a regular expression that the control's value is checked against. Use the `title` attribute to describe the pattern to help the user. This attribute only applies when the value of the `type` attribute is `text`, `search`, `tel`, `url` or `email`.

`placeholder`

A string that represents the element's `placeholder` attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute only applies when the value of the `type` attribute is `text`, `search`, `tel`, `url` or `email`.

`readOnly`

A boolean that represents the element's `readonly` attribute, indicating that the user cannot modify the value of the control. This is ignored if the `type` is `hidden`, `range`, `color`, `checkbox`, `radio`, `file`, or a button type.

`selectionDirection`

A string that represents the direction in which selection occurred. Possible values are: `forward` (the selection was performed in the start-to-end direction of the current locale), `backward` (the opposite direction) or `none` (the direction is unknown).

`selectionEnd`

A number that represents the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.

`selectionStart`

A number that represents the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the `<input>` element.

`size`

A number that represents the element's `size` attribute, containing visual size of the control. This value is in pixels unless the value of `type` is `text` or `password`, in which case, it is an integer number of characters. Applies only when `type` is set to `text`, `search`, `tel`, `url`, `email`, or `password`.

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

*Also inherits methods from its parent interface, `HTMLElement`.*

`checkValidity()`

Returns a boolean value that is `false` if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an `invalid` event at the element. It returns `true` if the element is not a candidate for constraint validation, or if it satisfies its constraints.

`reportValidity()`

Runs the `checkValidity()` method, and if it returns false (for an invalid input or no pattern attribute provided), then it reports to the user that the input is invalid in the same manner as if you submitted a form.

`select()`

Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content.

`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.

`setRangeText()`

Replaces a range of text in the input element with new text.

`setSelectionRange()`

Selects a range of text in the input element (but does not focus it).

`showPicker()`

Shows a browser picker for date, time, color, and files.

`stepDown()`

Decrements the `value` by (`step` \* n), where n defaults to 1 if not specified.

`stepUp()`

Increments the `value` by (`step` \* n), where n defaults to 1 if not specified.

Events
------

*Also inherits events from its parent interface, `HTMLElement`.*

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

`invalid` event

Fired when an element does not satisfy its constraints during constraint validation.

`search` event
Non-standard

Fired when a search is initiated on an `<input>` of `type="search"`.

`select` event

Fired when some text has been selected.

`selectionchange` event
Experimental

Fires when the text selection in a `<input>` element has been changed.

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

| Specification |
| --- |
| HTML Standard # htmlinputelement |

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

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

See also
--------

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