XRSession: requestAnimationFrame() method - Web APIs

XRSession: requestAnimationFrame() method
=========================================

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

 The `XRSession`
 method **`requestAnimationFrame()`**, much like the
 `Window` method of the same name, schedules a callback to be executed the
 next time the browser is ready to paint the session's virtual environment to the XR
 display. The specified callback is executed once before the next repaint; if
 you wish for it to be executed for the following repaint, you must
 call `requestAnimationFrame()` again. This can be done from within the
 callback itself.

 The callback takes two parameters as inputs: an `XRFrame` describing the
 state of all tracked objects for the session, and a timestamp you can use to compute
 any animation updates needed.

 You can cancel a previously scheduled animation by calling
 `cancelAnimationFrame()`.

**Note:** Despite the obvious similarities between these methods and the
 global `requestAnimationFrame()` function
 provided by the `Window` interface, you *must not* treat these as
 interchangeable. There is *no* guarantee that the latter will work at all while
 an immersive XR session is underway.

Syntax
------

```js
requestAnimationFrame(animationFrameCallback)
```

### Parameters

`animationFrameCallback`

 A function which is called before the next repaint in order to allow you to update
 and render the XR scene based on elapsed time, animation, user input changes, and so
 forth. The callback receives as input two parameters:

`time`

 A `DOMHighResTimeStamp` indicating the time offset at which the
 updated viewer state was received from the WebXR device.

`xrFrame`

 An `XRFrame` object describing the state of the objects being
 tracked by the session. This can be used to obtain the poses of the viewer and the
 scene itself, as well as other information needed to render a frame of an AR or VR
 scene.

### Return value

 An integer value which serves as a unique, non-zero ID or handle you may pass to
 `cancelAnimationFrame()` if you need to
 remove the pending animation frame request.

Examples
--------

 The following example requests `XRSession` with "inline" mode so that it can
 be displayed in an HTML element (without the need for a separate AR or VR device).

**Note:** A real application should check that the device and the User
 Agent support WebXR API at all and then that they both support the desired session
 type via `XRSystem.isSessionSupported()`.

```js
// Obtain XR object
const XR = navigator.xr;

// Request a new XRSession
XR.requestSession("inline").then((xrSession) => {
  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,
      );

      // WebGL draw calls will now be rendered into the appropriate viewport.
    }
  });
});
```

 The following example was taken directly from the spec draft. This example demonstrates
 a design pattern that ensures seamless transition between non-immersive animations
 created via `Window.requestAnimationFrame` and immersive XR animations.

```js
let xrSession = null;

function onWindowAnimationFrame(time) {
  window.requestAnimationFrame(onWindowAnimationFrame);

  // This may be called while an immersive session is running on some devices,
  // such as a desktop with a tethered headset. To prevent two loops from
  // rendering in parallel, skip drawing in this one until the session ends.
  if (!xrSession) {
    renderFrame(time, null);
  }
}

// The window animation loop can be started immediately upon the page loading.
window.requestAnimationFrame(onWindowAnimationFrame);

function onXRAnimationFrame(time, xrFrame) {
  xrSession.requestAnimationFrame(onXRAnimationFrame);
  renderFrame(time, xrFrame);
}

function renderFrame(time, xrFrame) {
  // Shared rendering logic.
}

// Assumed to be called by a user gesture event elsewhere in code.
function startXRSession() {
  navigator.xr.requestSession("immersive-vr").then((session) => {
    xrSession = session;
    xrSession.addEventListener("end", onXRSessionEnded);
    // Do necessary session setup here.
    // Begin the session's animation loop.
    xrSession.requestAnimationFrame(onXRAnimationFrame);
  });
}

function onXRSessionEnded() {
  xrSession = null;
}
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrsession-requestanimationframe |

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

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

See also
--------

* `Window.requestAnimationFrame()`
* `XRSession.cancelAnimationFrame()`


XRSession: visibilitychange event - Web APIs

XRSession: visibilitychange event
=================================

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

The **`visibilitychange`** event is sent to an `XRSession` to inform it when it becomes visible or hidden, or when it becomes visible but not currently focused. Upon receiving the event, you can check the value of the session's `visibilityState` property to determine the new visibility state.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("visibilitychange", (event) => {});

onvisibilitychange = (event) => {};
```

Event type
----------

An `XRSessionEvent`. Inherits from `Event`.

Event

XRSessionEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`session` Read only

The `XRSession` to which the event refers.

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

### Trigger

Triggered when an `XRSession` becomes visible or hidden, or when it becomes visible but not currently focused.

When the `XRSession` receives this event, the visibility state has already been changed.

### Use cases

Upon receiving the event, you can check the value of the session's `visibilityState` property to determine the new visibility state.

Examples
--------

This example demonstrates how to listen for a `visibilitychange` event on a WebXR session, using `addEventListener()` to begin listening for the event:

```js
navigator.xr.requestSession("inline").then((xrSession) => {
  xrSession.addEventListener("visibilitychange", (e) => {
    switch (e.session.visibilityState) {
      case "visible":
      case "visible-blurred":
        mySessionVisible(true);
        break;
      case "hidden":
        mySessionVisible(false);
        break;
    }
  });
});
```

When a visibility state change occurs, the event is received and dispatched to a function `mySessionVisible()`, with a Boolean parameter indicating whether or not the session is presently being displayed to the user.

You can also create the event handler by assigning it to the `XRSession`'s `onvisibilitychange` event handler property, like this:

```js
xrSession.onvisibilitychange = (e) => {
  /\* event handled here \*/
};
```

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

| Specification |
| --- |
| WebXR Device API # eventdef-xrsession-visibilitychange |
| WebXR Device API # dom-xrsession-onvisibilitychange |

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

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


XRSession: selectend event - Web APIs

XRSession: selectend event
==========================

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

The WebXR event **`selectend`** is sent to an `XRSession` when one of its input sources ends its primary action or when an input source that's in the process of handling an ongoing primary action is disconnected without successfully completing the action.

The `beforexrselect` is fired before this event and can prevent this event from being raised.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("selectend", (event) => {});

onselectend = (event) => {};
```

Event type
----------

An `XRInputSourceEvent`. Inherits from `Event`.

Event

XRInputSourceEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`frame` Read only

An `XRFrame` object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an *event* frame, not an *animation* frame, you cannot call the `XRFrame` method `getViewerPose()` on it; instead, use `getPose()`.

`inputSource` Read only

An `XRInputSource` object indicating which input source generated the input event.

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

### Trigger

Triggered when the user stops to press triggers or buttons, taps a touchpad, speaks a command, or performs a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.

### Use cases

The `selectend` and `selectstart` events tell you when you might want to display something to the user indicating that the primary action is going on. This might be drawing a controller with the activated button in a new color, or showing the targeted object being grabbed and moved around, starting when `selectstart` arrives and stopping when `selectend` is received.

The `select` event is the event that tells your code that the user has completed the action they want to complete. This might be as simple as throwing an object or pulling the trigger of a gun in a game, or as involved as placing a dragged object in a new location.

If your primary action is a simple trigger action and you don't need to animate anything while the trigger is engaged, you can ignore the `selectstart` and `selectend` events and act on the start event.

Examples
--------

See the `selectstart` event for example code.

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

| Specification |
| --- |
| WebXR Device API # eventdef-xrsession-selectend |
| WebXR Device API # dom-xrsession-onselectend |

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

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

See also
--------

* `select` and `selectstart`
* `beforexrselect`


XRSession: squeezeend event - Web APIs

XRSession: squeezeend event
===========================

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

The WebXR event **`squeezeend`** is sent to an `XRSession` when one of its input sources ends its primary action or when an input source that's in the process of handling an ongoing primary action is disconnected without successfully completing the action.

Primary squeeze actions include things like users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("squeezeend", (event) => {});

onsqueezeend = (event) => {};
```

Event type
----------

An `XRInputSourceEvent`. Inherits from `Event`.

Event

XRInputSourceEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`frame` Read only

An `XRFrame` object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an *event* frame, not an *animation* frame, you cannot call `XRFrame.getViewerPose()` on it; instead, use `getPose()`.

`inputSource` Read only

An `XRInputSource` object indicating which input source generated the input event.

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

### Trigger

Triggered when users stop squeezing the controller, making a hand gesture that mimes grabbing something, or using (squeezing) a trigger.

### Use cases

The `squeezestart` event is sent indicating that the user has begun a squeeze action.

If the primary squeeze action ends successfully, the session is sent a `squeeze` event.

A `squeezeend` event is sent to indicate that the squeeze action is no longer underway. This is sent whether the squeeze action succeeded or not.

Examples
--------

See the `squeezestart` event for example code.

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

| Specification |
| --- |
| WebXR Device API # eventdef-xrsession-squeezeend |
| WebXR Device API # dom-xrsession-onsqueezeend |

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

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


XRSession: inputSources property - Web APIs

XRSession: inputSources property
================================

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

 The read-only **`inputSources`** property of the
 `XRSession` interface returns an `XRInputSourceArray` object
 which lists all controllers and input devices which are expressly associated with the
 XR device and are currently available. These controllers may include handheld
 controllers, XR-equipped gloves, optically tracked hands, and gaze-based input methods.
 Keyboards, gamepads, and mice are *not* considered WebXR input sources.

**Note:** Traditional gamepad controllers are supported using the Gamepad API.

Value
-----

 An `XRInputSourceArray` object listing all of the currently-connected
 input controllers which are linked specifically to the XR device currently in use. The
 returned object is **live**; as devices are connected to and removed from
 the user's system, the list's contents update to reflect the changes.

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

 You can add a handler for the `XRSession` event
 `inputsourceschange` to be advised
 when the contents of the session's connected devices list changes. You can then either
 get the value of `inputSources` to examine the list, or you can refer to a
 reference to the list that you've previously saved.

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

| Specification |
| --- |
| WebXR Device API # dom-xrsession-inputsources |

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

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

See also
--------

* `XRInputSource`
* The `inputsourceschange` event
* Gamepad API


XRSession: inputsourceschange event - Web APIs

XRSession: inputsourceschange event
===================================

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

The **`inputsourceschange`** event is sent to an `XRSession` when the set of available WebXR input devices changes.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("inputsourceschange", (event) => {});

oninputsourceschange = (event) => {};
```

Event type
----------

An `XRInputSourcesChangeEvent`. Inherits from `Event`.

Event

XRInputSourcesChangeEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`added` Read only

An array of zero or more `XRInputSource` objects, each representing an input device which has been recently connected or enabled.

`removed` Read only

An array of zero or more `XRInputSource` objects representing the input devices recently disconnected or disabled.

`session` Read only

The `XRSession` to which this input source change event is being directed.

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

### Trigger

Triggered when the set of available WebXR input devices changes.

### Use cases

You can use this event to detect newly-available devices or when devices have become unavailable.

Examples
--------

The following example shows how to set up an event handler which uses `inputsourceschange` events to detect newly-available pointing devices and to load their models in preparation for displaying them in the next animation frame.

```js
xrSession.addEventListener("inputsourceschange", onInputSourcesChange);

function onInputSourcesChange(event) {
  for (const input of event.added) {
    if (input.targetRayMode === "tracked-pointer") {
      loadControllerMesh(input);
    }
  }
}
```

You can also add a handler for `inputsourceschange` events by setting the `oninputsourceschange` event handler:

```js
xrSession.oninputsourceschange = onInputSourcesChange;
```

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

| Specification |
| --- |
| WebXR Device API # eventdef-xrsession-inputsourceschange |
| WebXR Device API # dom-xrsession-oninputsourceschange |

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

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


XRSession: preferredReflectionFormat property - Web APIs

XRSession: preferredReflectionFormat property
=============================================

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

The *read-only* **`preferredReflectionFormat`** property of the `XRSession` interface returns this session's preferred reflection format used for lighting estimation texture data.

Value
-----

A string representing the reflection format. Possible values:

| XRReflectionFormat | WebGL Format | WebGL Internal Format | WebGPU Format | HDR |
| --- | --- | --- | --- | --- |
| "srgba8" | RGBA | SRGB8\_ALPHA8 | "rgba8unorm-srgb" |  |
| "rgba16f" | RGBA | RGBA16F | "rgba16float" | ✓ |

Examples
--------

### Requesting a light probe with the system's preferred format

You can request a light probe with `XRSession.requestLightProbe()` and specify the system's preferred format by setting the `reflectionFormat` option equal to `XRSession.preferredReflectionFormat`.

```js
const lightProbe = await xrSession.requestLightProbe({
  reflectionFormat: xrSession.preferredReflectionFormat,
});
```

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

| Specification |
| --- |
| WebXR Lighting Estimation API Level 1 # dom-xrsession-preferredreflectionformat |

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

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

See also
--------

* `XRSession.requestLightProbe()`


XRSession: end() method - Web APIs

XRSession: end() method
=======================

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

 The **`end()`** method shuts down the
 `XRSession` on which it's called, returning a promise which resolves once
 the session has fully shut down.

Syntax
------

```js
end()
```

### Parameters

None.

### Return value

 A `promise` that resolves without a value after any platform-specific steps
 related to shutting down the session have completed. You can use the promise to do
 things like update UI elements to reflect the shut down connection, trigger application
 shut down, or whatever else you might need to do.

Examples
--------

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

| Specification |
| --- |
| WebXR Device API # dom-xrsession-end |

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

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


XRSession: requestHitTestSource() method - Web APIs

XRSession: requestHitTestSource() method
========================================

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

 The **`requestHitTestSource()`** method of the
 `XRSession` interface returns a `Promise` that resolves with an `XRHitTestSource` object that can be passed to `XRFrame.getHitTestResults()`.

Syntax
------

```js
requestHitTestSource(options)
```

### Parameters

`options`

An object containing configuration options, specifically:

`space`

The `XRSpace` that will be tracked by the hit test source.

`entityTypes` Optional

An `Array` specifying the types of entities to be used for hit test source creation. If no entity type is specified, the array defaults to a single element with the `plane` type. Possible types:

* `point`: Compute hit test results based on characteristic points detected.
* `plane`: Compute hit test results based on real-world planes detected.
* `mesh`: Compute hit test results based on meshes detected.

`offsetRay` Optional

The `XRRay` object that will be used to perform hit test. If no `XRRay` object has been provided, a new `XRRay` object is constructed without any parameters.

### Return value

A `Promise` that resolves with an `XRHitTestSource` object.

### Exceptions

 Rather than throwing true exceptions, `requestHitTestSource()` rejects the
 returned promise with a `DOMException`, specifically, one of the following:

`NotSupportedError` `DOMException`

Thrown if `hit-test` is not an enabled feature in `XRSystem.requestSession()`.

`InvalidStateError` `DOMException`

Thrown if the session has already ended.

`NotAllowedError` `DOMException`

Thrown if there is an unreasonable amount of requests. Some user agents might limit usage for privacy reasons.

Examples
--------

### Requesting a hit test source

To request a hit test source, start an `XRSession` with the `hit-test` session feature enabled. Next, configure the hit test source and store it for later use in the frame loop and call `XRFrame.getHitTestResults()` to obtain the result.

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

let hitTestSource = null;

xrSession
  .requestHitTestSource({
    space: viewerSpace, // obtained from xrSession.requestReferenceSpace("viewer");
    offsetRay: new XRRay({ y: 0.5 }),
  })
  .then((viewerHitTestSource) => {
    hitTestSource = viewerHitTestSource;
  });

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

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

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

| Specification |
| --- |
| WebXR Hit Test Module # dom-xrsession-requesthittestsource |

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

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

See also
--------

* `XRSession.requestHitTestSourceForTransientInput()`


XRSession: domOverlayState property - Web APIs

XRSession: domOverlayState property
===================================

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

 The *read-only* **`domOverlayState`** property of an `immersive-ar`
`XRSession` provides information about the DOM overlay, if the feature is enabled.

Value
-----

Returns `null` if the DOM overlay feature is not supported or not enabled or an object containing information about the DOM overlay state with the following properties:

`type`

A string indicating how the DOM overlay is being displayed. Possible values:

`screen`

The overlay is drawn on the entire screen-based device (for handheld AR devices).

`head-locked`

The overlay is drawn at a head-locked UI that fills the renderable viewport and follows the user's head movement.

`floating`

The overlay appears as a rectangle floating in space that's kept in front of the user. It doesn't necessarily fill up the entire space and/or is strictly head-locked.

Examples
--------

### Checking which DOM overlay got enabled

```js
if (session.domOverlayState) {
  console.log(session.domOverlayState.type);
} else {
  console.log("DOM overlay not supported or enabled!");
}
```

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

| Specification |
| --- |
| WebXR DOM Overlays Module # dom-xrsession-domoverlaystate |

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

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

See also
--------

* `beforexrselect`


XRSession: requestLightProbe() method - Web APIs

XRSession: requestLightProbe() method
=====================================

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

 The **`requestLightProbe()`** method of the
 `XRSession` interface returns a `Promise` that resolves with an `XRLightProbe` object that estimates lighting information at a given point in the user's environment.

Syntax
------

```js
requestLightProbe()
requestLightProbe(options)
```

### Parameters

`options` Optional

An object containing configuration options, specifically:

`reflectionFormat`

The internal reflection format indicating how the texture data is represented, either `srgba8` (default value) or `rgba16f`. See also `XRSession.preferredReflectionFormat`.

### Return value

A `Promise` that resolves with an `XRLightProbe` object.

### Exceptions

 Rather than throwing true exceptions, `requestLightProbe()` rejects the
 returned promise with a `DOMException`, specifically, one of the following:

`NotSupportedError` `DOMException`

Thrown if `lighting-estimation` is not an enabled feature in `XRSystem.requestSession()` or if the `reflectionFormat` is not `srgb8` or the `preferredReflectionFormat`.

`InvalidStateError` `DOMException`

Thrown if the session has already ended.

Examples
--------

### Requesting a light probe with the system's preferred format

The default format is `srgb8`, however, some rendering engines may use other (high dynamic range) formats. You can request the light probe with `XRSession.preferredReflectionFormat` which reports the preferred internal format.

```js
const lightProbe = await xrSession.requestLightProbe({
  reflectionFormat: xrSession.preferredReflectionFormat,
});
```

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

| Specification |
| --- |
| WebXR Lighting Estimation API Level 1 # dom-xrsession-requestlightprobe |

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

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

See also
--------

* `XRSession.preferredReflectionFormat`


XRSession: select event - Web APIs

XRSession: select event
=======================

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

The WebXR **`select`** event is sent to an `XRSession` when one of the session's input sources has completed a primary action.

The `beforexrselect` is fired before this event and can prevent this event from being raised.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("select", (event) => {});

onselect = (event) => {};
```

Event type
----------

An `XRInputSourceEvent`. Inherits from `Event`.

Event

XRInputSourceEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`frame` Read only

An `XRFrame` object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an *event* frame, not an *animation* frame, you cannot call `XRFrame.getViewerPose()` on it; instead, use `getPose()`.

`inputSource` Read only

An `XRInputSource` object indicating which input source generated the input event.

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

### Trigger

Triggered when a user presses triggers or buttons, taps a touchpad, speaks a command or performs a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.

### Use cases

The `selectstart` and `selectend` events tell you when you might want to display something to the user indicating that the primary action is going on. This might be drawing a controller with the activated button in a new color, or showing the targeted object being grabbed and moved around, starting when `selectstart` arrives and stopping when `selectend` is received.

The `select` event tells your code that the user has completed an action. This might be as simple as throwing an object or pulling the trigger of a gun in a game, or as involved as placing a dragged object at a new location.

If your primary action is a simple trigger action and you don't need to animate anything while the trigger is engaged, you can ignore the `selectstart` and `selectend` events and act on the start event.

Examples
--------

The following example uses `addEventListener()` to set up a handler for the `select` event. The handler fetches the pose representing the target ray for `tracked-pointer` inputs and sends the pose's transform to a function called `myHandleSelectWithRay()`.

```js
xrSession.addEventListener("select", (event) => {
  if (event.inputSource.targetRayMode === "tracked-pointer") {
    let targetRayPose = event.frame.getPose(
      event.inputSource.targetRaySpace,
      myRefSpace,
    );
    if (targetRayPose) {
      myHandleSelectWithRay(targetRayPose.transform);
    }
  }
});
```

You can also set up a handler for `select` events by setting the `XRSession` object's `onselect` event handler property to a function that handles the event:

```js
xrSession.onselect = (event) => {
  if (event.inputSource.targetRayMode === "tracked-pointer") {
    let targetRayPose = event.frame.getPose(
      event.inputSource.targetRaySpace,
      myRefSpace,
    );
    if (targetRayPose) {
      myHandleSelectWithRay(targetRayPose.transform);
    }
  }
};
```

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

| Specification |
| --- |
| WebXR Device API # eventdef-xrsession-select |
| WebXR Device API # dom-xrsession-onselect |

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

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

See also
--------

* `selectstart` and `selectend`
* `beforexrselect`


XRSession: updateRenderState() method - Web APIs

XRSession: updateRenderState() method
=====================================

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

The `updateRenderState()` method of the `XRSession` interface of the WebXR API schedules changes to be applied to the active render state (`XRRenderState`) prior to rendering of the next frame.

Syntax
------

```js
updateRenderState()
updateRenderState(state)
```

### Parameters

`state` Optional

An optional object to configure the `XRRenderState`. If none is provided, a default configuration will be used.

* `baseLayer` Optional: An `XRWebGLLayer` object from which the WebXR compositor will obtain imagery. This is `null` by default. To specify other (or multiple) layers, see the `layers` option.
* `depthFar` Optional: A floating-point value specifying the distance in meters from the viewer to the far clip plane, which is a plane parallel to the display surface beyond which no further rendering will occur. All rendering will take place between the distances specified by `depthNear` and `depthFar`. This is 1000 meters (1 kilometer) by default.
* `depthNear` Optional: A floating-point value indicating the distance in meters from the viewer to a plane parallel to the display surface to be the **near clip plane**. No part of the scene on the viewer's side of this plane will be rendered. This is 0.1 meters (10 centimeters) by default.
* `inlineVerticalFieldOfView` Optional: A floating-point value indicating the default field of view, in radians, to be used when computing the projection matrix for an `inline` `XRSession`. The projection matrix calculation also takes into account the output canvas's aspect ratio. This property *must not* be specified for immersive sessions, so the value is `null` by default for immersive sessions. The default value is otherwise π \* 0.5 (half of the value of pi).
* `layers` Optional: An ordered array of `XRLayer` objects specifying the layers that should be presented to the XR device. Setting `layers` will override the `baseLayer` if one is present, with `baseLayer` reporting `null`. The order of the layers given is "back-to-front". For alpha blending of layers, see the `XRCompositionLayer.blendTextureSourceAlpha` property.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown in any of the following situations:

* The `XRSession` has already ended, so you cannot change its render state.
* The `baseLayer` was created by an `XRSession` other than the one on which `updateRenderState()` was called.
* The `inlineVerticalFieldOfView` option was set, but the session is immersive, and therefore, does not allow this property to be used.

`NotSupportedError` `DOMException`

Thrown in any of the following situations:

* The `layers` option is used in a session that has been created without the `layers` feature.
* Both the `baseLayer` and `layers` options are specified.

`TypeError`

Thrown if the `layers` option contains duplicate instances.

Examples
--------

### Adding a `baseLayer`

This example creates a WebGL context that is compatible with an immersive XR device and then uses it to create an `XRWebGLLayer`. The method `updateRenderState()` is then called to associate the new `XRWebGLLayer`.

```js
function onXRSessionStarted(xrSession) {
  let glCanvas = document.createElement("canvas");
  let gl = glCanvas.getContext("webgl", { xrCompatible: true });

  loadWebGLResources();

  xrSession.updateRenderState({
    baseLayer: new XRWebGLLayer(xrSession, gl),
  });
}
```

### Setting the `layers` array

To use WebXR layers, the XR session needs to be created with the `layers` feature descriptor (see `XRSystem.requestSession()`). You can then create various WebXR layers such as

* `XREquirectLayer`
* `XRCubeLayer`
* `XRCylinderLayer`
* `XRQuadLayer`

Other layers, such as `XRProjectionLayer` or `XRWebGLLayer` are also available.

Layers will be presented in the order they are given in the `layers` array, with layers being given in "back-to-front" order.

```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
  optionalFeatures: ["layers"],
});

function onXRSessionStarted(xrSession) {
  const glCanvas = document.createElement("canvas");
  const gl = glCanvas.getContext("webgl", { xrCompatible: true });
  const xrGlBinding = new XRWebGLBinding(xrSession, gl);
  const projectionLayer = new XRWebGLLayer(xrSession, gl);
  const quadLayer = xrGlBinding.createQuadLayer({
    pixelWidth: 1024,
    pixelHeight: 1024,
  });

  xrSession.updateRenderState({
    layers: [projectionLayer, quadLayer],
  });
}
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrsession-updaterenderstate |

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

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

See also
--------

* WebXR Device API
* `XRRenderState`
* `XRSession.renderState`


XRSession: interactionMode property - Web APIs

XRSession: interactionMode property
===================================

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

 The `XRSession` interface's *read-only* **`interactionMode`** property
 describes the best space (according to the user agent) for the application to draw an interactive UI for the current session.

Value
-----

 A string describing the best space (according to the user agent) for the application to draw an interactive UI
 for the current session.

Possible values are:

`screen-space`

Indicates that the UI should be drawn directly to the screen without projection. This is typically the mode reported from handheld devices.

`world-space`

Indicates that the UI should be drawn in the world, some distance from the user, so that they may interact with it using controllers. This is typically the mode reported from headworn devices.

Examples
--------

```js
if (xrSession.interactionMode === "world-space") {
  // draw UI in the world
} else {
  // draw UI directly to the screen
}
```

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

| Specification |
| --- |
| WebXR Augmented Reality Module - Level 1 # dom-xrsession-interactionmode |

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

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


XRSession: selectstart event - Web APIs

XRSession: selectstart event
============================

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

The WebXR **`selectstart`** event is sent to an `XRSession` when the user begins a primary action on one of its input sources.

The `beforexrselect` is fired before this event and can prevent this event from being raised.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("selectstart", (event) => {});

onselectstart = (event) => {};
```

Event type
----------

An `XRInputSourceEvent`. Inherits from `Event`.

Event

XRInputSourceEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`frame` Read only

An `XRFrame` object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an *event* frame, not an *animation* frame, you cannot call `XRFrame.getViewerPose()` on it; instead, use `getPose()`.

`inputSource` Read only

An `XRInputSource` object indicating which input source generated the input event.

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

### Trigger

Triggered when the user presses triggers or buttons, taps a touchpad, speaks a command, or performs a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.

### Use cases

The `selectstart` and `selectend` events tell you when you might want to display something to the user indicating that the primary action is going on. This might be drawing a controller with the activated button in a new color, or showing the targeted object being grabbed and moved around, starting when `selectstart` arrives and stopping when `selectend` is received.

The `select` event tells your code that the user has completed the action they want to complete. This might be as simple as throwing an object or pulling the trigger of a gun in a game, or as involved as placing a dragged object in a new location.

If your primary action is a simple trigger action and you don't need to animate anything while the trigger is engaged, you can ignore the `selectstart` and `selectend` events and act on the start event.

Examples
--------

The following example uses `addEventListener()` to establish handlers for the selection events: `selectstart`, `selectend`, and `select`. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around.

In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing those tasks does the `onSelectionEvent()` function below dispatch the action out to a specialized function to handle things.

After checking to ensure that the received event is a `tracked-pointer` event (the only kind we handle here), the target ray's pose is obtained using `getPose()`.

If the target ray pose was fetched successfully, the code then uses the value of `Event` property `type` to route control to an appropriate function to handle the event which arrived:

* For `selectstart` events, a `myBeginTracking()` function is called with the target ray pose's `matrix`. The `myBeginTracking()` function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. `myBeginTracking()` returns an object representing the object the user has begun to drag.
* Upon receiving a `select` event, the `myDropObject()` function is called with the target object, and the current target ray pose transform as inputs. This places the object into its new position in the world and triggers any effects that may arise, like scheduling an animation of a splash if dropped in water, etc.
* The `selectend` event results in a `myStopTracking()` function being called with the object being dragged and the final target ray pose's transform.

```js
xrSession.addEventListener("selectstart", onSelectionEvent);
xrSession.addEventListener("select", onSelectionEvent);
xrSession.addEventListener("selectend", onSelectionEvent);

function onSelectionEvent(event) {
  let source = event.inputSource;
  let targetObj = null;

  if (source.targetRayMode !== "tracked-pointer") {
    return;
  }

  let targetRayPose = event.frame.getPose(source.targetRaySpace, myRefSpace);
  if (!targetRayPose) {
    return;
  }

  switch (event.type) {
    case "selectstart":
      targetObj = myBeginTracking(targetRayPose.matrix);
      break;
    case "select":
      myDropObject(targetObj, targetRayPose.matrix);
      break;
    case "selectend":
      myStopTracking(targetObj, targetRayPose.matrix);
      break;
  }
}
```

You can also set up a handler for `selectend` events by setting the `XRSession` object's `onselectend` event handler property to a function that handles the event:

```js
xrSession.onselectstart = onSelectionEvent;
xrSession.onselect = onSelectionEvent;
xrSession.onselectend = onSelectionEvent;
```

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

| Specification |
| --- |
| WebXR Device API # eventdef-xrsession-selectstart |
| WebXR Device API # dom-xrsession-onselectstart |

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

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

See also
--------

* `select` and `selectend`
* `beforexrselect`


XRSession: requestHitTestSourceForTransientInput() method - Web APIs

XRSession: requestHitTestSourceForTransientInput() method
=========================================================

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

 The **`requestHitTestSourceForTransientInput()`** method of the
 `XRSession` interface returns a `Promise` that resolves with an `XRTransientInputHitTestSource` object that can be passed to `XRFrame.getHitTestResultsForTransientInput()`.

Syntax
------

```js
requestHitTestSourceForTransientInput(options)
```

### Parameters

`options`

An object containing configuration options, specifically:

`profile`

A string specifying the input profile name of the transient input source that will be used to compute hit test results.

`entityTypes` Optional

An `Array` specifying the types of entities to be used for hit test source creation. If no entity type is specified, the array defaults to a single element with the `plane` type. Possible types:

* `point`: Compute hit test results based on characteristic points detected.
* `plane`: Compute hit test results based on real-world planes detected.
* `mesh`: Compute hit test results based on meshes detected.

`offsetRay` Optional

The `XRRay` object that will be used to perform hit test. If no `XRRay` object has been provided, a new `XRRay` object is constructed without any parameters.

### Return value

A `Promise` that resolves with an `XRTransientInputHitTestSource` object.

### Exceptions

 Rather than throwing true exceptions, `requestHitTestSourceForTransientInput()` rejects the
 returned promise with a `DOMException`, specifically, one of the following:

`NotSupportedError` `DOMException`

Thrown if `hit-test` is not an enabled feature in `XRSystem.requestSession()`.

`InvalidStateError` `DOMException`

Thrown if the session has already ended.

`NotAllowedError` `DOMException`

Thrown if there is an unreasonable amount of requests. Some user agents might limit usage for privacy reasons.

Examples
--------

### Requesting a transient hit test source

To request a hit test source, start an `XRSession` with the `hit-test` session feature enabled. Next, configure the hit test source and store it for later use in the frame loop and call `XRFrame.getHitTestResultsForTransientInput()` to obtain the result.

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

let transientHitTestSource = null;

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

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

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

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

| Specification |
| --- |
| WebXR Hit Test Module # dom-xrsession-requesthittestsourcefortransientinput |

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

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

See also
--------

* `XRSession.requestHitTestSource()`


XRSession: requestReferenceSpace() method - Web APIs

XRSession: requestReferenceSpace() method
=========================================

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

 The **`requestReferenceSpace()`** method of the
 `XRSession` interface returns a `promise` that resolves with
 an instance of either `XRReferenceSpace`
 or `XRBoundedReferenceSpace` as appropriate given the type of reference
 space requested.

Syntax
------

```js
requestReferenceSpace(referenceSpaceType)
```

### Parameters

`type`

 A string specifying the type of reference space for which an instance is to be returned.
 The string must be one of the values below.

### Return value

A `Promise` that resolves with an `XRReferenceSpace` object.

The types of reference space are listed below, with brief information about their use cases and which interface is used to implement them.

`bounded-floor`

An `XRBoundedReferenceSpace` similar to the `local` type, except the user is not expected to move outside a predetermined boundary, given by the `boundsGeometry` in the returned object.

`local`

An `XRReferenceSpace` tracking space whose native origin is located near the viewer's position at the time the session was created. The exact position depends on the underlying platform and implementation. The user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. For devices with six degrees of freedom (6DoF) tracking, the `local` reference space tries to keep the origin stable relative to the environment.

`local-floor`

An `XRReferenceSpace` similar to the `local` type, except the starting position is placed in a safe location for the viewer to stand, where the value of the y axis is 0 at floor level. If that floor level isn't known, the user agent will estimate the floor level. If the estimated floor level is non-zero, the browser is expected to round it such a way as to avoid fingerprinting (likely to the nearest centimeter).

`unbounded`

An `XRReferenceSpace` tracking space which allows the user total freedom of movement, possibly over extremely long distances from their origin point. The viewer isn't tracked at all; tracking is optimized for stability around the user's current position, so the native origin may drift as needed to accommodate that need.

`viewer`

An `XRReferenceSpace` tracking space whose native origin tracks the viewer's position and orientation. This is used for environments in which the user can physically move around, and is supported by all instances of `XRSession`, both immersive and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. Otherwise, typically, one of the other reference space types will be used more often.

### Exceptions

 Rather than throwing true exceptions, `requestReferenceSpace()` rejects the
 returned promise with a `DOMException` whose name is found in the list
 below:

`NotSupportedError`

The requested reference space is not supported.

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

| Specification |
| --- |
| WebXR Device API # dom-xrsession-requestreferencespace |

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

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


XRSession: depthUsage property - Web APIs

XRSession: depthUsage property
==============================

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

 The *read-only* **`depthUsage`** property of an `immersive-ar`
`XRSession` describes which depth-sensing usage is used.

Value
-----

This property can return the following values:

`cpu-optimized`

The depth data is intended to be used on the CPU; see the `XRCPUDepthInformation` interface.

`gpu-optimized`

The depth data is intended to be used on the GPU; see the `XRWebGLDepthInformation` interface.

Examples
--------

To request the desired usage method, you need to specify a `usagePreference` when requesting a session using `XRSystem.requestSession()`. Here, the caller is able to handle both CPU- and GPU-optimized usage. The order indicates preference for CPU:

```js
navigator.xr.requestSession("immersive-ar", {
  requiredFeatures: ["depth-sensing"],
  depthSensing: {
    usagePreference: ["cpu-optimized", "gpu-optimized"],
    formatPreference: ["luminance-alpha", "float32"],
  },
});
```

To check which usage was selected by the user agent, you can call the `depthUsage` property:

```js
console.log(session.depthUsage); // either "cpu-optimized" or "gpu-optimized"
```

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

| Specification |
| --- |
| WebXR Depth Sensing Module # dom-xrsession-depthusage |

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

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


XRSession: environmentBlendMode property - Web APIs

XRSession: environmentBlendMode property
========================================

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

 The `XRSession` interface's *read-only* **`environmentBlendMode`**
 property identifies if, and to what degree, the computer-generated imagery is overlaid atop the real world.

 This is used to differentiate between fully-immersive VR sessions and AR sessions which render
 over a pass-through image of the real world, possibly partially transparently.

Value
-----

A string defining if and how virtual, rendered content is overlaid atop the image of the real world.

Possible values are:

`opaque`

The rendered image is drawn without allowing any pass-through imagery. This is primarily used by fully-immersive VR headsets, which totally obscure the surrounding environment, with none of the real world shown to the user at all. The alpha values specified in the `XRSession`'s `renderState` property's `baseLayer` field are ignored since the alpha values for the rendered imagery are all treated as being 1.0 (fully opaque).

`additive`

Primarily used by AR devices with transparent lenses which directly allow reality to pass through to the user's eyes, the `additive` blending mode is designed to be used in a situation in which the device has no control over the background and its brightness, since that isn't being digitally controlled. All the device can do is add more light to the image; it can't make things get darker. Therefore, black is rendered as fully transparent, and there's no way to make a pixel fully opaque. As with the `opaque` setting, alpha values specified are ignored and treated as if they were 1.0.

`alpha-blend`

 Used by headsets or goggles which use cameras to capture the real world and display it digitally on the screen or screens used to render the content for the user to see, this offers a way to create an AR presentation using a VR device. Alpha blending can also be used by non-wearable devices that provide AR modes, such as phones or tablets using cameras to capture the real world for use in AR apps. Since the real world is being digitally presented, the brightness of each pixel can be controlled, whether it's reality or the rendered XR image, the user's environment can be blended with the virtual environment with each pixel having its color and brightness precisely controlled.
 In this mode, the `XRSession`'s `renderState.baseLayer` property provides relative weights of the artificial layer during the compositing process. Pixels whose alpha value is 1.0 are rendered fully opaque, totally obscuring the real world, while pixels with an alpha of 0.0 are totally transparent, leaving the surrounding environment to pass through.

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

| Specification |
| --- |
| WebXR Augmented Reality Module - Level 1 # dom-xrsession-environmentblendmode |

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

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


XRSession: end event - Web APIs

XRSession: end event
====================

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

An `end` event is fired at an `XRSession` object when the WebXR session has ended, either because the web application has chosen to stop the session, or because the user agent terminated the session.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("end", (event) => {});

onend = (event) => {};
```

Event type
----------

An `XRSessionEvent`. Inherits from `Event`.

Event

XRSessionEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`session` Read only

The `XRSession` to which the event refers.

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

### Trigger

Triggered when the WebXR session has ended, either because the web application has chosen to stop the session, or because the user agent terminated the session.

This event is not cancelable and does not bubble.

### Use cases

You can use this event to react to the ending of an WebXR session. You may want to display a UI element informing about the termination of the session, for example.

Examples
--------

To be informed when a WebXR session comes to an end, you can add a handler to your `XRSession` instance using `addEventListener()`, like this:

```js
XRSession.addEventListener("end", (event) => {
  /\* the session has shut down \*/
});
```

Alternatively, you can use the `XRSession.onend` event handler property to establish a handler for the `end` event:

```js
XRSession.onend = (event) => {
  /\* the session has shut down \*/
};
```

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

| Specification |
| --- |
| WebXR Device API # eventdef-xrsession-end |
| WebXR Device API # dom-xrsession-onend |

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

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


XRSession: visibilityState property - Web APIs

XRSession: visibilityState property
===================================

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

 The *read-only* **`visibilityState`** property of the
 `XRSession` interface is a string indicating whether the WebXR content is
 currently visible to the user, and if it is, whether it's the primary focus.

 Every time the visibility state changes, a
 `visibilitychange` event is fired on the
 `XRSession` object.

Value
-----

 A string indicating whether or not the XR content is
 visible to the user and if it is, whether or not it's currently the primary focus.

The possible values of `visibilityState` are:

`hidden`

 The virtual scene generated by the `XRSession` is not currently visible to the user,
 so its `requestAnimationFrame()`
 callbacks are *not* being executed until the `visibilityState` changes.
 Input controllers are *not* being handled for the session.

`visible`

 The virtual scene rendered by the `XRSession` is currently visible to the user
 and is the primary focus of the user's attention. To that end, the session's
 `requestAnimationFrame()` callbacks are being processed
 at the XR device's native refresh rate and input controllers are being processed as normal.

`visible-blurred`

 While the virtual scene rendered by the `XRSession` may currently be visible to the user,
 it is not the user's primary focus at the moment; it's also possible the session is not currently visible at all.
 In order to optimize resource utilization, the user agent may be handling the session's
 `requestAnimationFrame()` callbacks at a throttled rate.
 Input controllers are *not* being processed for the session.

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

 It's important to keep in mind that because an immersive WebXR session is potentially
 being shown using a different display than the HTML document in which it's running (such
 as when being shown on a headset), the value of a
 session's `visibilityState` may not necessarily be the same as the owning
 *`document`'s* `visibilityState`. For instance, if the viewer is using a headset tethered to a
 computer and the immersive scene is obscured by a configuration UI, the user could peek
 out from behind the headset and still be able to see the document itself on their
 computer's monitor.

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

| Specification |
| --- |
| WebXR Device API # dom-xrsession-visibilitystate |

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

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

See also
--------

* `visibilitychange` event


XRSession: squeeze event - Web APIs

XRSession: squeeze event
========================

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

The WebXR **`squeeze`** event is sent to an `XRSession` when one of the session's input sources has completed a primary squeeze action. Examples of common kinds of primary action are users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.

For details on how the `squeezestart`, `squeeze`, and `squeezeend` events work, and how you should react to them, see Inputs and input sources.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("squeeze", (event) => {});

onsqueeze = (event) => {};
```

Event type
----------

An `XRInputSourceEvent`. Inherits from `Event`.

Event

XRInputSourceEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`frame` Read only

An `XRFrame` object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an *event* frame, not an *animation* frame, you cannot call `XRFrame.getViewerPose()` on it; instead, use `getPose()`.

`inputSource` Read only

An `XRInputSource` object indicating which input source generated the input event.

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

### Trigger

Triggered when users are squeezing the controller, making a hand gesture that mimes grabbing something, or using (squeezing) a trigger.

### Use cases

The `squeezestart` event indicates that the user has begun a squeeze action.

If the primary squeeze action ends successfully, the session is sent a `squeeze` event.

A `squeezeend` event is sent to indicate that the squeeze action is no longer underway. This is sent whether the squeeze action succeeded or not.

Examples
--------

The following example uses `addEventListener()` to set up a handler for the `squeeze` event. The handler fetches the pose representing the target ray for `tracked-pointer` inputs and sends the pose's transform to a function called `myHandleSqueezeWithRay()`.

This code treats the squeeze as an instantaneous action that doesn't involve tracking an ongoing activity. If you need to track a squeeze action that isn't instantaneous, listen for the `squeezestart` and `squeezeend` events to sense when the squeeze action begins and ends.

```js
xrSession.addEventListener("squeeze", (event) => {
  if (event.inputSource.targetRayMode === "tracked-pointer") {
    let targetRayPose = event.frame.getPose(
      event.inputSource.targetRaySpace,
      myRefSpace,
    );
    if (targetRayPose) {
      myHandleSqueezeWithRay(targetRayPose.transform);
    }
  }
});
```

You can also set up a handler for `squeeze` events by setting the `XRSession` object's `onsqueeze` event handler property to a function that handles the event:

```js
xrSession.onsqueeze = (event) => {
  if (event.inputSource.targetRayMode === "tracked-pointer") {
    let targetRayPose = event.frame.getPose(
      event.inputSource.targetRaySpace,
      myRefSpace,
    );
    if (targetRayPose) {
      myHandleSqueezeWithRay(targetRayPose.transform);
    }
  }
};
```

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

| Specification |
| --- |
| WebXR Device API # eventdef-xrsession-squeeze |
| WebXR Device API # dom-xrsession-onsqueeze |

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

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

See also
--------

* `squeezestart` and `squeezeend` event


DeprecationReportBody: id property - Web APIs

DeprecationReportBody: id property
==================================

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

The **`id`** read-only property of the `DeprecationReportBody` interface returns a string representing the feature or API that is deprecated. This can be used to group or count related reports.

Value
-----

A string.

Examples
--------

In this example we create a new `ReportingObserver` to observe deprecation reports, then print the value of `id` to the console.

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

let observer = new ReportingObserver((reports, observer) => {
  let firstReport = reports[0];
  console.log(firstReport.type); // deprecation
  console.log(firstReport.body.id);
}, options);
```

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

| Specification |
| --- |
| Deprecation Reporting # dom-deprecationreportbody-id |

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

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


DeprecationReportBody: anticipatedRemoval property - Web APIs

DeprecationReportBody: anticipatedRemoval property
==================================================

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

The **`anticipatedRemoval`** read-only property of the `DeprecationReportBody` interface returns the date that the browser version which removes the feature will ship. This value can be used to prioritize warnings. If this property returns `null` because the date is unknown, then the deprecation should be considered low priority.

Value
-----

A `date` object, or `null` if the date is not known.

Examples
--------

In this example we create a new `ReportingObserver` to observe deprecation reports, then print the value of `anticipatedRemoval` to the console.

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

let observer = new ReportingObserver((reports, observer) => {
  let firstReport = reports[0];
  console.log(firstReport.type); // deprecation
  console.log(firstReport.body.anticipatedRemoval);
}, options);
```

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

| Specification |
| --- |
| Deprecation Reporting # dom-deprecationreportbody-anticipatedremoval |

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

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


DeprecationReportBody: sourceFile property - Web APIs

DeprecationReportBody: sourceFile property
==========================================

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

The **`sourceFile`** read-only property of the `DeprecationReportBody` interface returns the path to the source file where the deprecated feature was used.

**Note:** This property can be used with `DeprecationReportBody.lineNumber` and `DeprecationReportBody.columnNumber` to locate the column and line in the file where the error occurred.

Value
-----

A string, or `null` if the path is not known.

Examples
--------

In this example we create a new `ReportingObserver` to observe deprecation reports, then print the value of `sourceFile` to the console.

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

let observer = new ReportingObserver((reports, observer) => {
  let firstReport = reports[0];
  console.log(firstReport.type); // deprecation
  console.log(firstReport.body.sourceFile);
}, options);
```

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

| Specification |
| --- |
| Deprecation Reporting # dom-deprecationreportbody-sourcefile |

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

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


DeprecationReportBody: toJSON() method - Web APIs

DeprecationReportBody: toJSON() method
======================================

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

The **`toJSON()`** method of the `DeprecationReportBody` interface is a *serializer*, and returns a JSON representation of the `InterventionReportBody` object.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A JSON object that is the serialization of the `DeprecationReportBody` object.

Examples
--------

In this example we create a new `ReportingObserver` to observe deprecation reports, then return a JSON representation of the first entry.

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

let observer = new ReportingObserver((reports, observer) => {
  let firstReport = reports[0];
  console.log(firstReport.toJSON());
}, options);
```

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

| Specification |
| --- |
| Deprecation Reporting # dom-deprecationreportbody-tojson |

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

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


DeprecationReportBody: message property - Web APIs

DeprecationReportBody: message property
=======================================

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

The **`message`** read-only property of the `DeprecationReportBody` interface returns a human-readable description of the deprecation. This typically matches the message a browser will display in its DevTools console regarding a deprecated feature.

Value
-----

A string.

Examples
--------

In this example we create a new `ReportingObserver` to observe deprecation reports, then print the value of `message` to the console.

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

let observer = new ReportingObserver((reports, observer) => {
  let firstReport = reports[0];
  console.log(firstReport.type); // deprecation
  console.log(firstReport.body.message);
}, options);
```

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

| Specification |
| --- |
| Deprecation Reporting # dom-deprecationreportbody-message |

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

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


DeprecationReportBody: columnNumber property - Web APIs

DeprecationReportBody: columnNumber property
============================================

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

The **`columnNumber`** read-only property of the `DeprecationReportBody` interface returns the line in the source file in which the deprecated feature was used.

**Note:** This property is most useful alongside `DeprecationReportBody.sourceFile` and `DeprecationReportBody.lineNumber` as it enables the location of the column in that file and line where the error occurred.

Value
-----

An integer, or `null` if the column is not known.

Examples
--------

In this example we create a new `ReportingObserver` to observe deprecation reports, then print the value of `columnNumber` to the console.

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

let observer = new ReportingObserver((reports, observer) => {
  let firstReport = reports[0];
  console.log(firstReport.type); // deprecation
  console.log(firstReport.body.sourceFile); // the source file
  console.log(firstReport.body.lineNumber); // the line in that file
  console.log(firstReport.body.columnNumber); // the column in that file.
}, options);
```

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

| Specification |
| --- |
| Deprecation Reporting # dom-deprecationreportbody-columnnumber |

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

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


DeprecationReportBody: lineNumber property - Web APIs

DeprecationReportBody: lineNumber property
==========================================

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

The **`lineNumber`** read-only property of the `DeprecationReportBody` interface returns the line in the source file in which the deprecated feature was used.

**Note:** This property is most useful alongside `DeprecationReportBody.sourceFile` as it enables the location of the line in that file where the error occurred.

Value
-----

An integer, or `null` if the line is not known.

Examples
--------

In this example we create a new `ReportingObserver` to observe deprecation reports, then print the value of `lineNumber` to the console.

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

let observer = new ReportingObserver((reports, observer) => {
  let firstReport = reports[0];
  console.log(firstReport.type); // deprecation
  console.log(firstReport.body.sourceFile); // the source file
  console.log(firstReport.body.lineNumber); // the line in that file
}, options);
```

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

| Specification |
| --- |
| Deprecation Reporting # dom-deprecationreportbody-linenumber |

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

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


ProgressEvent: ProgressEvent() constructor - Web APIs

ProgressEvent: ProgressEvent() constructor
==========================================

The **`ProgressEvent()`** constructor returns a new `ProgressEvent` object, representing the current completion of a long process.

Syntax
------

```js
new ProgressEvent(type)
new ProgressEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers set it to `loadstart`, `progress`, `abort`, `error`, `load`, `timeout`, or `loadend`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`lengthComputable` Optional

 A boolean value indicating if the total work to be done, and the
 amount of work already done, by the underlying process is calculable. In other words,
 it tells if the progress is measurable or not. It defaults to `false`.

`loaded` Optional

 A number representing the amount of work already
 performed by the underlying process. The ratio of work done can be calculated with the
 property and `ProgressEvent.total`. When downloading a resource using HTTP,
 this only represent the part of the content itself, not headers and other overhead. It
 defaults to `0`.

`total` Optional

 A number representing the total amount of work that the
 underlying process is in the progress of performing. When downloading a resource using
 HTTP, this only represent the content itself, not headers and other overhead. It
 defaults to `0`.

### Return value

A new `ProgressEvent` object.

Example
-------

The example demonstrates how a `ProgressEvent` is built using a constructor. This is particularly useful for tracking the progress of processes like file uploads, downloads, or any long-running tasks.

```js
function updateProgress(loaded, total) {
  const progressEvent = new ProgressEvent("progress", {
    lengthComputable: true,
    loaded: loaded,
    total: total,
  });

  document.dispatchEvent(progressEvent);
}

document.addEventListener("progress", (event) => {
  console.log(`Progress: ${event.loaded}/${event.total}`);
});

updateProgress(50, 100);
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # dom-progressevent-progressevent |

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

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

See also
--------

* The `ProgressEvent` interface it belongs to.


ProgressEvent: loaded property - Web APIs

ProgressEvent: loaded property
==============================

 The **`ProgressEvent.loaded`** read-only property is an integer
 representing the amount of work already performed by the underlying process. The ratio
 of work done can be calculated with the property and `ProgressEvent.total`.
 When downloading a resource using HTTP, this value is specified in bytes (not bits), and only represents the part of the content
 itself, not headers and other overhead.

Value
-----

A number.

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

| Specification |
| --- |
| XMLHttpRequest Standard # dom-progressevent-loaded |

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

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

See also
--------

* The `ProgressEvent` interface it belongs to.


ProgressEvent: lengthComputable property - Web APIs

ProgressEvent: lengthComputable property
========================================

 The
 **`ProgressEvent.lengthComputable`** read-only property is a
 boolean flag indicating if the resource concerned by the
 `ProgressEvent` has a length that can be calculated. If not, the
 `ProgressEvent.total` property has no significant value.

Value
-----

A boolean.

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

| Specification |
| --- |
| XMLHttpRequest Standard # dom-progressevent-lengthcomputable |

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

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

See also
--------

* The `ProgressEvent` interface it belongs to.


ProgressEvent: total property - Web APIs

ProgressEvent: total property
=============================

 The **`ProgressEvent.total`** read-only property is an unsigned
 64-bit integer value indicating the total size of the data being processed or
 transmitted. In the case of an HTTP transmission, this is the size of the body of the
 message (the `Content-Length`), and does not include headers and other
 overhead.

 If the event's `lengthComputable`
 property is `false`, this value is meaningless and should be ignored.

Value
-----

An integer.

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

| Specification |
| --- |
| XMLHttpRequest Standard # dom-progressevent-total |

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

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

See also
--------

* The `ProgressEvent` interface it belongs to.


SpeechRecognitionResult: length property - Web APIs

SpeechRecognitionResult: length property
========================================

 The **`length`** read-only property of the
 `SpeechRecognitionResult` interface returns the length of the "array"
 — the number of `SpeechRecognitionAlternative` objects contained
 in the result (also referred to as "n-best alternatives".)

 The number of alternatives contained in the result depends on what the
 `SpeechRecognition.maxAlternatives` property was set to when the speech
 recognition was first initiated.

Value
-----

A number.

Examples
--------

This code is excerpted from our Speech color changer example.

```js
recognition.onresult = (event) => {
  // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
  // The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
  // It has a getter so it can be accessed like an array
  // The first [0] returns the SpeechRecognitionResult at position 0.
  // Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
  // that contain individual results.
  // These also have getters so they can be accessed like arrays.
  // The second [0] returns the SpeechRecognitionAlternative at position 0.
  // We then return the transcript property of the SpeechRecognitionAlternative object
  const color = event.results[0][0].transcript;
  diagnostic.textContent = `Result received: ${color}.`;
  bg.style.backgroundColor = color;

  console.log(event.results[0].length);
};
```

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

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

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

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

See also
--------

* Web Speech API


SpeechRecognitionResult: isFinal property - Web APIs

SpeechRecognitionResult: isFinal property
=========================================

 The **`isFinal`** read-only property of the
 `SpeechRecognitionResult` interface is a boolean value that states
 whether this result is final (`true`) or not (`false`) — if so,
 then this is the final time this result will be returned; if not, then this result is an
 interim result, and may be updated later on.

Value
-----

A boolean value.

Examples
--------

```js
recognition.onresult = (event) => {
  // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
  // The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
  // It has a getter so it can be accessed like an array
  // The first [0] returns the SpeechRecognitionResult at position 0.
  // Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
  // that contain individual results.
  // These also have getters so they can be accessed like arrays.
  // The second [0] returns the SpeechRecognitionAlternative at position 0.
  // We then return the transcript property of the SpeechRecognitionAlternative object
  const color = event.results[0][0].transcript;
  diagnostic.textContent = `Result received: ${color}.`;
  bg.style.backgroundColor = color;

  console.log(event.results[0].isFinal);
};
```

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognitionresult-isfinal |

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

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

See also
--------

* Web Speech API


SpeechRecognitionResult: item() method - Web APIs

SpeechRecognitionResult: item() method
======================================

 The **`item`** getter of the
 `SpeechRecognitionResult` interface is a standard getter that allows
 `SpeechRecognitionAlternative` objects within the result to be accessed via
 array syntax.

Syntax
------

```js
item(index)
```

### Parameters

`index`

Index of the item to retrieve.

### Return value

A `SpeechRecognitionAlternative` object.

Examples
--------

This code is excerpted from our Speech color changer example.

```js
recognition.onresult = (event) => {
  // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
  // The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
  // It has a getter so it can be accessed like an array
  // The first [0] returns the SpeechRecognitionResult at position 0.
  // Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
  // that contain individual results.
  // These also have getters so they can be accessed like arrays.
  // The second [0] returns the SpeechRecognitionAlternative at position 0.
  // We then return the transcript property of the SpeechRecognitionAlternative object
  const color = event.results[0][0].transcript;
  diagnostic.textContent = `Result received: ${color}.`;
  bg.style.backgroundColor = color;
};
```

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

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

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

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

See also
--------

* Web Speech API


CSSRule: type property - Web APIs

CSSRule: type property
======================

**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 read-only **`type`** property of the
 `CSSRule` interface is a deprecated property that returns an integer
 indicating which type of rule the `CSSRule` represents.

If you need to distinguish different types of CSS rule, a good alternative is to use `constructor.name`:

```js
const sheets = Array.from(document.styleSheets);
const rules = sheets.map((sheet) => Array.from(sheet.cssRules)).flat();

for (const rule of rules) {
  console.log(rule.constructor.name);
}
```

Value
-----

`CSSRule.STYLE_RULE` (`1`)

The rule is a `CSSStyleRule`, the most common kind of rule: `selector { prop1: val1; prop2: val2; }`.

`CSSRule.IMPORT_RULE` (`3`)

The rule is a `CSSImportRule` and represents an `@import` rule.

`CSSRule.MEDIA_RULE` (`4`)

The rule is a `CSSMediaRule`.

`CSSRule.FONT_FACE_RULE` (`5`)

The rule is a `CSSFontFaceRule`

`CSSRule.PAGE_RULE` (`6`)

The rule is a `CSSPageRule`.

`CSSRule.KEYFRAMES_RULE` (`7`)

The rule is a `CSSKeyframesRule`.

`CSSRule.KEYFRAME_RULE` (`8`)

The rule is a `CSSKeyframeRule`.

`CSSRule.NAMESPACE_RULE` (`10`)

The rule is a `CSSNamespaceRule`.

`CSSRule.COUNTER_STYLE_RULE` (`11`)

The rule is a `CSSCounterStyleRule`.

`CSSRule.SUPPORTS_RULE` (`12`)

The rule is a `CSSSupportsRule`.

`CSSRule.FONT_FEATURE_VALUES_RULE` (`14`)

The rule is a `CSSFontFeatureValuesRule`.

The values `CSSRule.UNKNOWN_RULE` (`0`), `CSSRule.CHARSET_RULE` (`2`), `CSSRule.DOCUMENT_RULE` (`13`), `CSSRule.VIEWPORT_RULE` (`14`), and `CSSRule.REGION_STYLE_RULE` (`16`) cannot be obtained anymore.

Examples
--------

```js
const rules = document.styleSheets[0].cssRules;
console.log(rules[0].type);
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # concept-css-rule-type |

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

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


CSSRule: parentStyleSheet property - Web APIs

CSSRule: parentStyleSheet property
==================================

 The **`parentStyleSheet`** property of the
 `CSSRule` interface returns the `StyleSheet` object in which
 the current rule is defined.

Value
-----

A `StyleSheet` object.

Examples
--------

```js
const docRules = document.styleSheets[0].cssRules;
console.log(docRules[0].parentStyleSheet == document.styleSheets[0]); // returns true
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssrule-parentstylesheet |

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

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


CSSRule: cssText property - Web APIs

CSSRule: cssText property
=========================

 The **`cssText`** property of the `CSSRule`
 interface returns the actual text of a `CSSStyleSheet` style-rule.

**Note:** Do not confuse this property with element-style
 `CSSStyleDeclaration.cssText`.

 Be aware that this property can no longer be set directly, as it is now specified
 to be *functionally* modify-only, and silently so. In other words, attempting to
 set it *does absolutely nothing*, and doesn't even omit a warning or error.
 Furthermore, it has no settable sub-properties. Therefore, to modify it, use the
 stylesheet's `cssRules``[index]` properties
 `.selectorText` and
 `.style` (or its sub-properties). See Using dynamic styling information for details.

Value
-----

A string containing the actual text of the `CSSStyleSheet` rule.

Examples
--------

```css
body {
  background-color: darkblue;
}
```

```js
let stylesheet = document.styleSheets[0];
console.log(stylesheet.cssRules[0].cssText); // body { background-color: darkblue; }
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssrule-csstext |

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

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


CSSRule: parentRule property - Web APIs

CSSRule: parentRule property
============================

 The **`parentRule`** property of the `CSSRule`
 interface returns the containing rule of the current rule if this exists, or otherwise
 returns null.

Value
-----

A `CSSRule` which is the type of the containing rules. If the current rule is inside a media query, this would return `CSSMediaRule`. Otherwise it returns null.

Examples
--------

```css
@media (min-width: 500px) {
  .box {
    width: 100px;
    height: 200px;
    background-color: red;
  }

  body {
    color: blue;
  }
}
```

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

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssrule-parentrule |

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

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


HTMLFontElement: face property - Web APIs

HTMLFontElement: face property
==============================

**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 obsolete
 **`HTMLFontElement.face`**
 property is a string that reflects the `face` HTML attribute, containing a comma-separated list of one or more font
 names.

 The document text, in the default style, is rendered as the first font face that the
 client's browser supports. If no font listed is installed on the local system, the
 browser typically defaults to the proportional or fixed-width font for that system.

The format of the string must follow one of the following HTML microsyntax:

| Microsyntax | Description | Examples |
| --- | --- | --- |
| List of one or more valid font family names | *A list of font names, that have to be present on the local system* | `courier,verdana` |

Value
-----

A string.

Examples
--------

```js
// Assumes there is <font id="f"> element in the HTML

const f = document.getElementById("f");
f.face = "arial";
```

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

 The `<font>` element has been deprecated and is no longer supported and, as a result, neither is
 `<font>.face`.

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

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

See also
--------

* The `HTMLFontElement` interface it belongs to.


HTMLFontElement: color property - Web APIs

HTMLFontElement: color property
===============================

**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 obsolete
 **`HTMLFontElement.color`**
 property is a string that reflects the `color` HTML attribute, containing either a named color or a color specified in the
 hexadecimal #RRGGBB format.

The format of the string must follow one of the following HTML microsyntaxes:

| Microsyntax | Description | Examples |
| --- | --- | --- |
| Valid name color string | *nameOfColor (case insensitive)* | `Green`, `green`, `GREEN` |
| Valid hex color string | *in* `RGB format`*: #RRGGBB* | `#008000` |
| RGB using decimal values | *rgb(x,x,x) (x in 0-255 range)* | `rgb(0 128 0)` |

Value
-----

A string.

Examples
--------

```js
// Assumes there is <font id="f"> element in the HTML

const f = document.getElementById("f");
f.color = "green";
```

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

The `<font>` element has been deprecated and is no longer supported and, as a result, neither is `<font>.color`.

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

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

See also
--------

* The `HTMLFontElement` interface it belongs to.


HTMLFontElement: size property - Web APIs

HTMLFontElement: size property
==============================

**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 obsolete
 **`HTMLFontElement.size`** property is a
 string that reflects the `size` HTML
 attribute. It contains either a font size ranging from 1 to 7 or a
 number relative to the default value 3, for example -2 or +1.

The format of the string must follow one of the following HTML microsyntaxes:

| Microsyntax | Description | Examples |
| --- | --- | --- |
| Valid size number string | *integer number in the range of 1-7* | `6` |
| Relative size string | *+x or -x, where x is a number relative to 3 (the result should be in the range of 1-7)* | `+2-1` |

Value
-----

A string.

Examples
--------

```js
// Assumes there is <font id="f"> element in the HTML

const f = document.getElementById("f");
f.size = "6";
```

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

 The `<font>` element has been deprecated and is no longer supported and, as a result, neither is
 `<font>.size`.

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

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

See also
--------

* The `HTMLFontElement` interface it belongs to.


GPUPipelineError: GPUPipelineError() constructor - Web APIs

GPUPipelineError: GPUPipelineError() constructor
================================================

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

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

Syntax
------

```js
new GPUPipelineError(message, options)
```

### Parameters

`message` Optional

A string providing a human-readable message that explains why the error occurred. If not specified, `message` defaults to an empty string (`""`).

`options`

An object, which can contain the following properties:

`reason`

An enumerated value that defines the reason the pipeline creation failed in a machine-readable way. The value can be one of:

* `"internal"`: Pipeline creation failed because of an internal error (see `GPUInternalError` for more information about these kinds of error).
* `"validation"`: Pipeline creation failed because of a validation error (see `GPUValidationError` for more information about these kinds of error).

Examples
--------

A developer would not manually use the constructor to create a `GPUPipelineError` object. The user agent uses this constructor to create an appropriate object when a `Promise` returned by a `GPUDevice.createComputePipelineAsync()` or `GPUDevice.createRenderPipelineAsync()` call rejects, signalling a pipeline failure.

See the main `GPUPipelineError` page for an example involving a `GPUPipelineError` object instance.

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

| Specification |
| --- |
| WebGPU # dom-gpupipelineerror-constructor |

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


GPUPipelineError: reason property - Web APIs

GPUPipelineError: reason property
=================================

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

 The **`reason`** read-only property of the
 `GPUPipelineError` interface defines the reason the pipeline creation failed in a machine-readable way.

Value
-----

An enumerated value that can be one of:

`"internal"`

Pipeline creation failed because of an internal error (see `GPUInternalError` for more information about these kinds of error.)

`"validation"`

Pipeline creation failed because of a validation error (see `GPUValidationError` for more information about these kinds of error.)

Examples
--------

See the main `GPUPipelineError` page for an example involving a `GPUPipelineError` object instance.

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

| Specification |
| --- |
| WebGPU # dom-gpupipelineerror-reason |

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

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

See also
--------

* The WebGPU API


Storage: removeItem() method - Web APIs

Storage: removeItem() method
============================

 The **`removeItem()`** method of the `Storage`
 interface, when passed a key name, will remove that key from the given
 `Storage` object if it exists.
 The **`Storage`** interface of the Web Storage API provides access to a
 particular domain's session or local storage.

If there is no item associated with the given key, this method will do nothing.

Syntax
------

```js
removeItem(keyName)
```

### Parameters

`keyName`

A string containing the name of the key you want to remove.

### Return value

None (`undefined`).

Examples
--------

 The following function creates three data items inside local storage, then removes the
 `image` data item.

```js
function populateStorage() {
  localStorage.setItem("bgcolor", "red");
  localStorage.setItem("font", "Helvetica");
  localStorage.setItem("image", "myCat.png");

  localStorage.removeItem("image");
}
```

We can do the same for the session storage.

```js
function populateStorage() {
  sessionStorage.setItem("bgcolor", "red");
  sessionStorage.setItem("font", "Helvetica");
  sessionStorage.setItem("image", "myCat.png");

  sessionStorage.removeItem("image");
}
```

**Note:** To see this used within a real-world example, see our Web Storage Demo.

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

| Specification |
| --- |
| HTML Standard # dom-storage-removeitem-dev |

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

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

See also
--------

Using the Web Storage API


Storage: setItem() method - Web APIs

Storage: setItem() method
=========================

 The **`setItem()`** method of the `Storage`
 interface, when passed a key name and value, will add that key to the given
 `Storage` object, or update that key's value if it already exists.

Syntax
------

```js
setItem(keyName, keyValue)
```

### Parameters

`keyName`

A string containing the name of the key you want to create/update.

`keyValue`

 A string containing the value you want to give the key you are
 creating/updating.

### Return value

None (`undefined`).

### Exceptions

`QuotaExceededError` `DOMException`

Thrown if the storage run out of disk quota or the user declined to grant you more space.

Examples
--------

The following function creates three data items inside local storage.

```js
function populateStorage() {
  localStorage.setItem("bgcolor", "red");
  localStorage.setItem("font", "Helvetica");
  localStorage.setItem("image", "myCat.png");
}
```

**Note:** To see this used within a real-world example, see our Web Storage Demo.

`Storage` only supports storing and retrieving strings. If you want to save other data types, you have to convert them to strings. For plain objects and arrays, you can use `JSON.stringify()`.

```js
const person = { name: "Alex" };
localStorage.setItem("user", person);
console.log(localStorage.getItem("user")); // "[object Object]"; not useful!
localStorage.setItem("user", JSON.stringify(person));
console.log(JSON.parse(localStorage.getItem("user"))); // { name: "Alex" }
```

However, there's no generic way to store arbitrary data types. Furthermore, the retrieved object is a deep copy of the original object and mutations to it do not affect the original object.

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

| Specification |
| --- |
| HTML Standard # dom-storage-setitem-dev |

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

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

See also
--------

* Storage.getItem()
* Storage.removeItem()
* Using the Web Storage API