XRJointSpace - Web APIs

XRJointSpace
============

The **`XRJointSpace`** interface is an `XRSpace` and represents the position and orientation of an `XRHand` joint.

EventTarget

XRSpace

XRJointSpaceInstance properties
-------------------

`XRJointSpace.jointName` Read only

The name of the joint that is tracked. See `XRHand` for possible hand joint names.

Examples
--------

### Using `XRJointSpace` objects

You can use an `XRJointSpace` object and an `XRReferenceSpace` to get an `XRJointPose` by calling `XRFrame.getJointPose()`.

```js
navigator.xr
  .requestSession({ optionalFeatures: ["hand-tracking"] })
  .then(/\*\* … \*/);

function renderFrame(session, frame) {
  // …

  for (const inputSource of session.inputSources) {
    if (inputSource.hand) {
      const indexFingerTipJoint = inputSource.hand.get("index-finger-tip"); // XRJointSpace
      indexFingerTipJoint.jointName; // "index-finger-tip"
      frame.getJointPose(indexFingerTipJoint, referenceSpace); // XRJointPose
    }
  }
}
```

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

| Specification |
| --- |
| WebXR Hand Input Module - Level 1 # xrhand-interface |

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

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

See also
--------

* `XRHand`
* `XRReferenceSpace`
* `XRJointPose`
* `XRFrame.getJointPose()`


URL API - Web APIs

URL API
=======

The URL API is a component of the URL standard, which defines what constitutes a valid Uniform Resource Locator and the API that accesses and manipulates URLs. The URL standard also defines concepts such as domains, hosts, and IP addresses, and also attempts to describe in a standard way the legacy `application/x-www-form-urlencoded` MIME type used to submit web forms' contents as a set of key/value pairs.

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

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

The majority of the URL standard is taken up by the definition of a URL and how it is structured and parsed. Also covered are definitions of various terms related to addressing of computers on a network, and the algorithms for parsing IP addresses and DOM addresses are specified. More interesting to most developers is the API itself.

### Accessing URL components

Creating an `URL` object for a given URL parses the URL and provides quick access to its constituent parts through its properties.

```js
let addr = new URL("https://developer.mozilla.org/en-US/docs/Web/API/URL\_API");
let host = addr.host;
let path = addr.pathname;
```

The snippet above creates a `URL` object for the article you're reading right now, then fetches the `host` and `pathname` properties. In this case, those strings are `developer.mozilla.org` and `/en-US/docs/Web/API/URL_API`, respectively.

### Changing the URL

Most of the properties of `URL` are settable; you can write new values to them to alter the URL represented by the object. For example, to create a URL and set its username:

```js
let myUsername = "someguy";
let addr = new URL("https://example.com/login");
addr.username = myUsername;
```

Setting the value of `username` not only sets that property's value, but it updates the overall URL. After executing the code snippet above, the value returned by `href` is `https://someguy@example.com/login`. This is true for any of the writable properties.

### Queries

The `search` property on a `URL` contains the query string portion of the URL. For example, if the URL is `https://example.com/login?user=someguy&page=news`, then the value of the `search` property is `?user=someguy&page=news`. You can also look up the values of individual parameters with the `URLSearchParams` object's `get()` method:

```js
let addr = new URL("https://example.com/login?user=someguy&page=news");
try {
  loginUser(addr.searchParams.get("user"));
  gotoPage(addr.searchParams.get("page"));
} catch (err) {
  showErrorMessage(err);
}
```

For example, in the above snippet, the username and target page are taken from the query and passed to appropriate functions that are used by the site's code to log in and route the user to their desired destination within the site.

Other functions within `URLSearchParams` let you change the value of keys, add and delete keys and their values, and even sort the list of parameters.

Interfaces
----------

The URL API is a simple one, with only a couple of interfaces to its name:

`URL`

Can be used to parse, construct, normalize, and encode URLs.

`URLSearchParams`

Defines utility methods to work with the query string of a URL.

Examples
--------

If you want to process the parameters included in a URL, you could do it manually, but it's much easier to create a `URL` object to do it for you. The `fillTableWithParameters()` function below takes as input a `HTMLTableElement` object representing a `<table>`. Rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value.

Note the call to `URLSearchParams.sort()` to sort the parameter list before generating the table.

```js
function fillTableWithParameters(tbl) {
  const url = new URL(document.location.href);
  url.searchParams.sort();
  const keys = url.searchParams.keys();

  for (const key of keys) {
    const val = url.searchParams.get(key);
    const row = document.createElement("tr");
    const cell1 = document.createElement("td");
    cell1.innerText = key;
    row.appendChild(cell1);
    const cell2 = document.createElement("td");
    cell2.innerText = val;
    row.appendChild(cell2);
    tbl.appendChild(row);
  }
}
```

A working version of this example can be found on Glitch. Just add parameters to the URL when loading the page to see them in the table. For instance, try `https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable`.

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

| Specification |
| --- |
| URL Standard # api |

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

### api.URL

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

### api.URLSearchParams

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

See also
--------

* Fetch API
* CSS `<url>()` type
* `encodeURI()`
* `encodeURIComponent()`


GPUInternalError - Web APIs

GPUInternalError
================

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

The **`GPUInternalError`** interface of the WebGPU API describes an application error indicating that an operation did not pass the WebGPU API's validation constraints.

It represents one of the types of errors surfaced by `GPUDevice.popErrorScope` and the `uncapturederror` event.

Internal errors occur when something happens in the WebGPU implementation that wasn't caught by validation and wasn't clearly identifiable as an out-of-memory error. It generally means that an operation your code performed hit a system limit in a way that was difficult to express with WebGPU's supported limits. The same operation might succeed on a different device. These can only be raised by pipeline creation, usually if the shader is too complex for the device.

GPUError

GPUInternalErrorConstructor
-----------

`GPUInternalError()`
Experimental

Creates a new `GPUInternalError` object instance.

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

The `message` property is inherited from its parent, `GPUError`:

`message`
Experimental
 Read only

A string providing a human-readable message that explains why the error occurred.

Examples
--------

The following example uses an error scope to capture a suspected validation error, logging it to the console.

```js
device.pushErrorScope("internal");

const module = device.createShaderModule({
  code: shader, // REALLY complex shader
});

device.popErrorScope().then((error) => {
  if (error) {
    // error is a GPUInternalError object instance
    module = null;
    console.error(`An error occurred while creating shader: ${error.message}`);
  }
});
```

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

| Specification |
| --- |
| WebGPU # gpuinternalerror |

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

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

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices


XRWebGLBinding - Web APIs

XRWebGLBinding
==============

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

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

The **`XRWebGLBinding`** interface is used to create layers that have a GPU backend.

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

`XRWebGLBinding()`
Experimental

Creates a new `XRWebGLBinding` object for the specified XR session and WebGL rendering context.

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

`XRWebGLBinding.nativeProjectionScaleFactor` Read only
Experimental

The `scaleFactor` that was passed in during the construction of the projection layer. The native buffer size is scaled by this number.

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

`XRWebGLBinding.createCubeLayer()`
Experimental

Returns an `XRCubeLayer` object, which is a layer that renders directly from a cubemap, and projects it onto the inside faces of a cube.

`XRWebGLBinding.createCylinderLayer()`
Experimental

Returns an `XRCylinderLayer` object which is a layer that takes up a curved rectangular space in the virtual environment.

`XRWebGLBinding.createEquirectLayer()`
Experimental

Returns an `XREquirectLayer` object which is a layer that maps equirectangular coded data onto the inside of a sphere.

`XRWebGLBinding.createProjectionLayer()`
Experimental

Returns an `XRProjectionLayer` object which is a layer that fills the entire view of the observer and is refreshed close to the device's native frame rate.

`XRWebGLBinding.createQuadLayer()`
Experimental

Returns an `XRQuadLayer` object which is a two-dimensional object positioned and oriented in 3D space.

`XRWebGLBinding.getDepthInformation()`
Experimental

Returns an `XRWebGLDepthInformation` object containing WebGL depth information.

`XRWebGLBinding.getReflectionCubeMap()`
Experimental

Returns a `WebGLTexture` object containing a reflection cube map texture.

`XRWebGLBinding.getSubImage()`
Experimental

Returns an `XRWebGLSubImage` object representing the WebGL texture to render.

`XRWebGLBinding.getViewSubImage()`
Experimental

Returns an `XRWebGLSubImage` object representing the WebGL texture to render for an `XRView`.

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

| Specification |
| --- |
| WebXR Layers API Level 1 # XRWebGLBindingtype |

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

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

See also
--------

* `XRWebGLLayer`
* `WebGLRenderingContext` and `WebGL2RenderingContext`


TransformStreamDefaultController - Web APIs

TransformStreamDefaultController
================================

The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated `ReadableStream` and `WritableStream`.

When constructing a `TransformStream`, the `TransformStreamDefaultController` is created. It therefore has no constructor. The way to get an instance of `TransformStreamDefaultController` is via the callback methods of `TransformStream()`.

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

`TransformStreamDefaultController.desiredSize` Read only

Returns the desired size to fill the readable side of the stream's internal queue.

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

`TransformStreamDefaultController.enqueue()`

Enqueues a chunk (single piece of data) in the readable side of the stream.

`TransformStreamDefaultController.error()`

Errors both the readable and writable side of the transform stream.

`TransformStreamDefaultController.terminate()`

Closes the readable side and errors the writable side of the stream.

Examples
--------

In the following example, a transform stream passes through all chunks it receives as `Uint8Array` values, using the `error()` and `enqueue()` methods.

```js
const transformContent = {
  start() {}, // required.
  async transform(chunk, controller) {
    chunk = await chunk;
    switch (typeof chunk) {
      case "object":
        // just say the stream is done I guess
        if (chunk === null) {
          controller.terminate();
        } else if (ArrayBuffer.isView(chunk)) {
          controller.enqueue(
            new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength),
          );
        } else if (
          Array.isArray(chunk) &&
          chunk.every((value) => typeof value === "number")
        ) {
          controller.enqueue(new Uint8Array(chunk));
        } else if (
          typeof chunk.valueOf === "function" &&
          chunk.valueOf() !== chunk
        ) {
          this.transform(chunk.valueOf(), controller); // hack
        } else if ("toJSON" in chunk) {
          this.transform(JSON.stringify(chunk), controller);
        }
        break;
      case "symbol":
        controller.error("Cannot send a symbol as a chunk part");
        break;
      case "undefined":
        controller.error("Cannot send undefined as a chunk part");
        break;
      default:
        controller.enqueue(this.textencoder.encode(String(chunk)));
        break;
    }
  },
  flush() {
    /\* do any destructor work here \*/
  },
};

class AnyToU8Stream extends TransformStream {
  constructor() {
    super({ ...transformContent, textencoder: new TextEncoder() });
  }
}
```

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

| Specification |
| --- |
| Streams Standard # ts-default-controller-class |

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

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


CSSTransition - Web APIs

CSSTransition
=============

The **`CSSTransition`** interface of the Web Animations API represents an `Animation` object used for a CSS Transition.

EventTarget

Animation

CSSTransitionInstance properties
-------------------

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

`CSSTransition.transitionProperty` Read only

Returns the transition CSS property name as a string.

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

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

No specific methods.

Examples
--------

### Inspecting the returned CSSTransition

The transition in the following example changes the width of the box on hover. Calling `Element.getAnimations()` returns an array of all `Animation` objects. In our case this returns a `CSSTransition` object, representing the animation created.

```css
.box {
  background-color: #165baa;
  color: #fff;
  width: 100px;
  height: 100px;
  transition: width 4s;
}

.box:hover {
  width: 200px;
}
```

```js
const item = document.querySelector(".box");
item.addEventListener("transitionrun", () => {
  let animations = document.querySelector(".box").getAnimations();
  console.log(animations[0]);
});
```

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

| Specification |
| --- |
| CSS Transitions Level 2 # the-CSSTransition-interface |

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

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


HashChangeEvent - Web APIs

HashChangeEvent
===============

The **`HashChangeEvent`** interface represents events that fire when the fragment identifier of the URL has changed.

The fragment identifier is the part of the URL that follows (and includes) the `#` symbol.

Event

HashChangeEventConstructor
-----------

`HashChangeEvent()`

Creates a new `HashChangeEvent` object.

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

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

`HashChangeEvent.newURL` Read only

The new URL to which the window is navigating.

`HashChangeEvent.oldURL` Read only

The previous URL from which the window was navigated.

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

*This interface has no methods of its own, but inherits the methods of its parent, `Event`.*

Examples
--------

### Basic example

```js
function locationHashChanged() {
  if (location.hash === "#somecoolfeature") {
    somecoolfeature();
  }
}

window.addEventListener("hashchange", locationHashChanged);
```

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

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

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

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

Related events
--------------

* `hashchange`
* `popstate`


SVGUnitTypes - Web APIs

SVGUnitTypes
============

The **`SVGUnitTypes`** interface defines a commonly used set of constants used for reflecting `gradientUnits`, `patternContentUnits` and other similar attributes.

Constants
---------

`SVG_UNIT_TYPE_UNKNOWN` (0)

The type is not one of predefined types. It is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.

`SVG_UNIT_TYPE_USERSPACEONUSE` (1)

Corresponds to the value `userSpaceOnUse`.

`SVG_UNIT_TYPE_OBJECTBOUNDINGBOX` (2)

Corresponds to the value `objectBoundingBox`.

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

*This interface doesn't implement any specific properties.*

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

*This interface doesn't implement any specific methods.*

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

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

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

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


SVGLineElement - Web APIs

SVGLineElement
==============

The **`SVGLineElement`** interface provides access to the properties of `<line>` elements, as well as methods to manipulate them.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGGeometryElement

SVGLineElementInstance properties
-------------------

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

`SVGLineElement.x1` Read only

Returns an `SVGAnimatedLength` that corresponds to attribute `x1` on the given `<line>` element.

`SVGLineElement.y1` Read only

Returns an `SVGAnimatedLength` that corresponds to attribute `y1` on the given `<line>` element.

`SVGLineElement.x2` Read only

Returns an `SVGAnimatedLength` that corresponds to attribute `x2` on the given `<line>` element.

`SVGLineElement.y2` Read only

Returns an `SVGAnimatedLength` that corresponds to attribute `y2` on the given `<line>` element.

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

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

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

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

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

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

See also
--------

* `<line>` SVG Element


WritableStreamDefaultController - Web APIs

WritableStreamDefaultController
===============================

The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a `WritableStream`'s state. When constructing a `WritableStream`, the underlying sink is given a corresponding `WritableStreamDefaultController` instance to manipulate.

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

None. `WritableStreamDefaultController` instances are created automatically during `WritableStream` construction.

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

`WritableStreamDefaultController.signal` Read only

Returns the `AbortSignal` associated with the controller.

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

`WritableStreamDefaultController.error()`

Causes any future interactions with the associated stream to error.

Examples
--------

```js
const writableStream = new WritableStream({
  start(controller) {
    // do stuff with controller

    // error stream if necessary
    controller.error("My stream is broken");
  },
  write(chunk, controller) {
    // ...
  },
  close(controller) {
    // ...
  },
  abort(err) {
    // ...
  },
});
```

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

| Specification |
| --- |
| Streams Standard # ws-default-controller-class |

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

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


Notification - Web APIs

Notification
============

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

The **`Notification`** interface of the Notifications API is used to configure and display desktop notifications to the user.

These notifications' appearance and specific functionality vary across platforms but generally they provide a way to asynchronously provide information to the user.

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

EventTarget

NotificationConstructor
-----------

`Notification()`

Creates a new instance of the `Notification` object.

Static properties
-----------------

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

`Notification.permission` Read only

A string representing the current permission to display notifications. Possible values are:

* `denied` — The user refuses to have notifications displayed.
* `granted` — The user accepts having notifications displayed.
* `default` — The user choice is unknown and therefore the browser will act as if the value were denied.

`Notification.maxActions` Read only
Experimental

The maximum number of actions supported by the device and the User Agent.

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

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

`Notification.actions` Read only
Experimental

The actions array of the notification as specified in the constructor's `options` parameter.

`Notification.badge` Read only

A string containing the URL of an image to represent the notification when there is not enough space to display the notification itself such as for example, the Android Notification Bar. On Android devices, the badge should accommodate devices up to 4x resolution, about 96 by 96 px, and the image will be automatically masked.

`Notification.body` Read only

The body string of the notification as specified in the constructor's `options` parameter.

`Notification.data` Read only

Returns a structured clone of the notification's data.

`Notification.dir` Read only

The text direction of the notification as specified in the constructor's `options` parameter.

`Notification.icon` Read only

The URL of the image used as an icon of the notification as specified in the constructor's `options` parameter.

`Notification.image` Read only
Experimental

The URL of an image to be displayed as part of the notification, as specified in the constructor's `options` parameter.

`Notification.lang` Read only

The language code of the notification as specified in the constructor's `options` parameter.

`Notification.renotify` Read only
Experimental

Specifies whether the user should be notified after a new notification replaces an old one.

`Notification.requireInteraction` Read only

A boolean value indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automatically.

`Notification.silent` Read only

Specifies whether the notification should be silent — i.e., no sounds or vibrations should be issued, regardless of the device settings.

`Notification.tag` Read only

The ID of the notification (if any) as specified in the constructor's `options` parameter.

`Notification.timestamp` Read only
Experimental

Specifies the time at which a notification is created or applicable (past, present, or future).

`Notification.title` Read only

The title of the notification as specified in the first parameter of the constructor.

`Notification.vibrate` Read only
Experimental

Specifies a vibration pattern for devices with vibration hardware to emit.

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

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

`Notification.requestPermission()`

Requests permission from the user to display notifications.

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

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

`Notification.close()`

Programmatically closes a notification instance.

Events
------

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

`click`

Fires when the user clicks the notification.

`close`

Fires when the user closes the notification.

`error`

Fires when the notification encounters an error.

`show`

Fires when the notification is displayed.

Examples
--------

Assume this basic HTML:

```html
<button onclick="notifyMe()">Notify me!</button>
```

It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.

```js
function notifyMe() {
  if (!("Notification" in window)) {
    // Check if the browser supports notifications
    alert("This browser does not support desktop notification");
  } else if (Notification.permission === "granted") {
    // Check whether notification permissions have already been granted;
    // if so, create a notification
    const notification = new Notification("Hi there!");
    // …
  } else if (Notification.permission !== "denied") {
    // We need to ask the user for permission
    Notification.requestPermission().then((permission) => {
      // If the user accepts, let's create a notification
      if (permission === "granted") {
        const notification = new Notification("Hi there!");
        // …
      }
    });
  }

  // At last, if the user has denied notifications, and you
  // want to be respectful there is no need to bother them anymore.
}
```

We no longer show a live sample on this page, as Chrome and Firefox no longer allow notification permissions to be requested from cross-origin `<iframe>`s, with other browsers to follow. To see an example in action, check out our To-do list example (also see the app running live).

**Note:** In the above example we spawn notifications in response to a user gesture (clicking a button). This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example.

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

| Specification |
| --- |
| Notifications API Standard # api |

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

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

See also
--------

* Using the Notifications API


XRSession - Web APIs

XRSession
=========

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

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

The `WebXR Device API`'s **`XRSession`** interface represents an ongoing XR session, providing methods and properties used to interact with and control the session. To open a WebXR session, use the `XRSystem` interface's `requestSession()` method.

With `XRSession` methods, you can poll the viewer's position and orientation (the `XRViewerPose`), gather information about the user's environment, and present imagery to the user. `XRSession` supports both inline and immersive virtual and augmented reality modes.

EventTarget

XRSessionInstance properties
-------------------

*In addition to the properties listed below, `XRSession` inherits properties from its parent interface, `EventTarget`.*

`depthDataFormat`
Experimental
 Read only

Returns the depth-sensing data format with which the session was configured.

`depthUsage`
Experimental
 Read only

Returns the depth-sensing usage with which the session was configured.

`domOverlayState`
Experimental
 Read only

Provides information about the DOM overlay, if the feature is enabled.

`environmentBlendMode`
Experimental
 Read only

Returns this session's blend mode which denotes how much of the real-world environment is visible through the XR device and how the device will blend the device imagery with it.

`inputSources`
Experimental
 Read only

Returns a list of this session's `XRInputSource`s, each representing an input device used to control the camera and/or scene.

`interactionMode`
Experimental
 Read only

Returns this session's interaction mode, which describes the best space (according to the user agent) for the application to draw interactive UI for the current session.

`preferredReflectionFormat`
Experimental
 Read only

Returns this session's preferred reflection format used for lighting estimation texture data.

`renderState`
Experimental
 Read only

An `XRRenderState` object which contains options affecting how the imagery is rendered. This includes things such as the near and far clipping planes (distances defining how close and how far away objects can be and still get rendered), as well as field of view information.

`visibilityState`
Experimental
 Read only

A string indicating whether or not the session's imagery is visible to the user, and if so, if it's being visible but not currently the target for user events.

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

*`XRSession` provides the following methods in addition to those inherited from its parent interface, `EventTarget`.*

`cancelAnimationFrame()`
Experimental

Removes a callback from the animation frame painting callback from `XRSession`'s set of animation frame rendering callbacks, given the identifying handle returned by a previous call to `requestAnimationFrame()`.

`end()`
Experimental

Ends the WebXR session. Returns a `promise` which resolves when the session has been shut down.

`requestAnimationFrame()`
Experimental

Schedules the specified method to be called the next time the user agent is working on rendering an animation frame for the WebXR device. Returns an integer value which can be used to identify the request for the purposes of canceling the callback using `cancelAnimationFrame()`. This method is comparable to the `Window.requestAnimationFrame()` method.

`requestHitTestSource()`
Experimental

Requests an `XRHitTestSource` object that handles hit test subscription.

`requestHitTestSourceForTransientInput()`
Experimental

Requests an `XRTransientInputHitTestSource` object that handles hit test subscription for a transient input source.

`requestLightProbe()`
Experimental

Requests an `XRLightProbe` that estimates lighting information at a given point in the user's environment.

`requestReferenceSpace()`
Experimental

Requests that a new `XRReferenceSpace` of the specified type be created. Returns a promise which resolves with the `XRReferenceSpace` or `XRBoundedReferenceSpace` which was requested, or throws a `NotSupportedError` `DOMException` if the requested space type isn't supported by the device.

`updateRenderState()`
Experimental

Updates the properties of the session's render state.

Events
------

*The following events are delivered to `XRSession` objects.*

`end`
Experimental

Sent to the `XRSession` object after the WebXR session has ended and all hardware-related functions have completed. The event is represented by an object of type `XRSessionEvent`. Also available through the `onend` event handler property.

`inputsourceschange`
Experimental

An event of type `XRInputSourcesChangeEvent` sent to the `XRSession` when the list of active XR input sources has changed. Also available through the `oninputsourceschange` event handler property.

`select`
Experimental

An event of type `XRInputSourceEvent` which is sent to the session when one of the session's input sources has successfully completed a primary action. This generally corresponds to the user pressing a trigger, touchpad, or button, speaks a command, or performs a recognizable gesture. The `select` event is sent after the `selectstart` event is sent and immediately before the `selectend` event is sent. If `select` is *not* sent, then the select action was aborted before being completed. Also available through the `onselect` event handler property.

`selectend`
Experimental

An event of type `XRInputSourceEvent` which gets sent to the session object when one of its input devices finishes its primary action or gets disconnected while in the process of handling a primary action. For example: for button or trigger actions, this means the button has been released; for spoken commands, it means the user has finished speaking. This is the last of the three `select*` events to be sent. Also available through the `onselectend` event handler property.

`selectstart`
Experimental

An event of type `XRInputSourceEvent` which is sent to the session object when one of its input devices is first engaged by the user in such a way as to cause the primary action to begin. This is the first of the `session*` event to be sent. Also available through the `onselectstart` event handler property.

`squeeze`
Experimental

An `XRInputSourceEvent` sent to indicate that a primary squeeze action has successfully completed. This indicates that the device being squeezed has been released, and may represent dropping a grabbed object, for example. It is sent immediately before the `squeezeend` event is sent to indicate that the squeeze action is over. Also available through the `onsqueeze` event handler property.

`squeezeend`
Experimental

An `XRInputSourceEvent` sent to the `XRSession` when the primary squeeze action ends, whether or not the action was successful. Also available using the `onsqueezeend` event handler property.

`squeezestart`
Experimental

An event of type `XRInputSourceEvent` which is sent to the `XRSession` when the user initially squeezes a squeezable controller. This may be, for example, a trigger which is used to represent grabbing objects, or might represent actual squeezing when wearing a haptic glove. Also available through the `onsqueezestart` event handler property.

`visibilitychange`
Experimental

An `XRSessionEvent` which is sent to the session when its visibility state as indicated by the `visibilityState` changes. Also available through the `onvisibilitychange` event handler property.

Example
-------

This example establishes a new `XRSession` in `inline` mode so that it can be displayed within an HTML element, avoiding the need for a dedicated AR or VR viewing device such as a headset.

```js
const XR = navigator.xr;

if (XR) {
  XR.requestSession("inline").then((xrSession) => {
    xrSession.requestReferenceSpace("local").then((xrReferenceSpace) => {
      xrSession.requestAnimationFrame((time, xrFrame) => {
        const viewer = xrFrame.getViewerPose(xrReferenceSpace);

        gl.bindFramebuffer(xrWebGLLayer.framebuffer);

        for (const xrView of viewer.views) {
          const xrViewport = xrWebGLLayer.getViewport(xrView);
          gl.viewport(
            xrViewport.x,
            xrViewport.y,
            xrViewport.width,
            xrViewport.height,
          );
        }
      });
    });
  });
} else {
  /\* WebXR is not available \*/
}
```

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

| Specification |
| --- |
| WebXR Device API # xrsession-interface |

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

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


SVGFEMorphologyElement - Web APIs

SVGFEMorphologyElement
======================

The **`SVGFEMorphologyElement`** interface corresponds to the `<feMorphology>` element.

EventTarget

Node

Element

SVGElement

SVGFEMorphologyElementConstants
---------

| Name | Value | Description |
| --- | --- | --- |
| `SVG_MORPHOLOGY_OPERATOR_UNKNOWN` | 0 |
 The type is not one of predefined types. It is invalid to attempt to
 define a new value of this type or to attempt to switch an existing
 value to this type.
  |
| `SVG_MORPHOLOGY_OPERATOR_ERODE` | 1 | Corresponds to the `erode` value. |
| `SVG_MORPHOLOGY_OPERATOR_DILATE` | 2 | Corresponds to `dilate` value. |

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

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

`SVGFEMorphologyElement.height` Read only

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

`SVGFEMorphologyElement.in1` Read only

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

`SVGFEMorphologyElement.operator` Read only

An `SVGAnimatedEnumeration` corresponding to the `operator` attribute of the given element. It takes one of the `SVG_MORPHOLOGY_OPERATOR_*` constants defined on this interface.

`SVGFEMorphologyElement.radiusX` Read only

An `SVGAnimatedNumber` corresponding to the X component of the `radius` attribute of the given element.

`SVGFEMorphologyElement.radiusY` Read only

An `SVGAnimatedNumber` corresponding to the Y component of the `radius` attribute of the given element.

`SVGFEMorphologyElement.result` Read only

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

`SVGFEMorphologyElement.width` Read only

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

`SVGFEMorphologyElement.x` Read only

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

`SVGFEMorphologyElement.y` Read only

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

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

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

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

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

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

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

See also
--------

* `<feMorphology>`


SharedWorkerGlobalScope - Web APIs

SharedWorkerGlobalScope
=======================

The **`SharedWorkerGlobalScope`** object (the `SharedWorker` global scope) is accessible through the `self` keyword. Some additional global functions, namespaces objects, and constructors, not typically associated with the worker global scope, but available on it, are listed in the JavaScript Reference. See the complete list of functions available to workers.

EventTarget

WorkerGlobalScope

SharedWorkerGlobalScopeInstance properties
-------------------

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

`SharedWorkerGlobalScope.name` Read only

The name that the `SharedWorker` was (optionally) given when it was created using the `SharedWorker()` constructor. This is mainly useful for debugging purposes.

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

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

`SharedWorkerGlobalScope.close()`

Discards any tasks queued in the `SharedWorkerGlobalScope`'s event loop, effectively closing this particular scope.

Events
------

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

`connect`

Fired on shared workers when a new client connects.

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

| Specification |
| --- |
| HTML Standard # shared-workers-and-the-sharedworkerglobalscope-interface |

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

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

See also
--------

* `SharedWorker`
* `WorkerGlobalScope`
* Using Web workers
* Functions available to workers


AudioProcessingEvent - Web APIs

AudioProcessingEvent
====================

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

The `AudioProcessingEvent` interface of the Web Audio API represents events that occur when a `ScriptProcessorNode` input buffer is ready to be processed.

An `audioprocess` event with this interface is fired on a `ScriptProcessorNode` when audio processing is required. During audio processing, the input buffer is read and processed to produce output audio data, which is then written to the output buffer.

**Warning:** This feature has been deprecated and should be replaced by an `AudioWorklet`.

Event

AudioProcessingEventConstructor
-----------

`AudioProcessingEvent()`
Deprecated

Creates a new `AudioProcessingEvent` object.

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

*Also implements the properties inherited from its parent, `Event`*.

`playbackTime` Read only
Deprecated

 A double representing the time when the audio will be played,
 as defined by the time of `AudioContext.currentTime`.

`inputBuffer` Read only
Deprecated

 An `AudioBuffer` that is the buffer containing the input audio data to be processed.
 The number of channels is defined as a parameter `numberOfInputChannels`,
 of the factory method `AudioContext.createScriptProcessor()`.
 Note that the returned `AudioBuffer` is only valid in the scope of the event handler.

`outputBuffer` Read only
Deprecated

 An `AudioBuffer` that is the buffer where the output audio data should be written.
 The number of channels is defined as a parameter, `numberOfOutputChannels`,
 of the factory method `AudioContext.createScriptProcessor()`.
 Note that the returned `AudioBuffer` is only valid in the scope of the event handler.

Examples
--------

### Adding white noise using a script processor

 The following example shows how to use of a `ScriptProcessorNode` to take a
 track loaded via `AudioContext.decodeAudioData()`, process it, adding a bit
 of white noise to each audio sample of the input track (buffer) and play it through the
 `AudioDestinationNode`. For each channel and each sample frame, the
 `scriptNode.onaudioprocess` function takes the associated
 `audioProcessingEvent` and uses it to loop through each channel of the input
 buffer, and each sample in each channel, and add a small amount of white noise, before
 setting that result to be the output sample in each case.

**Note:** For a full working example, see our script-processor-node
 GitHub repo. (You can also access the source code.)

```js
const myScript = document.querySelector("script");
const myPre = document.querySelector("pre");
const playButton = document.querySelector("button");

// Create AudioContext and buffer source
let audioCtx;

async function init() {
  audioCtx = new AudioContext();
  const source = audioCtx.createBufferSource();

  // Create a ScriptProcessorNode with a bufferSize of 4096 and
  // a single input and output channel
  const scriptNode = audioCtx.createScriptProcessor(4096, 1, 1);

  // Load in an audio track using fetch() and decodeAudioData()
  try {
    const response = await fetch("viper.ogg");
    const arrayBuffer = await response.arrayBuffer();
    source.buffer = await audioCtx.decodeAudioData(arrayBuffer);
  } catch (err) {
    console.error(
      `Unable to fetch the audio file: ${name} Error: ${err.message}`,
    );
  }

  // Give the node a function to process audio events
  scriptNode.addEventListener("audioprocess", (audioProcessingEvent) => {
    // The input buffer is the song we loaded earlier
    let inputBuffer = audioProcessingEvent.inputBuffer;

    // The output buffer contains the samples that will be modified
    // and played
    let outputBuffer = audioProcessingEvent.outputBuffer;

    // Loop through the output channels (in this case there is only one)
    for (let channel = 0; channel < outputBuffer.numberOfChannels; channel++) {
      let inputData = inputBuffer.getChannelData(channel);
      let outputData = outputBuffer.getChannelData(channel);

      // Loop through the 4096 samples
      for (let sample = 0; sample < inputBuffer.length; sample++) {
        // make output equal to the same as the input
        outputData[sample] = inputData[sample];

        // add noise to each output sample
        outputData[sample] += (Math.random() \* 2 - 1) \* 0.1;
      }
    }
  });

  source.connect(scriptNode);
  scriptNode.connect(audioCtx.destination);
  source.start();

  // When the buffer source stops playing, disconnect everything
  source.addEventListener("ended", () => {
    source.disconnect(scriptNode);
    scriptNode.disconnect(audioCtx.destination);
  });
}

// wire up play button
playButton.addEventListener("click", () => {
  if (!audioCtx) {
    init();
  }
});
```

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

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

See also
--------

* Using the Web Audio API


FileSystemFileEntry - Web APIs

FileSystemFileEntry
===================

The **`FileSystemFileEntry`** interface of the File and Directory Entries API represents a file in a file system. It offers properties describing the file's attributes, as well as the `file()` method, which creates a `File` object that can be used to read the file.

FileSystemEntry

FileSystemFileEntryInstance properties
-------------------

*Inherits the properties of its parent interface, `FileSystemEntry`, but has no properties unique to this interface.*

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

`file()`

Creates a new `File` object which can be used to read the file.

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

| Specification |
| --- |
| File and Directory Entries API # api-fileentry |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API


HIDInputReportEvent - Web APIs

HIDInputReportEvent
===================

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

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

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

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

The **`HIDInputReportEvent`** interface of the `WebHID API` is passed to `HIDDevice.inputreport_event` when an input report is received from any associated HID device.

Event

HIDInputReportEventInstance properties
-------------------

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

`HIDInputReportEvent.data` Read only
Experimental

A `DataView` containing the data from the input report, excluding the `reportId` if the HID interface uses report IDs.

`HIDInputReportEvent.device` Read only
Experimental

The `HIDDevice` instance that represents the HID interface that sent the input report.

`HIDInputReportEvent.reportId` Read only
Experimental

The one-byte identification prefix for this report, or 0 if the HID interface does not use report IDs.

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

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

Examples
--------

The following example demonstrates listening for an `inputReport` that will allow the application to detect which button is pressed on a Joy-Con Right device. You can see more examples, and live demos in the article Connecting to uncommon HID devices.

```js
device.addEventListener("inputreport", (event) => {
  const { data, device, reportId } = event;

  // Handle only the Joy-Con Right device and a specific report ID.
  if (device.productId !== 0x2007 && reportId !== 0x3f) return;

  const value = data.getUint8(0);
  if (value === 0) return;

  const someButtons = { 1: "A", 2: "X", 4: "B", 8: "Y" };
  console.log(`User pressed button ${someButtons[value]}.`);
});
```

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

| Specification |
| --- |
| WebHID API # dom-hidinputreportevent |

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

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


EXT_texture_filter_anisotropic extension - Web APIs

EXT\_texture\_filter\_anisotropic extension
===========================================

The **`EXT_texture_filter_anisotropic`** extension is part of the WebGL API and exposes two constants for anisotropic filtering (AF).

AF improves the quality of mipmapped texture access when viewing a textured primitive at an oblique angle. Using just mipmapping, these lookups have a tendency to average to grey.

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

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

Constants
---------

`ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT`

This is the `pname` argument to the `gl.getParameter()` call, and it returns the maximum available anisotropy.

`ext.TEXTURE_MAX_ANISOTROPY_EXT`

This is the `pname` argument to the `gl.getTexParameter()` and `gl.texParameterf()` / `gl.texParameteri()` calls and sets the desired maximum anisotropy for a texture.

Examples
--------

```js
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE\_2D, texture);
const ext =
  gl.getExtension("EXT\_texture\_filter\_anisotropic") ||
  gl.getExtension("MOZ\_EXT\_texture\_filter\_anisotropic") ||
  gl.getExtension("WEBKIT\_EXT\_texture\_filter\_anisotropic");
if (ext) {
  const max = gl.getParameter(ext.MAX\_TEXTURE\_MAX\_ANISOTROPY\_EXT);
  gl.texParameterf(gl.TEXTURE\_2D, ext.TEXTURE\_MAX\_ANISOTROPY\_EXT, max);
}
```

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

| Specification |
| --- |
| WebGL EXT\_texture\_filter\_anisotropic Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`


CaptureController - Web APIs

CaptureController
=================

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

The **`CaptureController`** interface provides methods that can be used to further manipulate a capture session separate from its initiation via `MediaDevices.getDisplayMedia()`.

A `CaptureController` object is associated with a capture session by passing it into a `getDisplayMedia()` call as the value of the options object's `controller` property.

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

`CaptureController()`
Experimental

Creates a new `CaptureController` object instance.

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

`setFocusBehavior()`
Experimental

Controls whether the captured tab or window will be focused or whether the focus will remain with the tab containing the capturing app.

Examples
--------

```js
// Create a new CaptureController instance
const controller = new CaptureController();

// Prompt the user to share a tab, window, or screen.
const stream = await navigator.mediaDevices.getDisplayMedia({ controller });

// Query the displaySurface value of the captured video track
const [track] = stream.getVideoTracks();
const displaySurface = track.getSettings().displaySurface;

if (displaySurface == "browser") {
  // Focus the captured tab.
  controller.setFocusBehavior("focus-captured-surface");
} else if (displaySurface == "window") {
  // Do not move focus to the captured window.
  // Keep the capturing page focused.
  controller.setFocusBehavior("no-focus-change");
}
```

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

| Specification |
| --- |
| Screen Capture # dom-capturecontroller |

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

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

See also
--------

* Screen Capture API
* `MediaDevices.getDisplayMedia()`
* Better screen sharing with Conditional Focus


SVGFEFuncGElement - Web APIs

SVGFEFuncGElement
=================

The **`SVGFEFuncGElement`** interface corresponds to the `<feFuncG>` element.

EventTarget

Node

Element

SVGElement

SVGComponentTransferFunctionElement

SVGFEFuncGElementInstance properties
-------------------

*This interface not provide any specific properties, but inherits properties from its parent interface, `SVGComponentTransferFunctionElement`.*

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

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

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

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

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

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

See also
--------

* `<feFuncG>`


SVGUseElement - Web APIs

SVGUseElement
=============

SVG use DOM interface
---------------------

The **`SVGUseElement`** interface corresponds to the `<use>` element.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGUseElementInstance properties
-------------------

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

`SVGUseElement.href` Read only

An `SVGAnimatedString` corresponding to the `href` or `xlink:href`
Deprecated
 attribute of the given element.

`SVGUseElement.x` Read only

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

`SVGUseElement.y` Read only

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

`SVGUseElement.width` Read only

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

`SVGUseElement.height` Read only

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

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

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

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

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

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

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

See also
--------

* `<use>`


GPUDevice - Web APIs

GPUDevice
=========

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

The **`GPUDevice`** interface of the WebGPU API represents a logical GPU device. This is the main interface through which the majority of WebGPU functionality is accessed.

A `GPUDevice` object is requested using the `GPUAdapter.requestDevice()` method.

EventTarget

GPUDeviceInstance properties
-------------------

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

`features`
Experimental
 Read only

A `GPUSupportedFeatures` object that describes additional functionality supported by the device.

`label`
Experimental

A string providing a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

`limits`
Experimental
 Read only

A `GPUSupportedLimits` object that describes the limits supported by the device.

`lost`
Experimental
 Read only

Contains a `Promise` that remains pending throughout the device's lifetime and resolves with a `GPUDeviceLostInfo` object when the device is lost.

`queue`
Experimental
 Read only

Returns the primary `GPUQueue` for the device.

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

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

`createBindGroup()`
Experimental

Creates a `GPUBindGroup` based on a `GPUBindGroupLayout` that defines a set of resources to be bound together in a group and how those resources are used in shader stages.

`createBindGroupLayout()`
Experimental

Creates a `GPUBindGroupLayout` that defines the structure and purpose of related GPU resources such as buffers that will be used in a pipeline, and is used as a template when creating `GPUBindGroup`s.

`createBuffer()`
Experimental

Creates a `GPUBuffer` in which to store raw data to use in GPU operations.

`createCommandEncoder()`
Experimental

Creates a `GPUCommandEncoder`, which is used to encode commands to be issued to the GPU.

`createComputePipeline()`
Experimental

Creates a `GPUComputePipeline` that can control the compute shader stage and be used in a `GPUComputePassEncoder`.

`createComputePipelineAsync()`
Experimental

Returns a `Promise` that fulfills with a `GPUComputePipeline`, which can control the compute shader stage and be used in a `GPUComputePassEncoder`, once the pipeline can be used without any stalling.

`createPipelineLayout()`
Experimental

Creates a `GPUPipelineLayout` that defines the `GPUBindGroupLayout`s used by a pipeline. `GPUBindGroup`s used with the pipeline during command encoding must have compatible `GPUBindGroupLayout`s.

`createQuerySet()`
Experimental

Creates a `GPUQuerySet` that can be used to record the results of queries on passes, such as occlusion or timestamp queries.

`createRenderBundleEncoder()`
Experimental

Creates a `GPURenderBundleEncoder` that can be used to pre-record bundles of commands. These can be reused in `GPURenderPassEncoder`s via the `executeBundles()` method, as many times as required.

`createRenderPipeline()`
Experimental

Creates a `GPURenderPipeline` that can control the vertex and fragment shader stages and be used in a `GPURenderPassEncoder` or `GPURenderBundleEncoder`.

`createRenderPipelineAsync()`
Experimental

Returns a `Promise` that fulfills with a `GPURenderPipeline`, which can control the vertex and fragment shader stages and be used in a `GPURenderPassEncoder` or `GPURenderBundleEncoder`, once the pipeline can be used without any stalling.

`createSampler()`
Experimental

Creates a `GPUSampler`, which controls how shaders transform and filter texture resource data.

`createShaderModule()`
Experimental

Creates a `GPUShaderModule` from a string of WGSL source code.

`createTexture()`
Experimental

Creates a `GPUTexture` in which to store texture data to use in GPU rendering operations.

`destroy()`
Experimental

Destroys the device, preventing further operations on it.

`importExternalTexture()`
Experimental

Takes an `HTMLVideoElement` as an input and returns a `GPUExternalTexture` wrapper object containing a snapshot of the video that can be used in GPU rendering operations.

`popErrorScope()`
Experimental

Pops an existing GPU error scope from the error scope stack and returns a `Promise` that resolves to an object (`GPUInternalError`, `GPUOutOfMemoryError`, or `GPUValidationError`) describing the first error captured in the scope, or `null` if no error occurred.

`pushErrorScope()`
Experimental

Pushes a new GPU error scope onto the device's error scope stack, allowing you to capture errors of a particular type.

Events
------

`uncapturederror`
Experimental

Fired when an error is thrown that has not been observed by a GPU error scope, to provide a way to report unexpected errors. Known error cases should be handled using `pushErrorScope()` and `popErrorScope()`.

Examples
--------

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

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

  const device = await adapter.requestDevice();

  const shaderModule = device.createShaderModule({
    code: shaders,
  });

  //...
}
```

See the individual member pages listed above and the following demo sites for a lot more examples of `GPUDevice` usage:

* Basic compute demo
* Basic render demo
* WebGPU samples
Specifications
--------------

| Specification |
| --- |
| WebGPU # gpudevice |

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

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

See also
--------

* The WebGPU API


PerformanceMark - Web APIs

PerformanceMark
===============

**`PerformanceMark`** is an interface for `PerformanceEntry` objects with an `entryType` of "`mark`".

Entries of this type are typically created by calling `performance.mark()` to add a *named* `DOMHighResTimeStamp` (the *mark*) to the browser's performance timeline. To create a performance mark that isn't added to the browser's performance timeline, use the constructor.

PerformanceEntry

PerformanceMark

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

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

`PerformanceMark()`

Creates a new `PerformanceMark` object that isn't added to the browser's performance timeline.

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

This interface extends the following `PerformanceEntry` properties by qualifying/constraining the properties as follows:

`PerformanceEntry.entryType` Read only

Returns "`mark`".

`PerformanceEntry.name` Read only

Returns the name given to the mark when it was created via a call to `performance.mark()`.

`PerformanceEntry.startTime` Read only

Returns the `DOMHighResTimeStamp` when `performance.mark()` was called.

`PerformanceEntry.duration` Read only

Returns "`0`". (A mark has no *duration*.)

This interface also supports the following properties:

`PerformanceMark.detail` Read only

Returns arbitrary metadata that has been included in the mark upon construction.

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

This interface has no methods.

Example
-------

See the example in Using the User Timing API.

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

| Specification |
| --- |
| User Timing # performancemark |

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

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

See also
--------

* User Timing (Overview)
* Using the User Timing API


ShadowRoot - Web APIs

ShadowRoot
==========

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

* Learn more
* See full compatibility
* Report feedback
The **`ShadowRoot`** interface of the Shadow DOM API is the root node of a DOM subtree that is rendered separately from a document's main DOM tree.

You can retrieve a reference to an element's shadow root using its `Element.shadowRoot` property, provided it was created using `Element.attachShadow()` with the `mode` option set to `open`.

EventTarget

Node

DocumentFragment

ShadowRootInstance properties
-------------------

`ShadowRoot.activeElement` Read only

Returns the `Element` within the shadow tree that has focus.

`ShadowRoot.adoptedStyleSheets`

 Add an array of constructed stylesheets to be used by the shadow DOM subtree.
 These may be shared with other DOM subtrees that share the same parent `Document` node, and the document itself.

`ShadowRoot.clonable` Read only

Returns a boolean that indicates whether the shadow root is clonable, which can be set via the `Element.attachShadow()` `clonable` option.

`ShadowRoot.delegatesFocus` Read only

Returns a boolean that indicates whether `delegatesFocus` was set when the shadow was attached (see `Element.attachShadow()`).

`ShadowRoot.fullscreenElement` Read only

The element that's currently in full screen mode for this shadow tree.

`ShadowRoot.host` Read only

Returns a reference to the DOM element the `ShadowRoot` is attached to.

`ShadowRoot.innerHTML`

Sets or returns a reference to the DOM tree inside the `ShadowRoot`.

`ShadowRoot.mode` Read only

 The mode of the `ShadowRoot`, either `open` or `closed`.
 This defines whether or not the shadow root's internal features are accessible from JavaScript.

`ShadowRoot.pictureInPictureElement` Read only

Returns the `Element` within the shadow tree that is currently being presented in picture-in-picture mode.

`ShadowRoot.pointerLockElement` Read only

 Returns the `Element` set as the target for mouse events while the pointer is locked.
 `null` if lock is pending, pointer is unlocked, or if the target is in another tree.

`ShadowRoot.slotAssignment` Read only

Returns a string containing the type of slot assignment, either `manual` or `named`.

`ShadowRoot.styleSheets` Read only

Returns a `StyleSheetList` of `CSSStyleSheet` objects for stylesheets explicitly linked into, or embedded in a shadow tree.

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

`ShadowRoot.getAnimations()`

Returns an array of all `Animation` objects currently in effect, whose target elements are descendants of the shadow tree.

`ShadowRoot.getSelection()`
Non-standard

Returns a `Selection` object representing the range of text selected by the user, or the current position of the caret.

`ShadowRoot.elementFromPoint()`
Non-standard

Returns the topmost element at the specified coordinates.

`ShadowRoot.elementsFromPoint()`
Non-standard

Returns an array of all elements at the specified coordinates.

Events
------

The following events are available to `ShadowRoot` via event bubbling from `HTMLSlotElement`:

`HTMLSlotElement` `slotchange` event

An event fired when the node(s) contained in that slot change.

Examples
--------

The following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes.

Inside the `<custom-square>` element's class definition we include some life cycle callbacks that make a call to an external function, `updateStyle()`, which actually applies the size and color to the element. You'll see that we are passing it `this` (the custom element itself) as a parameter.

```js
connectedCallback() {
  console.log('Custom square element added to page.');
  updateStyle(this);
}

attributeChangedCallback(name, oldValue, newValue) {
  console.log('Custom square element attributes changed.');
  updateStyle(this);
}
```

 In the `updateStyle()` function itself, we get a reference to the shadow DOM using `Element.shadowRoot`.
 From here we use standard DOM traversal techniques to find the `<style>` element inside the shadow DOM and then update the CSS found inside it:

```js
function updateStyle(elem) {
  const shadow = elem.shadowRoot;
  const childNodes = shadow.childNodes;
  for (const node of childNodes) {
    if (node.nodeName === "STYLE") {
      node.textContent = `
div {
 width: ${elem.getAttribute("l")}px;
 height: ${elem.getAttribute("l")}px;
 background-color: ${elem.getAttribute("c")};
}
 `;
    }
  }
}
```

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

| Specification |
| --- |
| DOM Standard # interface-shadowroot |

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

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


AbstractRange - Web APIs

AbstractRange
=============

The **`AbstractRange`** abstract interface is the base class upon which all DOM range types are defined. A **range** is an object that indicates the start and end points of a section of content within the document.

**Note:** As an abstract interface, you will not directly instantiate an object of type `AbstractRange`. Instead, you will use the `Range` or `StaticRange` interfaces. To understand the difference between those two interfaces, and how to choose which is appropriate for your needs, consult each interface's documentation.

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

`collapsed` Read only

A Boolean value which is `true` if the range is *collapsed*. A collapsed range is a range whose start position and end position are the same, resulting in a zero-character-long range.

`endContainer` Read only

The `Node` object in which the end of the range, as specified by the `endOffset` property, is located.

`endOffset` Read only

An integer value indicating the offset, in characters, from the beginning of the node's contents to the last character of the range represented by the range object. This value must be less than the length of the `endContainer` node.

`startContainer` Read only

The DOM `Node` in which the beginning of the range, as specified by the `startOffset` property, is located.

`startOffset` Read only

An integer value indicating the offset, in characters, from the beginning of the node's contents to the first character of the contents referred to by the range object. This value must be less than the length of the node indicated in `startContainer`.

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

*The `AbstractRange` interface doesn't provide any methods.*

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

### Range types

All ranges of content within a `document` are described using instances of interfaces based on `AbstractRange`. There are two such interfaces:

`Range`

The `Range` interface has been around for a long time and has only recently been redefined to be based upon `AbstractRange` as the need arose to define other forms of range data. `Range` provides methods that allow you to alter the range's endpoints, as well as methods to compare ranges, detect intersections between ranges, and so forth.

`StaticRange`

A `StaticRange` is a basic range which cannot be changed once it's been created. Specifically, as the node tree mutates and changes, the range does not. This is useful when you need to specify a range that will only be used once, since it avoids the performance and resource impact of the more complex `Range` interface.

### Contents of elements

When trying to access the contents of an element, keep in mind that the element itself is a node, but so is any text inside it. In order to set a range endpoint within the text of an element, be sure to find the text node inside the element:

```js
const startElem = document.querySelector("p");
const endElem = startElem.querySelector("span");
const range = document.createRange();

range.setStart(startElem, 0);
range.setEnd(endElem, endElem.childNodes[0].length / 2);
const contents = range.cloneContents();

document.body.appendChild(contents);
```

This example creates a new range, `range`, and sets its starting point to the third child node of the first element whose class is `elementclass`. The end point is set to be the middle of the first child of the span, and then the range is used to copy the contents of the range.

### Ranges and the hierarchy of the DOM

In order to define a range of characters within a document in a way that is able to span across zero or more node boundaries, and which is as resilient as possible to changes to the DOM, you can't specify the offset to the first and last characters in the HTML. There are a few good reasons for that.

First, after your page is loaded, the browser isn't thinking in terms of HTML. Once it's been loaded, the page is a tree of DOM `Node` objects, so you need to specify the beginning and ending locations of a range in terms of nodes and positions within nodes.

Second, in order to support the mutability of the DOM tree as much as possible, you need a way to represent positions relative to nodes in the tree, rather than global positions within the entire document. By defining points within the document as offsets within a given node, those positions remain consistent with the content even as nodes are added to, removed from, or moved around within the DOM tree—within reason. There are fairly obvious limitations (such as if a node is moved to be after the endpoint of a range, or if the content of a node is heavily altered), but it's far better than nothing.

Third, using node-relative positions to define the start and end positions will generally be easier to make perform well. Rather than having to negotiate the DOM figuring out what your global offset refers to, the user agent (browser) can instead go directly to the node indicated by the starting position and start from there, working its way forward until it reaches the given offset into the ending node.

To illustrate this, consider the HTML below:

```html
<div class="container">
  <div class="header">
    <img src="" class="sitelogo" />
    <h1>The Ultimate Website</h1>
  </div>
  <article>
    <section class="entry" id="entry1">
      <h2>Section 1: An interesting thing…</h2>
      <p>A <em>very</em> interesting thing happened on the way to the forum…</p>
      <aside class="callout">
        <h2>Aside</h2>
        <p>An interesting aside to share with you…</p>
      </aside>
    </section>
  </article>
  <pre id="log"></pre>
</div>
```

After loading the HTML and constructing the DOM representation of the document, the resulting DOM tree looks like this:

![Diagram of the DOM for a simple web page](/en-US/docs/Web/API/AbstractRange/simpledom.svg)

In this diagram, the nodes representing HTML elements are shown in green. Each row beneath them shows the next layer of depth into the DOM tree. Blue nodes are text nodes, containing the text that gets shown onscreen. Each element's contents are linked below it in the tree, potentially spawning a series of branches below as elements include other elements and text nodes.

If you want to create a range that incorporates the contents of the `<p>` element whose contents are `"A <em>very</em> interesting thing happened on the way to the forum…"`, you can do so like this:

```js
const pRange = document.createRange();
pRange.selectNodeContents(document.querySelector("#entry1 p"));
```

Since we wish to select the entire contents of the `<p>` element, including its descendants, this works perfectly.

If we wish to instead copy the text "An interesting thing…" from the `<section>`'s heading (an h2 element) through the end of the letters "ve" in the `<em>` within the paragraph below it, the following code would work:

```js
const range = document.createRange();
const startNode = document.querySelector("section h2").childNodes[0];
range.setStart(startNode, 11);

const endNode = document.querySelector("#entry1 p em").childNodes[0];
range.setEnd(endNode, 2);

const fragment = range.cloneContents();
```

Here an interesting problem arises—we are capturing content from multiple nodes located at different levels of the DOM hierarchy, and then only part of one of them. What should the result look like?

As it turns out, the DOM specification fortunately addresses this exact issue. For example, in this case, we're calling `cloneContents()` on the range to create a new `DocumentFragment` object providing a DOM subtree which replicates the contents of the specified range. To do this, `cloneContents()` constructs all the nodes needed to preserve the structure of the indicated range, but no more than necessary.

In this example, the start of the specified range is found within the text node below the section's heading, which means that the new `DocumentFragment` will need to contain an h2 and, below it, a text node.

The range's end is located below the `<p>` element, so that will be needed within the new fragment. So will the text node containing the word "A", since that's included in the range. Finally, an `<em>` and a text node below it will be added below the `<p>` as well.

The contents of the text nodes are then determined by the offsets into those text nodes given when calling `setStart()` and `setEnd()`. Given the offset of 11 into the heading's text, that node will contain "An interesting thing…". Similarly, the last text node will contain "ve", given the request for the first two characters of the ending node.

The resulting document fragment looks like this:

![A DocumentFragment representing the cloned content](/en-US/docs/Web/API/AbstractRange/dom-fragment.svg)

Notice especially that the contents of this fragment are all *below* the shared common parent of the topmost nodes within it. The parent `<section>` is not needed to replicate the cloned content, so it isn't included.

Example
-------

Consider this simple HTML fragment of HTML.

```html
<p><strong>This</strong> is a paragraph.</p>
```

Imagine using a `Range` to extract the word "paragraph" from this. The code to do that looks like the following:

```js
const paraNode = document.querySelector("p");
const paraTextNode = paraNode.childNodes[1];

const range = document.createRange();
range.setStart(paraTextNode, 6);
range.setEnd(paraTextNode, paraTextNode.length - 1);

const fragment = range.cloneContents();
document.body.appendChild(fragment);
```

First we get references to the paragraph node itself as well as to the *second* child node within the paragraph. The first child is the `<strong>` element. The second child is the text node " is a paragraph.".

With the text node reference in hand, we create a new `Range` object by calling `createRange()` on the `Document` itself. We set the starting position of the range to the sixth character of the text node's string, and the end position to the length of the text node's string minus one. This sets the range to encompass the word "paragraph".

We then finish up by calling `cloneContents()` on the `Range` to create a new `DocumentFragment` object which contains the portion of the document encompassed by the range. After that, we use `appendChild()` to add that fragment at the end of the document's body, as obtained from `document.body`.

The result looks like this:

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

| Specification |
| --- |
| DOM Standard # interface-abstractrange |

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

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


AudioDestinationNode - Web APIs

AudioDestinationNode
====================

The `AudioDestinationNode` interface represents the end destination of an audio graph in a given context — usually the speakers of your device. It can also be the node that will "record" the audio data when used with an `OfflineAudioContext`.

`AudioDestinationNode` has no output (as it *is* the output, no more `AudioNode` can be linked after it in the audio graph) and one input. The number of channels in the input must be between `0` and the `maxChannelCount` value or an exception is raised.

The `AudioDestinationNode` of a given `AudioContext` can be retrieved using the `AudioContext.destination` property.

EventTarget

AudioNode

AudioDestinationNode

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `0` |
| Channel count mode | `"explicit"` |
| Channel count | `2` |
| Channel interpretation | `"speakers"` |

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

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

`AudioDestinationNode.maxChannelCount`

An `unsigned long` defining the maximum number of channels that the physical device can handle.

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

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

Example
-------

There is no complex set up for using an `AudioDestinationNode` — by default, this represents the output of the user's system (e.g. their speakers), so you can get it hooked up inside an audio graph using only a few lines of code:

```js
const audioCtx = new AudioContext();
const source = audioCtx.createMediaElementSource(myMediaElement);
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
```

To see a more complete implementation, check out one of our MDN Web Audio examples, such as Voice-change-o-matic or Violent Theremin.

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

| Specification |
| --- |
| Web Audio API # AudioDestinationNode |

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

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

See also
--------

* Using the Web Audio API


CanvasGradient - Web APIs

CanvasGradient
==============

The **`CanvasGradient`** interface represents an opaque object describing a gradient. It is returned by the methods `CanvasRenderingContext2D.createLinearGradient()`, `CanvasRenderingContext2D.createConicGradient()` or `CanvasRenderingContext2D.createRadialGradient()`.

It can be used as a `fillStyle` or `strokeStyle`.

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

*As an opaque object, there is no exposed property.*

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

`CanvasGradient.addColorStop()`

Adds a new stop, defined by an `offset` and a `color`, to the gradient.

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

| Specification |
| --- |
| HTML Standard # canvasgradient |

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

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

See also
--------

* Creator methods in `CanvasRenderingContext2D`.
* The `<canvas>` element and its associated interface, `HTMLCanvasElement`.


ReadableStreamDefaultReader - Web APIs

ReadableStreamDefaultReader
===========================

The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request).

A `ReadableStreamDefaultReader` can be used to read from a `ReadableStream` that has an underlying source of any type (unlike a `ReadableStreamBYOBReader`, which can only be used with readable streams that have an *underlying byte source*).

 Note however that zero-copy transfer from an underlying source is only supported for underlying byte sources that autoallocate buffers.
 In other words, the stream must have been constructed specifying both `type="bytes"` and `autoAllocateChunkSize`.
 For any other underlying source, the stream will always satisfy read requests with data from internal queues.

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

`ReadableStreamDefaultReader()`

Creates and returns a `ReadableStreamDefaultReader` object instance.

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

`ReadableStreamDefaultReader.closed` Read only

Returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process.

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

`ReadableStreamDefaultReader.cancel()`

Returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. The supplied `reason` argument will be given to the underlying source, which may or may not use it.

`ReadableStreamDefaultReader.read()`

Returns a promise providing access to the next chunk in the stream's internal queue.

`ReadableStreamDefaultReader.releaseLock()`

Releases the reader's lock on the stream.

Examples
--------

In the following example, an artificial `Response` is created to stream HTML fragments fetched from another resource to the browser.

It demonstrates the usage of a `ReadableStream` in combination with a `Uint8Array`.

```js
fetch("https://www.example.org/").then((response) => {
  const reader = response.body.getReader();
  const stream = new ReadableStream({
    start(controller) {
      // The following function handles each data chunk
      function push() {
        // "done" is a Boolean and value a "Uint8Array"
        return reader.read().then(({ done, value }) => {
          // Is there no more data to read?
          if (done) {
            // Tell the browser that we have finished sending data
            controller.close();
            return;
          }

          // Get the data and send it to the browser via the controller
          controller.enqueue(value);
          push();
        });
      }

      push();
    },
  });

  return new Response(stream, { headers: { "Content-Type": "text/html" } });
});
```

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

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

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

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

See also
--------

* Streams API concepts
* Using readable streams
* `ReadableStream`
* WHATWG Stream Visualizer, for a basic visualization of readable, writable, and transform streams.
* Web-streams-polyfill or sd-streams - polyfills


VideoTrack - Web APIs

VideoTrack
==========

The `VideoTrack` interface represents a single video track from a `<video>` element.

The most common use for accessing a `VideoTrack` object is to toggle its `selected` property in order to make it the active video track for its `<video>` element.

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

`selected`

A Boolean value which controls whether or not the video track is active. Only a single video track can be active at any given time, so setting this property to `true` for one track while another track is active will make that other track inactive.

`id` Read only

A string which uniquely identifies the track within the media. This ID can be used to locate a specific track within a video track list by calling `VideoTrackList.getTrackById()`. The ID can also be used as the fragment part of the URL if the media supports seeking by media fragment per the Media Fragments URI specification.

`kind` Read only

A string specifying the category into which the track falls. For example, the main video track would have a `kind` of `"main"`.

`label` Read only

A string providing a human-readable label for the track. For example, a track whose `kind` is `"sign"` might have a `label` of `"A sign-language interpretation"`. This string is empty if no label is provided.

`language` Read only

A string specifying the video track's primary language, or an empty string if unknown. The language is specified as a BCP 47 (RFC 5646) language code, such as `"en-US"` or `"pt-BR"`.

`sourceBuffer` Read only

The `SourceBuffer` that created the track. Returns null if the track was not created by a `SourceBuffer` or the `SourceBuffer` has been removed from the `MediaSource.sourceBuffers` attribute of its parent media source.

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

To get a `VideoTrack` for a given media element, use the element's `videoTracks` property, which returns a `VideoTrackList` object from which you can get the individual tracks contained in the media:

```js
const el = document.querySelector("video");
const tracks = el.videoTracks;
```

You can then access the media's individual tracks using either array syntax or functions such as `forEach()`.

This first example gets the first video track on the media:

```js
const firstTrack = tracks[0];
```

The next example scans through all of the media's video tracks, activating the first video track that is in the user's preferred language (taken from a variable `userLanguage`).

```js
for (const track of tracks) {
  if (track.language === userLanguage) {
    track.selected = true;
    break;
  }
}
```

The `language` is in standard (RFC 5646) format. For US English, this would be `"en-US"`, for example.

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

| Specification |
| --- |
| HTML Standard # videotrack |

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

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


NavigationTransition - Web APIs

NavigationTransition
====================

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

The **`NavigationTransition`** interface of the Navigation API represents an ongoing navigation, that is, a navigation that hasn't yet reached the `navigatesuccess` or `navigateerror` stage.

It is accessed via the `Navigation.transition` property.

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

`finished` Read only
Experimental

Returns a `Promise` that fulfills at the same time the `navigatesuccess` event fires, or rejects at the same time the `navigateerror` event fires.

`from` Read only
Experimental

Returns the `NavigationHistoryEntry` that the transition is coming from.

`navigationType` Read only
Experimental

Returns the type of the ongoing navigation.

Examples
--------

```js
async function cleanupNavigation() {
  await navigation.transition.finished;
  // Navigation has completed successfully
  // Cleanup any ongoing monitoring
}
```

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

| Specification |
| --- |
| HTML Standard # navigationtransition |

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

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

See also
--------

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


Web Serial API - Web APIs

Web Serial API
==============

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

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

The **Web Serial API** provides a way for websites to read from and write to serial devices. These devices may be connected via a serial port, or be USB or Bluetooth devices that emulate a serial port.

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

The Web Serial API is one of a set of APIs that allow websites to communicate with peripherals connected to a user's computer. It provides the ability to connect to devices that are required by the operating system to communicate via the serial API, rather than USB which can be accessed via the `WebUSB API`, or input devices that can be accessed via `WebHID API`.

Examples of serial devices include 3D printers, and microcontrollers such as the BBC micro:bit board.

Interfaces
----------

`Serial`
Experimental

Provides attributes and methods for finding and connecting to serial ports from a web page.

`SerialPort`
Experimental

Provides access to a serial port on the host device.

Extensions to other interfaces
------------------------------

`Navigator.serial` Read only
Experimental

Returns a `Serial` object, which represents the entry point into the `Web Serial API` to enable the control of serial ports.

`WorkerNavigator.serial` Read only
Experimental

Returns a `Serial` object, which represents the entry point into the `Web Serial API` to enable the control of serial ports.

Examples
--------

The following examples demonstrate some of the functionality provided by the Web Serial API.

### Checking for available ports

The following example shows how to check for available ports and allows the user to grant it permission to access additional ports.

The `connect` and `disconnect` events let sites react when a device is connected or disconnected from the system. The `getPorts()` method is then called to see connected ports that the site already has access to.

If the site doesn't have access to any connected ports it has to wait until it has user activation to proceed. In this example we use a `click` event handler on a button for this task. A filter is passed to `requestPort()` with a USB vendor ID in order to limit the set of devices shown to the user to only USB devices built by a particular manufacturer.

```js
navigator.serial.addEventListener("connect", (e) => {
  // Connect to `e.target` or add it to a list of available ports.
});

navigator.serial.addEventListener("disconnect", (e) => {
  // Remove `e.target` from the list of available ports.
});

navigator.serial.getPorts().then((ports) => {
  // Initialize the list of available ports with `ports` on page load.
});

button.addEventListener("click", () => {
  const usbVendorId = 0xabcd;
  navigator.serial
    .requestPort({ filters: [{ usbVendorId }] })
    .then((port) => {
      // Connect to `port` or add it to the list of available ports.
    })
    .catch((e) => {
      // The user didn't select a port.
    });
});
```

### Reading data from a port

 The following example shows how to read data from a port. The outer loop handles non-fatal errors,
 creating a new reader until a fatal error is encountered and `SerialPort.readable` becomes `null`.

```js
while (port.readable) {
  const reader = port.readable.getReader();
  try {
    while (true) {
      const { value, done } = await reader.read();
      if (done) {
        // |reader| has been canceled.
        break;
      }
      // Do something with |value|...
    }
  } catch (error) {
    // Handle |error|...
  } finally {
    reader.releaseLock();
  }
}
```

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

| Specification |
| --- |
| Web Serial API # serial-interface |

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

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

See also
--------

* Read from and write to a serial port
* Getting started with the Web Serial API


ReportBody - Web APIs

ReportBody
==========

The **`ReportBody`** interface of the Reporting API represents the body of a report. Individual report types inherit from this interface, adding specific attributes relevant to the particular report.

### Reports that inherit from `ReportBody`

* `CSPViolationReportBody`
* `DeprecationReportBody`
* `InterventionReportBody`

An instance of `ReportBody` is returned as the value of `Report.body`. The interface has no constructor.

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

`ReportBody.toJSON()`

A *serializer* which returns a JSON representation of the `ReportBody` object.

Examples
--------

In this example we create a new `ReportingObserver` to observe intervention reports. The `InterventionReportBody` interface inherits from `ReportBody`.

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

const observer = new ReportingObserver(([firstReport], observer) => {
  console.log(firstReport.type); // intervention
}, options);
```

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

| Specification |
| --- |
| Reporting API # reportbody |

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

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


IIRFilterNode - Web APIs

IIRFilterNode
=============

The **`IIRFilterNode`** interface of the Web Audio API is a `AudioNode` processor which implements a general **infinite impulse response** (IIR) filter; this type of filter can be used to implement tone control devices and graphic equalizers as well. It lets the parameters of the filter response be specified, so that it can be tuned as needed.

EventTarget

AudioNode

IIRFilterNode

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"max"` |
| Channel count | Same as on the input |
| Channel interpretation | `"speakers"` |

Typically, it's best to use the `BiquadFilterNode` interface to implement higher-order filters. There are several reasons why:

* Biquad filters are typically less sensitive to numeric quirks.
* The filter parameters of biquad filters can be automated.
* All even-ordered IIR filters can be created using `BiquadFilterNode`.

However, if you need to create an odd-ordered IIR filter, you'll need to use `IIRFilterNode`. You may also find this interface useful if you don't need automation, or for other reasons.

**Note:** Once the node has been created, you can't change its coefficients.

`IIRFilterNode`s have a tail-time reference; they continue to output non-silent audio with zero input. As an IIR filter, the non-zero input continues forever, but this can be limited after some finite time in practice, when the output has approached zero closely enough. The actual time that takes depends on the filter coefficients provided.

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

`IIRFilterNode()`

Creates a new instance of an IIRFilterNode object.

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

*This interface has no properties of its own; however, it inherits properties from its parent, `AudioNode`*.

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

*Inherits methods from its parent, `AudioNode`. It also has the following additional methods:*

`getFrequencyResponse()`

Uses the filter's current parameter settings to calculate the response for frequencies specified in the provided array of frequencies.

Examples
--------

You can find a simple IIR filter demo live on Codepen. Also see the source code on GitHub. It includes some different coefficient values for different lowpass frequencies — you can change the value of the `filterNumber` constant to a value between 0 and 3 to check out the different available effects.

Also see our Using IIR filters guide for a full explanation.

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

| Specification |
| --- |
| Web Audio API # IIRFilterNode |

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

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

See also
--------

* Using the Web Audio API
* `AudioNode`
* `BiquadFilterNode`