RTCTransportStats - Web APIs

RTCTransportStats
=================

The **`RTCTransportStats`** dictionary of the WebRTC API provides information about the transport (`RTCDtlsTransport` and its underlying `RTCIceTransport`) used by a particular candidate pair.

 The *BUNDLE* feature is an SDP extension that allows negotiation to use a single transport for sending and receiving media described by multiple SDP media descriptions.
 If the remote endpoint is aware of this feature, all `MediaStreamTrack` and data channels are bundled onto a single transport at the completion of negotiation.
 This is true for current browsers, but if connecting to an older endpoint that is not BUNDLE-aware, then separate transports might be used for different media.
 The policy to use in the negotiation is configured in the `RTCPeerConnection` constructor.

These statistics can be obtained by iterating the `RTCStatsReport` returned by `RTCPeerConnection.getStats()` until you find a report with the `type` of `transport`.

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

`bytesReceived` Optional

The total number of payload bytes received on this transport (bytes received, not including headers, padding or ICE connectivity checks).

`bytesSent` Optional

The total number of payload bytes sent on this transport (bytes sent, not including headers, padding or ICE connectivity checks).

`dtlsCipher` Optional

 A string indicating the name of the cipher suite used for the DTLS transport, as defined in the "Description" column of the TLS Cipher Suites section in the *IANA cipher suite registry*.
 For example `"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"`.

`dtlsRole` Optional
Experimental

 The DTLS role of the associated `RTCPeerConnection`.
 This is one of:

* `client`
* `server`
* `unknown` (before the DTLS negotiation starts).

`dtlsState`

 A string indicating the current `state` of the underlying `RTCDtlsTransport`.
 This is one of:

* `new`
* `connecting`
* `connected`
* `closed`
* `failed`

`iceLocalUsernameFragment` Optional
Experimental

 A string indicating the local username fragment used in message validation procedures for this transport.
 This is the same value as the local `RTCIceCandidate.usernameFragment`, and will change if the connection is renegotiated.

`iceRole` Optional
Experimental

 A string indicating the ICE `role` of the underlying `RTCDtlsTransport.iceTransport`.
 This is one of:

* `controlled`
* `controlling`
* `unknown`

`iceState` Optional
Experimental

 A string indicating the current `state` of the underlying `RTCIceTransport`.
 This is one of:

* `new`
* `checking`
* `connected`
* `completed`
* `disconnected`
* `failed`
* `closed`

`selectedCandidatePairId` Optional

A string containing the unique identifier for the object that was inspected to produce the `RTCIceCandidatePairStats` associated with this transport.

`localCertificateId` Optional

 A string containing the id of the local certificate used by this transport.
 Only present for DTLS transports, and after DTLS has been negotiated.

`packetsSent` Optional
Experimental

The total number of packets sent over this transport.

`packetsReceived` Optional
Experimental

The total number of packets received on this transport.

`remoteCertificateId` Optional

 A string containing the id or the remote certificate used by this transport.
 Only present for DTLS transports, and after DTLS has been negotiated.

`selectedCandidatePairChanges` Optional

 The number of times that the selected candidate pair of this transport has changed.
 The value is initially zero and increases whenever a candidate pair selected or lost.

`srtpCipher` Optional

A string indicating the descriptive name of the protection profile used for the Secure Real-time Transport Protocol (SRTP) transport, as defined in the "Profile" column of the IANA DTLS-SRTP protection profile registry and RFC5764.

For example `"AES_CM_128_HMAC_SHA1_80"` specifies the following profile, where `maximum_lifetime` is the maximum number of packets that can be protected by a single set of keys.
```

SRTP_AES128_CM_HMAC_SHA1_80
 cipher: AES_128_CM
 cipher_key_length: 128
 cipher_salt_length: 112
 maximum_lifetime: 2^31
 auth_function: HMAC-SHA1
 auth_key_length: 160
 auth_tag_length: 80
```

`tlsVersion` Optional

 A string containing the negotiated TLS version.
 This is present for DTLS transports, and only exists after DTLS has been negotiated.

 The value comes from the DTLS handshake `ServerHello.version`, and is represented as four upper case hexadecimal digits, where the digits represent the two bytes of the version.
 Note however that the bytes might not map directly to version numbers.
 For example, DTLS represents version 1.2 as `'FEFD'` which numerically is `{254, 253}`.

### Common instance properties

The following properties are common to all WebRTC statistics objects.

`id`

A string that uniquely identifies the object that is being monitored to produce this set of statistics.

`timestamp`

A `DOMHighResTimeStamp` object indicating the time at which the sample was taken for this statistics object.

`type`

A string with the value `"transport"`, indicating the type of statistics that the object contains.

Examples
--------

This example shows a function to return the transport statistics, or `null` if no statistics are provided.

 The function waits for the result of a call to `RTCPeerConnection.getStats()` and then iterates the returned `RTCStatsReport` to get just the stats of type `"transport"`.
 It then returns the statistics, or `null`, using the data in the report.

```js
async function numberOpenConnections (peerConnection) {
  const stats = await peerConnection.getStats();
  let transportStats = null;

  stats.forEach((report) => {
    if (report.type === "transport") {
      transportStats = report;
      break;
    }
  });

return transportStats
}
```

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstatstype-transport |

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

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


ScriptProcessorNode - Web APIs

ScriptProcessorNode
===================

**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 `ScriptProcessorNode` interface allows the generation, processing, or analyzing of audio using JavaScript.

EventTarget

AudioNode

ScriptProcessorNode

**Note:** This feature was replaced by AudioWorklets and the `AudioWorkletNode` interface.

The `ScriptProcessorNode` interface is an `AudioNode` audio-processing module that is linked to two buffers, one containing the input audio data, one containing the processed output audio data. An event, implementing the `AudioProcessingEvent` interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data.

![The ScriptProcessorNode stores the input in a buffer, send the audioprocess event. The EventHandler takes the input buffer and fill the output buffer which is sent to the output by the ScriptProcessorNode.](/en-US/docs/Web/API/ScriptProcessorNode/webaudioscriptprocessingnode.png)

The size of the input and output buffer are defined at the creation time, when the `BaseAudioContext.createScriptProcessor` method is called (both are defined by `BaseAudioContext.createScriptProcessor`'s `bufferSize` parameter). The buffer size must be a power of 2 between `256` and `16384`, that is `256`, `512`, `1024`, `2048`, `4096`, `8192` or `16384`. Small numbers lower the *latency*, but large number may be necessary to avoid audio breakup and glitches.

If the buffer size is not defined, which is recommended, the browser will pick one that its heuristic deems appropriate.

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"max"` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `"speakers"` |

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

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

`ScriptProcessorNode.bufferSize` Read only
Deprecated

Returns an integer representing both the input and output buffer size. Its value can be a power of 2 value in the range `256` – `16384`.

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

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

Events
------

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

`audioprocess`
Deprecated

 Fired when an input buffer of a `ScriptProcessorNode` is ready to be processed.
 Also available via the `onaudioprocess` event handler property.

Examples
--------

See `BaseAudioContext.createScriptProcessor()` for example code.

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

Since the August 29, 2014 Web Audio API specification publication, this feature has been deprecated. It is no longer on track to become a standard.

It was replaced by AudioWorklets and the `AudioWorkletNode` interface.

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

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

See also
--------

* Using the Web Audio API


ExtendableEvent - Web APIs

ExtendableEvent
===============

The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like `FetchEvent`) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.

If `waitUntil()` is called outside of the `ExtendableEvent` handler, the browser should throw an `InvalidStateError`; note also that multiple calls will stack up, and the resulting promises will be added to the list of extend lifetime promises.

**Note:** The behavior described in the above paragraph was fixed in Firefox 43 (see Firefox bug 1180274.)

This interface inherits from the `Event` interface.

Event

ExtendableEvent

**Note:** This interface is only available when the global scope is a `ServiceWorkerGlobalScope`. It is not available when it is a `Window`, or the scope of another kind of worker.

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

`ExtendableEvent()`

Creates a new `ExtendableEvent` object.

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

*Doesn't implement any specific properties, but inherits properties from its parent, `Event`.*

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

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

`ExtendableEvent.waitUntil()`

Extends the lifetime of the event. It is intended to be called in the `install` event handler for the `installing` worker and on the `activate` event handler for the `active` worker.

Examples
--------

This code snippet is from the service worker prefetch sample (see prefetch example live.) The code calls `ExtendableEvent.waitUntil()` in `oninstall`, delaying treating the `ServiceWorkerRegistration.installing` worker as installed until the passed promise resolves successfully. The promise resolves when all resources have been fetched and cached, or else when any exception occurs.

The code snippet also shows a best practice for versioning caches used by the service worker. Though there's only one cache in this example, the same approach can be used for multiple caches. It maps a shorthand identifier for a cache to a specific, versioned cache name.

**Note:** In Chrome, logging statements are visible via the "Inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals.

```js
const CACHE\_VERSION = 1;
const CURRENT\_CACHES = {
  prefetch: `prefetch-cache-v${CACHE\_VERSION}`,
};

self.addEventListener("install", (event) => {
  const urlsToPrefetch = [
    "./static/pre\_fetched.txt",
    "./static/pre\_fetched.html",
    "https://www.chromium.org/\_/rsrc/1302286216006/config/customLogo.gif",
  ];

  console.log(
    "Handling install event. Resources to pre-fetch:",
    urlsToPrefetch,
  );

  event.waitUntil(
    caches
      .open(CURRENT\_CACHES["prefetch"])
      .then((cache) => {
        return cache
          .addAll(
            urlsToPrefetch.map((urlToPrefetch) => {
              return new Request(urlToPrefetch, { mode: "no-cors" });
            }),
          )
          .then(() => {
            console.log("All resources have been fetched and cached.");
          });
      })
      .catch((error) => {
        console.error("Pre-fetching failed:", error);
      }),
  );
});
```

**Note:** When fetching resources, it's very important to use `{mode: 'no-cors'}` if there is any chance that the resources are served off of a server that doesn't support CORS. In this example, www.chromium.org doesn't support CORS.

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

| Specification |
| --- |
| Service Workers # extendableevent-interface |

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

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

See also
--------

* Using Service Workers
* Service workers basic code example
* Using web workers


MIDIMessageEvent - Web APIs

MIDIMessageEvent
================

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

The **`MIDIMessageEvent`** interface of the Web MIDI API represents the event passed to the `midimessage` event of the `MIDIInput` interface. A `midimessage` event is fired every time a MIDI message is sent from a device represented by a `MIDIInput`, for example when a MIDI keyboard key is pressed, a knob is tweaked, or a slider is moved.

Event

MIDIMessageEventConstructor
-----------

`MIDIMessageEvent()`

Creates a new `MIDIMessageEvent` object instance.

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

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

`MIDIMessageEvent.data`

A `Uint8Array` containing the data bytes of a single MIDI message. See the MIDI specification for more information on its form.

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

*This interface doesn't implement any specific methods, but inherits methods from `Event`.*

Examples
--------

The following example prints all MIDI messages to the console.

```js
navigator.requestMIDIAccess().then((midiAccess) => {
  Array.from(midiAccess.inputs).forEach((input) => {
    input[1].onmidimessage = (msg) => {
      console.log(msg);
    };
  });
});
```

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

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

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

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


WritableStreamDefaultWriter - Web APIs

WritableStreamDefaultWriter
===========================

The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by `WritableStream.getWriter()` and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink.

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

`WritableStreamDefaultWriter()`

Creates a new `WritableStreamDefaultWriter` object instance.

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

`WritableStreamDefaultWriter.closed` Read only

Allows you to write code that responds to an end to the streaming process. Returns a promise that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released.

`WritableStreamDefaultWriter.desiredSize` Read only

Returns the desired size required to fill the stream's internal queue.

`WritableStreamDefaultWriter.ready` Read only

Returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure.

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

`WritableStreamDefaultWriter.abort()`

Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.

`WritableStreamDefaultWriter.close()`

Closes the associated writable stream.

`WritableStreamDefaultWriter.releaseLock()`

Releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed.

`WritableStreamDefaultWriter.write()`

Writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation.

Examples
--------

The following example shows the creation of a `WritableStream` with a custom sink and an API-supplied queuing strategy. It then calls a function called `sendMessage()`, passing the newly created stream and a string. Inside this function it calls the stream's `getWriter()` method, which returns an instance of `WritableStreamDefaultWriter`. A `forEach()` call is used to write each chunk of the string to the stream. Finally, `write()` and `close()` return promises that are processed to deal with success or failure of chunks and streams.

```js
const list = document.querySelector("ul");

async function sendMessage(message, writableStream) {
  // defaultWriter is of type WritableStreamDefaultWriter
  const defaultWriter = writableStream.getWriter();
  const encoder = new TextEncoder();
  const encoded = encoder.encode(message);

  try {
    for (const chunk of encoded) {
      await defaultWriter.ready;
      await defaultWriter.write(chunk);
      console.log("Chunk written to sink.");
    }
    // Call ready again to ensure that all chunks are written
    // before closing the writer.
    await defaultWriter.ready;
    await defaultWriter.close();
    console.log("All chunks written");
  } catch (err) {
    console.log("Error:", err);
  }
}

const decoder = new TextDecoder("utf-8");
const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });
let result = "";
const writableStream = new WritableStream(
  {
    // Implement the sink
    write(chunk) {
      return new Promise((resolve, reject) => {
        const buffer = new ArrayBuffer(1);
        const view = new Uint8Array(buffer);
        view[0] = chunk;
        const decoded = decoder.decode(view, { stream: true });
        const listItem = document.createElement("li");
        listItem.textContent = `Chunk decoded: ${decoded}`;
        list.appendChild(listItem);
        result += decoded;
        resolve();
      });
    },
    close() {
      const listItem = document.createElement("li");
      listItem.textContent = `[MESSAGE RECEIVED] ${result}`;
      list.appendChild(listItem);
    },
    abort(err) {
      console.log("Sink error:", err);
    },
  },
  queuingStrategy,
);

sendMessage("Hello, world.", writableStream);
```

You can find the full code in our Simple writer example.

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

| Specification |
| --- |
| Streams Standard # default-writer-class |

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

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


EyeDropper API - Web APIs

EyeDropper API
==============

**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 **EyeDropper API** provides a mechanism for creating an eyedropper tool. Using this tool, users can sample colors from their screens, including outside of the browser window.

Concept
-------

Creative applications often allow users to sample colors from drawings or shapes in the application to reuse. Web applications can use the **EyeDropper API** to provide a similar eyedropper mode, provided by the browser.

Using the API, a web application can start the eyedropper mode. Once started, the cursor changes to indicate to the user that the mode is active. The user can then either select a color from anywhere on the screen, or dismiss the eyedropper mode by pressing `Escape`.

Security and privacy measures
-----------------------------

To prevent malicious websites from getting pixel data from a user's screen without them realizing, the **EyeDropper API** implements the following measures:

* The API doesn't let the eyedropper mode start without user intent. The `EyeDropper.open()` method can only be called in response to a user action (such as a button click).
* No pixel information can be retrieved without user intent. The promise returned by `EyeDropper.open()` only resolves to a color value in response to a user action (clicking on a pixel). So the eyedropper cannot be used in the background without the user noticing it.
* To help users notice the eyedropper mode more easily, it is made obvious by browsers. The normal mouse cursor disappears after a short delay and a magnifying glass appears instead. There is also a delay between when the eyedropper mode starts and when the user can select a pixel to ensure the user has had time to see the magnifying glass.
* Users are also able to cancel the eyedropper mode at any time (by pressing the `Escape` key).
Interfaces
----------

`EyeDropper`
Experimental

The **`EyeDropper`** interface represents an instance of an eyedropper tool that can be opened and used by the user to select colors from the screen.

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

| Specification |
| --- |
| EyeDropper API # eyedropper-interface |

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

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

See also
--------

* Picking colors of any pixel on the screen with the EyeDropper API
* The EyeDropper API W3C/SMPTE Joint Workshop


EXT_frag_depth extension - Web APIs

EXT\_frag\_depth extension
==========================

The **`EXT_frag_depth`** extension is part of the WebGL API and enables to set a depth value of a fragment from within the fragment shader.

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

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

Examples
--------

Enable the extension:

```js
gl.getExtension("EXT\_frag\_depth");
```

Now the output variable `gl_FragDepthEXT` is available to set a depth value of a fragment from within the fragment shader:

```html
<script type="x-shader/x-fragment">
 void main() {
 gl\_FragColor = vec4(1.0, 0.0, 1.0, 1.0);
 gl\_FragDepthEXT = 0.5;
 }
</script>
```

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

| Specification |
| --- |
| WebGL EXT\_frag\_depth 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()`


Media Capture and Streams API (Media Stream) - Web APIs

Media Capture and Streams API (Media Stream)
============================================

The **Media Capture and Streams** API, often called the **Media Streams API** or **MediaStream API**, is an API related to WebRTC which provides support for streaming audio and video data.

It provides the interfaces and methods for working with the streams and their constituent tracks, the constraints associated with data formats, the success and error callbacks when using the data asynchronously, and the events that are fired during the process.

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

The API is based on the manipulation of a `MediaStream` object representing a flux of audio- or video-related data. See an example in Get the media stream.

A `MediaStream` consists of zero or more `MediaStreamTrack` objects, representing various audio or video **tracks**. Each `MediaStreamTrack` may have one or more **channels**. The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like *left* or *right* in a stereo audio track.

`MediaStream` objects have a single **input** and a single **output**. A `MediaStream` object generated by `getUserMedia()` is called *local*, and has as its source input one of the user's cameras or microphones. A non-local `MediaStream` may be representing a media element, like `<video>` or `<audio>`, a stream originating over the network, and obtained via the WebRTC `RTCPeerConnection` API, or a stream created using the Web Audio API `MediaStreamAudioDestinationNode`.

The output of the `MediaStream` object is linked to a **consumer**. It can be a media element, like `<audio>` or `<video>`, the WebRTC `RTCPeerConnection` API or a Web Audio API `MediaStreamAudioSourceNode`.

Interfaces
----------

In these reference articles, you'll find the fundamental information you'll need to know about each of the interfaces that make up the Media Capture and Streams API.

* `CanvasCaptureMediaStreamTrack`
* `InputDeviceInfo`
* `MediaDeviceInfo`
* `MediaDevices`
* `MediaStream`
* `MediaStreamTrack`
* `MediaStreamTrackEvent`
* `MediaTrackConstraints`
* `MediaTrackSettings`
* `MediaTrackSupportedConstraints`
* `OverconstrainedError`
Events
------

* `addtrack`
* `ended`
* `mute`
* `removetrack`
* `unmute`
Guides and tutorials
--------------------

The Capabilities, constraints, and settings article discusses the concepts of **constraints** and **capabilities**, as well as media settings, and includes a Constraint Exerciser that lets you experiment with the results of different constraint sets being applied to the audio and video tracks coming from the computer's A/V input devices (such as its webcam and microphone).

The Taking still photos with getUserMedia() article shows how to use `getUserMedia()` to access the camera on a computer or mobile phone with `getUserMedia()` support and take a photo with it.

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

### api.MediaStream

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

### api.MediaStreamTrack

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

### api.MediaDevices

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

### api.MediaDeviceInfo

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

### api.InputDeviceInfo

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

### api.CanvasCaptureMediaStreamTrack

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

See also
--------

* WebRTC - the introductory page to the API
* Taking still photos with WebRTC: a demonstration and tutorial about using `getUserMedia()`.


ValidityState - Web APIs

ValidityState
=============

Baseline 2023
-------------

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

* Learn more
* See full compatibility
* Report feedback
The **`ValidityState`** interface represents the *validity states* that an element can be in, with respect to constraint validation. Together, they help explain why an element's value fails to validate, if it's not valid.

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

For each of these Boolean properties, a value of `true` indicates that the specified reason validation may have failed is true, with the exception of the `valid` property, which is `true` if the element's value obeys all constraints.

`badInput` Read only

A boolean value that is `true` if the user has provided input that the browser is unable to convert.

`customError` Read only

A boolean value indicating whether the element's custom validity message has been set to a non-empty string by calling the element's `setCustomValidity()` method.

`patternMismatch` Read only

A boolean value that is `true` if the value does not match the specified `pattern`, and `false` if it does match. If `true`, the element matches the `:invalid` CSS pseudo-class.

`rangeOverflow` Read only

A boolean value that is `true` if the value is greater than the maximum specified by the `max` attribute, or `false` if it is less than or equal to the maximum. If `true`, the element matches the `:invalid` and `:out-of-range` and CSS pseudo-classes.

`rangeUnderflow` Read only

A boolean value that is `true` if the value is less than the minimum specified by the `min` attribute, or `false` if it is greater than or equal to the minimum. If `true`, the element matches the `:invalid` and `:out-of-range` CSS pseudo-classes.

`stepMismatch` Read only

A boolean value that is `true` if the value does not fit the rules determined by the `step` attribute (that is, it's not evenly divisible by the step value), or `false` if it does fit the step rule. If `true`, the element matches the `:invalid` and `:out-of-range` CSS pseudo-classes.

`tooLong` Read only

A boolean value that is `true` if the value exceeds the specified `maxlength` for `HTMLInputElement` or `HTMLTextAreaElement` objects, or `false` if its length is less than or equal to the maximum length. *Note: This property is never `true` in Gecko, because elements' values are prevented from being longer than `maxlength`.* If `true`, the element matches the `:invalid` and `:out-of-range` CSS pseudo-classes.

`tooShort` Read only

A boolean value that is `true` if the value fails to meet the specified `minlength` for `HTMLInputElement` or `HTMLTextAreaElement` objects, or `false` if its length is greater than or equal to the minimum length. If `true`, the element matches the `:invalid` and `:out-of-range` CSS pseudo-classes.

`typeMismatch` Read only

A boolean value that is `true` if the value is not in the required syntax (when `type` is `email` or `url`), or `false` if the syntax is correct. If `true`, the element matches the `:invalid` CSS pseudo-class.

`valid` Read only

A boolean value that is `true` if the element meets all its validation constraints, and is therefore considered to be valid, or `false` if it fails any constraint. If `true`, the element matches the `:valid` CSS pseudo-class; the `:invalid` CSS pseudo-class otherwise.

`valueMissing` Read only

A boolean value that is `true` if the element has a `required` attribute, but no value, or `false` otherwise. If `true`, the element matches the `:invalid` CSS pseudo-class.

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

| Specification |
| --- |
| HTML Standard # the-constraint-validation-api:validitystate-3 |

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

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

See also
--------

* Guide: Constraint validation
* Tutorial: Form data validation


RTCRtpScriptTransform - Web APIs

RTCRtpScriptTransform
=====================

The **`RTCRtpScriptTransform`** interface of the WebRTC API is used to insert a WebRTC Encoded Transform (a `TransformStream` running in a worker thread) into the WebRTC sender and receiver pipelines.

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

`RTCRtpScriptTransform()`

Creates a new instance of the `RTCRtpScriptTransform` object.

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

None.

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

None.

Description
-----------

**`RTCRtpScriptTransform`** instances are constructed with a `Worker`, in which the transform stream code will run, along with an (optional) `options` object and array of transferrable object that will be passed to the worker.
 They are then added into incoming and outgoing RTC pipelines by assigning them to `RTCRtpReceiver.transform` and `RTCRtpSender.transform`, respectively.

 On construction of this object, and whenever an encoded frame arrives, the `rtctransform` event is fired on the worker global object.
 The event's `transformer` property is a `RTCRtpScriptTransformer`, the worker-side counterpart to the main-thread `RTCRtpScriptTransform`.
 This has `readable` (`ReadableStream`) and `writable` (`WritableStream`) properties that have been shared from the main thread `RTCRtpScriptTransform` — where they are not public.
 If the corresponding `RTCRtpScriptTransform` is used with an `RTCRtpReceiver`, then the `readable` queues incoming encoded audio or video frames from the packetizer.
 If it is used with `RTCRtpSender` then `readable` contains frames coming from a codec.

 The worker thread `rtctransform` event handler defines a pipe chain.
 This pipes encoded frames from `event.transformer.readable`, through a `TransformStream` which defines the transformation function, through to `event.transformer.writable`.
 The `event.transformer` also has the `options` object passed from the `RTCRtpScriptTransform` constructor (if defined) that can be used to determine the source of the event, and hence the specific `TransformStream` to add to the chain.

Examples
--------

 Note that these examples show how `RTCRtpScriptTransform` is defined and used.
 Worker thread transform code is covered as part of the more complete example in Using WebRTC Encoded Transforms.

### Adding a transform for outgoing frames

 This example shows how you might stream video from a user's webcam over WebRTC, adding a WebRTC encoded transform to modify the outgoing streams.
 The code assumes that there is an `RTCPeerConnection` called `peerConnection` that is already connected to a remote peer.

First we gets a `MediaStreamTrack`, using `getUserMedia()` to get a video `MediaStream` from a media device, and then the `MediaStream.getTracks()` method to get the first `MediaStreamTrack` in the stream.

 The track is added to the peer connection using `addTrack()` and sent.
 The `addTrack()` method returns the `RTCRtpSender` that is being used to send the track.

```js
// Get Video stream and MediaTrack
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
const [track] = stream.getTracks();
const videoSender = peerConnection.addTrack(track, stream);
```

 An `RTCRtpScriptTransform` is then constructed taking a worker script, which defines the transform, and an optional object that can be used to pass arbitrary messages to the worker (in this case we've used a `name` property with value "senderTransform" to tell the worker that this transform will be added to the outbound stream).
 We then add the transform to the sender by assigning it to the `RTCRtpSender.transform` property.

```js
// Create a worker containing a TransformStream
const worker = new Worker("worker.js");
videoSender.transform = new RTCRtpScriptTransform(worker, {
  name: "senderTransform",
});
```

 Note that you can add the transform at any time.
 However by adding it immediately after calling `addTrack()` the transform will get the first encoded frame that is sent.

### Adding a transform for incoming frames

 This example shows how you add a WebRTC encoded transform to modify an incoming stream.
 The code assumes that there is an `RTCPeerConnection` called `peerConnection` that is already connected to a remote peer.

 First we add an `RTCPeerConnection` `track` event handler to catch the event when a new track is streamed.
 Within the handler we construct an `RTCRtpScriptTransform` and add it to `event.receiver.transform` (`event.receiver` is a `RTCRtpReceiver`).
 As in the previous example, the constructor takes an object with `name` property: but here we use `receiverTransform` as the value to tell the worker that frames are incoming from the packetizer.

```js
peerConnection.ontrack = (event) => {
  const worker = new Worker("worker.js");
  event.receiver.transform = new RTCRtpScriptTransform(worker, {
    name: "receiverTransform",
  });
  received_video.srcObject = event.streams[0];
};
```

 Note again that you can add the transform stream at any time.
 However by adding it in the `track` event handler ensures that the transform stream will get the first encoded frame for the track.

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

| Specification |
| --- |
| WebRTC Encoded Transform # rtcrtpscripttransform |

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

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

See also
--------

* Using WebRTC Encoded Transforms
* `TransformStream`
* `RTCRtpScriptTransformer`


OfflineAudioCompletionEvent - Web APIs

OfflineAudioCompletionEvent
===========================

The Web Audio API `OfflineAudioCompletionEvent` interface represents events that occur when the processing of an `OfflineAudioContext` is terminated. The `complete` event uses this interface.

**Note:** This interface is marked as deprecated; it is still supported for legacy reasons, but it will soon be superseded when the promise version of `OfflineAudioContext.startRendering` is supported in browsers, which will no longer need it.

Event

OfflineAudioCompletionEventConstructor
-----------

`OfflineAudioCompletionEvent()`

Creates a new `OfflineAudioCompletionEvent` object instance.

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

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

`OfflineAudioCompletionEvent.renderedBuffer` Read only

An `AudioBuffer` containing the result of processing an `OfflineAudioContext`.

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

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

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

| Specification |
| --- |
| Web Audio API # OfflineAudioCompletionEvent |

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

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

See also
--------

* Using the Web Audio API


The WebSocket API (WebSockets) - Web APIs

The WebSocket API (WebSockets)
==============================

The **WebSocket API** is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

**Note:** While a WebSocket connection is functionally somewhat similar to standard Unix-style sockets, they are not related.

Interfaces
----------

`WebSocket`

The primary interface for connecting to a WebSocket server and then sending and receiving data on the connection.

`CloseEvent`

The event sent by the WebSocket object when the connection closes.

`MessageEvent`

The event sent by the WebSocket object when a message is received from the server.

Guides
------

* Writing WebSocket client applications
* Writing WebSocket servers
* Writing a WebSocket server in C#
* Writing a WebSocket server in Java
* Writing a WebSocket server in JavaScript (Deno)
Tools
-----

* AsyncAPI: A specification for describing event-driven architectures based on protocols like WebSocket. You can use it to describe WebSocket-based APIs just as you would describe REST APIs with the OpenAPI specification. Learn why you should consider using AsyncAPI with WebSocket and how to do so.
* HumbleNet: A cross-platform networking library that works in the browser. It consists of a C wrapper around WebSockets and WebRTC that abstracts away cross-browser differences, facilitating the creation of multi-user networking functionality for games and other apps.
* µWebSockets: Highly scalable WebSocket server and client implementation for C++11 and Node.js.
* Socket.IO: A long polling/WebSocket based third party transfer protocol for Node.js.
* SocketCluster: A pub/sub WebSocket framework for Node.js with a focus on scalability.
* WebSocket-Node: A WebSocket server API implementation for Node.js.
* Total.js: Web application framework for Node.js (Example: WebSocket chat)
* Faye: A `WebSocket` (two-ways connections) and EventSource (one-way connections) for Node.js Server and Client.
* SignalR: SignalR will use WebSockets under the covers when it's available, and gracefully fallback to other techniques and technologies when it isn't, while your application code stays the same.
* Caddy: A web server capable of proxying arbitrary commands (stdin/stdout) as a websocket.
* ws: a popular WebSocket client & server library for Node.js.
* jsonrpc-bidirectional: Asynchronous RPC which, on a single connection, may have functions exported on the server and, and the same time, on the client (client may call server, server may also call client).
* cowboy: Cowboy is a small, fast and modern HTTP server for Erlang/OTP with WebSocket support.
* ZeroMQ: ZeroMQ is embeddable networking library that carries messages across in-process, IPC, TCP, UDP, TIPC, multicast and WebSocket.
* WebSocket King: A client tool to help develop, test and work with WebSocket servers.
* PHP WebSocket Server: Server written in PHP to handle connections via websockets wss:// or ws://and normal sockets over ssl:// ,tcp://
* Channels: Django library that adds support for WebSockets (and other protocols that require long running asynchronous connections).
* Flask-SocketIO: gives Flask applications access to low latency bi-directional communications between the clients and the server.
* Gorilla WebSocket: Gorilla WebSocket is a Go implementation of the WebSocket protocol.
Specifications
--------------

| Specification |
| --- |
| WebSockets Standard # the-websocket-interface |

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

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

See also
--------

* RFC 6455 — The WebSocket Protocol
* WebSocket API Specification
* Server-Sent Events


XMLHttpRequest API - Web APIs

XMLHttpRequest API
==================

**Note:** This feature is available in Web Workers, except for Service Workers

The **XMLHttpRequest API** enables web apps to make HTTP requests to web servers and receive the responses programmatically using JavaScript. This in turn enables a website to update just part of a page with data from the server, rather than having to navigate to a whole new page. This practice is also sometimes known as Ajax.

The Fetch API is the more flexible and powerful replacement for the XMLHttpRequest API. The Fetch API uses promises instead of events to handle asynchronous responses, integrates well with service workers, and supports advanced aspects of HTTP such as CORS. For these reasons, the Fetch API is usually used in modern web apps instead of `XMLHttpRequest`.

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

The central interface in the XMLHttpRequest API is `XMLHttpRequest`. To make an HTTP request:

1. Create a new `XMLHttpRequest` instance by calling its constructor.
2. Initialize it by calling `XMLHttpRequest.open()`. At this point you provide the URL for the request, the HTTP method to use, and optionally, a username and password.
3. Attach event handlers to get the result of the request. For example, the `load` event is fired when the request has successfully completed, and the `error` event is fired in various error conditions.
4. Send the request by calling `XMLHttpRequest.send()`.

For an in-depth guide to the XMLHttpRequest API, see Using XMLHttpRequest.

Interfaces
----------

`FormData`

An object representing `<form>` fields and their values, which can be sent to a server using `XMLHttpRequest` or `fetch()`.

`ProgressEvent`

A subclass of `Event` which is passed into the `progress`, and which contains information about how much of the request has been completed.

`XMLHttpRequest`

Represents a single HTTP request.

`XMLHttpRequestEventTarget`

A superclass of both `XMLHttpRequest` and `XMLHttpRequestUpload`, defining the events that are available in both of those interfaces.

`XMLHttpRequestUpload`

Represents the upload process for an HTTP upload. Provides events enabling code to track the progress of an upload.

Examples
--------

### Fetching JSON data from the server

In this example we fetch a JSON file from https://raw.githubusercontent.com/, adding event listeners to show the progress of the event.

#### HTML

```html
<div class="controls">
  <button class="xhr" type="button">Click to start XHR</button>
</div>

<textarea readonly class="event-log"></textarea>
```

```
.event-log {
  width: 25rem;
  height: 5rem;
  border: 1px solid black;
  margin: 0.5rem;
  padding: 0.2rem;
}

button {
  width: 12rem;
  margin: 0.5rem;
}
```

#### JavaScript

```js
const xhrButton = document.querySelector(".xhr");
const log = document.querySelector(".event-log");
const url =
  "https://raw.githubusercontent.com/mdn/content/main/files/en-us/\_wikihistory.json";

function handleEvent(e) {
  log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`;
}

function addListeners(xhr) {
  xhr.addEventListener("loadstart", handleEvent);
  xhr.addEventListener("load", handleEvent);
  xhr.addEventListener("loadend", handleEvent);
  xhr.addEventListener("progress", handleEvent);
  xhr.addEventListener("error", handleEvent);
  xhr.addEventListener("abort", handleEvent);
}

xhrButton.addEventListener("click", () => {
  log.textContent = "";

  const xhr = new XMLHttpRequest();
  xhr.open("GET", url);
  addListeners(xhr);
  xhr.send();
});
```

#### Result

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

| Specification |
| --- |
| XMLHttpRequest Standard  |

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

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

See also
--------

* Fetch API


Encrypted Media Extensions API - Web APIs

Encrypted Media Extensions API
==============================

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

The Encrypted Media Extensions API provides interfaces for controlling the playback of content which is subject to a digital restrictions management scheme.

Access to this API is provided through `Navigator.requestMediaKeySystemAccess()`.

Interfaces
----------

`MediaEncryptedEvent`

Represents a specific `encrypted` event thrown when a `HTMLMediaElement` encounters some initialization data.

`MediaKeyMessageEvent`

Contains the content and related data when the content decryption module (CDM) generates a message for the session.

`MediaKeys`

Represents a set of keys that an associated `HTMLMediaElement` can use for decryption of media data during playback.

`MediaKeySession`

Represents a context for message exchange with a content decryption module (CDM).

`MediaKeyStatusMap`

A read-only map of media key statuses by key IDs.

`MediaKeySystemAccess`

Provides access to a key system for decryption and/or a content protection provider.

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

| Specification |
| --- |
| Encrypted Media Extensions # navigator-extension-requestmediakeysystemaccess |

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

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


DOMPoint - Web APIs

DOMPoint
========

A **`DOMPoint`** object represents a 2D or 3D point in a coordinate system; it includes values for the coordinates in up to three dimensions, as well as an optional perspective value. `DOMPoint` is based on `DOMPointReadOnly` but allows its properties' values to be changed.

In general, a positive `x` component represents a position to the right of the origin, a positive `y` component is downward from the origin, and a positive `z` component extends outward from the screen (in other words, toward the user).

DOMPointReadOnly

DOMPointConstructor
-----------

`DOMPoint()`

Creates and returns a new `DOMPoint` object given the values of zero or more of its coordinate components and optionally the `w` perspective value. You can also use an existing `DOMPoint` or `DOMPointReadOnly` or an object to create a new point by calling the `DOMPoint.fromPoint()` static method.

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

*`DOMPoint` may also inherit properties from its parent, `DOMPointReadOnly`.*

`DOMPoint.x`

The `x` coordinate of the `DOMPoint`.

`DOMPoint.y`

The `y` coordinate of the `DOMPoint`.

`DOMPoint.z`

The `z` coordinate of the `DOMPoint`.

`DOMPoint.w`

The perspective value of the `DOMPoint`.

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

*`DOMPoint` inherits instance methods from its parent, `DOMPointReadOnly`.*

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

*`DOMPoint` may also inherit static methods from its parent, `DOMPointReadOnly`.*

`DOMPoint.fromPoint()`

Creates a new mutable `DOMPoint` object given an existing point (or an object containing matching properties), which provides the values for its properties.

Examples
--------

In the WebXR Device API, `DOMPointReadOnly` values represent positions and orientations. In the following snippet, the pose of the XR device (such as a VR headset or phone with AR capabilities) can be retrieved by calling using `XRFrame.getViewerPose()` during an `XRSession` animation frame, then accessing the resulting `XRPose`'s `transform` property, which contains two `DOMPointReadOnly` attributes: `position` as a vector and `orientation` as a quaternion.

```js
function onXRFrame(time, xrFrame) {
  let viewerPose = xrFrame.getViewerPose(xrReferenceSpace);

  if (viewerPose) {
    let position = viewerPose.transform.position;
    let orientation = viewerPose.transform.orientation;

    console.log(
      `XR Viewer Position: {x: ${roundToTwo(position.x)}, y: ${roundToTwo(
 position.y,
 )}, z: ${roundToTwo(position.z)}`,
    );

    console.log(
      `XR Viewer Orientation: {x: ${roundToTwo(orientation.x)}, y: ${roundToTwo(
 orientation.y,
 )}, z: ${roundToTwo(orientation.z)}, w: ${roundToTwo(orientation.w)}`,
    );
  }
}
```

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # DOMPoint |

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

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

See also
--------

* `DOMRect`
* `DOMMatrix`


GainNode - Web APIs

GainNode
========

The `GainNode` interface represents a change in volume. It is an `AudioNode` audio-processing module that causes a given gain to be applied to the input data before its propagation to the output. A `GainNode` always has exactly one input and one output, both with the same number of channels.

The gain is a unitless value, changing with time, that is multiplied to each corresponding sample of all input channels. If modified, the new gain is instantly applied, causing unaesthetic 'clicks' in the resulting audio. To prevent this from happening, never change the value directly but use the exponential interpolation methods on the `AudioParam` interface.

![The GainNode is increasing the gain of the output.](/en-US/docs/Web/API/GainNode/webaudiogainnode.png)

EventTarget

AudioNode

GainNode

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"max"` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `"speakers"` |

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

`GainNode()`

Creates and returns a new `GainNode` object. As an alternative, you can use the `BaseAudioContext.createGain()` factory method; see Creating an AudioNode.

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

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

`GainNode.gain` Read only

An a-rate `AudioParam` representing the amount of gain to apply. You have to set `AudioParam.value` or use the methods of `AudioParam` to change the effect of gain.

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

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

Example
-------

See `BaseAudioContext.createGain()` for example code showing how to use an `AudioContext` to create a `GainNode`.

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

| Specification |
| --- |
| Web Audio API # GainNode |

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

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

See also
--------

* Using the Web Audio API


SVGAnimateMotionElement - Web APIs

SVGAnimateMotionElement
=======================

The **`SVGAnimateMotionElement`** interface corresponds to the `<animateMotion>` element.

EventTarget

Node

Element

SVGElement

SVGAnimationElement

SVGAnimateMotionElementInstance properties
-------------------

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

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

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

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

| Specification |
| --- |
| SVG Animations Level 2 # InterfaceSVGAnimateMotionElement |

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

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


PushSubscriptionOptions - Web APIs

PushSubscriptionOptions
=======================

The **`PushSubscriptionOptions`** interface of the Push API represents the options associated with a push subscription.

The read-only `PushSubscriptionOptions` object is returned by calling `PushSubscription.options` on a `PushSubscription`. This interface has no constructor of its own.

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

`PushSubscriptionOptions.userVisibleOnly` Read only

 A boolean value indicating that the returned push
 subscription will only be used for messages whose effect is made visible to the user.

`PushSubscriptionOptions.applicationServerKey` Read only

 A public key your push server will use to send
 messages to client apps via a push server.

Examples
--------

Calling `PushSubscription.options` on a `PushSubscription` returns a `PushSubscriptionOptions` object. In the example below this is printed to the console.

```js
navigator.serviceWorker.ready.then((reg) => {
  reg.pushManager.getSubscription().then((subscription) => {
    const options = subscription.options;
    console.log(options); // a PushSubscriptionOptions object
  });
});
```

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

| Specification |
| --- |
| Push API # dom-pushsubscriptionoptions |

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

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


WebGLSync - Web APIs

WebGLSync
=========

The **`WebGLSync`** interface is part of the WebGL 2 API and is used to synchronize activities between the GPU and the application.

WebGLObject

WebGLSync
When working with `WebGLSync` objects, the following methods of the `WebGL2RenderingContext` are useful:

* `WebGL2RenderingContext.fenceSync()`
* `WebGL2RenderingContext.deleteSync()`
* `WebGL2RenderingContext.isSync()`
* `WebGL2RenderingContext.clientWaitSync()`
* `WebGL2RenderingContext.waitSync()`
* `WebGL2RenderingContext.getSyncParameter()`
Examples
--------

### Creating a `WebGLSync` object

in this example, `gl` must be a `WebGL2RenderingContext`. `WebGLSync` objects are not available in WebGL 1.

```js
const sync = gl.fenceSync(gl.SYNC\_GPU\_COMMANDS\_COMPLETE, 0);
```

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

| Specification |
| --- |
| WebGL 2.0 Specification # 3.4 |

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

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

See also
--------

* `WebGLRenderingContext.finish()`


DOMParser - Web APIs

DOMParser
=========

 The **`DOMParser`** interface provides
 the ability to parse XML or HTML source code from a
 string into a DOM `Document`.

 You can perform the opposite operation—converting a DOM tree into XML or HTML
 source—using the `XMLSerializer` interface.

 In the case of an HTML document, you can also replace portions of the DOM with new DOM
 trees built from HTML by setting the value of the `Element.innerHTML` and
 `outerHTML` properties. These properties can also be
 read to fetch HTML fragments corresponding to the corresponding DOM subtree.

 Note that `XMLHttpRequest` can parse XML and HTML directly
 from a URL-addressable resource, returning a `Document` in its
 `response` property.

**Note:** Be aware that block-level elements
 like `<p>` will be automatically closed if another
 block-level element is nested inside and therefore parsed before the closing `</p>` tag.

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

`DOMParser()`

Creates a new `DOMParser` object.

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

`DOMParser.parseFromString()`

Parses a string using either the HTML parser or the XML parser, returning an `HTMLDocument` or `XMLDocument`.

Examples
--------

The documentation for `DOMParser.parseFromString()`, this interface's only method, contains examples for parsing XML, SVG, and HTML strings.

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

| Specification |
| --- |
| HTML Standard # dom-parsing-and-serialization |

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

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

See also
--------

* Parsing and serializing XML
* `XMLHttpRequest`
* `XMLSerializer`
* `JSON.parse()` - counterpart for `JSON` documents.


SVGFEImageElement - Web APIs

SVGFEImageElement
=================

The **`SVGFEImageElement`** interface corresponds to the `<feImage>` element.

EventTarget

Node

Element

SVGElement

SVGFEImageElementInstance properties
-------------------

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

`SVGFEImageElement.crossOrigin` Read only

An `SVGAnimatedString` reflects the `crossorigin` attribute of the given element, limited to only known values.

`SVGFEImageElement.height` Read only

An `SVGAnimatedLength` corresponding to the `height` attribute of the given element.

`SVGFEImageElement.href` Read only

An `SVGAnimatedString` that reflects the `href` or `xlink:href`
Deprecated
 attribute of the given element.

`SVGFEImageElement.preserveAspectRatio` Read only

An `SVGAnimatedPreserveAspectRatio` corresponding to the `preserveAspectRatio` attribute of the given element.

`SVGFEImageElement.result` Read only

An `SVGAnimatedString` corresponding to the `result` attribute of the given element.

`SVGFEImageElement.width` Read only

An `SVGAnimatedLength` corresponding to the `width` attribute of the given element.

`SVGFEImageElement.x` Read only

An `SVGAnimatedLength` corresponding to the `x` attribute of the given element.

`SVGFEImageElement.y` Read only

An `SVGAnimatedLength` corresponding to the `y` attribute of the given element.

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

*This interface does not provide any specific methods, but implements those of its parent, `SVGElement`.*

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

| Specification |
| --- |
| Filter Effects Module Level 1 # InterfaceSVGFEImageElement |

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

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

See also
--------

* `<feImage>`


URL - Web APIs

URL
===

The **`URL`** interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.

You normally create a new `URL` object by specifying the URL as a string when calling its constructor, or by providing a relative URL and a base URL. You can then easily read the parsed components of the URL or make changes to the URL.

If a browser doesn't yet support the `URL()` constructor, you can access a URL object using the `Window` interface's `URL` property. Be sure to check to see if any of your target browsers require this to be prefixed.

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

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

`URL()`

Creates and returns a `URL` object referencing the URL specified using an absolute URL string, or a relative URL string and a base URL string.

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

`hash`

A string containing a `'#'` followed by the fragment identifier of the URL.

`host`

A string containing the domain (that is the *hostname*) followed by (if a port was specified) a `':'` and the *port* of the URL.

`hostname`

A string containing the domain of the URL.

`href`

A stringifier that returns a string containing the whole URL.

`origin` Read only

Returns a string containing the origin of the URL, that is its scheme, its domain and its port.

`password`

A string containing the password specified before the domain name.

`pathname`

A string containing an initial `'/'` followed by the path of the URL, not including the query string or fragment.

`port`

A string containing the port number of the URL.

`protocol`

A string containing the protocol scheme of the URL, including the final `':'`.

`search`

A string indicating the URL's parameter string; if any parameters are provided, this string includes all of them, beginning with the leading `?` character.

`searchParams` Read only

A `URLSearchParams` object which can be used to access the individual query parameters found in `search`.

`username`

A string containing the username specified before the domain name.

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

`canParse()`

Returns a boolean indicating whether or not a URL defined from a URL string and optional base URL string is parsable and valid.

`createObjectURL()`

Returns a string containing a unique blob URL, that is a URL with `blob:` as its scheme, followed by an opaque string uniquely identifying the object in the browser.

`revokeObjectURL()`

Revokes an object URL previously created using `URL.createObjectURL()`.

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

`toString()`

Returns a string containing the whole URL. It is a synonym for `URL.href`, though it can't be used to modify the value.

`toJSON()`

Returns a string containing the whole URL. It returns the same string as the `href` property.

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

The constructor takes a `url` parameter, and an optional `base` parameter to use as a base if the `url` parameter is a relative URL:

```js
const url = new URL("../cats", "http://www.example.com/dogs");
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"
```

 The constructor will raise an exception if the URL cannot be parsed to a valid URL.
 You can either call the above code in a `try...catch` block or use the `canParse()` static method to first check the URL is valid:

```js
if (URL.canParse("../cats", "http://www.example.com/dogs")) {
  const url = new URL("../cats", "http://www.example.com/dogs");
  console.log(url.hostname); // "www.example.com"
  console.log(url.pathname); // "/cats"
} else {
  console.log("Invalid URL"); //Invalid URL
}
```

URL properties can be set to construct the URL:

```js
url.hash = "tabby";
console.log(url.href); // "http://www.example.com/cats#tabby"
```

URLs are encoded according to the rules found in RFC 3986. For instance:

```js
url.pathname = "démonstration.html";
console.log(url.href); // "http://www.example.com/d%C3%A9monstration.html"
```

The `URLSearchParams` interface can be used to build and manipulate the URL query string.

To get the search params from the current window's URL, you can do this:

```js
// https://some.site/?id=123
const parsedUrl = new URL(window.location.href);
console.log(parsedUrl.searchParams.get("id")); // "123"
```

The `toString()` method of `URL` just returns the value of the `href` property, so the constructor can be used to normalize and encode a URL directly.

```js
const response = await fetch(
  new URL("http://www.example.com/démonstration.html"),
);
```

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

| Specification |
| --- |
| URL Standard # url |

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

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

See also
--------

* Polyfill of `URL` in `core-js`
* URL API
* What is a URL?
* Property to obtain a `URL` object: `URL`.
* `URLSearchParams`.


SpeechGrammar - Web APIs

SpeechGrammar
=============

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

The **`SpeechGrammar`** interface of the Web Speech API represents a set of words or patterns of words that we want the recognition service to recognize.

Grammar is defined using JSpeech Grammar Format (**JSGF**.) Other formats may also be supported in the future.

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

`SpeechGrammar()`
Non-standard

Experimental

Creates a new `SpeechGrammar` object.

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

`SpeechGrammar.src`
Experimental

Sets and returns a string containing the grammar from within in the `SpeechGrammar` object instance.

`SpeechGrammar.weight` Optional
Experimental

Sets and returns the weight of the `SpeechGrammar` object.

Examples
--------

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;

console.log(speechRecognitionList[0].src); // should return the same as the contents of the grammar variable
console.log(speechRecognitionList[0].weight); // should return 1 - the same as the weight set in line 4.
```

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

| Specification |
| --- |
| Web Speech API # speechreco-speechgrammar |

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

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

See also
--------

* Web Speech API


CSSValueList - Web APIs

CSSValueList
============

**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 **`CSSValueList`** interface derives from the `CSSValue` interface and provides the abstraction of an ordered collection of CSS values.

**Note:** This interface was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do
 not implement it.

To achieve your purpose, you can use:

* the untyped CSS Object Model, widely supported, or
* the modern CSS Typed Object Model API, less supported and considered experimental.

Some properties allow an empty list in their syntax. In that case, these properties take the `none` identifier. So, an empty list means that the property has the value `none`.

The items in the `CSSValueList` are accessible via an integral index, starting from 0.

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

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

`CSSValueList.length` Read only
Deprecated

An `unsigned long` representing the number of `CSSValues` in the list.

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

`CSSValueList.item()`
Deprecated

This method is used to retrieve a `CSSValue` by ordinal index. The order in this collection represents the order of the values in the CSS style property. If index is greater than or equal to the number of values in the list, this returns `null`.

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

 This feature was originally defined in the DOM Style Level 2 specification, but has been dropped from any
 standardization effort since then.

It has been superseded by a modern, but incompatible, CSS Typed Object Model API that is now on the standard track.

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

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

See also
--------

* `CSSPrimitiveValue`
* `CSSValue`


GPUSupportedLimits - Web APIs

GPUSupportedLimits
==================

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

The **`GPUSupportedLimits`** interface of the WebGPU API describes the limits supported by a `GPUAdapter`.

The `GPUSupportedLimits` object for the current adapter is accessed via the `GPUAdapter.limits` property.

You should note that, rather than reporting the exact limits of each GPU, browsers will likely report different tier values of different limits to reduce the unique information available to drive-by fingerprinting. For example, the tiers of a certain limit might be 2048, 8192, and 32768. If your GPU's actual limit is 16384, the browser will still report 8192.

Given that different browsers will handle this differently and the tier values may change over time, it is hard to provide an accurate account of what limit values to expect — thorough testing is advised.

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

The following limits are represented by properties in a `GPUSupportedLimits` object. See the Limits section of the specification for detailed descriptions of what the limits relate to.

| Limit name | Default value |
| --- | --- |
| `maxTextureDimension1D` | 8192 |
| `maxTextureDimension2D` | 8192 |
| `maxTextureDimension3D` | 2048 |
| `maxTextureArrayLayers` | 256 |
| `maxBindGroups` | 4 |
| `maxBindingsPerBindGroup` | 640 |
| `maxDynamicUniformBuffersPerPipelineLayout` | 8 |
| `maxDynamicStorageBuffersPerPipelineLayout` | 4 |
| `maxSampledTexturesPerShaderStage` | 16 |
| `maxSamplersPerShaderStage` | 16 |
| `maxStorageBuffersPerShaderStage` | 8 |
| `maxStorageTexturesPerShaderStage` | 4 |
| `maxUniformBuffersPerShaderStage` | 12 |
| `maxUniformBufferBindingSize` | 65536 bytes |
| `maxStorageBufferBindingSize` | 134217728 bytes (128 MB) |
| `minUniformBufferOffsetAlignment` | 256 bytes |
| `minStorageBufferOffsetAlignment` | 256 bytes |
| `maxVertexBuffers` | 8 |
| `maxBufferSize` | 268435456 bytes (256 MB) |
| `maxVertexAttributes` | 16 |
| `maxVertexBufferArrayStride` | 2048 bytes |
| `maxInterStageShaderComponents` | 60 |
| `maxInterStageShaderVariables` | 16 |
| `maxColorAttachments` | 8 |
| `maxColorAttachmentBytesPerSample` | 32 |
| `maxComputeWorkgroupStorageSize` | 16384 bytes |
| `maxComputeInvocationsPerWorkgroup` | 256 |
| `maxComputeWorkgroupSizeX` | 256 |
| `maxComputeWorkgroupSizeY` | 256 |
| `maxComputeWorkgroupSizeZ` | 64 |
| `maxComputeWorkgroupsPerDimension` | 65535 |

Examples
--------

In the following code we query the `GPUAdapter.limits` value of `maxBindGroups` to see if it is equal to or greater than 6. Our theoretical example app ideally needs 6 bind groups, so if the returned value is >= 6, we add a maximum limit of 6 to the `requiredLimits` object. We then request a device with that limit requirement using `GPUAdapter.requestDevice()`:

```js
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const requiredLimits = {};

  // App ideally needs 6 bind groups, so we'll try to request what the app needs
  if (adapter.limits.maxBindGroups >= 6) {
    requiredLimits.maxBindGroups = 6;
  }

  const device = await adapter.requestDevice({
    requiredLimits,
  });

  // ...
}
```

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

| Specification |
| --- |
| WebGPU # gpusupportedlimits |

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

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

See also
--------

* The WebGPU API


AnalyserNode - Web APIs

AnalyserNode
============

The **`AnalyserNode`** interface represents a node able to provide real-time frequency and time-domain analysis information. It is an `AudioNode` that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations.

An `AnalyserNode` has exactly one input and one output. The node works even if the output is not connected.

![Without modifying the audio stream, the node allows to get the frequency and time-domain data associated to it, using a FFT.](/en-US/docs/Web/API/AnalyserNode/fttaudiodata_en.svg)

EventTarget

AudioNode

AnalyserNode

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` (but may be left unconnected) |
| Channel count mode | `"max"` |
| Channel count | `2` |
| Channel interpretation | `"speakers"` |

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

`AnalyserNode()`

Creates a new instance of an `AnalyserNode` object.

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

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

`AnalyserNode.fftSize`

An unsigned long value representing the size of the FFT (Fast Fourier Transform) to be used to determine the frequency domain.

`AnalyserNode.frequencyBinCount` Read only

An unsigned long value half that of the FFT size. This generally equates to the number of data values you will have to play with for the visualization.

`AnalyserNode.minDecibels`

A double value representing the minimum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the minimum value for the range of results when using `getByteFrequencyData()`.

`AnalyserNode.maxDecibels`

A double value representing the maximum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the maximum value for the range of results when using `getByteFrequencyData()`.

`AnalyserNode.smoothingTimeConstant`

A double value representing the averaging constant with the last analysis frame — basically, it makes the transition between values over time smoother.

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

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

`AnalyserNode.getFloatFrequencyData()`

Copies the current frequency data into a `Float32Array` array passed into it.

`AnalyserNode.getByteFrequencyData()`

Copies the current frequency data into a `Uint8Array` (unsigned byte array) passed into it.

`AnalyserNode.getFloatTimeDomainData()`

Copies the current waveform, or time-domain, data into a `Float32Array` array passed into it.

`AnalyserNode.getByteTimeDomainData()`

Copies the current waveform, or time-domain, data into a `Uint8Array` (unsigned byte array) passed into it.

Examples
--------

**Note:** See the guide Visualizations with Web Audio API for more information on creating audio visualizations.

### Basic usage

 The following example shows basic usage of an `AudioContext` to create an `AnalyserNode`, then `requestAnimationFrame` and `<canvas>` to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108-193 for relevant code).

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// …

const analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;

const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);

// Connect the source to be analysed
source.connect(analyser);

// Get a canvas defined with ID "oscilloscope"
const canvas = document.getElementById("oscilloscope");
const canvasCtx = canvas.getContext("2d");

// draw an oscilloscope of the current audio source

function draw() {
  requestAnimationFrame(draw);

  analyser.getByteTimeDomainData(dataArray);

  canvasCtx.fillStyle = "rgb(200 200 200)";
  canvasCtx.fillRect(0, 0, canvas.width, canvas.height);

  canvasCtx.lineWidth = 2;
  canvasCtx.strokeStyle = "rgb(0 0 0)";

  canvasCtx.beginPath();

  const sliceWidth = (canvas.width \* 1.0) / bufferLength;
  let x = 0;

  for (let i = 0; i < bufferLength; i++) {
    const v = dataArray[i] / 128.0;
    const y = (v \* canvas.height) / 2;

    if (i === 0) {
      canvasCtx.moveTo(x, y);
    } else {
      canvasCtx.lineTo(x, y);
    }

    x += sliceWidth;
  }

  canvasCtx.lineTo(canvas.width, canvas.height / 2);
  canvasCtx.stroke();
}

draw();
```

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

| Specification |
| --- |
| Web Audio API # AnalyserNode |

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

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

See also
--------

* Using the Web Audio API


NamedNodeMap - Web APIs

NamedNodeMap
============

The **`NamedNodeMap`** interface represents a collection of `Attr` objects. Objects inside a `NamedNodeMap` are not in any particular order, unlike `NodeList`, although they may be accessed by an index as in an array.

A `NamedNodeMap` object is *live* and will thus be auto-updated if changes are made to its contents internally or elsewhere.

**Note:** Although called `NamedNodeMap`, this interface doesn't deal with `Node` objects but with `Attr` objects, which are a specialized class of `Node` objects.

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

*This interface doesn't inherit any property.*

`NamedNodeMap.length` Read only

Returns the amount of objects in the map.

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

*This interface doesn't inherit any method.*

`NamedNodeMap.getNamedItem()`

Returns an `Attr`, corresponding to the given name.

`NamedNodeMap.setNamedItem()`

Replaces, or adds, the `Attr` identified in the map by the given name.

`NamedNodeMap.removeNamedItem()`

Removes the `Attr` identified by the given map.

`NamedNodeMap.item()`

Returns the `Attr` at the given index, or `null` if the index is higher or equal to the number of nodes.

`NamedNodeMap.getNamedItemNS()`

Returns an `Attr` identified by a namespace and related local name.

`NamedNodeMap.setNamedItemNS()`

Replaces, or adds, the `Attr` identified in the map by the given namespace and related local name.

`NamedNodeMap.removeNamedItemNS()`

Removes the `Attr` identified by the given namespace and related local name.

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

| Specification |
| --- |
| DOM Standard # interface-namednodemap |

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

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

See also
--------

* `Element.attributes`


ContactAddress - Web APIs

ContactAddress
==============

**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 **`ContactAddress`** interface of the Contact Picker API represents a physical address. Instances of this interface are retrieved from the `address` property of the objects returned by `ContactsManager.getProperties()`.

It may be useful to refer to the Universal Postal Union website's Addressing S42 standard materials, which provide information about international standards for postal addresses.

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

`ContactAddress.addressLine` Read only
Experimental

An array of strings providing each line of the address not included among the other properties. The exact size and content varies by country or location and can include, for example, a street name, house number, apartment number, rural delivery route, descriptive instructions, or post office box number.

`ContactAddress.country` Read only
Experimental

A string specifying the country in which the address is located, using the ISO-3166-1 alpha-2 standard. The string is always given in its canonical upper-case form. Some examples of valid `country` values: `"US"`, `"GB"`, `"CN"`, or `"JP"`.

`ContactAddress.city` Read only
Experimental

A string which contains the city or town portion of the address.

`ContactAddress.dependentLocality` Read only
Experimental

A string giving the dependent locality or sublocality within a city, for example, a neighborhood, borough, district, or UK dependent locality.

`ContactAddress.organization` Read only
Experimental

A string specifying the name of the organization, firm, company, or institution at the address.

`ContactAddress.phone` Read only
Experimental

A string specifying the telephone number of the recipient or contact person.

`ContactAddress.postalCode` Read only
Experimental

A string specifying a code used by a jurisdiction for mail routing, for example, the ZIP code in the United States or the PIN code in India.

`ContactAddress.recipient` Read only
Experimental

A string giving the name of the recipient, purchaser, or contact person at the address.

`ContactAddress.region` Read only
Experimental

A string containing the top level administrative subdivision of the country, for example a state, province, oblast, or prefecture.

`ContactAddress.sortingCode` Read only
Experimental

A string providing a postal sorting code such as is used in France.

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

`ContactAddress.toJSON()`
Experimental

A standard serializer that returns a JSON representation of the `ContactAddress` object's properties.

Examples
--------

The following example prompts the user to select contacts, then prints the first returned address to the console.

```js
const props = ["address"];
const opts = { multiple: true };

async function getContacts() {
  try {
    const contacts = await navigator.contacts.select(props, ops);
    const contactAddress = contacts[0].address[0];
    console.log(contactAddress);
  } catch (ex) {
    // Handle any errors here.
  }
}
```

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

| Specification |
| --- |
| Contact Picker API # contactaddress |

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

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


OES_vertex_array_object extension - Web APIs

OES\_vertex\_array\_object extension
====================================

The **OES\_vertex\_array\_object** extension is part of the WebGL API and provides vertex array objects (VAOs) which encapsulate vertex array states. These objects keep pointers to vertex data and provide names for different sets of vertex data.

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

**Note:** This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default and the constants and methods are available without the "`OES`" suffix.

Constants
---------

This extension exposes one new constant, which can be used in the `gl.getParameter()` method:

`ext.VERTEX_ARRAY_BINDING_OES`

Returns a `WebGLVertexArrayObject` object when used in the `gl.getParameter()` method as the `pname` parameter.

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

This extension exposes four new methods.

`ext.createVertexArrayOES()`

Creates a new `WebGLVertexArrayObject`.

`ext.deleteVertexArrayOES()`

Deletes a given `WebGLVertexArrayObject`.

`ext.isVertexArrayOES()`

Returns `true` if a given object is a `WebGLVertexArrayObject`.

`ext.bindVertexArrayOES()`

Binds a given `WebGLVertexArrayObject` to the buffer.

Examples
--------

```js
const oes_vao_ext = gl.getExtension("OES\_vertex\_array\_object");
const vao = oes_vao_ext.createVertexArrayOES();
oes_vao_ext.bindVertexArrayOES(vao);

// …
// calls to bindBuffer or vertexAttribPointer
// which will be "recorded" in the VAO
// …
```

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

| Specification |
| --- |
| WebGL OES\_vertex\_array\_object 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.vertexAttribPointer()`
* WebGL2 equivalent methods:
    + `WebGL2RenderingContext.createVertexArray()`
    + `WebGL2RenderingContext.deleteVertexArray()`
    + `WebGL2RenderingContext.isVertexArray()`
    + `WebGL2RenderingContext.bindVertexArray()`


VRDisplayEvent - Web APIs

VRDisplayEvent
==============

**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 **`VRDisplayEvent`** interface of the WebVR API represents the event object of WebVR-related events (see the list of WebVR window extensions).

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

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

`VRDisplayEvent()`
Deprecated

Non-standard

Creates a `VRDisplayEvent` object instance.

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

*`VRDisplayEvent` also inherits properties from its parent object, `Event`.*

`VRDisplayEvent.display`
Deprecated
 Read only
Non-standard

The `VRDisplay` associated with this event.

`VRDisplayEvent.reason`
Deprecated
 Read only
Non-standard

A human-readable reason why the event was fired.

Examples
--------

```js
window.addEventListener("vrdisplaypresentchange", (e) => {
  console.log(
    `Display ${e.display.displayId} presentation has changed. Reason given: ${e.reason}.`,
  );
});
```

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


IDBTransaction - Web APIs

IDBTransaction
==============

The **`IDBTransaction`** interface of the IndexedDB API provides a static, asynchronous transaction on a database using event handler attributes. All reading and writing of data is done within transactions. You use `IDBDatabase` to start transactions, `IDBTransaction` to set the mode of the transaction (e.g. is it `readonly` or `readwrite`), and you access an `IDBObjectStore` to make a request. You can also use an `IDBTransaction` object to abort transactions.

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

EventTarget

IDBTransaction
Transactions are started when the transaction is created, not when the first request is placed; for example consider this:

```js
const trans1 = db.transaction("foo", "readwrite");
const trans2 = db.transaction("foo", "readwrite");
const objectStore2 = trans2.objectStore("foo");
const objectStore1 = trans1.objectStore("foo");
objectStore2.put("2", "key");
objectStore1.put("1", "key");
```

After the code is executed the object store should contain the value "2", since `trans2` should run after `trans1`.

Transaction failures
--------------------

Transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback:

* Abort due to bad requests, e.g. trying to `add()` the same key twice, or `put()` with the same index key with a uniqueness constraint. This causes an error on the request, which can bubble up to an error on the transaction, which aborts the transaction. This can be prevented by using `preventDefault()` on the error event on the request.
* An explicit `abort()` call from script.
* An uncaught exception in the request's `success`/`error` handler.
* An I/O error (e.g. an actual failure to write to disk, or other OS/hardware failure).
* Quota exceeded.
* A user agent crash.
Firefox durability guarantees
-----------------------------

Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see Firefox bug 1112702.) Previously in a `readwrite` transaction, a `complete` event was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the `complete` event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The `complete` event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.

If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the `complete` event by creating a transaction using the experimental (non-standard) `readwriteflush` mode (see `IDBDatabase.transaction`.

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

`IDBTransaction.db` Read only

The database connection with which this transaction is associated.

`IDBTransaction.durability` Read only

Returns the durability hint the transaction was created with.

`IDBTransaction.error` Read only

Returns a `DOMException` indicating the type of error that occurred when there is an unsuccessful transaction. This property is `null` if the transaction is not finished, is finished and successfully committed, or was aborted with the `IDBTransaction.abort()` function.

`IDBTransaction.mode` Read only

The mode for isolating access to data in the object stores that are in the scope of the transaction. The default value is `readonly`.

`IDBTransaction.objectStoreNames` Read only

Returns a `DOMStringList` of the names of `IDBObjectStore` objects associated with the transaction.

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

Inherits from: `EventTarget`

`IDBTransaction.abort()`

Rolls back all the changes to objects in the database associated with this transaction. If this transaction has been aborted or completed, this method fires an error event.

`IDBTransaction.objectStore()`

Returns an `IDBObjectStore` object representing an object store that is part of the scope of this transaction.

`IDBTransaction.commit()`

For an active transaction, commits the transaction. Note that this doesn't normally *have* to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made. `commit()` can be used to start the commit process without waiting for events from outstanding requests to be dispatched.

Events
------

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

`abort`

 An event fired when the `IndexedDB` transaction is aborted.
 Also available via the `onabort` property; this event bubbles to `IDBDatabase`.

`complete`

 An event fired when the transaction successfully completes.
 Also available via the `oncomplete` property.

`error`

 An event fired when a request returns an error and the event bubbles up to the connection object (`IDBDatabase`).
 Also available via the `onerror` property.

Mode constants
--------------

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

**Warning:** These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. (Firefox bug 888598)

Transactions can have one of three modes:

| Constant | Value | Description |
| --- | --- | --- |
| `READ\_ONLY` | "readonly" (0 in Chrome) | Allows data to be read but not changed. |
| `READ\_WRITE` | "readwrite" (1 in Chrome) |
 Allows reading and writing of data in existing data stores to be
 changed.
  |
| `VERSION\_CHANGE` | "versionchange" (2 in Chrome) |
 Allows any operation to be performed, including ones that delete and
 create object stores and indexes. Transactions of this mode cannot run
 concurrently with other transactions. Transactions in this mode are
 known as "upgrade transactions."
  |

Even if these constants are now deprecated, you can still use them to provide backward compatibility if required (in Chrome the change was made in version 21). You should code defensively in case the object is not available anymore:

```js
const myIDBTransaction = window.IDBTransaction ||
  window.webkitIDBTransaction || { READ\_WRITE: "readwrite" };
```

Examples
--------

In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. For a full working example, see our To-do Notifications app (view example live).

```js
const note = document.getElementById("notifications");

// an instance of a db object for us to store the IDB data in
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db
  // variable. This is used a lot below
  db = DBOpenRequest.result;

  // Add the data to the database
  addData();
};

function addData() {
  // Create a new object to insert into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready to add data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = (event) => {
    note.innerHTML +=
      "<li>Transaction completed: database modification finished.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");

  // add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of the request (this does not mean the item
    // has been stored successfully in the DB - for that you need transaction.oncomplete)
    note.innerHTML += "<li>Request successful.</li>";
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # transaction |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


RsaOaepParams - Web APIs

RsaOaepParams
=============

The **`RsaOaepParams`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.encrypt()`, `SubtleCrypto.decrypt()`, `SubtleCrypto.wrapKey()`, or `SubtleCrypto.unwrapKey()`, when using the RSA\_OAEP algorithm.

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

`name`

A string. This should be set to `RSA-OAEP`.

`label` Optional

An `ArrayBuffer`, a `TypedArray`, or a `DataView` — an array of bytes that does not itself need to be encrypted but which should be bound to the ciphertext. A digest of the label is part of the input to the encryption operation.

Unless your application calls for a label, you can just omit this argument and it will not affect the security of the encryption operation.

Examples
--------

See the examples for `SubtleCrypto.encrypt()` and `SubtleCrypto.decrypt()`.

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

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

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

Browsers that support the "RSA-OAEP" algorithm for the `SubtleCrypto.encrypt()`, `SubtleCrypto.decrypt()`, `SubtleCrypto.wrapKey()`, or `SubtleCrypto.unwrapKey()` methods will support this type.

See also
--------

* `SubtleCrypto.encrypt()`.
* `SubtleCrypto.decrypt()`.
* `SubtleCrypto.wrapKey()`.
* `SubtleCrypto.unwrapKey()`.