Orientation and motion data explained - Web APIs

Orientation and motion data explained
=====================================

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

When using orientation and motion events, it's important to understand what the values you're given by the browser mean. This article provides details about the coordinate systems at play and how you use them.

About coordinate frames
-----------------------

A **coordinate frame** is a system whereby the orientation of the three axes (X, Y, and Z) are defined in reference to an object. There are two coordinate frames to consider when using orientation and motion events:

### Earth coordinate frame

The Earth coordinate frame is the coordinate frame fixed on the center of the Earth; that is, the axes are aligned based on the pull of gravity and the standard magnetic north orientation. We use upper-case letters ("X", "Y", and "Z") to describe the axes of the Earth coordinate frame.

* The **X** axis follows along the ground plane, perpendicular to the Y axis and positive toward the east (and therefore negative toward the west).
* The **Y** axis follows along the ground plane, and is positive toward true north (that is, the North Pole, not magnetic north) and negative toward true south.
* The **Z** axis is perpendicular to the ground plane; think of it as a line drawn between the device and the center of the Earth. The value of the Z coordinate is positive upward (away from the center of the Earth) and negative downward (toward the center of the Earth).
### Device coordinate frame

The device coordinate frame is the coordination frame fixed on the center of the device. We use lower-case letters ("x", "y", and "z") to describe the axes of the device coordinate frame.

![Drawing representing three axes of a mobile device](/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained/axes.png)

* The **x** axis is in the plane of the screen and is positive toward the right and negative toward the left.
* The **y** axis is in the plane of the screen and is positive toward the top and negative toward the bottom.
* The **z** axis is perpendicular to the screen or keyboard, and is positive extending outward from the screen.

**Note:** On a phone or tablet, the orientation of the device is always considered in relation to the standard orientation of the screen; this is the "portrait" orientation on most devices. On a laptop computer, the orientation is considered in relation to the keyboard. If you want to detect changes in device orientation in order to compensate, you can use the `change` event.

About rotation
--------------

Rotation is described about any given axis in terms of the number of degrees of difference between the device's coordinate frame and the Earth coordinate frame, and is measured in degrees.

### Alpha

Rotation around the z axis — that is, twisting the device — causes the **alpha** rotation angle to change:

![Positive alpha rotates the device counter-clockwise.](/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained/alpha.png)

The alpha angle is 0° when top of the device is pointed directly toward the Earth's north pole, and increases as the device is rotated toward the left.

### Beta

Rotation around the x axis — that is, tipping the device away from or toward the user — causes the **beta** rotation angle to change:

![Positive beta pitches the device forward toward the user.](/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained/beta2.png)

The beta angle is 0° when the device's top and bottom are the same distance from the Earth's surface; it increases toward 180° as the device is tipped forward toward the user, and it decreases toward -180° as the device is tipped backward away from the user.

### Gamma

Rotation around the y axis — that is, tilting the device toward the left or right — causes the **gamma** rotation angle to change:

![Positive gamma tilts the devices toward the right.](/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained/gamma.png)

The gamma angle is 0° when the device's left and right sides are the same distance from the surface of the Earth, and increases toward 90° as the device is tipped toward the right, and toward -90° as the device is tipped toward the left.


HTMLTrackElement: cuechange event - Web APIs

HTMLTrackElement: cuechange event
=================================

The **`cuechange`** event fires when a `TextTrack` has changed the currently displaying cues. The event is fired on both the `TextTrack` and the `HTMLTrackElement` in which it's being presented, if any.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

The underlying `TextTrack`, indicated by the `track` property, receives a `cuechange` event every time the currently-presented cue is changed. This happens even if the track isn't associated with a media element.

If the track *is* associated with a media element, using the `<track>` element as a child of the `<audio>` or `<video>` element, the `cuechange` event is also sent to the `HTMLTrackElement`.

```js
let textTrackElem = document.getElementById("texttrack");

textTrackElem.addEventListener("cuechange", (event) => {
  let cues = event.target.track.activeCues;
});
```

Alternatively, you can use the `oncuechange` event handler:

```js
let textTrackElem = document.getElementById("texttrack");

textTrackElem.oncuechange = (event) => {
  let cues = event.target.track.activeCues;
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-cuechange |
| HTML Standard # handler-oncuechange |

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

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

See also
--------

* WebVTT
* The same event on `TextTrack`: `cuechange`


HTMLTrackElement: src property - Web APIs

HTMLTrackElement: src property
==============================

 The **`HTMLTrackElement.src`** property reflects the value of
 the `<track>` element's `src` attribute, which
 indicates the URL of the text track's data.

Value
-----

A string object containing the URL of the text track data.

Example
-------

```js
// coming soon
```

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

| Specification |
| --- |
| HTML Standard # dom-track-src |

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

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

See also
--------

* `HTMLTrackElement`: Interface used to define the `HTMLTrackElement.src` property
* `<track>`


CSSValue: cssValueType property - Web APIs

CSSValue: cssValueType 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 **`cssValueType`** read-only property of the
 `CSSValue` interface represents the type of the current computed CSS
 property value.

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

To achieve your purpose, you can use:

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

Value
-----

 An `unsigned short` representing a code defining the type of the value.
 Possible values are:

| Constant | Description |
| --- | --- |
| `CSS_CUSTOM` | The value is a custom value. |
| `CSS_INHERIT` |
 The value is inherited and the `cssText` contains
 `"inherit"`.
  |
| `CSS_PRIMITIVE_VALUE` |
 The value is a primitive value and an instance of the
 `CSSPrimitiveValue` interface can be obtained
 by using binding-specific casting methods on this instance of the
 `CSSValue` interface.
  |
| `CSS_VALUE_LIST` |
 The value is a `CSSValue` list and an instance of the
 `CSSValueList` interface can be obtained by using
 binding-specific casting methods on this instance of the
 `CSSValue` interface.
  |

Examples
--------

```js
const styleDeclaration = document.styleSheets[0].cssRules[0].style;
const cssValue = styleDeclaration.getPropertyCSSValue("color");
console.log(cssValue.cssValueType);
```

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

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

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

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

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


CSSValue: cssText property - Web APIs

CSSValue: cssText 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 **`cssText`** property of the `CSSValue`
 interface represents the current computed CSS property value.

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

To achieve your purpose, you can use:

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

Value
-----

A string representing the current CSS property value.

Examples
--------

```js
const styleDeclaration = document.styleSheets[0].cssRules[0].style;
const cssValue = styleDeclaration.getPropertyCSSValue("color");
console.log(cssValue.cssText);
```

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

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

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

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

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

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

See also
--------

* `CSSStyleDeclaration.getPropertyCSSValue()`


AudioTrackList: change event - Web APIs

AudioTrackList: change event
============================

The `change` event is fired when an audio track is enabled or disabled, for example by changing the track's `enabled` property.

This event is not cancelable and does not bubble.

Syntax
------

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

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

onchange = (event) => { }
```

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

A generic `Event`.

Examples
--------

Using `addEventListener()`:

```js
const videoElement = document.querySelector("video");
videoElement.audioTracks.addEventListener("change", (event) => {
  console.log(`'${event.type}' event fired`);
});

// changing the value of `enabled` will trigger the `change` event
const toggleTrackButton = document.querySelector(".toggle-track");
toggleTrackButton.addEventListener("click", () => {
  const track = videoElement.audioTracks[0];
  track.enabled = !track.enabled;
});
```

Using the `onchange` event handler property:

```js
const videoElement = document.querySelector("video");
videoElement.audioTracks.onchange = (event) => {
  console.log(`'${event.type}' event fired`);
};

// changing the value of `enabled` will trigger the `change` event
const toggleTrackButton = document.querySelector(".toggle-track");
toggleTrackButton.addEventListener("click", () => {
  const track = videoElement.audioTracks[0];
  track.enabled = !track.enabled;
});
```

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

| Specification |
| --- |
| HTML Standard # event-media-change |
| HTML Standard # handler-tracklist-onchange |

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

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

See also
--------

* Related events: `addtrack`, `removetrack`
* This event on `VideoTrackList` targets: `change`
* Media Capture and Streams API
* WebRTC API


AudioTrackList: length property - Web APIs

AudioTrackList: length property
===============================

 The read-only **`AudioTrackList`**
 property **`length`** returns the number of entries in the
 `AudioTrackList`, each of which is an `AudioTrack`
 representing one audio track in the media element. A value of 0 indicates that
 there are no audio tracks in the media.

Value
-----

 A number indicating how many audio tracks are included in the
 `AudioTrackList`. Each track can be accessed by treating the
 `AudioTrackList` as an array of objects of type `AudioTrack`.

Examples
--------

 This snippet gets the number of audio tracks in the first `<video>`
 element found in the DOM by `querySelector()`.

```js
const videoElem = document.querySelector("video");
let numAudioTracks = 0;

if (videoElem.audioTracks) {
  numAudioTracks = videoElem.audioTracks.length;
}
```

 Note that this sample checks to be sure `HTMLMediaElement.audioTracks` is
 defined, to avoid failing on browsers without support for `AudioTrack`.

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

| Specification |
| --- |
| HTML Standard # dom-audiotracklist-length-dev |

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

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


AudioTrackList: removetrack event - Web APIs

AudioTrackList: removetrack event
=================================

The `removetrack` event is fired when a track is removed from an `AudioTrackList`.

Syntax
------

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

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

onremovetrack = (event) => { }
```

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

A `TrackEvent`. Inherits from `Event`.

Event

TrackEventEvent properties
----------------

*`TrackEvent` is based on `Event`, so properties of `Event` are also available on `TrackEvent` objects.*

`track` Read only

The DOM track object the event is in reference to. If not `null`, this is always an object of one of the media track types: `AudioTrack`, `VideoTrack`, or `TextTrack`).

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

### Trigger

 The `removetrack` event is called whenever a track is removed from the media
 element whose audio tracks are represented by the `AudioTrackList` object.

This event is not cancelable and does not bubble.

### Use cases

You can use this event to react to a new audio track becoming unavailable. You may want to update your UI elements to disallow for user selection of the removed audio track, for example.

Examples
--------

Using `addEventListener()`:

```js
const videoElement = document.querySelector("video");

videoElement.audioTracks.addEventListener("removetrack", (event) => {
  console.log(`Audio track: ${event.track.label} removed`);
});
```

Using the `onremovetrack` event handler property:

```js
const videoElement = document.querySelector("video");

videoElement.audioTracks.onremovetrack = (event) => {
  console.log(`Audio track: ${event.track.label} removed`);
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-removetrack |
| HTML Standard # handler-tracklist-onremovetrack |

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

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

See also
--------

* Related events: `addtrack`, `change`
* This event on `VideoTrackList` targets: `removetrack`
* This event on `MediaStream` targets: `removetrack`
* Media Capture and Streams API
* WebRTC


AudioTrackList: addtrack event - Web APIs

AudioTrackList: addtrack event
==============================

The `addtrack` event is fired when a track is added to an `AudioTrackList`.

Syntax
------

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

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

onaddtrack = (event) => { }
```

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

A `TrackEvent`. Inherits from `Event`.

Event

TrackEventEvent properties
----------------

*`TrackEvent` is based on `Event`, so properties of `Event` are also available on `TrackEvent` objects.*

`track` Read only

The DOM track object the event is in reference to. If not `null`, this is always an object of one of the media track types: `AudioTrack`, `VideoTrack`, or `TextTrack`).

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

### Trigger

 The `addtrack` event is called whenever a new track is added to the media
 element whose audio tracks are represented by the `AudioTrackList` object.
 This happens when tracks are added to the element when the media is first attached to
 the element; one `addtrack` event will occur for each audio track in the
 media resource.

This event is not cancelable and does not bubble.

### Use cases

You can use this event to react to a new audio track becoming available. You may want to update your UI elements to allow for user selection of the new audio track, for example.

Examples
--------

Using `addEventListener()`:

```js
const videoElement = document.querySelector("video");

videoElement.audioTracks.addEventListener("addtrack", (event) => {
  console.log(`Audio track: ${event.track.label} added`);
});
```

Using the `onaddtrack` event handler property:

```js
const videoElement = document.querySelector("video");

videoElement.audioTracks.onaddtrack = (event) => {
  console.log(`Audio track: ${event.track.label} added`);
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-addtrack |
| HTML Standard # handler-tracklist-onaddtrack |

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

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

See also
--------

* Related events: `removetrack`, `change`
* This event on `VideoTrackList` targets: `addtrack`
* This event on `MediaStream` targets: `addtrack`
* Media Capture and Streams API
* WebRTC


AudioTrackList: getTrackById() method - Web APIs

AudioTrackList: getTrackById() method
=====================================

 The **`AudioTrackList`** method
 **`getTrackById()`** returns the first
 `AudioTrack` object from the track list whose `id` matches the specified string. This lets you find a specified track if
 you know its ID string.

Syntax
------

```js
getTrackById(id)
```

### Parameters

`id`

 A string indicating the ID of the track to locate within the track
 list.

### Return value

 An `AudioTrack` object indicating the first track found within the
 `AudioTrackList` whose `id` matches the specified string. If no
 match is found, this method returns `null`.

 The tracks are searched in their natural order; that is, in the order defined by the
 media resource itself, or, if the resource doesn't define an order, the relative order
 in which the tracks are declared by the media resource.

Examples
--------

 This example suggests a hypothetical game in which movies are used as cut-scenes or
 other key set pieces within the game. Each movie has one audio track for each character,
 as well as one for the music, sound effects, and so forth. This function allows the game
 to disable a specific character's audio in order to adjust the movie's performance based
 on occurrences within the game; if the character's dialog isn't relevant, it gets left
 out. Obviously, that would require some clever graphic design to make work, but it's a
 hypothetical game.

```js
function disableCharacter(videoElem, characterName) {
  videoElem.audioTracks.getTrackById(characterName).enabled = false;
}
```

 This short function gets the `AudioTrackList` containing the video's audio
 tracks using `HTMLMediaElement.audioTracks`, then calls
 `getTrackById()` on it, specifying the character's name. The resulting
 track's audio is then disabled by setting its `enabled` flag to `false`.

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

| Specification |
| --- |
| HTML Standard # dom-audiotracklist-gettrackbyid-dev |

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

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


Response: headers property - Web APIs

Response: headers property
==========================

 The **`headers`** read-only property of the
 `Response` interface contains the `Headers` object associated
 with the response.

Value
-----

A `Headers` object.

Examples
--------

 In our Fetch Response example (see Fetch Response live)
 we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`,
 create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

Note that at the top of the `fetch()` block, we log the response headers to the console.

```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    console.log("response.headers =", response.headers);
    return response.blob();
  })
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

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

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

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

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

See also
--------

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


Response: text() method - Web APIs

Response: text() method
=======================

 The **`text()`** method of the `Response` interface takes a `Response` stream and reads it to completion.
 It returns a promise that resolves with a `String`.
 The response is *always* decoded using UTF-8.

Syntax
------

```js
text()
```

### Parameters

None.

### Return value

A Promise that resolves with a `String`.

Examples
--------

 In our fetch text example (run fetch text live), we have an `<article>` element and three links (stored in the `myLinks` array.)
 First, we loop through all of these and give each one an `onclick` event handler so that the `getData()` function is run — with the link's `data-page` identifier passed to it as an argument — when one of the links is clicked.

 When `getData()` is run, we create a new request using the `Request()` constructor, then use it to fetch a specific `.txt` file.
 When the fetch is successful, we read a string out of the response using `text()`, then set the `innerText` of the `<article>` element equal to the text object.

```js
const myArticle = document.querySelector("article");
const myLinks = document.querySelectorAll("ul a");

for (const link of myLinks) {
  link.onclick = (e) => {
    e.preventDefault();
    const linkData = e.target.getAttribute("data-page");
    getData(linkData);
  };
}

function getData(pageId) {
  console.log(pageId);
  const myRequest = new Request(`${pageId}.txt`);
  fetch(myRequest)
    .then((response) => response.text())
    .then((text) => {
      myArticle.innertext = text;
    });
}
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-text① |

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

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

See also
--------

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


Response: error() static method - Web APIs

Response: error() static method
===============================

The **`error()`** static method of the `Response` interface returns a new `Response` object associated with a network error.

This is mainly useful when writing service workers: it enables a service worker to send a response from a `fetch` event handler that will cause the `fetch()` call in the main app code to reject the promise.

An error response has its `type` set to `error`.

Syntax
------

```js
Response.error()
```

### Parameters

None.

### Return value

A `Response` object.

Examples
--------

### Returning a network error from a service worker

Suppose a web app has a service worker, which contains the following `fetch` event handler:

```js
// service-worker.js

self.addEventListener("fetch", (event) => {
  const url = new URL(event.request.url);
  if (url.pathname === "/salamander.jpg") {
    event.respondWith(Response.error());
  }
});
```

With this service worker, all fetch requests from the app will pass through the service worker to the network, except for requests to fetch "salamander.jpg", which will reject. This means that the following main thread code would throw an error, and the `catch` handler will run.

```js
// main.js

const image = document.querySelector("#image");

try {
  const response = await fetch("salamander.jpg");
  const blob = await response.blob();
  const objectURL = URL.createObjectURL(blob);
  image.src = objectURL;
} catch (e) {
  console.error(e);
}
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-error① |

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

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

See also
--------

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


Response: Response() constructor - Web APIs

Response: Response() constructor
================================

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

Syntax
------

```js
new Response()
new Response(body)
new Response(body, options)
```

### Parameters

`body` Optional

 An object defining a body for the response. This can be `null` (which is
 the default value), or one of:

* `Blob`
* `ArrayBuffer`
* `TypedArray`
* `DataView`
* `FormData`
* `ReadableStream`
* `URLSearchParams`
* `String`
* string literal

`options` Optional

An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are:

`status`

 The status code for the response.
 The default value is `200`.

`statusText`

 The status message associated with the status code, such as `"OK"`.
 The default value is `""`.

`headers`

 Any headers you want to add to your response, contained within a `Headers` object or object literal of `String` key/value pairs (see HTTP headers for a reference).
 By default this is empty.

Examples
--------

 In our Fetch Response example (see Fetch Response live)
 we create a new `Response` object using the constructor, passing it a new `Blob` as a body, and an init object containing a custom `status` and `statusText`:

```js
const myBlob = new Blob();
const myOptions = { status: 200, statusText: "SuperSmashingGreat!" };
const myResponse = new Response(myBlob, myOptions);
```

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

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

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

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

See also
--------

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


Response: ok property - Web APIs

Response: ok property
=====================

The **`ok`** read-only property of the `Response` interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not.

Value
-----

A boolean value.

Examples
--------

 In our Fetch Response example (see Fetch Response live)
 we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`, create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

**Note:** at the top of the `fetch()` block we log the response `ok` value to the console.

```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest).then((response) => {
  console.log(response.ok); // returns true if the response returned successfully
  response.blob().then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
});
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-ok② |

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

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

See also
--------

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


Response: status property - Web APIs

Response: status property
=========================

The **`status`** read-only property of the `Response` interface contains the HTTP status codes of the response.

For example, `200` for success, `404` if the resource could not be found.

Value
-----

 An unsigned short number.
 This is one of the HTTP response status codes.

Examples
--------

 In our Fetch Response example (see Fetch Response live)
 we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`, create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

Note that at the top of the `fetch()` block we log the response `status` value to the console.

```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    console.log("response.status =", response.status); // response.status = 200
    return response.blob();
  })
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-status① |

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

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

See also
--------

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


Response: statusText property - Web APIs

Response: statusText property
=============================

The **`statusText`** read-only property of the `Response` interface contains the status message corresponding to the HTTP status code in `Response.status`.

For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`.

Value
-----

 A `String` containing the HTTP status message associated with the response.
 The default value is "".

 See HTTP response status codes for a list of codes and their associated status messages.
 Note that HTTP/2 does not support status messages.

Examples
--------

 In our Fetch Response example (see Fetch Response live) we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`, create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

Note that at the top of the `fetch()` block we log the response `statusText` value to the console.

```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    console.log("response.statusText =", response.statusText); // response.statusText = "OK"
    return response.blob();
  })
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-statustext① |

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

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

See also
--------

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


Response: arrayBuffer() method - Web APIs

Response: arrayBuffer() method
==============================

 The **`arrayBuffer()`** method of the `Response` interface
 takes a `Response` stream and reads it to completion. It returns a promise
 that resolves with an `ArrayBuffer`.

Syntax
------

```js
arrayBuffer()
```

### Parameters

None.

### Return value

A promise that resolves with an `ArrayBuffer`.

Examples
--------

### Playing music

 In our fetch array buffer live, we have a Play button. When pressed, the `getData()`
 function is run. Note that before playing full audio file will be downloaded. If you
 need to play ogg during downloading (stream it) - consider
 `HTMLAudioElement`:

```js
new Audio("music.ogg").play();
```

 In `getData()` we create a new request using the
 `Request()` constructor, then use it to fetch an OGG
 music track. We also use `AudioContext.createBufferSource` to create an
 audio buffer source. When the fetch is successful, we read an `ArrayBuffer`
 out of the response using `arrayBuffer()`, decode the audio data using
 `AudioContext.decodeAudioData()`, set the decoded data as the audio buffer
 source's buffer (`source.buffer`), then connect the source up to the
 `AudioContext.destination`.

 Once `getData()` has finished running, we start the audio source playing
 with `start(0)`, then disable the play button so it can't be clicked again
 when it is already playing (this would cause an error.)

```js
function getData() {
  const audioCtx = new AudioContext();

  return fetch("viper.ogg")
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error, status = ${response.status}`);
      }
      return response.arrayBuffer();
    })
    .then((buffer) => audioCtx.decodeAudioData(buffer))
    .then((decodedData) => {
      const source = new AudioBufferSourceNode();
      source.buffer = decodedData;
      source.connect(audioCtx.destination);
      return source;
    });
}

// wire up buttons to stop and play audio

play.onclick = () => {
  getData().then((source) => {
    source.start(0);
    play.setAttribute("disabled", "disabled");
  });
};
```

### Reading files

 The `Response()` constructor accepts
 `File`s and `Blob`s, so it may be used to read a
 `File` into other formats.

```js
function readFile(file) {
  return new Response(file).arrayBuffer();
}
```

```html
<input type="file" onchange="readFile(this.files[0])" />
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-arraybuffer① |

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

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

See also
--------

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


Response: blob() method - Web APIs

Response: blob() method
=======================

 The **`blob()`** method of the `Response` interface takes
 a `Response` stream and reads it to completion. It returns a promise that
 resolves with a `Blob`.

Syntax
------

```js
blob()
```

### Parameters

None.

**Note:** If the `Response` has a
 `Response.type` of `"opaque"`, the resulting `Blob`
 will have a `Blob.size` of `0` and a `Blob.type` of
 empty string `""`, which renders it *useless* for methods like
 `URL.createObjectURL()`.

### Return value

A promise that resolves with a `Blob`.

Examples
--------

 In our fetch request example (run fetch request live), we
 create a new request using the `Request()` constructor,
 then use it to fetch a JPG. When the fetch is successful, we read a `Blob`
 out of the response using `blob()`, put it into an object URL using
 `URL.createObjectURL()`, and then set that URL as the source of an
 `<img>` element to display the image.

```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => response.blob())
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-blob① |

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

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

See also
--------

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


Response: json() static method - Web APIs

Response: json() static method
==============================

 The **`json()`** static method of the `Response` interface returns a `Response` that contains the provided JSON data as body, and a `Content-Type` header which is set to `application/json`.
 The response status, status message, and additional headers can also be set.

 The method makes it easy to create `Response` objects for returning JSON encoded data.
 Service workers, for example, intercept fetch requests made by a browser, and might use `json()` to construct a `Response` from cached JSON data to return to the main thread.
 The `json()` method can also be used in server code to return JSON data for single page applications, and any other applications where a JSON response is expected.

Syntax
------

```js
Response.json(data)
Response.json(data, options)
```

### Parameters

`data`

The JSON data to be used as the response body.

`options` Optional

 An options object containing settings for the response, including the status code, status text, and headers.
 This is the same as the options parameter of the `Response()` constructor.

`status`

The status code for the response, such as `200`.

`statusText`

 The status message associated with the status code.
 For a status of `200` this might be `OK`.

`headers`

Any headers you want to add to your response, contained within a `Headers` object or object literal of `String` key/value pairs (see HTTP headers for a reference).

### Return value

A `Response` object.

### Exceptions

`TypeError`

 Thrown if `data` cannot be converted to a JSON string.
 This might happen if the data is a JavaScript object that has method, or that has a circular reference, or if the passed object is `undefined`.

Examples
--------

### Response with JSON data

This live example shows how you can create a JSON response object, and logs the newly created object for inspection (the logging code is hidden as it is not relevant).
```

<pre id="log"></pre>
```

```
const logElement = document.getElementById("log");
function log(text) {
  logElement.innerText += `${text}\n`;
}

async function logResponse(response) {
  const responseText = await jsonResponse.text();
  log(`body: ${responseText}`);
  jsonResponse.headers.forEach((header) => log(`header: ${header}`));
  log(`status: ${jsonResponse.status}`);
  log(`statusText: ${jsonResponse.statusText}`);
  log(`type: ${jsonResponse.type}`);
  log(`url: ${jsonResponse.url}`);
  log(`ok: ${jsonResponse.ok}`);
  log(`redirected: ${jsonResponse.redirected}`);
  log(`bodyUsed: ${jsonResponse.bodyUsed}`);
}
```

The code below creates a `Response` object with JSON body `{ my: "data" }` and header set to `application/json`.

```js
const jsonResponse = Response.json({ my: "data" });
logResponse(jsonResponse);
```

 The object has the following properties.
 Note the body and header are set as expected, and that the default status is set to `200`.

### Response with JSON data and options

This example shows how you can create a JSON response object with `status` and `statusText` options.
```

<pre id="log"></pre>
```

```
const logElement = document.getElementById("log");
function log(text) {
  logElement.innerText += `${text}\n`;
}

async function logResponse(response) {
  const responseText = await jsonResponse.text();
  log(`body: ${responseText}`);
  jsonResponse.headers.forEach((header) => log(`header: ${header}`));
  log(`status: ${jsonResponse.status}`);
  log(`statusText: ${jsonResponse.statusText}`);
  log(`type: ${jsonResponse.type}`);
  log(`url: ${jsonResponse.url}`);
  log(`ok: ${jsonResponse.ok}`);
  log(`redirected: ${jsonResponse.redirected}`);
  log(`bodyUsed: ${jsonResponse.bodyUsed}`);
}
```

 The code below creates a `Response` object with JSON body `{ some: "data", more: "information" }` and header set to `application/json`.
 It also sets the status to `307` and sets the appropriate status text ("Temporary Redirect").

```js
const jsonResponse = Response.json(
  { some: "data", more: "information" },
  { status: 307, statusText: "Temporary Redirect" },
);
logResponse(jsonResponse);
```

 The object has the following properties, which are set as expected.
 Note that the `ok` property of the response changed to `false` as the status value is not in the range of 200 to 299.

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-json① |

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

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

See also
--------

* Service Worker API


Response: bodyUsed property - Web APIs

Response: bodyUsed property
===========================

The **`bodyUsed`** read-only property of the `Response` interface is a boolean value that indicates whether the body has been read yet.

Value
-----

A boolean value.

Examples
--------

### Checking `bodyUsed`

This example illustrates that reading the body of a response changes the value of `bodyUsed` from `false` to `true`.

The example contains an empty image.

When the example's JavaScript runs, we fetch an image and assigns the returned promise to a variable `responsePromise`.

When the user clicks "Use response", we check whether the response has been used already. If it has, we print a message. If it has not, we read the response body and used it to provide a value for the image's `src` attribute.

#### HTML

```html
<button id="use">Use response</button>
<button id="reset">Reset</button>
<br />
<img id="my-image" src="" />
<pre id="log"></pre>
```

#### JavaScript

```js
const useResponse = document.querySelector("#use");
const reset = document.querySelector("#reset");
const myImage = document.querySelector("#my-image");
const log = document.querySelector("#log");

const responsePromise = fetch(
  "https://upload.wikimedia.org/wikipedia/commons/7/77/Delete\_key1.jpg",
);

useResponse.addEventListener("click", async () => {
  const response = await responsePromise;
  if (response.bodyUsed) {
    log.textContent = "Body has already been used!";
  } else {
    const result = await response.blob();
    const objectURL = URL.createObjectURL(result);
    myImage.src = objectURL;
  }
});

reset.addEventListener("click", () => {
  document.location.reload();
});
```

#### Result

Initially there is no value for the image. If you click "Use response" once, then `bodyUsed` is `false`, so we read the response and set the image. If you then click "Use response" again, then `bodyUsed` is `true`, and we print the message.

Click "Reset" to reload the example, so you can try again.

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-bodyused① |

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

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

See also
--------

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


Response: body property - Web APIs

Response: body property
=======================

The **`body`** read-only property of the `Response` interface is a `ReadableStream` of the body contents.

Value
-----

A `ReadableStream`, or else `null` for any `Response` object constructed with a null `body` property, or for any actual HTTP response that has no body.

The stream is a readable byte stream, which supports zero-copy reading using a `ReadableStreamBYOBReader`.

**Note:** Current browsers don't actually conform to the spec requirement to set the `body` property to `null` for responses with no body (for example, responses to `HEAD` requests, or `204 No Content` responses).

Examples
--------

### Copying an image

 In our simple stream pump example we fetch an image,
 expose the response's stream using `response.body`, create a reader using `ReadableStream.getReader()`,
 then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image.

```js
const image = document.getElementById("target");

// Fetch the original image
fetch("./tortoise.png")
  // Retrieve its body as ReadableStream
  .then((response) => response.body)
  .then((body) => {
    const reader = body.getReader();

    return new ReadableStream({
      start(controller) {
        return pump();

        function pump() {
          return reader.read().then(({ done, value }) => {
            // When no more data needs to be consumed, close the stream
            if (done) {
              controller.close();
              return;
            }

            // Enqueue the next data chunk into our target stream
            controller.enqueue(value);
            return pump();
          });
        }
      },
    });
  })
  .then((stream) => new Response(stream))
  .then((response) => response.blob())
  .then((blob) => URL.createObjectURL(blob))
  .then((url) => console.log((image.src = url)))
  .catch((err) => console.error(err));
```

### Creating a BYOB reader

In this example we construct a `ReadableStreamBYOBReader` from the body using `ReadableStream.getReader({mode: 'byob'})`. We can then use this reader to implement zero copy transfer of the response data.

```js
async function getProducts(url) {
  const response = await fetch(url);
  const reader = response.body.getReader({ mode: "byob" });
  // read the response
}

getProducts(
  "https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
```

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

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

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

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

See also
--------

* Fetch API
* Streams API
* ServiceWorker API


Response: redirect() static method - Web APIs

Response: redirect() static method
==================================

The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL.

**Note:** This can be used alongside the ServiceWorker API.
 A controlling service worker could intercept a page's request and redirect it as desired.
 This will actually lead to a real redirect if a service worker sends it upstream.

Syntax
------

```js
Response.redirect(url)
Response.redirect(url, status)
```

### Parameters

`url`

The URL that the new response is to originate from.

`status` Optional

An optional number indicating the status code for the response: one of `301`, `302`, `303`, `307`, or `308`. If omitted, `302 (Found)` is used by default.

### Return value

A `Response` object.

### Exceptions

`RangeError`

The specified status is not a redirect status.

`TypeError`

The specified URL is invalid.

Examples
--------

```js
Response.redirect("https://www.example.com", 302);
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-redirect① |

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

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

See also
--------

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


Response: url property - Web APIs

Response: url property
======================

 The **`url`** read-only property of the `Response` interface contains the URL of the response.
 The value of the `url` property will be the final URL obtained after any redirects.

Value
-----

A string.

Examples
--------

 In our Fetch Response example (see Fetch Response live) we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`, create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

Note that at the top of the `fetch()` block we log the response `URL` to the console.

```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    console.log("response.url =", response.url); // response.url = https://mdn.github.io/dom-examples/fetch/fetch-response/flowers.jpg
    return response.blob();
  })
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-url① |

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

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

See also
--------

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


Response: json() method - Web APIs

Response: json() method
=======================

 The **`json()`** method of the `Response` interface takes
 a `Response` stream and reads it to completion. It returns a promise which
 resolves with the result of parsing the body text as `JSON`.

Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.

Syntax
------

```js
json()
```

### Parameters

None.

### Return value

 A `Promise` that resolves to a JavaScript object. This object could be
 anything that can be represented by JSON — an object, an array, a string, a number…

Examples
--------

 In our fetch JSON example (run fetch JSON live), we create a new request using the `Request()` constructor, then use it to fetch a `.json` file. When the
 fetch is successful, we read and parse the data using `json()`, then read
 values out of the resulting objects as you'd expect and insert them into list items to
 display our product data.

```js
const myList = document.querySelector("ul");
const myRequest = new Request("products.json");

fetch(myRequest)
  .then((response) => response.json())
  .then((data) => {
    for (const product of data.products) {
      const listItem = document.createElement("li");
      listItem.appendChild(document.createElement("strong")).textContent =
        product.Name;
      listItem.append(` can be found in ${product.Location}. Cost: `);
      listItem.appendChild(document.createElement("strong")).textContent =
        `£${product.Price}`;
      myList.appendChild(listItem);
    }
  })
  .catch(console.error);
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-json① |

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

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

See also
--------

* ServiceWorker API
* Cross-Origin Resource Sharing (CORS)
* HTTP


Response: type property - Web APIs

Response: type property
=======================

 The **`type`** read-only property of the `Response` interface contains the type of the response.
 It can be one of the following:

* `basic`: Normal, same origin response, with all headers exposed except "Set-Cookie".
* `cors`: Response was received from a valid cross-origin request. Certain headers and the body may be accessed.
* `error`: Network error.
 No useful information describing the error is available.
 The Response's status is 0, headers are empty and immutable.
 This is the type for a Response obtained from `Response.error()`.
* `opaque`: Response for "no-cors" request to cross-origin resource.
 Severely restricted.
* `opaqueredirect`: The fetch request was made with `redirect: "manual"`.
 The Response's status is 0, headers are empty, body is null and trailer is empty.

**Note:** An "error" Response never really gets exposed to script: such a response to a `fetch()` would reject the promise.

Value
-----

A `ResponseType` string indicating the type of the response.

Examples
--------

 In our Fetch Response example (see Fetch Response live) we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`, create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

Note that at the top of the `fetch()` block we log the response `type` to the console.

```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    console.log("response.type =", response.type); // response.type = 'basic'
    return response.blob();
  })
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-type① |

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

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

See also
--------

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


Response: redirected property - Web APIs

Response: redirected property
=============================

The read-only **`redirected`** property of the `Response` interface indicates whether or not the response is the result of a request you made which was redirected.

**Note:** Relying on redirected to filter out redirects makes it easy for a forged redirect to prevent your content from working as expected.
 Instead, you should do the filtering when you call `fetch()`.
 See the example Disallowing redirects, which shows this being done.

Value
-----

A boolean value which is `true` if the response indicates that your request was redirected.

Examples
--------

### Detecting redirects

 Checking to see if the response comes from a redirected request is as simple as checking this flag on the `Response` object.
 In the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation.
 Note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under Disallowing redirects below.

The `url` property returns the final URL after redirects.

```js
fetch("awesome-picture.jpg")
  .then((response) => {
    const elem = document.getElementById("warning-message-box");
    elem.textContent = response.redirected ? "Unexpected redirect" : "";
    // final url obtained after redirects
    console.log(response.url);
    return response.blob();
  })
  .then((imageBlob) => {
    const imgObjectURL = URL.createObjectURL(imageBlob);
    document.getElementById("img-element-id").src = imgObjectURL;
  });
```

### Disallowing redirects

Because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to `"error"` in the `init` parameter when calling `fetch()`, like this:

```js
fetch("awesome-picture.jpg", { redirect: "error" })
  .then((response) => response.blob())
  .then((imageBlob) => {
    const imgObjectURL = URL.createObjectURL(imageBlob);
    document.getElementById("img-element-id").src = imgObjectURL;
  });
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-redirected① |

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

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

See also
--------

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


Response: formData() method - Web APIs

Response: formData() method
===========================

 The **`formData()`** method of the `Response` interface
 takes a `Response` stream and reads it to completion. It returns a promise
 that resolves with a `FormData` object.

**Note:** This is mainly relevant to service workers. If a user submits
 a form and a service worker intercepts the request, you could for example call
 `formData()` on it to obtain a key-value map, modify some fields, then send
 the form onwards to the server (or use it locally).

Syntax
------

```js
formData()
```

### Parameters

None.

### Return value

A `Promise` that resolves with a `FormData` object.

Examples
--------

TBD.

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-formdata① |

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

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

See also
--------

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


Response: clone() method - Web APIs

Response: clone() method
========================

The **`clone()`** method of the `Response` interface creates a clone of a response object, identical in every way, but stored in a different variable.

 Like the underlying `ReadableStream.tee` api,
 the `body` of a cloned `Response`
 will signal backpressure at the rate of the *faster* consumer of the two bodies,
 and unread data is enqueued internally on the slower consumed `body`
 without any limit or backpressure.
 Backpressure refers to the mechanism by which the streaming consumer of data
 (in this case, the code that reads the body)
 slows down the producer of data (such as the TCP server)
 so as not to load large amounts of data in memory
 that is waiting to be used by the application.
 If only one cloned branch is consumed, then the entire body will be buffered in memory.
 Therefore, `clone()` is one way to read a response twice in sequence,
 but you should not use it to read very large bodies
 in parallel at different speeds.

`clone()` throws a `TypeError` if the response body has already been used.
 In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.)

Syntax
------

```js
clone()
```

### Parameters

None.

### Return value

A `Response` object.

Examples
--------

 In our Fetch Response clone example (see Fetch Response clone live) we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`.
 When the fetch resolves successfully, we clone it, extract a blob from both responses using two `Response.blob` calls, create object URLs out of the blobs using
 `URL.createObjectURL()`, and display them in two separate `<img>` elements.

```js
const image1 = document.querySelector(".img1");
const image2 = document.querySelector(".img2");

const myRequest = new Request("flowers.jpg");

fetch(myRequest).then((response) => {
  const response2 = response.clone();

  response.blob().then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    image1.src = objectURL;
  });

  response2.blob().then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    image2.src = objectURL;
  });
});
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-clone① |

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

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

See also
--------

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


WebTransportDatagramDuplexStream: outgoingMaxAge property - Web APIs

WebTransportDatagramDuplexStream: outgoingMaxAge property
=========================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`outgoingMaxAge`** property of the `WebTransportDatagramDuplexStream` interface gets or sets the maximum age for outgoing datagrams, in milliseconds.

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

Value
-----

A number, or `null` if no maximum age has been set.

Examples
--------

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

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

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

  const datagrams = transport.datagrams;

  // set outgoingMaxAge
  datagrams.outgoingMaxAge = 2000;

  // get outgoingMaxAge
  console.log(datagrams.outgoingMaxAge);
}
```

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

| Specification |
| --- |
| WebTransport # dom-webtransportdatagramduplexstream-outgoingmaxage |

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

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

See also
--------

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


WebTransportDatagramDuplexStream: incomingMaxAge property - Web APIs

WebTransportDatagramDuplexStream: incomingMaxAge property
=========================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`incomingMaxAge`** property of the `WebTransportDatagramDuplexStream` interface gets or sets the maximum age for incoming datagrams, in milliseconds.

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

Value
-----

A number, or `null` if no maximum age has been set.

Examples
--------

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

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

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

  const datagrams = transport.datagrams;

  // set incomingMaxAge
  datagrams.incomingMaxAge = 2000;

  // get incomingMaxAge
  console.log(datagrams.incomingMaxAge);
}
```

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

| Specification |
| --- |
| WebTransport # dom-webtransportdatagramduplexstream-incomingmaxage |

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

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

See also
--------

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


WebTransportDatagramDuplexStream: outgoingHighWaterMark property - Web APIs

WebTransportDatagramDuplexStream: outgoingHighWaterMark property
================================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`outgoingHighWaterMark`** property of the `WebTransportDatagramDuplexStream` interface gets or sets the high water mark for outgoing chunks of data — this is the maximum size, in chunks, that the outgoing `WritableStream`'s internal queue can reach before it is considered full. See Internal queues and queuing strategies for more information.

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

Value
-----

A number.

Examples
--------

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

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

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

  const datagrams = transport.datagrams;

  // set outgoingHighWaterMark
  datagrams.outgoingHighWaterMark = 20000;

  // get outgoingHighWaterMark
  console.log(datagrams.outgoingHighWaterMark);
}
```

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

| Specification |
| --- |
| WebTransport # dom-webtransportdatagramduplexstream-outgoinghighwatermark |

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

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

See also
--------

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


WebTransportDatagramDuplexStream: incomingHighWaterMark property - Web APIs

WebTransportDatagramDuplexStream: incomingHighWaterMark property
================================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`incomingHighWaterMark`** property of the `WebTransportDatagramDuplexStream` interface gets or sets the high water mark for incoming chunks of data — this is the maximum size, in chunks, that the incoming `ReadableStream`'s internal queue can reach before it is considered full. See Internal queues and queuing strategies for more information.

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

Value
-----

A number.

Examples
--------

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

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

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

  const datagrams = transport.datagrams;

  // set incomingHighWaterMark
  datagrams.incomingHighWaterMark = 20000;

  // get incomingHighWaterMark
  console.log(datagrams.incomingHighWaterMark);
}
```

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

| Specification |
| --- |
| WebTransport # dom-webtransportdatagramduplexstream-incominghighwatermark |

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

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

See also
--------

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


WebTransportDatagramDuplexStream: maxDatagramSize property - Web APIs

WebTransportDatagramDuplexStream: maxDatagramSize property
==========================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`maxDatagramSize`** read-only property of the `WebTransportDatagramDuplexStream` interface returns the maximum allowable size of outgoing datagrams, in bytes, that can be written to `writable`.

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

Value
-----

A number.

Examples
--------

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

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

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

  const datagrams = transport.datagrams;

  // get maxDatagramSize
  console.log(datagrams.maxDatagramSize);
}
```

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

| Specification |
| --- |
| WebTransport # dom-webtransportdatagramduplexstream-maxdatagramsize |

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

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

See also
--------

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


WebTransportDatagramDuplexStream: readable property - Web APIs

WebTransportDatagramDuplexStream: readable property
===================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`readable`** read-only property of the `WebTransportDatagramDuplexStream` interface returns a `ReadableStream` instance that can be used to unreliably read incoming datagrams from the stream.

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

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

Value
-----

A `ReadableStream`.

Examples
--------

See the main `WebTransportDatagramDuplexStream` interface page.

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

| Specification |
| --- |
| WebTransport # dom-webtransportdatagramduplexstream-readable |

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

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

See also
--------

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


WebTransportDatagramDuplexStream: writable property - Web APIs

WebTransportDatagramDuplexStream: writable property
===================================================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`writable`** read-only property of the `WebTransportDatagramDuplexStream` interface returns a `WritableStream` instance that can be used to unreliably write outgoing datagrams to the stream.

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

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

Value
-----

A `WritableStream`.

Examples
--------

See the main `WebTransportDatagramDuplexStream` interface page.

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

| Specification |
| --- |
| WebTransport # dom-webtransportdatagramduplexstream-writable |

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

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

See also
--------

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


ValidityState: badInput property - Web APIs

ValidityState: badInput property
================================

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

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

* Learn more
* See full compatibility
* Report feedback
The read-only **`badInput`** property of a ValidityState object indicates if the user has provided input that the browser is unable to convert. For example, if you have a number input element whose content is a string.

Value
-----

A boolean.

Examples
--------

```html
<input type="number" id="age" />
```

```js
const input = document.getElementById("age");
if (input.validity.badInput) {
  console.log("Bad input detected…");
} else {
  console.log("Content of input OK.");
}
```

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

| Specification |
| --- |
| HTML Standard # dom-validitystate-badinput-dev |

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

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

See also
--------

* Guide: Constraint validation
* Tutorial: Form data validation


ValidityState: rangeOverflow property - Web APIs

ValidityState: rangeOverflow property
=====================================

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

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

* Learn more
* See full compatibility
* Report feedback
The read-only **`rangeOverflow`** property of a **`ValidityState`** object indicates if the value of an `<input>`, after having been edited by the user, does not conform to the constraints set by the element's `max` attribute.

If the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and a `max` value is set, if the value doesn't conform to the constraints set by the `max` value, the `rangeOverflow` property will be true.

Given the following:

```html
<input type="number" min="20" max="40" step="2" />
```

if `value > 40`, `rangeOverflow` will be true. When `true`, the element matches the `:invalid` and `:out-of-range` CSS pseudo-classes.

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

| Specification |
| --- |
| HTML Standard # dom-validitystate-rangeoverflow |

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

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

See also
--------

* `ValidityState.rangeUnderflow`
* Constraint validation
* Forms: Data form validation
* `step` attribute
* `min` attribute


ValidityState: tooLong property - Web APIs

ValidityState: tooLong property
===============================

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

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

* Learn more
* See full compatibility
* Report feedback
The read-only **`tooLong`** property of a **`ValidityState`** object indicates if the value of an `<input>` or `<textarea>`, after having been edited by the user, exceeds the maximum code-unit length established by the element's `maxlength` attribute.

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

| Specification |
| --- |
| HTML Standard # dom-validitystate-toolong-dev |

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

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

See also
--------

* Constraint validation
* Forms: Data form validation


ValidityState: patternMismatch property - Web APIs

ValidityState: patternMismatch property
=======================================

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

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

* Learn more
* See full compatibility
* Report feedback
The read-only **`patternMismatch`** property of a **`ValidityState`** object indicates if the value of an `<input>`, after having been edited by the user, does not conform to the constraints set by the element's `pattern` attribute.

The `patternMismatch` property will be true if and only if the following conditions are all true:

* the field supports the `pattern` attribute — which means the `<input>` is of `type` text, tel, email, url, password, or search
* the `pattern` attribute contains a valid regular expression
* the `<input>` value doesn't conform to the constraints set by the `pattern` value.
Examples
--------

Given the following:

```html
<p>
  <label
 >Enter your phone number in the format (123)456-7890 (<input
 name="tel1"
 type="tel"
 pattern="[0-9]{3}"
 placeholder="###"
 aria-label="3-digit area code"
 size="2" />)-
    <input
 name="tel2"
 type="tel"
 pattern="[0-9]{3}"
 placeholder="###"
 aria-label="3-digit prefix"
 size="2" />
    -
    <input
 name="tel3"
 type="tel"
 pattern="[0-9]{4}"
 placeholder="####"
 aria-label="4-digit number"
 size="3" />
  </label>
</p>
```

Here we have 3 sections for a North American phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the `pattern` attribute set on each.

If the values are too long or too short, or contain characters that aren't digits, `patternMismatch` will be true. When `true`, the element matches the `:invalid` CSS pseudo-classes.

```css
input:invalid {
  border: red solid 3px;
}
```

Note, in this case, we get a `patternMismatch` not a `validityState.tooLong` or `validityState.tooShort` if the values are too long or too short because it is the pattern that is dictating the length of the value. Had we used `minlength` and `maxlength` attributes instead, we may have seen `validityState.tooLong` or `validityState.tooShort` being true.

**Note:** The `email` input type requires, at minimum, a match of `x@y` and the `url` type requires, at minimum, a match to x:, with no pattern attribute present. When invalid, the `validityState.typeMismatch` will be true, if there is no pattern attribute (or if the pattern attribute is not valid for that input type).

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

| Specification |
| --- |
| HTML Standard # dom-validitystate-patternmismatch |

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

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

See also
--------

* Constraint validation
* Forms: Data form validation
* Regular Expressions


ValidityState: valueMissing property - Web APIs

ValidityState: valueMissing property
====================================

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

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

* Learn more
* See full compatibility
* Report feedback
The read-only **`valueMissing`** property of a **`ValidityState`** object indicates if a `required` control, such as an `<input>`, `<select>`, or `<textarea>`, has an empty value.

If the `required` attribute is set, and no `<option>` is selected or a `<textarea>` or user-editable `<input>` is empty, the `valueMissing` property will be `true`. The property is only `true` if the field is required and has no value; if the field is not required, or if the field is required and has a value, the value is `false`.

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

| Specification |
| --- |
| HTML Standard # dom-validitystate-valuemissing-dev |

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

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

See also
--------

* Constraint validation
* Forms: Data form validation
* Regular Expressions


ValidityState: rangeUnderflow property - Web APIs

ValidityState: rangeUnderflow property
======================================

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

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

* Learn more
* See full compatibility
* Report feedback
The read-only **`rangeUnderflow`** property of a **`ValidityState`** object indicates if the value of an `<input>`, after having been edited by the user, does not conform to the constraints set by the element's `min` attribute.

If the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and a `min` value is set, if the value doesn't conform to the constraints set by the `min` value, the `rangeUnderflow` property will be true.

Given the following:

```html
<input type="number" min="20" max="40" step="2" />
```

if `value < 20`, `rangeUnderflow` will be true. When `true`, the element matches the `:invalid` and `:out-of-range` CSS pseudo-classes.

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

| Specification |
| --- |
| HTML Standard # dom-validitystate-rangeunderflow |

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

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

See also
--------

* `ValidityState.rangeOverflow`
* Constraint validation
* Forms: Data form validation
* `step` attribute
* `max` attribute


ValidityState: typeMismatch property - Web APIs

ValidityState: typeMismatch property
====================================

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

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

* Learn more
* See full compatibility
* Report feedback
The read-only **`typeMismatch`** property of a **`ValidityState`** object indicates if the value of an `<input>`, after having been edited by the user, does not conform to the constraints set by the element's `type` attribute.

If the `type` attribute expects specific strings, such as the email and url types and the value doesn't conform to the constraints set by the type, the `typeMismatch` property will be true.

The email input type expects one or more valid email addresses, depending on whether the `multiple` attribute is present. A valid email address includes an email prefix and a domain, with or without a top level domain. If the value of the email input is not an empty string, a single valid email address, or one or more comma separated email address if the `multiple` attribute is present, there is a `typeMismatch`.

The url input type expects one or more valid URLs, depending on whether the `multiple` attribute is present. A valid URL includes a protocol, optionally with an IP address, or an optional subdomain, domain, and top level domain combination. If the value of the URL input is not an empty string, a single valid URL, or one or more comma separated URLS if the `multiple` attribute is present, there is a `typeMismatch`.

| Input type | Value | Expected value |
| --- | --- | --- |
| email | `x@y` or `x@y.z` | email address, with or without TLD |
| url | `x:` or `x://y.z` | protocol or full URL with protocol |

Examples
--------

Given the following:

```html
<p>
  <label>
    Enter an email address:
    <input type="email" value="example.com" />
  </label>
</p>
<p>
  <label>
    Enter a URL:
    <input type="url" value="example.com" />
  </label>
</p>
```

```css
input:invalid {
  border: red solid 3px;
}
```

The above each produce a `typeMismatch` because the email address is just a domain and the URL has no protocol

The `typeMismatch` occurs when there is a disconnect between the `value` expected via the `type` attribute and the data that is actually present. The `typeMismatch` is only one of the many possible errors and is only relevant for the email and url types. When the value provided doesn't match the expected value based on the type for other input types, you get different errors. For example, if the number input value is not a floating point number, the `badInput` is `true`. If the email is `required` but is empty, the `valueMissing` will be `true`.

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

| Specification |
| --- |
| HTML Standard # dom-validitystate-typemismatch |

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

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

See also
--------

* Constraint validation
* Forms: Data form validation
* Regular Expressions


ValidityState: tooShort property - Web APIs

ValidityState: tooShort property
================================

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

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

* Learn more
* See full compatibility
* Report feedback
The read-only **`tooShort`** property of a **`ValidityState`** object indicates if the value of an `<input>`, `<button>`, `<select>`, `<output>`, `<fieldset>` or `<textarea>`, after having been edited by the user, is less than the minimum code-unit length established by the element's `minlength` attribute.

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

| Specification |
| --- |
| HTML Standard # dom-validitystate-tooshort-dev |

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

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

See also
--------

* Guide: Constraint validation
* Tutorial: Form data validation


ValidityState: stepMismatch property - Web APIs

ValidityState: stepMismatch property
====================================

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

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

* Learn more
* See full compatibility
* Report feedback
The read-only **`stepMismatch`** property of a **`ValidityState`** object indicates if the value of an `<input>`, after having been edited by the user, does not conform to the constraints set by the element's `step` attribute.

If the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and the step value is not `any`, if the value don't doesn't conform to the constraints set by the `step` and `min` values, then `stepMismatch` will be true. If the remainder of the form control's value less the `min` value, divided by the `step` value (which defaults to 1 if omitted) is not zero, there is a mismatch.

Given the following:

```html
<input type="number" min="20" max="40" step="2" />
```

if `(value - min) % 2 !== 0`, `stepMismatch` will be true.

If true, the element matches the `:invalid` and `:out-of-range` CSS pseudo-classes.

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

| Specification |
| --- |
| HTML Standard # dom-validitystate-stepmismatch |

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

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

See also
--------

* Constraint validation
* Forms: Data form validation
* `step` attribute


XRSession: squeezestart event - Web APIs

XRSession: squeezestart event
=============================

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

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

Primary squeeze actions are actions which are meant to represent gripping or squeezing using your hands, and may be simulated using triggers on hand controllers.

Syntax
------

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

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

onsqueezestart = (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 begin 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
--------

The following example uses `addEventListener()` to establish handlers for the squeeze events: `squeezestart`, `squeezeend`, and `squeeze`. 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 `onSqueezeEvent()` 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 `squeezestart` 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 `squeeze` 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 `squeezeend` event results in a `myStopTracking()` function being called with the object being dragged and the final target ray pose's transform.

```js
xrSession.addEventListener("squeezestart", onSqueezeEvent);
xrSession.addEventListener("squeeze", onSqueezeEvent);
xrSession.addEventListener("squeezeend", onSqueezeEvent);

function onSqueezeEvent(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 "squeezestart":
      targetObj = myBeginTracking(targetRayPose.matrix);
      break;
    case "squeeze":
      myDropObject(targetObj, targetRayPose.matrix);
      break;
    case "squeezeend":
      myStopTracking(targetObj, targetRayPose.matrix);
      break;
  }
}
```

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

```js
xrSession.onsqueezestart = onSqueezeEvent;
xrSession.onsqueeze = onSqueezeEvent;
xrSession.onsqueezeend = onSqueezeEvent;
```

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

| Specification |
| --- |
| WebXR Device API # eventdef-xrsession-squeezestart |
| WebXR Device API # dom-xrsession-onsqueezestart |

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

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


XRSession: depthDataFormat property - Web APIs

XRSession: depthDataFormat property
===================================

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

 The *read-only* **`depthDataFormat`** property of an `immersive-ar`
`XRSession` describes which depth sensing data format is used.

Value
-----

This property can return the following values:

`luminance-alpha`

 2-byte unsigned integer data buffers (`LUMINANCE_ALPHA` `GLEnum`).
 CPU usage: interpret `XRCPUDepthInformation.data` as `Uint8Array`.
 GPU usage: inspect Luminance and Alpha channels to reassemble single value.

`float32`

 4-byte floating point data buffers (`R32F` `GLEnum`).
 CPU usage: interpret `XRCPUDepthInformation.data` as `Float32Array`.
 GPU usage: inspect Red channel and use the value.

Examples
--------

To request the desired data format, you need to specify a `dataFormatPreference` when requesting a session using `XRSystem.requestSession()`. Here, the caller is able to handle both "luminance-alpha" and "float32" formats. The order indicates preference for "luminance-alpha":

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

To check which data format was selected by the user agent, you can call the `depthDataFormat` property:

```js
console.log(session.depthDataFormat); // either "luminance-alpha" or "float32"
```

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

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

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

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


XRSession: cancelAnimationFrame() method - Web APIs

XRSession: cancelAnimationFrame() method
========================================

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

 The **`cancelAnimationFrame()`** method of
 the `XRSession` interface cancels an animation frame which was previously
 requested by calling `requestAnimationFrame`.

Syntax
------

```js
cancelAnimationFrame(handle)
```

### Parameters

`handle`

 The unique value returned by the call
 to `requestAnimationFrame()` that
 previously scheduled the animation callback.

### Return value

None (`undefined`).

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

This function has no effect if the specified `handle` cannot be found.

Examples
--------

 In the example below we see code which starts up a WebXR session if immersive VR mode
 is supported. Once started, the session schedules its first frame to be rendered by
 calling `requestAnimationFrame()`.

 The `pauseXR()` function shown at the bottom can be called to suspend the
 WebVR session, in essence, by canceling any pending animation frame callback. Since each
 frame callback schedules the next one, removing the callback terminates updating of the
 WebXR scene.

```js
const XR = navigator.xr;

let requestHandle = null;
let xrSession = null;

if (XR) {
  XR.isSessionSupported("immersive-vr").then((isSupported) => {
    if (isSupported) {
      startXR();
    }
  });
}

function frameCallback(time, xrFrame) {
  xrSession.requestAnimationFrame(frameCallback);

  // Update and render the frame
}

async function startXR() {
  xrSession = XR.requestSession("immersive-vr");

  if (xrSession) {
    stopButton.onclick = stopXR;
    requestHandle = xrSession.requestAnimationFrame(frameCallback);
  }
}

function pauseXR() {
  if (xrSession && requestHandle) {
    xrSession.cancelAnimationFrame(requestHandle);
    requestHandle = null;
  }
}
```

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

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

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

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

See also
--------

* `Window.cancelAnimationFrame`
* `XRSession.requestAnimationFrame`


XRSession: renderState property - Web APIs

XRSession: renderState property
===============================

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

 The
 *read-only* **`renderState`** property of an
 `XRSession` object indicates the returns a `XRRenderState`
 object describing how the user's environment which should be rendered. The
 information provided covers the minimum and maximum distance at which to render objects,
 the vertical field of view to use when rendering the in the `inline` session
 mode, and the `XRWebGLLayer` to render into for inline composition.

 While this property is read only, you can call the `XRSession` method
 `updateRenderState()` to make changes.

Value
-----

An `XRRenderState` object describing how to render the scene.

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

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

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

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