Window: requestAnimationFrame() method - Web APIs

Window: requestAnimationFrame() method
======================================

 The **`window.requestAnimationFrame()`** method tells the
 browser you wish to perform an animation. It requests the browser to call a
 user-supplied callback function before the next repaint.

 The frequency of calls to the callback function will generally match the display
 refresh rate. The most common refresh rate is 60hz,
 (60 cycles/frames per second), though 75hz, 120hz, and 144hz are also widely used.
 `requestAnimationFrame()` calls are paused in most browsers when running in
 background tabs or hidden `<iframe>`s, in order to improve
 performance and battery life.

**Note:** Your callback function must call `requestAnimationFrame()` again if
 you want to animate another frame. `requestAnimationFrame()` is one-shot.

**Warning:** Be sure always to use the first argument (or some other method for
 getting the current time) to calculate how much the animation will progress in
 a frame — **otherwise, the animation will run faster on high refresh-rate screens**.
 For ways to do that, see the examples below.

Syntax
------

```js
requestAnimationFrame(callback)
```

### Parameters

* `callback`
    + The function to call when it's time to update your animation for the next
     repaint. This callback function is passed a single argument: a
     `DOMHighResTimeStamp` indicating the end time of the previous frame's
     rendering (based on the number of milliseconds since
     time origin).
    + The timestamp is a decimal number, in milliseconds, but with a minimal
     precision of 1 millisecond. For `Window` objects (not `Workers`), it is equal to
     `document.timeline.currentTime`. This timestamp is shared
     between all windows that run on the same agent (all same-origin windows
     and, more importantly, same-origin iframes) — which allows synchronizing
     animations across multiple `requestAnimationFrame` callbacks. The timestamp
     value is also similar to calling `performance.now()` at the start
     of the callback function, but it is never the same value.
    + When multiple callbacks queued by `requestAnimationFrame()` begin to fire in
     a single frame, each receives the same timestamp even though time has passed
     during the computation of every previous callback's workload.
### Return value

 A `long` integer value, the request ID, that uniquely identifies the entry
 in the callback list. This is a non-zero value, but you may not make any other
 assumptions about its value. You can pass this value to
 `window.cancelAnimationFrame()` to cancel the refresh callback request.

Examples
--------

 In this example, an element is animated for 2 seconds (2000 milliseconds). The element
 moves at a speed of 0.1px/ms to the right, so its relative position (in CSS pixels) can
 be calculated in function of the time elapsed since the start of the animation (in
 milliseconds) with `0.1 * elapsed`. The element's final position is 200px
 (`0.1 * 2000`) to the right of its initial position.

```js
const element = document.getElementById("some-element-you-want-to-animate");
let start, previousTimeStamp;
let done = false;

function step(timeStamp) {
  if (start === undefined) {
    start = timeStamp;
  }
  const elapsed = timeStamp - start;

  if (previousTimeStamp !== timeStamp) {
    // Math.min() is used here to make sure the element stops at exactly 200px
    const count = Math.min(0.1 \* elapsed, 200);
    element.style.transform = `translateX(${count}px)`;
    if (count === 200) done = true;
  }

  if (elapsed < 2000) {
    // Stop the animation after 2 seconds
    previousTimeStamp = timeStamp;
    if (!done) {
      window.requestAnimationFrame(step);
    }
  }
}

window.requestAnimationFrame(step);
```

 The following three examples illustrate different approaches to setting the zero point in time,
 the baseline for calculating the progress of your animation in each frame. If you
 want to synchronize to an external clock, such as `BaseAudioContext.currentTime`,
 the highest precision available is the duration of a single frame, 16.67ms @60hz. The
 callback's timestamp argument represents the end of the previous frame, so the soonest
 your newly calculated value(s) will be rendered is in the next frame.

 This example waits until the first callback executes to set `zero`. If your animation
 jumps to a new value when it starts, you must structure it this way. If you do not need to
 synchronize to anything external, such as audio, then this approach is recommended because
 some browsers have a multi-frame delay between the initial call to `requestAnimationFrame()`
 and the first call to the callback function.

```js
let zero;
requestAnimationFrame(firstFrame);
function firstFrame(timeStamp) {
  zero = timeStamp;
  animate(timeStamp);
}
function animate(timeStamp) {
  const value = (timeStamp - zero) / duration;
  if (value < 1) {
    element.style.opacity = value;
    requestAnimationFrame((t) => animate(t));
  } else element.style.opacity = 1;
}
```

 This example uses `document.timeline.currentTime` to set a zero value
 before the first call to `requestAnimationFrame`. `document.timeline.currentTime`
 aligns with the `timeStamp` argument, so the zero value is equivalent to the
 0th frame's timestamp.

```js
const zero = document.timeline.currentTime;
requestAnimationFrame(animate);
function animate(timeStamp) {
  const value = (timeStamp - zero) / duration; // animation-timing-function: linear
  if (value < 1) {
    element.style.opacity = value;
    requestAnimationFrame((t) => animate(t));
  } else element.style.opacity = 1;
}
```

 This example animates using `performance.now()` instead of the callback's
 timestamp value. You might use this to achieve slightly higher synchronization
 precision, though the extra degree of precision is variable and not much of an increase.
 Note: This example does not allow you to synchronize animation callbacks reliably.

```js
const zero = performance.now();
requestAnimationFrame(animate);
function animate() {
  const value = (performance.now() - zero) / duration;
  if (value < 1) {
    element.style.opacity = value;
    requestAnimationFrame((t) => animate(t));
  } else element.style.opacity = 1;
}
```

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

| Specification |
| --- |
| HTML Standard # dom-animationframeprovider-requestanimationframe |

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

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

See also
--------

* `Window.cancelAnimationFrame()`
* `DedicatedWorkerGlobalScope.requestAnimationFrame()`
* Animating with JavaScript: from setInterval to requestAnimationFrame - Blog post
* TestUFO: Test your web browser for requestAnimationFrame() Timing Deviations


Window: getDefaultComputedStyle() method - Web APIs

Window: getDefaultComputedStyle() method
========================================

**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 **`getDefaultComputedStyle()`** method gives the default computed values of all the CSS
 properties of an element, ignoring author styling. That is, only user-agent and user
 styles are taken into account.

Syntax
------

```js
getDefaultComputedStyle(element)
getDefaultComputedStyle(element, pseudoElt)
```

### Parameters

`element`

The `Element` for which to get the computed style.

`pseudoElt` Optional

 A string specifying the pseudo-element to match. Must be `null` (or not
 specified) for regular elements.

### Return value

 The returned `style` is a `CSSStyleDeclaration`
 object. The object is of the same type as the object returned by
 `Window.getComputedStyle()`, but only takes into account user-agent and
 user rules.

Examples
--------

### Simple example

```js
const elem1 = document.getElementById("elemId");
const style = window.getDefaultComputedStyle(elem1);
```

### Longer example

```html
<style>
 #elem-container {
 position: absolute;
 left: 100px;
 top: 200px;
 height: 100px;
 }
</style>

<div id="elem-container">dummy</div>
<div id="output"></div>

<script>
 const elem = document.getElementById("elem-container");
 const theCSSprop = window.getDefaultComputedStyle(elem).position;
 document.getElementById("output").innerHTML = theCSSprop; // Will output "static"
</script>
```

### Use with pseudo-elements

 The `getDefaultComputedStyle()` method can pull style info from
 pseudo-elements (e.g., `::before` or `::after`).

```html
<style>
 h3:after {
 content: " rocks!";
 }
</style>

<h3>generated content</h3>

<script>
 const h3 = document.querySelector("h3");
 const result = getDefaultComputedStyle(h3, ":after").content;

 console.log("the generated content is: ", result); // returns 'none'
</script>
```

Notes
-----

 The returned value is, in certain known cases, expressly incorrect by deliberate
 intent. In particular, to avoid the so called CSS History Leak security issue, browsers
 may expressly "lie" about the used value for a link and always return values as if a
 user has never visited the linked site, and/or limit the styles that can be applied
 using the `:visited` pseudo-selector. See https://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/
 and https://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/
 for details of the examples of how this is implemented.

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

Proposed to the CSS working group.

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

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


ImageBitmap: width property - Web APIs

ImageBitmap: width property
===========================

The read-only **`ImageBitmap.width`** property returns the `ImageBitmap` object's width in CSS pixels.

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

| Specification |
| --- |
| HTML Standard # dom-imagebitmap-width-dev |

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

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


ImageBitmap: height property - Web APIs

ImageBitmap: height property
============================

The read-only **`ImageBitmap.height`** property returns the `ImageBitmap` object's height in CSS pixels.

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

| Specification |
| --- |
| HTML Standard # dom-imagebitmap-height-dev |

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

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


ImageBitmap: close() method - Web APIs

ImageBitmap: close() method
===========================

 The **`ImageBitmap.close()`**
 method disposes of all graphical resources associated with an `ImageBitmap`.

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");

// Perform some drawing using the gl context

const bitmap = offscreen.transferToImageBitmap();
// ImageBitmap { width: 256, height: 256 }

bitmap.close();
// ImageBitmap { width: 0, height: 0 } — disposed
```

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

| Specification |
| --- |
| HTML Standard # dom-imagebitmap-close-dev |

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

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

See also
--------

* The interface defining this method, `ImageBitmap`.


HMDVRDevice: setFieldOfView() method - Web APIs

HMDVRDevice: setFieldOfView() method
====================================

**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 **`setFieldOfView()`** method of the `HMDVRDevice` interface can be used to set the field of view for one eye, or both eyes simultaneously.

Syntax
------

```js
setFieldOfView(leftFOV, rightFOV, zNear, zFar)
```

### Parameters

`leftFOV` Optional

A `VRFieldOfView` object that defines the new field of view for the left eye. If not specified, the left eye field of view does not change.

`rightFOV` Optional

A `VRFieldOfView` object that defines the new field of view for the right eye. If not specified, the right eye field of view does not change.

`zNear` Optional

The distance from the eyes of the nearest point of the view. The closest things can be and still be in the view. If not specified, the default is used — `0.01`.

`zFar` Optional

The distance from the eyes of the farthest point of the view. The furthest away things can be and still be in the view. If not specified, the default is used — `10000.0`.

### Return value

None (`undefined`).

Examples
--------

The following simple example shows a function that can be used to set a custom field of view with four specified degree values for up, right, down and left. The `VRFieldOfView()` constructor is used to create a `VRFieldOfView` object from the supplied values, which is then fed into the `setFieldOfView()` method (the default `zNear` and `zFar` values are always used, in this case.)

```js
function setCustomFOV(up, right, down, left) {
  const testFOV = new VRFieldOfView(up, right, down, left);

  gHMD.setFieldOfView(testFOV, testFOV, 0.01, 10000.0);

  const lEye = gHMD.getEyeParameters("left");
  const rEye = gHMD.getEyeParameters("right");
  console.log(lEye.currentFieldOfView);
  console.log(rEye.currentFieldOfView);
}
```

**Note:** When testing, setting a weird/tiny field of view can really mess up your view. It is a good idea to grab the current field of view first (using `VREyeParameters.fieldOfView`) before making any drastic changes, so you can reset it afterwards if needed.

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

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

See also
--------

* WebVR API


HMDVRDevice: getEyeParameters() method - Web APIs

HMDVRDevice: getEyeParameters() method
======================================

**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 **`getEyeParameters()`** method of the `HMDVRDevice` interface returns current parameters for the eye specified as its argument ("left" or "right") — stored in a `VREyeParameters` object.

This includes field of view information, and more.

Syntax
------

```js
getEyeParameters(whichEye)
```

### Parameters

`whichEye`

A string representing the eye you want to return information about. The value can be `left` or `right`.

### Return value

A `VREyeParameters` object.

Examples
--------

The following example is taken from the Mozilla VR Team's threejs-vr-boilerplate code — to be precise, the VREffect.js file. Early on in the code the `getEyeParameters()` method is used to access information about each eye, which is then used for rendering calculations later on.

```js
if (vrHMD.getEyeParameters !== undefined) {
  const eyeParamsL = vrHMD.getEyeParameters("left");
  const eyeParamsR = vrHMD.getEyeParameters("right");

  eyeTranslationL = eyeParamsL.eyeTranslation;
  eyeTranslationR = eyeParamsR.eyeTranslation;
  eyeFOVL = eyeParamsL.recommendedFieldOfView;
  eyeFOVR = eyeParamsR.recommendedFieldOfView;
} else {
  // …
}
```

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

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

See also
--------

* WebVR API


Using the CSS properties and values API - Web APIs

Using the CSS properties and values API
=======================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **CSS Properties and Values API** — part of the CSS Houdini umbrella of APIs — allows the registration of `CSS custom properties`, allowing for property type checking, default values, and properties that do or do not inherit their value.

Registering a custom property
-----------------------------

Registering a custom property allows you to tell the browser how the custom property should behave; what types are allowed, whether the custom property inherits its value, and what the default value of the custom property is. There are two ways to register a property, in JavaScript or in CSS.

### CSS.registerProperty

The following will register a `CSS custom property` named `--my-prop` using `CSS.registerProperty`. `--my-prop` will use the CSS color syntax, it will have a default value of `#c0ffee`, and it will not inherit its value:

```js
window.CSS.registerProperty({
  name: "--my-prop",
  syntax: "<color>",
  inherits: false,
  initialValue: "#c0ffee",
});
```

### @property

The same registration can take place in CSS. The following will register a `CSS custom property` named `--my-prop` using the `@property` at-rule. `--my-prop` will use the CSS color syntax, it will have a default value of `#c0ffee`, and it will not inherit its value:

```css
@property --my-prop {
  syntax: "<color>";
  inherits: false;
  initial-value: #c0ffee;
}
```

Using registered custom properties
----------------------------------

One of the advantages of registering a property is that the browser now knows how to handle your custom property through things like transitions! When a property isn't registered, the browser doesn't know how to treat it, so it assumes that any value can be used and therefore can't animate it. When a property has a registered syntax, though, the browser can optimize around that syntax, including being able to animate it!

In this example, the custom property `--registered` has been registered using the syntax `<color>` and then used in a linear gradient. That property is then transitioned on hover or focus to a different color. Notice that the transition works with the registered property but not the unregistered one!

### HTML

```html
<button class="registered">Background Registered</button>
<button class="unregistered">Background Not Registered</button>
```

### CSS

```css
.registered {
  --registered: #c0ffee;
  background-image: linear-gradient(to right, #fff, var(--registered));
  transition: --registered 1s ease-in-out;
}

.registered:hover,
.registered:focus {
  --registered: #b4d455;
}

.unregistered {
  --unregistered: #c0ffee;
  background-image: linear-gradient(to right, #fff, var(--unregistered));
  transition: --unregistered 1s ease-in-out;
}

.unregistered:hover,
.unregistered:focus {
  --unregistered: #b4d455;
}

button {
  height: 40vh;
  display: block;
  width: 100%;
  font-size: 3vw;
}
```

### JavaScript

```js
window.CSS.registerProperty({
  name: "--registered",
  syntax: "<color>",
  inherits: false,
  initialValue: "red",
});
```

### Result

While not functionally accurate, a good way to think about the difference between the unregistered property in the above example and the registered property is the difference between a `<custom-ident>` and a number when trying to animate `height`. You cannot transition or animate from `auto` to a number because the browser doesn't know the value of `auto` until it's calculated. With an unregistered property, the browser likewise doesn't know what the value *may be* until it's calculated, and because of that, it can't set up a transition from one value to another. When registered, though, you've told the browser what type of value it should expect, and because it knows that, it can then set up the transitions properly.

Gotchas
-------

There are two gotchas when registering a property. The first is that, once a property is registered, there's no way to update it, and trying to re-register it with JavaScript will throw an error indicating it's already been defined.

Second, unlike standard properties, registered properties aren't validated when they're parsed. Rather, they're validated when they're computed. That means both that invalid values won't appear as invalid when inspecting the element's properties, and that including an invalid property after a valid one won't fall back to the valid property. An invalid property will, however, fall back to its registered default.

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

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


WebTransport: closed property - Web APIs

WebTransport: closed property
=============================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`closed`** read-only property of the `WebTransport` interface returns a promise that resolves when the transport is closed.

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

Value
-----

A `Promise` that resolves to an object containing the following properties:

`closeCode`

A number representing the error code for the error.

`reason`

A string representing the reason for closing the `WebTransport`.

Examples
--------

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

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

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

  // ...
}

// ...

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

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

| Specification |
| --- |
| WebTransport # dom-webtransport-closed |

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

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

See also
--------

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


WebTransport: incomingUnidirectionalStreams property - Web APIs

WebTransport: incomingUnidirectionalStreams property
====================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`incomingUnidirectionalStreams`** read-only property of the `WebTransport` interface represents one or more unidirectional streams opened by the server. Returns a `ReadableStream` of `WebTransportReceiveStream` objects. Each one can be used to reliably read data from the server.

"Reliable" means that transmission and order of data are guaranteed. This provides slower delivery (albeit faster than with WebSockets) than `datagrams`, but is needed in situations where reliability and ordering are important, like chat applications.

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

Value
-----

A `ReadableStream` of `WebTransportReceiveStream` objects.

Examples
--------

An initial function is used to read the `WebTransportReceiveStream` objects from the `ReadableStream`. Each object is then passed to another function to read from those streams.

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

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

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

| Specification |
| --- |
| WebTransport # dom-webtransport-incomingunidirectionalstreams |

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

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

See also
--------

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


WebTransport: datagrams property - Web APIs

WebTransport: datagrams property
================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`datagrams`** read-only property of the `WebTransport` interface returns a `WebTransportDatagramDuplexStream` instance that can be used to send and receive datagrams — unreliable data transmission.

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

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

Value
-----

A `WebTransportDatagramDuplexStream` object.

Examples
--------

### Writing an outgoing datagram

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

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

### Reading an incoming datagram

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

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

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

| Specification |
| --- |
| WebTransport # dom-webtransport-datagrams |

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

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

See also
--------

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


WebTransport: ready property - Web APIs

WebTransport: ready property
============================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`ready`** read-only property of the `WebTransport` interface returns a promise that resolves when the transport is ready to use.

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

Value
-----

A `Promise` that resolves to `undefined`.

Examples
--------

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

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

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

  // ...
}

// ...

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

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

| Specification |
| --- |
| WebTransport # dom-webtransport-ready |

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

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

See also
--------

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


WebTransport: getStats() method - Web APIs

WebTransport: getStats() method
===============================

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

The **`getStats()`** method of the `WebTransport` interface asynchronously returns an object containing HTTP/3 connection statistics.

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

Syntax
------

```js
getStats()
```

### Parameters

None.

### Return value

 A `Promise` that resolves to a object containing HTTP/3 connection statistics.
 The returned object may have the following properties/statistics:

`timestamp`

A `DOMHighResTimeStamp` indicating the timestamp at which the statistics were gathered, relative to Jan 1, 1970, UTC.

`bytesSent`

 A positive integer indicating the number of bytes sent on the QUIC connection, including retransmissions.
 Note that this count does not include additional data from protocols used by QUIC, such as UDP, or any other outer framing.

`packetsSent`

A positive integer indicating the number of packets sent on the QUIC connection, including those that are known to have been lost.

`packetsLost`

 A positive integer indicating the number of packets lost on the QUIC connection.
 This value will increase as packets are declared lost, and decrease if they are subsequently received.

`numOutgoingStreamsCreated`

A positive integer indicating the number of outgoing QUIC streams created on the QUIC connection.

`numIncomingStreamsCreated`

A positive integer indicating the number of incoming QUIC streams created on the QUIC connection.

`bytesReceived`

 A positive integer indicating the total number of bytes received on the QUIC connection.
 This count includes duplicate data from streams, but does not include additional data for protocols used by QUIC, such as UDP, or any other outer framing.

`packetsReceived`

A positive integer indicating the total number of packets received on the QUIC connection, including packets that were not processable.

`smoothedRtt`

A `DOMHighResTimeStamp` containing the smoothed round-trip time (RTT) currently observed on the connection, calculated as an exponentially weighted moving average of an endpoint's RTT samples after taking account of acknowledgement delays.

`rttVariation`

A `DOMHighResTimeStamp` containing the mean variation in round-trip time samples currently observed on the connection.

`minRtt`

A `DOMHighResTimeStamp` containing the minimum round-trip time observed on the entire connection.

`datagrams`

 An object containing statistics for datagram transmission over the connection.
 The object has the following properties:

`timestamp`

A `DOMHighResTimeStamp` indicating the timestamp at which the statistics were gathered, relative to Jan 1, 1970, UTC.

`expiredOutgoing`

 A positive integer indicating the number of datagrams that were dropped from the queue for sending because they expired.
 Note that the maximum age before a datagram in the send-queue expires can be found in `outgoingMaxAge`.

`droppedIncoming`

 A positive integer indicating the number incoming datagrams that were dropped.
 Incoming datagrams are dropped if the application does not read them before new datagrams overflow the `readable` stream receive queue.

`lostOutgoing`

 A positive integer indicating the number of sent datagrams that were declared lost.
 Note that a datagram may be declared lost if, for example, no acknowledgement arrived within a timeout, or an acknowledgement for a later datagram was received first.

Examples
--------

 The example below uses `await` to wait on the `Promise` returned by `getStats()`.
 When the promise fulfills, the result for the `bytesSent` property in the stats object is logged to the console.

```js
const stats = await transport.getStats();
console.log(`Bytes send: ${stats.bytesSent}`);
```

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

| Specification |
| --- |
| WebTransport # dom-webtransport-getstats |

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

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


WebTransport: WebTransport() constructor - Web APIs

WebTransport: WebTransport() constructor
========================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`WebTransport()`** constructor creates a new `WebTransport` object instance.

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

Syntax
------

```js
new WebTransport(url)
new WebTransport(url, options)
```

### Parameters

`url`

 A string representing the URL of the HTTP/3 server to connect to.
 The scheme must be HTTPS, and the port number needs to be explicitly specified.

`options` Optional

An object that may have the following properties:

`allowPooling` Optional

 A boolean value.
 If `true`, the network connection for this `WebTransport` can be shared with a pool of other HTTP/3 sessions.
 By default the value is `false`, and the connection cannot be shared.

`congestionControl` Optional

 A string indicating the application's preference that the congestion control algorithm used when sending data over this connection be tuned for either throughput or low-latency.
 This is a hint to the user agent.
 The allowed values are: `default` (default), `throughput`, and `low-latency`.

`requireUnreliable` Optional

 A boolean value.
 If `true`, the connection cannot be established over HTTP/2 if an HTTP/3 connection is not possible.
 By default the value is `false`.

`serverCertificateHashes` Optional

 An array of objects, each defining the hash value of a server certificate along with the name of the algorithm that was used to generate it.
 This option is only supported for transports using dedicated connections (`allowPooling` is `false`).

 If specified, the browser will attempt to authenticate the certificate provided by the server against the provided certificate hash(es) in order to connect, instead of using the Web public key infrastructure (PKI).
 If any hashes match, the browser knows that the server has possession of a trusted certificate and will connect as normal.
 If empty the user agent uses the same PKI certificate verification procedures it would use for a normal fetch operation.

This feature allows developers to connect to WebTransport servers that would normally find obtaining a publicly trusted certificate challenging, such as hosts that are not publicly routable, or ephemeral hosts like virtual machines.

**Note:** The web application might typically fetch the hashes from a trusted intermediary.
 For example, you might use a cloud provider to provision VMs that run your WebTransport servers.
 The provider has trusted access to the server and can request its certificate, generate hashes, and provide these to the application via an API (which is mediated via PKI), or a cloud console.
 The web application can now connect directly to the VM-hosted server using the supplied hashes, even though the VM itself does not have a long-lived TLS certificate.

 The certificate must be an X.509v3 certificate that has a validity period of less that 2 weeks, and the current time must be within that validity period.
 The format of the public key in the certificate depends on the implementation, but must minimally include ECDSA with the secp256r1 (NIST P-256) named group, and must not include RSA keys.
 An ECSDA key is therefore an interoperable default public key format.
 A user agent may add further requirements; these will be listed in the browser compatibility section if known.

Each object in the array has the following properties:

`algorithm`

 A string with the value: `sha-256` (case-insensitive).
 Note that this string represents the algorithm to use to verify the hash, and that any hash using an unknown algorithm will be ignored.
 At time of writing, `SHA-256` is the only hash algorithm listed in the specification.

`value`

An `ArrayBuffer` or `TypedArray` containing the hash value.

### Exceptions

`NotSupportedError` `DOMException`

Thrown if `serverCertificateHashes` is specified but the transport protocol does not support this feature.

`SyntaxError`

Thrown if the specified `url` is invalid, if the scheme is not HTTPS, or if the URL includes a fragment.

`TypeError`

Thrown if a `serverCertificateHashes` is set for a non-dedicated connection (in other words, if `allowPooling` is `true`).

Examples
--------

### Connecting with default options

This example shows how you might construct a `WebTransport` using just a URL, wait for it to connect, and then monitor the transport and report when it has closed.

 First we define an `async` method that takes an URL and uses it to construct the `WebTransport` object.
 No constructor options are specified, so the connection uses default options: dedicated connection, support for unreliable transports is not required, default congestion control, and normal Web PKI authentication with the server.
 Note that the scheme needs to be HTTPS, and the port number needs to be explicitly specified.

Once the `WebTransport.ready` promise fulfills, you can start using the connection.

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

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

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

 The `closeTransport()` method below shows how.
 Within a `try...catch` block it uses `await` to wait for the `closed` promise to fulfill or reject, and then reports whether or not the connection closed intentionally or due to error.

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

We might call the asynchronous functions above in their own asynchronous function, as shown below.

```js
// Use the transport
async function useTransport(url) {
  const transport = await initTransport(url);

  // Use the transport object to send and receive data
  // ...

  // When done, close the transport
  await closeTransport(transport);
}

const url = "https://example.com:4999/wt";
useTransport(url);
```

### Connecting with server certificate hashes

 The example below shows the code to construct a `WebTransport` that specifies the `serverCertificateHashes` option.
 In this case the array contains two hashes, both encoded using the SHA-256 algorithm.
 Note that the `allowPooling` option must be `false` (the default).

```js
const transport = new WebTransport(url, {
  serverCertificateHashes: [
    {
      algorithm: "sha-256",
      value: "5a155927eba7996228455e4721e6fe5f739ae15db6915d765e5db302b4f8a274",
    },
    {
      algorithm: "sha-256",
      value: "7d7094e7a8d3097feff3b5ee84fa5cab58e4de78f38bcfdee5ea8b51f4bfa8fd",
    },
  ],
});
```

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

| Specification |
| --- |
| WebTransport # dom-webtransport-webtransport |

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

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

See also
--------

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


WebTransport: congestionControl property - Web APIs

WebTransport: congestionControl property
========================================

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

The **`congestionControl`** read-only property of the `WebTransport` interface indicates the application's preference for either high throughput or low-latency when sending data.

The value is set in the `WebTransport()` constructor options.

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

Value
-----

A string with one of the following values:

`default`

 The default congestion control tuning for the transport.
 This is the default.

`throughput`

The application prefers congestion control to be tuned for throughput.

`low-latency`

The application prefers congestion control to be tuned for low-latency.

Examples
--------

 This example shows how to get the `congestionControl` preference.
 As this is not explicitly set in the constructor, the result is `default`.

```js
const url = "https://example.com:4999/wt";
const transport = new WebTransport(url);
console.log(transport.congestionControl); // default
```

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

| Specification |
| --- |
| WebTransport # dom-webtransport-congestioncontrol |

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

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


WebTransport: createUnidirectionalStream() method - Web APIs

WebTransport: createUnidirectionalStream() method
=================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`createUnidirectionalStream()`** method of the `WebTransport` interface asynchronously opens a unidirectional stream.

The method returns a `Promise` that resolves to a `WritableStream` object, which can be used to reliably write data to the server.

"Reliable" means that transmission and order of data are guaranteed. This provides slower delivery (albeit faster than with WebSockets) than `datagrams`, but is needed in situations where reliability and ordering are important, like chat applications.

 The relative order in which queued bytes are emptied from created streams can be specified using the `sendOrder` option.
 If set, queued bytes in streams with a higher send order are guaranteed to be sent before queued bytes for streams with a lower send order.
 If the order number is not set then the order in which bytes are sent is implementation dependent.
 Note however that even though bytes from higher send-order streams are sent first, they may not arrive first.

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

Syntax
------

```js
createUnidirectionalStream()
createUnidirectionalStream(options)
```

### Parameters

`options` Optional

An object that may have the following properties:

`sendOrder` Optional

 A integer value specifying the send priority of this stream relative to other streams for which the value has been set.
 Queued bytes are sent first for streams that have a higher value.
 If not set, the send order depends on the implementation.

### Return value

A `Promise` that resolves to a `WebTransportSendStream` object (this is a `WritableStream`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if `createUnidirectionalStream()` is invoked while the WebTransport is closed or failed.

Examples
--------

Use the `createUnidirectionalStream()` method to get a reference to a `WritableStream`. From this you can get a writer to allow data to be written to the stream and sent to the server.

Use the `close()` method of the resulting `WritableStreamDefaultWriter` to close the associated HTTP/3 connection. The browser tries to send all pending data before actually closing the associated connection.

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

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

You can also use `WritableStreamDefaultWriter.abort()` to abruptly terminate the stream. When using `abort()`, the browser may discard any pending data that hasn't yet been sent.

```js
// ...

const stream = await transport.createUnidirectionalStream();
const writer = ws.getWriter();

// ...

writer.write(...);
writer.write(...);
await writer.abort();
// Not all the data may have been written.
```

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

| Specification |
| --- |
| WebTransport # dom-webtransport-createunidirectionalstream |

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

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

See also
--------

* Using WebTransport
* `WebTransport.createBidirectionalStream()`
* WebSockets API
* Streams API
* WebTransport over HTTP/3


WebTransport: createBidirectionalStream() method - Web APIs

WebTransport: createBidirectionalStream() method
================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`createBidirectionalStream()`** method of the `WebTransport` interface asynchronously opens and returns a bidirectional stream.

 The method returns a `Promise` that resolves to a `WebTransportBidirectionalStream` object, which has `readable` and `writable` properties that can be used to reliably read from and write to the server.
 "Reliable" means that transmission and order of data are guaranteed.
 This provides slower delivery (albeit faster than with WebSockets) than `datagrams`, but is needed in situations where reliability and ordering are important, like chat applications.

 The relative order in which queued bytes are emptied from created streams can be specified using the `sendOrder` option.
 If set, queued bytes in streams with a higher send order are guaranteed to be sent before queued bytes for streams with a lower send order.
 If the order number is not set then the order in which bytes are sent is implementation dependent.
 Note however that even though bytes from higher send-order streams are sent first, they may not arrive first.

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

Syntax
------

```js
createBidirectionalStream()
createBidirectionalStream(options)
```

### Parameters

`options` Optional

An object that may have the following properties:

`sendOrder` Optional

 A integer value specifying the send priority of this stream relative to other streams for which the value has been set.
 Queued bytes are sent first for streams that have a higher value.
 If not set, the send order depends on the implementation.

### Return value

A `Promise` that resolves to a `WebTransportBidirectionalStream` object.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if `createBidirectionalStream()` is invoked while the `WebTransport` is closed or failed.

Examples
--------

An initial function is used to get references to the `WebTransportBidirectionalStream.readable` and `WebTransportBidirectionalStream.writable` properties. These are references to `WebTransportReceiveStream` and `WebTransportSendStream` instances, which are readable and writable streams that can be used to read from and write to the server.

```js
async function setUpBidirectional() {
  const stream = await transport.createBidirectionalStream({
    sendOrder: "596996858",
  });
  // stream is a WebTransportBidirectionalStream
  // stream.readable is a ReadableStream
  const readable = stream.readable;
  // stream.writable is a WritableStream
  const writable = stream.writable;

  // ...
}
```

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

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

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

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

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

| Specification |
| --- |
| WebTransport # dom-webtransport-createbidirectionalstream |

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

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

See also
--------

* Using WebTransport
* `WebTransport.createUnidirectionalStream()`
* WebSockets API
* Streams API
* WebTransport over HTTP/3


WebTransport: incomingBidirectionalStreams property - Web APIs

WebTransport: incomingBidirectionalStreams property
===================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`incomingBidirectionalStreams`** read-only property of the `WebTransport` interface represents one or more bidirectional streams opened by the server. Returns a `ReadableStream` of `WebTransportBidirectionalStream` objects. Each one can be used to reliably read data from the server and write data back to it.

"Reliable" means that transmission and order of data are guaranteed. This provides slower delivery (albeit faster than with WebSockets) than `datagrams`, but is needed in situations where reliability and ordering are important, like chat applications.

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

Value
-----

A `ReadableStream` of `WebTransportBidirectionalStream` objects.

Examples
--------

An initial function is used to read the `WebTransportBidirectionalStream` objects from the `ReadableStream`. For each one, the `WebTransportBidirectionalStream.readable` and `WebTransportBidirectionalStream.writable` values are passed to other functions to read from and write to those streams.

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

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

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

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

| Specification |
| --- |
| WebTransport # dom-webtransport-incomingbidirectionalstreams |

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

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

See also
--------

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


WebTransport: close() method - Web APIs

WebTransport: close() method
============================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`close()`** method of the `WebTransport` interface closes an ongoing WebTransport session.

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

Syntax
------

```js
close(info)
```

### Parameters

`info` Optional

An object containing the following properties:

`closeCode`

A number representing the error code for the error.

`reason`

A string representing the reason for closing the `WebTransport`.

### Return value

`undefined`.

### Exceptions

`WebTransportError`

Thrown if `close()` is invoked while the WebTransport is in the process of connecting.

Examples
--------

```js
const url = "https://example.com:4999/wt";
// Initialize transport connection
const transport = new WebTransport(url);

// ...

transport.close({
  closeCode: 017,
  reason: "CloseButtonPressed",
});
```

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

| Specification |
| --- |
| WebTransport # dom-webtransport-close |

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

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

See also
--------

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


WebTransport: reliability property - Web APIs

WebTransport: reliability property
==================================

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

The **`reliability`** read-only property of the `WebTransport` interface indicates whether the connection supports reliable transports only, or whether it also supports unreliable transports (such as UDP).

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

Value
-----

A string with one of the following values:

`pending`

 The connection has not yet been established.
 The reliability is not yet known.

`reliable-only`

The connection only supports reliable transports.

`supports-unreliable`

The connection supports both unreliable and reliable transports.

Examples
--------

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

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

  // Once ready fulfils the connection can be used
  // Prior to this the reliability is "pending"
  await transport.ready;

  if (transport.reliability == "reliable-only") {
    // Use connection only with reliable transports
  } else {
    // Use connection with either reliable or unreliable transports.
  }
  // ...
}
```

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

| Specification |
| --- |
| WebTransport # dom-webtransport-reliability |

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

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


SpeechGrammarList: SpeechGrammarList() constructor - Web APIs

SpeechGrammarList: SpeechGrammarList() constructor
==================================================

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

 The **`SpeechGrammarList()`** constructor creates a new
 `SpeechGrammarList` object instance.

Syntax
------

```js
new SpeechGrammarList()
```

### Parameters

None.

Examples
--------

 In our simple Speech color changer example, we create a new `SpeechRecognition` object
 instance using the `SpeechRecognition()` constructor, create a new `SpeechGrammarList`, add
 our grammar string to it using the `SpeechGrammarList.addFromString`
 method, and set it to be the grammar that will be recognized by the
 `SpeechRecognition` instance using the
 `SpeechRecognition.grammars` property.

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

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

| Specification |
| --- |
| Web Speech API # dom-speechgrammarlist-speechgrammarlist |

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

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

See also
--------

* Web Speech API


SpeechGrammarList: length property - Web APIs

SpeechGrammarList: length property
==================================

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

 The **`length`** read-only property of the
 `SpeechGrammarList` interface returns the number of
 `SpeechGrammar` objects contained in the `SpeechGrammarList`.

Value
-----

 A number indicating the number of `SpeechGrammar` objects contained in the
 `SpeechGrammarList`.

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;

speechRecognitionList.length; // should return 1.
```

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

| Specification |
| --- |
| Web Speech API # dom-speechgrammarlist-length |

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

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

See also
--------

* Web Speech API


SpeechGrammarList: item() method - Web APIs

SpeechGrammarList: item() method
================================

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

 The **`item`** getter of the `SpeechGrammarList`
 interface is a standard getter — it allows individual `SpeechGrammar`
 objects to be retrieved from the `SpeechGrammarList` using array syntax.

Syntax
------

```js
item(index)
```

### Parameters

`index`

Index of the item to retrieve.

### Return value

A `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;

const myFirstGrammar = speechRecognitionList[0]; // variable contain the object created above
```

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

| Specification |
| --- |
| Web Speech API # dom-speechgrammarlist-item |

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

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

See also
--------

* Web Speech API


SpeechGrammarList: addFromURI() method - Web APIs

SpeechGrammarList: addFromURI() method
======================================

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

 The **`addFromURI()`** method of the
 `SpeechGrammarList` interface takes a grammar present at a specific URI and
 adds it to the `SpeechGrammarList` as a new `SpeechGrammar`
 object.

 Note that some speech recognition services may support built-in grammars that can be
 specified by URI.

Syntax
------

```js
addFromURI(src)
addFromURI(src, weight)
```

### Parameters

`src`

A string representing the URI of the grammar to be added.

`weight` Optional

 A float representing the weight of the grammar relative to other grammars present in
 the `SpeechGrammarList`. The weight means the importance of this grammar,
 or the likelihood that it will be recognized by the speech recognition service. The
 value can be between `0.0` and `1.0`; If not specified, the
 default used is `1.0`.

### Return value

None (`undefined`).

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;

speechRecognitionList.addFromURI("http://www.example.com/grammar.txt"); // adds a second grammar to the list.
```

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

| Specification |
| --- |
| Web Speech API # dom-speechgrammarlist-addfromuri |

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

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

See also
--------

* Web Speech API


SpeechGrammarList: addFromString() method - Web APIs

SpeechGrammarList: addFromString() method
=========================================

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

 The **`addFromString()`** method of the
 `SpeechGrammarList` interface takes a grammar present in a specific
 string within the code base (e.g. stored in a variable) and adds it to
 the `SpeechGrammarList` as a new `SpeechGrammar` object.

Syntax
------

```js
addFromString(string)
addFromString(string, weight)
```

### Parameters

`string`

A string representing the grammar to be added.

`weight` Optional

 A float representing the weight of the grammar relative to other grammars present in
 the `SpeechGrammarList`. The weight means the importance of this grammar,
 or the likelihood that it will be recognized by the speech recognition service. The
 value can be between `0.0` and `1.0`; If not specified, the
 default used is `1.0`.

### Return value

None (`undefined`).

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

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

| Specification |
| --- |
| Web Speech API # dom-speechgrammarlist-addfromstring |

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

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

See also
--------

* Web Speech API


LaunchQueue: setConsumer() method - Web APIs

LaunchQueue: setConsumer() method
=================================

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

The **`setConsumer()`** method of the `LaunchQueue` interface is used to declare the callback that will handle custom launch navigation handling in a progressive web app (PWA). Such custom navigation is initiated via `Window.launchQueue` when a PWA has been launched with a `launch_handler` `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`.

Syntax
------

```js
setConsumer(callback)
```

### Parameters

`callback`

A callback function that handles custom navigation for the PWA. The callback is passed a `LaunchParams` object instance as a parameter.

### Return value

`undefined`.

Examples
--------

```js
if ("launchQueue" in window) {
  window.launchQueue.setConsumer((launchParams) => {
    if (launchParams.targetURL) {
      const params = new URL(launchParams.targetURL).searchParams;

      // Assuming a music player app that gets a track passed to it to be played
      const track = params.get("track");
      if (track) {
        audio.src = track;
        title.textContent = new URL(track).pathname.substr(1);
        audio.play();
      }
    }
  });
}
```

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

| Specification |
| --- |
| Web App Launch Handler API # dom-launchqueue-setconsumer |

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

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

See also
--------

* Launch Handler API: Control how your app is launched
* `Window.launchQueue`
* Musicr 2.0 demo app


RTCIceParameters: password property - Web APIs

RTCIceParameters: password property
===================================

 The **`RTCIceParameters`**
 dictionary's **`password`** property specifies the ICE
 password that, in tandem with the `usernameFragment`, uniquely identifies an ICE session for its entire
 duration.

Value
-----

 A string containing the password that corresponds to the transport's
 `usernameFragment` string

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

#### No specification found

No specification data found for `api.RTCIceParameters.password`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


RTCIceParameters: usernameFragment property - Web APIs

RTCIceParameters: usernameFragment property
===========================================

 The **`RTCIceParameters`** dictionary's
 **`usernameFragment`** property specifies the username fragment
 ("ufrag") that uniquely identifies the corresponding ICE session for the duration of the
 current ICE session.

Value
-----

 A string containing the username fragment that, in tandem with the
 `password`, uniquely identify the ICE session
 being used by the transport. The string may be up to 256 characters long.

 See `RTCIceCandidate.usernameFragment` to learn more about username
 fragments and their role in a connection.

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

#### No specification found

No specification data found for `api.RTCIceParameters.usernameFragment`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


OffscreenCanvasRenderingContext2D: commit() method - Web APIs

OffscreenCanvasRenderingContext2D: commit() method
==================================================

 The
 **`OffscreenCanvasRenderingContext2D.commit()`**
 method of the Canvas 2D API copies the rendering context's bitmap to the bitmap of the placeholder `<canvas>` element of the associated `OffscreenCanvas` object.
 The copy operation is synchronous. Calling this method is not needed for the transfer, since it happens automatically during the event-loop execution.

Syntax
------

```js
commit()
```

Examples
--------

```js
const placeholder = document.createElement("canvas");
const offscreen = placeholder.transferControlToOffscreen();
const ctx = offscreenCanvas.getContext("2d");

// Perform some drawing using the 2d context
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 10, 10);

// Push placeholder to the canvas element
ctx.commit();
```

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

| Specification |
| --- |
| HTML Standard # offscreencontext2d-commit |

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

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

See also
--------

* The interface defining this method: `OffscreenCanvasRenderingContext2D`


Headers: delete() method - Web APIs

Headers: delete() method
========================

 The **`delete()`** method of the `Headers`
 interface deletes a header from the current `Headers` object.

This method throws a `TypeError` for the following reasons:

* The value of the name parameter is not the name of an HTTP header.
* The value of Guard is `immutable`.

 For security reasons, some headers can only be controlled by the user agent. These
 headers include the forbidden header names
 and forbidden response header names.

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

Syntax
------

```js
delete(name)
```

### Parameters

`name`

The name of the HTTP header you want to delete from the `Headers` object.

### Return value

None (`undefined`).

Examples
--------

Creating an empty `Headers` object is simple:

```js
const myHeaders = new Headers(); // Currently empty
```

You could add a header to this using `Headers.append`:

```js
myHeaders.append("Content-Type", "image/jpeg");
myHeaders.get("Content-Type"); // Returns 'image/jpeg'
```

You can then delete it again:

```js
myHeaders.delete("Content-Type");
myHeaders.get("Content-Type"); // Returns null, as it has been deleted
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-headers-delete① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Headers: entries() method - Web APIs

Headers: entries() method
=========================

 The **`Headers.entries()`** method returns an
 `iterator` allowing to go through all key/value pairs
 contained in this object. Both the key and value of each pair are
 `String` objects.

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

Syntax
------

```js
entries()
```

### Parameters

None.

### Return value

Returns an `iterator`.

Examples
--------

```js
// Create a test Headers object
const myHeaders = new Headers();
myHeaders.append("Content-Type", "text/xml");
myHeaders.append("Vary", "Accept-Language");

// Display the key/value pairs
for (const pair of myHeaders.entries()) {
  console.log(`${pair[0]}: ${pair[1]}`);
}
```

The result is:
```

content-type: text/xml
vary: Accept-Language
```

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Headers: Headers() constructor - Web APIs

Headers: Headers() constructor
==============================

 The **`Headers()`** constructor creates a new
 `Headers` object.

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

Syntax
------

```js
new Headers()
new Headers(init)
```

### Parameters

`init` Optional

 An object containing any HTTP headers
 that you want to pre-populate your `Headers` object with. This can be a
 simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing
 `Headers` object. In the last case, the new `Headers` object
 copies its data from the existing `Headers` object.

Examples
--------

Creating an empty `Headers` object is simple:

```js
const myHeaders = new Headers(); // Currently empty
```

You could add a header to this using `Headers.append`:

```js
myHeaders.append("Content-Type", "image/jpeg");
myHeaders.get("Content-Type"); // Returns 'image/jpeg'
```

 Or you can add the headers you want as the `Headers` object is created. In
 the following snippet we create a new `Headers` object, adding some headers
 by passing the constructor an init object as an argument:

```js
const httpHeaders = {
  "Content-Type": "image/jpeg",
  "X-My-Custom-Header": "Zeke are cool",
};
const myHeaders = new Headers(httpHeaders);
```

 You can now create another `Headers` object, passing it the first
 `Headers` object as its init object:

```js
const secondHeadersObj = new Headers(myHeaders);
secondHeadersObj.get("Content-Type"); // Would return 'image/jpeg' — it inherits it from the first headers object
```

 You can also add the headers you want as the `Headers` object is created by using a two-dimensional array to add multiple headers with the same values. In
 the following snippet we create a new `Headers` object with multiple `Set-Cookie` headers
 by passing the constructor an init array as an argument:

```js
const headers = [
  ["Set-Cookie", "greeting=hello"],
  ["Set-Cookie", "name=world"],
];
const myHeaders = new Headers(headers);
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-headers① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Headers: has() method - Web APIs

Headers: has() method
=====================

 The **`has()`** method of the `Headers` interface
 returns a boolean stating whether a `Headers` object contains a certain
 header.

 For security reasons, some headers can only be controlled by the user agent. These
 headers include the forbidden header names
 and forbidden response header names.

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

Syntax
------

```js
has(name)
```

### Parameters

`name`

 The name of the HTTP header you want to test for. If the given name is not a valid
 HTTP header name, this method throws a `TypeError`.

### Return value

A boolean value.

Examples
--------

Creating an empty `Headers` object is simple:

```js
const myHeaders = new Headers(); // Currently empty
```

 You could add a header to this using `Headers.append`, then test for the
 existence of it using `has()`:

```js
myHeaders.append("Content-Type", "image/jpeg");
myHeaders.has("Content-Type"); // Returns true
myHeaders.has("Accept-Encoding"); // Returns false
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-headers-has① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Headers: get() method - Web APIs

Headers: get() method
=====================

 The **`get()`** method of the `Headers` interface
 returns a byte string of all the values of a header within a `Headers` object
 with a given name. If the requested header doesn't exist in the `Headers`
 object, it returns `null`.

 For security reasons, some headers can only be controlled by the user agent. These
 headers include the forbidden header names
 and forbidden response header names.

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

Syntax
------

```js
get(name)
```

### Parameters

`name`

 The name of the HTTP header whose values you want to retrieve from the
 `Headers` object. If the given name is not the name of an HTTP header, this
 method throws a `TypeError`. The name is case-insensitive.

### Return value

 A `String` sequence representing the values of the retrieved header or
 `null` if this header is not set.

Examples
--------

Creating an empty `Headers` object is simple:

```js
const myHeaders = new Headers(); // Currently empty
myHeaders.get("Not-Set"); // Returns null
```

 You could add a header to this using `Headers.append`, then retrieve it
 using `get()`:

```js
myHeaders.append("Content-Type", "image/jpeg");
myHeaders.get("Content-Type"); // Returns "image/jpeg"
```

 If the header has multiple values associated with it, the byte string will contain all
 the values, in the order they were added to the Headers object:

```js
myHeaders.append("Accept-Encoding", "deflate");
myHeaders.append("Accept-Encoding", "gzip");
myHeaders.get("Accept-Encoding"); // Returns "deflate, gzip"
myHeaders
  .get("Accept-Encoding")
  .split(",")
  .map((v) => v.trimStart()); // Returns [ "deflate", "gzip" ]
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-headers-get① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Headers: keys() method - Web APIs

Headers: keys() method
======================

 The **`Headers.keys()`** method returns an
 `iterator` allowing to go through all keys contained
 in this object. The keys are `String` objects.

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

Syntax
------

```js
keys()
```

### Parameters

None.

### Return value

Returns an `iterator`.

Examples
--------

```js
// Create a test Headers object
const myHeaders = new Headers();
myHeaders.append("Content-Type", "text/xml");
myHeaders.append("Vary", "Accept-Language");

// Display the keys
for (const key of myHeaders.keys()) {
  console.log(key);
}
```

The result is:
```

content-type
vary
```

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Headers: set() method - Web APIs

Headers: set() method
=====================

 The **`set()`** method of the `Headers` interface
 sets a new value for an existing header inside a `Headers` object, or adds
 the header if it does not already exist.

 The difference between `set()` and `Headers.append` is that if
 the specified header already exists and accepts multiple values, `set()`
 overwrites the existing value with the new one, whereas `Headers.append`
 appends the new value to the end of the set of values.

 For security reasons, some headers can only be controlled by the user agent. These
 headers include the forbidden header names
 and forbidden response header names.

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

Syntax
------

```js
set(name, value)
```

### Parameters

`name`

 The name of the HTTP header you want to set to a new value. If the given name is not
 the name of an HTTP header, this method throws a `TypeError`.

`value`

The new value you want to set.

### Return value

None (`undefined`).

Examples
--------

Creating an empty `Headers` object is simple:

```js
const myHeaders = new Headers(); // Currently empty
```

 You could add a header to this using `Headers.append`, then set a new
 value for this header using `set()`:

```js
myHeaders.append("Content-Type", "image/jpeg");
myHeaders.set("Content-Type", "text/html");
```

 If the specified header does not already exist, `set()` will create it and
 set its value to the specified value. If the specified header does already exist and
 does accept multiple values, `set()` will overwrite the existing value with
 the new one:

```js
myHeaders.set("Accept-Encoding", "deflate");
myHeaders.set("Accept-Encoding", "gzip");
myHeaders.get("Accept-Encoding"); // Returns 'gzip'
```

 You'd need `Headers.append` to append the new value onto the values, not
 overwrite it.

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-headers-set① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Headers: getSetCookie() method - Web APIs

Headers: getSetCookie() method
==============================

The **`getSetCookie()`** method of the `Headers` interface returns an array containing the values of all `Set-Cookie` headers associated with a response. This allows `Headers` objects to handle having multiple `Set-Cookie` headers, which wasn't possible prior to its implementation.

This method is intended for use on server environments (for example Node.js). Browsers block frontend JavaScript code from accessing the `Set-Cookie` header, as required by the Fetch spec, which defines `Set-Cookie` as a forbidden response-header name that must be filtered out from any response exposed to frontend code.

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

Syntax
------

```js
getSetCookie()
```

### Parameters

None.

### Return value

An array of strings representing the values of all the different `Set-Cookie` headers associated with a response.

If no `Set-Cookie` headers are set, the method will return an empty array (`[ ]`).

Examples
--------

As alluded to above, running code like the following on the client won't return any results — `Set-Cookie` is filtered out from `Headers` retrieved over the network.

```js
fetch("https://example.com").then((response) => {
  console.log(response.headers.getSetCookie());
  // No header values returned
});
```

However, the following could be used to query multiple `Set-Cookie` values. This is much more useful on the server, but it would also work on the client.

```js
const headers = new Headers({
  "Set-Cookie": "name1=value1",
});

headers.append("Set-Cookie", "name2=value2");

headers.getSetCookie();
// Returns ["name1=value1", "name2=value2"]
```

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

| Specification |
| --- |
| Fetch Standard # dom-headers-getsetcookie |

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

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

See also
--------

* HTTP
* `Set-Cookie`


Headers: forEach() method - Web APIs

Headers: forEach() method
=========================

The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object.

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

Syntax
------

```js
forEach(callbackFn)
forEach(callbackFn, thisArg)
```

### Parameters

`callbackFn`

Function to execute for each entry in the map. It takes the following arguments:

`value`

Value of the currently visited header entry.

`key`

Name of the currently visited header entry.

`object`

The Headers object being iterated.

`thisArg` Optional

Value to use as `this` when executing `callback`.

### Return value

`undefined`.

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

The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined.

Examples
--------

### Printing the contents of Headers object

The following code logs a line for each key/value in the `myHeaders` object.

```js
// Create a new test Headers object
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Cookie", "This is a demo cookie");
myHeaders.append("compression", "gzip");

// Display the key/value pairs
myHeaders.forEach((value, key) => {
  console.log(`${key} ==> ${value}`);
});
```

The result is:
```

compression ==> gzip
content-type ==> application/json
cookie ==> This is a demo cookie
```

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

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

See also
--------

* `Map.prototype.forEach()`
* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Headers: append() method - Web APIs

Headers: append() method
========================

 The **`append()`** method of the `Headers`
 interface appends a new value onto an existing header inside a `Headers`
 object, or adds the header if it does not already exist.

 The difference between `set()` and `append()` is
 that if the specified header already exists and accepts multiple values,
 `set()` will overwrite the existing value with the new one, whereas
 `append()` will append the new value onto the end of the set of values.

 For security reasons, some headers can only be controlled by the user agent. These
 headers include the forbidden header names
 and forbidden response header names.

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

Syntax
------

```js
append(name, value)
```

### Parameters

`name`

The name of the HTTP header you want to add to the `Headers` object.

`value`

The value of the HTTP header you want to add.

### Return value

None (`undefined`).

Examples
--------

Creating an empty `Headers` object is simple:

```js
const myHeaders = new Headers(); // Currently empty
```

You could add a header to this using `append()`:

```js
myHeaders.append("Content-Type", "image/jpeg");
myHeaders.get("Content-Type"); // Returns 'image/jpeg'
```

 If the specified header already exists, `append()` will change its value to
 the specified value. If the specified header already exists and accepts multiple values,
 `append()` will append the new value to the end of the value set:

```js
myHeaders.append("Accept-Encoding", "deflate");
myHeaders.append("Accept-Encoding", "gzip");
myHeaders.get("Accept-Encoding"); // Returns 'deflate, gzip'
```

To overwrite the old value with a new one, use `Headers.set`.

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-headers-append① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Headers: values() method - Web APIs

Headers: values() method
========================

 The **`Headers.values()`** method returns an
 `iterator` allowing to go through all values contained
 in this object. The values are `String` objects.

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

Syntax
------

```js
values()
```

### Parameters

None.

### Return value

Returns an `iterator`.

Examples
--------

```js
// Create a test Headers object
const myHeaders = new Headers();
myHeaders.append("Content-Type", "text/xml");
myHeaders.append("Vary", "Accept-Language");

// Display the values
for (const value of myHeaders.values()) {
  console.log(value);
}
```

The result is:
```

text/xml
Accept-Language
```

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


RTCIceCandidate: foundation property - Web APIs

RTCIceCandidate: foundation property
====================================

 The **`RTCIceCandidate`**
 interface's read-only **`foundation`** property is a string
 which uniquely identifies the candidate across multiple transports.

 The `foundation` can therefore be used to correlate candidates that are present on
 multiple `RTCIceTransport` objects

Value
-----

 A string which uniquely identifies the candidate across all
 `RTCIceTransport`s on which it is available.

**Note:** If `port` is `null` — and
 `port` is supported by the user agent — passing the
 candidate to `addIceCandidate()`
 will fail, throwing an `OperationError` exception.

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

 Consider this SDP attribute line (a-line) which describes an ICE
 candidate:
```

a=candidate:4234997325 1 udp 2043278322 192.0.2.172 44323 typ host
```

The field `"4234997325"` is the foundation.

Examples
--------

 This code snippet uses the `foundation` of two candidates to determine if
 they're actually the same candidate.

```js
if (candidate1.foundation === candidate2.foundation) {
  /\* the two candidates are the same, even if they're on
 different transports \*/
}
```

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

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

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

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


RTCIceCandidate: relatedPort property - Web APIs

RTCIceCandidate: relatedPort property
=====================================

The **`RTCIceCandidate`** interface's read-only **`relatedPort`** property indicates the port number of reflexive or relay candidates.

If the candidate is a host candidate (that is, its `address` is in fact the real IP address of the remote peer), `relatedPort` is `null`.

 The `relatedPort` field's value is set from the `candidateInfo` options object passed to the `RTCIceCandidate()` constructor.
 You can't specify the value of `relatedPort` directly in the options object, but its value is automatically extracted from the object's `candidate` a-line, if it's formatted properly (the `rel-port` field).

 The related address (`relatedAddress`) and port are not used at all by ICE itself; they are provided for
 analysis and diagnostic purposes only, and their inclusion may be blocked by security systems, so do not rely on them having non-`null` values.

Value
-----

 An unsigned 16-bit value containing the candidate's related port number, if any. For
 both peer and server reflexive candidates, the related address and port describe the
 base for that candidate. For relay candidates, the related address and port provide the
 mapped address selected by the TURN server.

For host candidates, `relatedPort` is `null`, meaning the field is not included in the candidate's a-line.

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

 The related address and port are not used by ICE itself, and are only present for
 diagnostic and Quality-of-Service purposes. They may in fact be omitted for security
 reasons, but if present can be a useful tool during debugging. See the Example, which shows a bit of this.

 Here's an SDP attribute line (a-line) describing an ICE candidate
 discovered by the STUN server:
```

a=candidate:4234997325 1 udp 2043278322 192.0.2.172 6502 typ srflx raddr 198.51.100.45 rport 32768 generation 0
```

The remote port, `relatedPort`, is the number immediately following the `"rport"` label on the a-line, or 32768.

Examples
--------

 In this example, the candidate's `type` is
 checked, and then debugging output is presented, based on the candidate type, including
 the candidate's type, address (`ip` and `port`), and related address (`relatedAddress` and `relatedPort`).

```js
const ip = candidate.ip;
const port = candidate.port;
const relIP = candidate.relatedAddress;
const relPort = candidate.relatedPort;

if (relIP && relPort) {
  console.log(
    `Candidate type '${type}' — contact address: ${ip} ${port}, related address: ${relIP} ${relPort}`,
  );
} else {
  console.log(`Host candidate address is ${ip} ${port}`);
}
```

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

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

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

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

See also
--------

* WebRTC API
* Introduction to WebRTC protocols
* WebRTC connectivity
* Lifetime of a WebRTC session
* `RTCIceCandidate.relatedAddress`
* `RTCIceCandidate.address` and `RTCIceCandidate.port`


RTCIceCandidate: sdpMid property - Web APIs

RTCIceCandidate: sdpMid property
================================

 The read-only property **`sdpMid`** on the `RTCIceCandidate` interface returns a string
 specifying the media stream identification tag of the media component with which the candidate is associated.
 This ID uniquely identifies a given stream for the component with which the candidate is associated.

 This property can be configured by specifying the value of the `sdpMid` property in the `candidateInfo` options object that is passed to the `RTCIceCandidate()` constructor.
 If you call the constructor with an m-line string instead of the options object, the value of `sdpMid` is extracted from the specified candidate m-line string.

Value
-----

 A string which uniquely identifies the source media component from
 which the candidate draws data, or `null` if no such association exists for the candidate.

**Note:** Attempting to add a candidate (using `addIceCandidate()`) that has a
 value of `null` for both `sdpMid` and `sdpMLineIndex` will throw a `TypeError` exception.

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

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

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

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


RTCIceCandidate: type property - Web APIs

RTCIceCandidate: type property
==============================

The **`RTCIceCandidate`** interface's read-only **`type`** specifies the type of candidate the object represents.

 The `type` field's value is set from the `candidateInfo` options object passed to the `RTCIceCandidate()` constructor.
 You can't specify the value of `type` directly in the options object, but its value is automatically extracted from the object's `candidate` a-line (the `cand-type` field), if it's formatted properly.

Value
-----

A string whose value is one of those defined below. These candidate types are listed in order of priority; the higher in the list they are, the more efficient they are.

`host`

The candidate is a host candidate, whose IP address as specified in the `RTCIceCandidate.address` property is in fact the true address of the remote peer.

`srflx`

 The candidate is a server reflexive candidate; the `ip` and port
 are a binding allocated by a NAT for an agent when it sent a
 packet through the NAT to a server. They can be learned by the STUN server and TURN server to represent the candidate's peer anonymously.

`prflx`

 The candidate is a peer reflexive candidate; the `ip` and port
 are a binding allocated by a NAT when it sent a STUN request to represent the candidate's peer anonymously.

`relay`

The candidate is a relay candidate, obtained from a TURN server. The relay candidate's IP address is an address the TURN server uses to forward the media between the two peers.

 If `type` is `null`, that information was missing from the
 `candidate`'s a-line, which will cause
 `RTCPeerConnection.addIceCandidate()` to throw an
 `OperationError` exception.

Examples
--------

 In this example, the candidate's `type` is used to
 present a modified user interface for host candidates (those where the
 `ip` refers directly to the remote peer, rather than
 an intermediary).

```js
if (candidate.type === "host") {
  showHostControls();
} else {
  hideHostControls();
}
```

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

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

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

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

See also
--------

* WebRTC API
* Introduction to WebRTC protocols
* WebRTC connectivity
* `RTCIceCandidate.tcpType`


RTCIceCandidate: toJSON() method - Web APIs

RTCIceCandidate: toJSON() method
================================

The `RTCIceCandidate` method **`toJSON()`** converts the `RTCIceCandidate` on which it's called into JSON.

A stringified version of the object can then be obtained by calling `stringify()` on the returned object.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A JSON object with the following properties, which have been set to the corresponding values in the `RTCIceCandidate` object:

`candidate` Optional

 A string describing the network connectivity information for the candidate.
 Additional information can be found in `RTCIceCandidate.candidate`.

`sdpMid` Optional

 A string containing the identification tag of the media stream with which the candidate is associated, or `null` if there is no associated media stream.
 Additional information can be found in `RTCIceCandidate.sdpMid`.

`sdpMLineIndex` Optional

 A number property containing the zero-based index of the m-line with which the candidate is associated, within the SDP of the media description, or `null` if no such associated exists.
 Additional information can be found in `RTCIceCandidate.sdpMLineIndex`.

`usernameFragment` Optional

 A string containing the username fragment (usually referred to in shorthand as "ufrag" or "ice-ufrag").
 This fragment, along with the ICE password ("ice-pwd"), uniquely identifies a single ongoing ICE interaction (including for any communication with the STUN server).
 Additional information can be found in `RTCIceCandidate.usernameFragment`.

**Note:** The returned JSON object has the same form/properties as the `candidateInfo` object that can optionally be passed to the `RTCIceCandidate() constructor` to configure the candidate.

Examples
--------

This simple example obtains a JSON string representing an `RTCIceCandidate` found in the variable `candidate`.

```js
let jsonString = candidate.toJSON().stringify();
```

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

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

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

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