PaymentRequestUpdateEvent: updateWith() method - Web APIs

PaymentRequestUpdateEvent: updateWith() method
==============================================

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

 The **`updateWith()`** method of the
 `PaymentRequestUpdateEvent` interface updates the details of an existing
 `PaymentRequest`.

Syntax
------

```js
updateWith(details)
```

### Parameters

`details`

An object specifying the changes applied to the payment request:

`displayItems` Optional

An array of objects, each describing one line item for the payment request. These represent the line items on a receipt or invoice, each with the following properties:

`amount`

An object describing the monetary value of the item. This object includes the following fields:

`currency`

A string containing a valid 3-letter ISO 4217 currency identifier (ISO 4217) indicating the currency used for the payment `value`.

`value`

A string containing a valid decimal value representing the mount of currency constituting the payment amount. This string must only contain an optional leading "-" to indicate a negative value, then one or more digits from 0 to 9, and an optional decimal point (".", regardless of locale) followed by at least one more digit. No whitespace is permitted.

`label`

A string specifying a human-readable name or description of the item or service being charged for. This may be displayed to the user by the user agent, depending on the design of the interface.

`pending`

A Boolean value which is `true` if the specified `amount` has not yet been finalized. This can be used to show items such as shipping or tax amounts that depend upon the selection of shipping address, shipping option, or so forth. The user agent may show this information but is not required to do so.

`error` Optional
Deprecated

Non-standard

A string specifying an error message to present to the user\*.\* When calling `updateWith()`, including `error` in the updated data causes the user agent to display the text as a general error message. For address field-specific errors, use the `shippingAddressErrors` field.

`modifiers` Optional

An `Array` of `PaymentDetailsModifier` objects, whose properties are described in `PaymentRequestEvent.modifiers`.

For example, you can use one to adjust the total payment amount based on the selected payment method ("5% cash discount!").

`shippingAddressErrors` Optional
Deprecated

Non-standard

An object which includes an error message for each property of the shipping address that could not be validated.

`shippingOptions` Optional
Deprecated

Non-standard

An array of objects, each describing one available shipping option from which the user may choose.

`total` Optional

An object with the same properties as the objects in `displayItems` providing an updated total for the payment. Make sure this equals the sum of all of the items in `displayItems`. *This is not calculated automatically*. You must update this value yourself anytime the total amount due changes. This lets you have flexibility for how to handle things like tax, discounts, and other adjustments to the total price charged.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Payment Request API 1.1 # dom-paymentrequestupdateevent-updatewith |

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

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


MediaSource: handle property - Web APIs

MediaSource: handle property
============================

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

The **`handle`** read-only property of the `MediaSource` interface returns a `MediaSourceHandle` object, a proxy for the `MediaSource` that can be transferred from a dedicated worker back to the main thread and attached to a media element via its `HTMLMediaElement.srcObject` property.

**Note:** `handle` is only visible on `MediaSource` instances inside dedicated workers.

Each `MediaSource` object created inside a dedicated worker has its own distinct `MediaSourceHandle`. The `handle` getter will always return the `MediaSourceHandle` instance specific to the associated dedicated worker `MediaSource` instance. If the handle has already been transferred to the main thread using `postMessage()`, the handle instance in the worker is technically detached and can't be transferred again.

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

Value
-----

A `MediaSourceHandle` object instance.

Examples
--------

The `handle` property can be accessed inside a dedicated worker and the resulting `MediaSourceHandle` object is then transferred over to the thread that created the worker (in this case the main thread) via a `postMessage()` call:

```js
// Inside dedicated worker
let mediaSource = new MediaSource();
let handle = mediaSource.handle;
// Transfer the handle to the context that created the worker
postMessage({ arg: handle }, [handle]);

mediaSource.addEventListener("sourceopen", () => {
  // Await sourceopen on MediaSource before creating SourceBuffers
  // and populating them with fetched media — MediaSource won't
  // accept creation of SourceBuffers until it is attached to the
  // HTMLMediaElement and its readyState is "open"
});
```

Over in the main thread, we receive the handle via a `message` event handler, attach it to a `<video>` via its `HTMLMediaElement.srcObject` property, and `play` the video:

```js
worker.addEventListener("message", (msg) => {
  let mediaSourceHandle = msg.data.arg;
  video.srcObject = mediaSourceHandle;
  video.play();
});
```

**Note:** `MediaSourceHandle`s cannot be successfully transferred into or via a shared worker or service worker.

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-handle |

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

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

See also
--------

* MSE-in-Workers Demo by Matt Wolenetz
* Media Source Extensions API
* `MediaSource`
* `SourceBuffer`


MediaSource: MediaSource() constructor - Web APIs

MediaSource: MediaSource() constructor
======================================

 The **`MediaSource()`** constructor of the
 `MediaSource` interface constructs and returns a new
 `MediaSource` object with no associated source buffers.

Syntax
------

```js
new MediaSource()
```

### Parameters

None.

Examples
--------

The following snippet is taken from a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation).

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

const assetURL = "frag\_bunny.mp4";
// Need to be specific for Blink regarding codecs
// ./mp4info frag\_bunny.mp4 | grep Codec
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';

if ("MediaSource" in window && MediaSource.isTypeSupported(mimeCodec)) {
  const mediaSource = new MediaSource();
  //console.log(mediaSource.readyState); // closed
  video.src = URL.createObjectURL(mediaSource);
  mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
  console.error("Unsupported MIME type or codec: ", mimeCodec);
}

// …
```

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

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

See also
--------

* `SourceBuffer`
* `SourceBufferList`


MediaSource: removeSourceBuffer() method - Web APIs

MediaSource: removeSourceBuffer() method
========================================

The **`removeSourceBuffer()`** method of the `MediaSource` interface removes the given `SourceBuffer` from the `SourceBufferList` associated with this `MediaSource` object.

Syntax
------

```js
removeSourceBuffer(sourceBuffer)
```

### Parameters

`sourceBuffer`

The `SourceBuffer` object to be removed.

### Return value

None (`undefined`).

### Exceptions

`NotFoundError` `DOMException`

Thrown if the supplied sourceBuffer doesn't exist in `MediaSource.sourceBuffers`.

Examples
--------

```js
for (let i = 0; i < 10; i++) {
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
}

mediaSource.removeSourceBuffer(mediaSource.sourceBuffers[0]);
```

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-removesourcebuffer |

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

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

See also
--------

* `SourceBuffer`
* `SourceBufferList`


MediaSource: setLiveSeekableRange() method - Web APIs

MediaSource: setLiveSeekableRange() method
==========================================

 The **`setLiveSeekableRange()`** method of the
 `MediaSource` interface sets the range that the user can seek to in the
 media element.

Syntax
------

```js
setLiveSeekableRange(start, end)
```

### Parameters

`start`

 The start of the seekable range to set in seconds measured from the beginning of the
 source. If the duration of the media source is positive infinity, then the
 `TimeRanges` object returned by the
 `HTMLMediaElement.seekable` property will have a start timestamp no
 greater than this value.

`end`

 The end of the seekable range to set in seconds measured from the beginning of the
 source. If the duration of the media source is positive infinity, then the
 `TimeRanges` object returned by the
 `HTMLMediaElement.seekable` property will have an end timestamp no
 less than this value.

### Return value

None (`undefined`).

Examples
--------

```js
// TBD
```

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-setliveseekablerange |

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

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


MediaSource: clearLiveSeekableRange() method - Web APIs

MediaSource: clearLiveSeekableRange() method
============================================

 The **`clearLiveSeekableRange()`** method of the
 `MediaSource` interface clears a seekable range previously set with a call
 to `setLiveSeekableRange()`.

Syntax
------

```js
clearLiveSeekableRange()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-clearliveseekablerange |

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

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


MediaSource: isTypeSupported() static method - Web APIs

MediaSource: isTypeSupported() static method
============================================

The **`MediaSource.isTypeSupported()`** static method returns a boolean value which is `true` if the given MIME type and (optional) codec are *likely* to be supported by the current user agent.

 That is, if it can successfully create `SourceBuffer` objects for that media type.
 If the returned value is `false`, then the user agent is certain that it *cannot* access media of the specified format.

Syntax
------

```js
MediaSource.isTypeSupported(type)
```

### Parameters

`type`

A string specifying the MIME type of the media and (optionally) a `codecs` parameter containing a comma-separated list of the supported codecs.

### Return value

A value of `false` if the media of the given type will *not* play.

 A value of `true` is returned if the browser can *probably* play media of the specified type.
 This is *not* a guarantee, and your code must be prepared for the possibility that the media will not play correctly if at all.

 All web APIs that work with media files use a "no/maybe/probably" approach (or, in this case, "no or probably") when determining if a media type can be used.
 This is because media files are complex, intricate constructs with far too many subtle variations to be absolutely certain of anything until you actually use the contents of the media.

Examples
--------

The following snippet is from an example written by Nick Desaulniers (view the full demo live, or download the source for further investigation). The function `getMediaSource()`, which is not defined here, returns a `MediaSource`.

```js
const assetURL = "frag\_bunny.mp4";
// Need to be specific for Blink regarding codecs
// ./mp4info frag\_bunny.mp4 | grep Codec
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
let mediaSource;

if ("MediaSource" in window && MediaSource.isTypeSupported(mimeCodec)) {
  mediaSource = getMediaSource();
  console.log(mediaSource.readyState); // closed
  video.src = URL.createObjectURL(mediaSource);
  mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
  console.error("Unsupported MIME type or codec: ", mimeCodec);
}

function sourceOpen() {
  console.log(this.readyState); // open
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  fetchAB(assetURL, (buf) => {
    sourceBuffer.addEventListener("updateend", () => {
      mediaSource.endOfStream();
      video.play();
      console.log(mediaSource.readyState); // ended
    });
    sourceBuffer.appendBuffer(buf);
  });
}
```

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-istypesupported |

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

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

See also
--------

* Media Source Extensions API
* Guide to media types and formats on the web
* Codecs in common media types
* `SourceBuffer`
* `SourceBufferList`


MediaSource: activeSourceBuffers property - Web APIs

MediaSource: activeSourceBuffers property
=========================================

 The **`activeSourceBuffers`** read-only property of the
 `MediaSource` interface returns a `SourceBufferList` object
 containing a subset of the `SourceBuffer` objects contained within
 `sourceBuffers` — the list of objects
 providing the selected video track, enabled audio tracks, and shown/hidden text tracks.

Value
-----

 A `SourceBufferList` containing the `SourceBuffer` objects
 for each of the active tracks.

Examples
--------

The following snippet is based on a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation). The function `getMediaSource()`, which is not defined here, returns a `MediaSource`.

```js
const mediaSource = getMediaSource();

function sourceOpen() {
  console.log(mediaSource.readyState); // open
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  fetchAB(assetURL, (buf) => {
    sourceBuffer.addEventListener("updateend", () => {
      mediaSource.endOfStream();
      console.log(mediaSource.activeSourceBuffers);
      // will contain the source buffer that was added above,
      // as it is selected for playing in the video player
      video.play();
      console.log(mediaSource.readyState); // ended
    });
    sourceBuffer.appendBuffer(buf);
  });
}

// …
```

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-activesourcebuffers |

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

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

See also
--------

* `SourceBuffer`
* `SourceBufferList`


MediaSource: addSourceBuffer() method - Web APIs

MediaSource: addSourceBuffer() method
=====================================

 The **`addSourceBuffer()`** method of the
 `MediaSource` interface creates a new `SourceBuffer` of the
 given MIME type and adds it to the `MediaSource`'s
 `sourceBuffers` list. The new
 `SourceBuffer` is also returned.

Syntax
------

```js
addSourceBuffer(mimeType)
```

### Parameters

`mimeType`

 A string specifying the MIME type of the
 `SourceBuffer` to create and add to the `MediaSource`.

### Return value

 A `SourceBuffer` object representing the new source buffer that has been
 created and added to the media source.

### Exceptions

`InvalidAccessError` `DOMException`

 Thrown if the value specified for `mimeType` is an empty string rather than a valid
 MIME type.

`InvalidStateError` `DOMException`

 Thrown if the `MediaSource` is not in the `"open"`
`readyState`.

`NotSupportedError` `DOMException`

 Thrown if the specified `mimeType` isn't supported by the user
 agent, or is not compatible with the MIME types of other
 `SourceBuffer` objects that are already included in the media source's
 `sourceBuffers` list.

`QuotaExceededError` `DOMException`

 Thrown if the user agent can't handle any more `SourceBuffer` objects, or creating
 a new `SourceBuffer` using the given `mimeType` would result in
 an unsupported configuration of `SourceBuffer`s.

Examples
--------

The following snippet is from a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation). The function `getMediaSource()`, which is not defined here, returns a `MediaSource`.

```js
const assetURL = "frag\_bunny.mp4";
// Need to be specific for Blink regarding codecs
// ./mp4info frag\_bunny.mp4 | grep Codec
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
const mediaSource = getMediaSource();

if ("MediaSource" in window && MediaSource.isTypeSupported(mimeCodec)) {
  console.log(mediaSource.readyState); // closed
  mediaSource.addEventListener("sourceopen", sourceOpen);
  video.src = URL.createObjectURL(mediaSource);
} else {
  console.error("Unsupported MIME type or codec: ", mimeCodec);
}

function sourceOpen() {
  console.log(this.readyState); // open
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  fetchAB(assetURL, (buf) => {
    sourceBuffer.addEventListener("updateend", () => {
      mediaSource.endOfStream();
      video.play();
      console.log(mediaSource.readyState); // ended
    });
    sourceBuffer.appendBuffer(buf);
  });
}
```

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-addsourcebuffer |

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

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

See also
--------

* `SourceBuffer`
* `SourceBufferList`


MediaSource: endOfStream() method - Web APIs

MediaSource: endOfStream() method
=================================

 The **`endOfStream()`** method of the
 `MediaSource` interface signals the end of the stream.

Syntax
------

```js
endOfStream()
endOfStream(endOfStreamError)
```

### Parameters

`endOfStreamError` Optional

 A string representing an error to throw when the end of the stream
 is reached. The possible values are:

`network`

 Terminates playback and signals that a network error has
 occurred. This can be used create a custom error handler related to media streams.
 For example, you might have a function that handles media chunk requests, separate
 from other network requests. When you make a `fetch()` request for a media
 chunk and receive a network error, you might want
 to call `endOfStream('network')`, display a descriptive message in the
 UI, and maybe retry the network request immediately or wait until the network is
 back up (via some kind of polling.)

`decode`

 Terminates playback and signals that a decoding error has
 occurred. This can be used to indicate that a parsing error has occurred while
 fetching media data; maybe the data is corrupt, or is encoded using a codec that
 the browser doesn't know how to decode.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

 Thrown if `MediaSource.readyState` is not equal to `open`, or one or more of the `SourceBuffer` objects in `MediaSource.sourceBuffers` are being updated (i.e. their `SourceBuffer.updating` property is
 `true`.)

Examples
--------

The following snippet is from a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation). The function `getMediaSource()`, which is not defined here, returns a `MediaSource`.

```js
const assetURL = "frag\_bunny.mp4";
// Need to be specific for Blink regarding codecs
// ./mp4info frag\_bunny.mp4 | grep Codec
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';

let mediaSource;

if ("MediaSource" in window && MediaSource.isTypeSupported(mimeCodec)) {
  mediaSource = getMediaSource();
  console.log(mediaSource.readyState); // closed
  video.src = URL.createObjectURL(mediaSource);
  mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
  console.error("Unsupported MIME type or codec: ", mimeCodec);
}

function sourceOpen() {
  console.log(this.readyState); // open
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  fetchAB(assetURL, (buf) => {
    sourceBuffer.addEventListener("updateend", () => {
      mediaSource.endOfStream();
      video.play();
      console.log(mediaSource.readyState); // ended
    });
    sourceBuffer.appendBuffer(buf);
  });
}
```

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-endofstream |

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

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

See also
--------

* `SourceBuffer`
* `SourceBufferList`


MediaSource: duration property - Web APIs

MediaSource: duration property
==============================

 The **`duration`** property of the `MediaSource`
 interface gets and sets the duration of the current media being presented.

Value
-----

A double. A value in seconds is expected.

### Exceptions

The following exceptions may be thrown when setting a new value for this property.

`InvalidAccessError` `DOMException`

Thrown if an attempt was made to set a duration value that was negative or `NaN`.

`InvalidStateError` `DOMException`

 Thrown if `MediaSource.readyState` is not equal to
 `open`, or one or more of the
 `SourceBuffer` objects in
 `MediaSource.sourceBuffers` are being updated
 (i.e. their `SourceBuffer.updating` property is
 `true`.)

Examples
--------

The following snippet is based on a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation). The function `getMediaSource()`, which is not defined here, returns a `MediaSource`.

```js
const mediaSource = getMediaSource();

function sourceOpen() {
  console.log(this.readyState); // open
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  fetchAB(assetURL, (buf) => {
    sourceBuffer.addEventListener("updateend", () => {
      mediaSource.endOfStream();
      mediaSource.duration = 120;
      video.play();
      console.log(mediaSource.readyState); // ended
    });
    sourceBuffer.appendBuffer(buf);
  });
}

// …
```

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-duration |

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

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

See also
--------

* `SourceBuffer`
* `SourceBufferList`


MediaSource: sourceBuffers property - Web APIs

MediaSource: sourceBuffers property
===================================

 The **`sourceBuffers`** read-only property of the
 `MediaSource` interface returns a `SourceBufferList` object
 containing the list of `SourceBuffer` objects associated with this
 `MediaSource`.

Value
-----

A `SourceBufferList`.

Examples
--------

The following snippet is based on a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation). The function `getMediaSource()`, which is not defined here, returns a `MediaSource`.

```js
const mediaSource = getMediaSource();

function sourceOpen() {
  console.log(this.readyState); // open
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  fetchAB(assetURL, (buf) => {
    sourceBuffer.addEventListener("updateend", () => {
      mediaSource.endOfStream();
      console.log(mediaSource.sourceBuffers); // will contain the source buffer that was added above
      video.play();
      console.log(mediaSource.readyState); // ended
    });
    sourceBuffer.appendBuffer(buf);
  });
}

// …
```

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-sourcebuffers |

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

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

See also
--------

* `SourceBuffer`
* `SourceBufferList`


MediaSource: canConstructInDedicatedWorker static property - Web APIs

MediaSource: canConstructInDedicatedWorker static property
==========================================================

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

The **`canConstructInDedicatedWorker`** static property of the `MediaSource` interface returns `true` if `MediaSource` worker support is implemented, providing a low-latency feature detection mechanism.

If this were not available, the alternative would be a much higher latency approach such as attempting the creation of a `MediaSource` object from a dedicated worker and transferring the result back to the main thread.

Value
-----

A boolean. Returns `true` if `MediaSource` worker support is implemented, or `false` otherwise.

Examples
--------

```js
if (MediaSource.canConstructInDedicatedWorker) {
  // MSE is available in workers; let's do this
}
```

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-canconstructindedicatedworker |

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

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

See also
--------

* MSE-in-Workers Demo by Matt Wolenetz
* Media Source Extensions API
* `MediaSource`
* `SourceBuffer`


MediaSource: readyState property - Web APIs

MediaSource: readyState property
================================

 The **`readyState`** read-only property of the
 `MediaSource` interface returns an enum representing the state of the
 current `MediaSource`. The three possible values are:

* `closed`: The source is not currently attached to a media element.
* `open`: The source is attached to a media element and ready to receive
 `SourceBuffer` objects.
* `ended`: The source is attached to a media element but the stream has
 been ended via a call to `MediaSource.endOfStream()`.
Value
-----

A string.

Examples
--------

The following snippet is from a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation). The function `getMediaSource()`, which is not defined here, returns a `MediaSource`.

```js
let mediaSource;

if ("MediaSource" in window && MediaSource.isTypeSupported(mimeCodec)) {
  mediaSource = getMediaSource();
  console.log(mediaSource.readyState); // closed
  video.src = URL.createObjectURL(mediaSource);
  mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
  console.error("Unsupported MIME type or codec: ", mimeCodec);
}

function sourceOpen() {
  console.log(this.readyState); // open
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  fetchAB(assetURL, (buf) => {
    sourceBuffer.addEventListener("updateend", () => {
      mediaSource.endOfStream();
      video.play();
      console.log(mediaSource.readyState); // ended
    });
    sourceBuffer.appendBuffer(buf);
  });
}
```

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

| Specification |
| --- |
| Media Source Extensions™ # dom-mediasource-readystate |

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

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

See also
--------

* `SourceBuffer`
* `SourceBufferList`


PaymentRequestEvent: topOrigin property - Web APIs

PaymentRequestEvent: topOrigin property
=======================================

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

 The **`topOrigin`** read-only property of the
 `PaymentRequestEvent` interface returns the top-level payee origin where
 the `PaymentRequest` object was initialized.

Value
-----

A string.

Examples
--------

```js
self.addEventListener("paymentrequest", (e) => {
  console.log(e.topOrigin);
});
```

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

| Specification |
| --- |
| Payment Handler API # dom-paymentrequestevent-toporigin |

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

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

See also
--------

* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


PaymentRequestEvent: methodData property - Web APIs

PaymentRequestEvent: methodData property
========================================

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

 The **`methodData`** read-only property of the
 `PaymentRequestEvent` interface returns an array of
 `PaymentMethodData` objects containing payment method identifiers for the
 payment methods that the website accepts and any associated payment method-specific
 data.

Value
-----

An array of `PaymentMethodData` objects. Each object contains the following properties:

`supportedMethods`

A payment method identifier for a payment method that the merchant website accepts.

`data`

An object that provides optional information that might be needed by the supported payment methods. If supplied, it will be JSON-serialized.

Examples
--------

```js
self.addEventListener("paymentrequest", (e) => {
  console.log(e.methodData);
});
```

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

| Specification |
| --- |
| Payment Handler API # dom-paymentrequestevent-methoddata |

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

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

See also
--------

* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


PaymentRequestEvent: openWindow() method - Web APIs

PaymentRequestEvent: openWindow() method
========================================

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

The **`openWindow()`** method of the `PaymentRequestEvent` interface opens the specified URL in a new window, only if the given URL is on the same origin as the calling page. It returns a `Promise` that resolves with a reference to a `WindowClient`.

Syntax
------

```js
openWindow(url)
```

### Parameters

`url`

 The URL to open in the new window. It must be on the same origin as the calling
 page.

### Return value

 A `Promise` that resolves with a reference to a
 `WindowClient`.

Examples
--------

```js
…
self.addEventListener('paymentrequest', async e => {
…
  // Retain a promise for future resolution
  // Polyfill for PromiseResolver at link below.
  resolver = new PromiseResolver();

  // Pass a promise that resolves when payment is done.
  e.respondWith(resolver.promise);
  // Open the checkout page.
  try {
    // Open the window and preserve the client
    client = await e.openWindow(checkoutURL);
    if (!client) {
      // Reject if the window fails to open
      throw 'Failed to open window';
    }
  } catch (err) {
    // Reject the promise on failure
    resolver.reject(err);
  };
});
…
```

See Open the payment handler window to display the web-based payment app frontend for more details about how this would be used.

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

| Specification |
| --- |
| Payment Handler API # dom-paymentrequestevent-openwindow |

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

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

See also
--------

* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


PaymentRequestEvent: paymentRequestId property - Web APIs

PaymentRequestEvent: paymentRequestId property
==============================================

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

 The **`paymentRequestId`** read-only property of the
 `PaymentRequestEvent` interface returns the ID of the
 `PaymentRequest` object.

Value
-----

A string containing the ID.

Examples
--------

```js
self.addEventListener("paymentrequest", (e) => {
  console.log(e.paymentRequestId);
});
```

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

| Specification |
| --- |
| Payment Handler API # dom-paymentrequestevent-paymentrequestid |

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

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

See also
--------

* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


PaymentRequestEvent: instrumentKey property - Web APIs

PaymentRequestEvent: instrumentKey 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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`instrumentKey`** read-only property of the
 `PaymentRequestEvent` interface returns a
 `PaymentInstrument` object reflecting the payment instrument selected by
 the user or an empty string if the user has not registered or chosen a payment
 instrument.

Value
-----

A `PaymentInstrument` object.

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

This feature is no longer part of any specification.

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

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


PaymentRequestEvent: respondWith() method - Web APIs

PaymentRequestEvent: respondWith() method
=========================================

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

The **`respondWith()`** method of the `PaymentRequestEvent` interface prevents the default event handling and allows you to provide a `Promise` for a `PaymentResponse` object yourself.

Syntax
------

```js
respondWith(promise)
```

### Parameters

`promise`

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

### Return value

A `PaymentHandlerResponse` object. This contains the following properties:

`methodName`

The payment method identifier for the payment method that the user selected to fulfill the transaction.

`details`

A JSON-serializable object that provides a payment method-specific message used by the merchant to process the transaction and determine a successful fund transfer. See 7.1.2 details attribute for more details.

Examples
--------

```js
…
self.addEventListener('paymentrequest', async e => {
…
  // Retain a promise for future resolution
  // Polyfill for PromiseResolver at link below.
  resolver = new PromiseResolver();

  // Pass a promise that resolves when payment is done.
  e.respondWith(resolver.promise);
  // Open the checkout page.
  try {
    // Open the window and preserve the client
    client = await e.openWindow(checkoutURL);
    if (!client) {
      // Reject if the window fails to open
      throw 'Failed to open window';
    }
  } catch (err) {
    // Reject the promise on failure
    resolver.reject(err);
  };
});
…
```

See Open the payment handler window to display the web-based payment app frontend for more details about how this would be used.

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

| Specification |
| --- |
| Payment Handler API # dom-paymentrequestevent-respondwith |

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

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

See also
--------

* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


PaymentRequestEvent: total property - Web APIs

PaymentRequestEvent: total property
===================================

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

 The **`total`** read-only property of the `PaymentRequestEvent` interface returns a
 `PaymentCurrencyAmount` object containing the total amount being requested for payment.

Value
-----

A `PaymentCurrencyAmount` object. This object contains the following properties:

`currency`

A string containing a three-letter ISO 4217 standard currency code representing the currency of the payment. Examples include `USD`, `CAN`, and `GBP`.

`value`

A string containing a decimal monetary value, e.g. `2.55`.

Examples
--------

```js
self.addEventListener("paymentrequest", (e) => {
  console.log(e.total);
});
```

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

| Specification |
| --- |
| Payment Handler API # dom-paymentrequestevent-total |

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

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

See also
--------

* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


PaymentRequestEvent: changePaymentMethod() method - Web APIs

PaymentRequestEvent: changePaymentMethod() method
=================================================

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

The **`changePaymentMethod()`** method of the `PaymentRequestEvent` interface is used by the payment handler to get an updated total, given such payment method details as the billing address.

When this method is invoked, a `PaymentMethodChangeEvent` is fired.

Syntax
------

```js
changePaymentMethod(methodName)
changePaymentMethod(methodName, methodDetails)
```

### Parameters

`methodName`

The name of the payment method to be used.

`methodDetails` Optional

An object containing method-specific details that are being updated.

### Return value

A `Promise` that resolves with a `PaymentRequestDetailsUpdate` object. This object contains the following properties:

`error`

A string that explains why the user-selected payment method cannot be used.

`total`

An updated total based on the changed payment method. The total can change, for example, because the billing address of the payment method selected by the user changes the applicable sales tax.

`modifiers`

An `Array` of `PaymentDetailsModifier` objects, whose properties are described in `PaymentRequestEvent.modifiers`.

`paymentMethodErrors`

An object containing validation errors for the payment method, if any.

Examples
--------

The following shows a trivial code snippet that could be used in a service worker to send a payment method change notification to the main payment handler window. For a complete test example, see Payment handler for testing payment method change event.

```js
function notifyPaymentMethodChanged(e) {
  e.changePaymentMethod("someMethod")
    .then((paymentMethodChangeResponse) => {
      paymentHandlerWindow.postMessage(paymentMethodChangeResponse);
    })
    .catch((error) => {
      sendMessage({ error: error.message });
    });
}
```

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

| Specification |
| --- |
| Payment Handler API # changepaymentmethod-method |

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

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

See also
--------

* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


PaymentRequestEvent: modifiers property - Web APIs

PaymentRequestEvent: modifiers property
=======================================

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

 The **`modifiers`** read-only property of the
 `PaymentRequestEvent` interface returns an `Array` of `PaymentDetailsModifier` objects containing modifiers for payment details.

Value
-----

An array of objects containing modifiers for payment details. These objects contain the following properties:

`supportedMethods`

A payment method identifier. The members of the object only apply to the payment if the user selects this payment method.

`total`

A `PaymentItem` object containing the following properties:

`label`

A string containing a human-readable description of the item, which may be displayed to the user.

`amount`

A `PaymentCurrencyAmount` object (see `total` > Value).

`pending`

A boolean. When set to true it means that the `amount` member is not final. This is commonly used to show items such as shipping or tax amounts that depend upon selection of shipping address or shipping option.

`additionalDisplayItems`

An array of `PaymentItem` objects providing additional display items to be included in the payment details. This member is commonly used to add a discount or surcharge line item indicating the reason for the different total amount for the selected payment method that the user agent MAY display.

`data`

An object that provides optional information that might be needed by the supported payment methods. If supplied, it will be JSON-serialized.

Examples
--------

```js
self.addEventListener("paymentrequest", (e) => {
  console.log(e.modifiers);
});
```

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

| Specification |
| --- |
| Payment Handler API # dom-paymentrequestevent-modifiers |

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

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

See also
--------

* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


PaymentRequestEvent: paymentRequestOrigin property - Web APIs

PaymentRequestEvent: paymentRequestOrigin property
==================================================

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

 The **`paymentRequestOrigin`** read-only property of the
 `PaymentRequestEvent` interface returns the origin where the
 `PaymentRequest` object was initialized.

Value
-----

A string.

Examples
--------

```js
self.addEventListener("paymentrequest", (e) => {
  console.log(e.paymentRequestOrigin);
});
```

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

| Specification |
| --- |
| Payment Handler API # dom-paymentrequestevent-paymentrequestorigin |

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

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

See also
--------

* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


PaymentRequestEvent: PaymentRequestEvent() constructor - Web APIs

PaymentRequestEvent: PaymentRequestEvent() constructor
======================================================

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

The **`PaymentRequestEvent`** constructor creates a new `PaymentRequestEvent` object instance.

Syntax
------

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

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers set it to `paymentrequest`.

`options` Optional

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

`methodData`

 An array of `PaymentMethodData` objects (see `methodData` > Value) containing payment method identifiers for the payment methods
 that the website accepts and any associated payment method-specific data.

`modifiers`

An array of objects containing changes to payment details.

`paymentRequestId`

The ID of the `PaymentRequest` object.

`paymentRequestOrigin`

The origin where the `PaymentRequest` object was initialized.

`topOrigin`

The top-level origin where the `PaymentRequest` object was initialized.

`total`

The total amount being requested for payment.

Return value
------------

A new `PaymentRequestEvent` object.

Examples
--------

A developer would not use this constructor manually. A new `PaymentRequestEvent` object is constructed when a handler is invoked as a result of the `paymentrequest` event firing.

```js
self.addEventListener("paymentrequest", (e) => {
  // ...
});
```

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

| Specification |
| --- |
| Payment Handler API # dom-paymentrequestevent-constructor |

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

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

See also
--------

* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


PointerEvent: getCoalescedEvents() method - Web APIs

PointerEvent: getCoalescedEvents() method
=========================================

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

 The **`getCoalescedEvents()`** method of the `PointerEvent` interface returns a sequence of `PointerEvent` instances that were coalesced (merged) into a single `pointermove` or `pointerrawupdate` event.
 Instead of a stream of many `pointermove` events, user agents coalesce multiple updates into a single event.
 This helps with performance as the user agent has less event handling to perform, but there is a reduction in the granularity and accuracy when tracking, especially with fast and large movements.

 The **`getCoalescedEvents()`** method lets applications access all un-coalesced position changes for precise handling of pointer movement data where necessary.
 Un-coalesced position changes are desirable in drawing applications, for instance, where having access to all events helps to build smoother curves that better match the movement of a pointer.

For an illustration of coalesced events, see Figure 7 in the specification.

Syntax
------

```js
getCoalescedEvents()
```

### Parameters

None.

### Return value

A sequence of `PointerEvent` instances.

Example
-------

### HTML

```html
<canvas id="target" width="600" height="300"></canvas>
```

### JavaScript

```js
const canvas = document.getElementById("target");
const ctx = canvas.getContext("2d");

const pointerEvents = [];

function drawCircle(x, y, color) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // draw the last 20 events
  if (pointerEvents.length > 20) {
    pointerEvents.shift();
  }
  pointerEvents.push({ x, y, color });

  for (const pointerEvent of pointerEvents) {
    ctx.beginPath();
    ctx.arc(pointerEvent.x, pointerEvent.y, 10, 0, 2 \* Math.PI);
    ctx.strokeStyle = pointerEvent.color;
    ctx.stroke();
  }
}

canvas.addEventListener("pointermove", (e) => {
  // draw a circle for the current event
  drawCircle(e.clientX, e.clientY, "black");

  const coalescedEvents = e.getCoalescedEvents();
  for (let coalescedEvent of coalescedEvents) {
    // give it an offset so we can see the difference and color it red
    drawCircle(coalescedEvent.clientX + 20, coalescedEvent.clientY + 20, "red");
  }
});
```

### Result

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-getcoalescedevents |

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

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


PointerEvent: isPrimary property - Web APIs

PointerEvent: isPrimary property
================================

 The **`isPrimary`** read-only property of the
 `PointerEvent` interface indicates whether or not the pointer device that
 created the event is the *primary* pointer. It returns `true` if the
 pointer that caused the event to be fired is the primary one and returns
 `false` otherwise.

 In a multi-pointer scenario (such as a touch screen that supports more than one touch
 point), this property is used to identify a *master pointer* among the set of
 active pointers for each pointer type. Only a primary pointer will produce
 *compatibility mouse events*. Authors who desire only single-pointer interaction
 can achieve that by ignoring non-primary pointers.

 A pointer is considered primary if the pointer represents a mouse device. A pointer
 representing pen input is considered the primary pen input if its
 `pointerdown` event was dispatched when no other active pointers representing
 pen input existed. A pointer representing touch input is considered the primary touch
 input if its `pointerdown` event was dispatched when no other active pointers
 representing touch input existed.

 When two or more pointer device types are being used concurrently, multiple pointers
 (one for each `pointerType`) are considered
 primary. For example, a touch contact and a mouse cursor moved simultaneously will
 produce pointers that are both considered primary. If there are multiple primary
 pointers, these pointers will all produce *compatibility mouse events* (see
 `Pointer_events` for more information about pointer, mouse and touch
 interaction).

Value
-----

A boolean, `true` if the pointer for this event is the primary pointer and returns `false` otherwise.

Examples
--------

 This example illustrates using the value of `isPrimary` to call the
 appropriate processing function.

```js
target.addEventListener(
  "pointerdown",
  (event) => {
    if (event.isPrimary) {
      process\_primary\_pointer(event);
    } else {
      process\_secondary\_pointer(event);
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-isprimary |

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

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


PointerEvent: PointerEvent() constructor - Web APIs

PointerEvent: PointerEvent() constructor
========================================

 The **`PointerEvent()`** constructor creates a new synthetic
 and untrusted `PointerEvent` object instance.

Syntax
------

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

### Parameters

`type`

 A string representing the name of the event
 (see PointerEvent event types).

`options` Optional

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

`pointerId`

A number, defaulting to `0`, that sets the value of the instance's `PointerEvent.pointerId`.

`width`

A number,, defaulting to `1`, that sets the value of the instance's `PointerEvent.width`.

`height`

A number,, defaulting to `1`, that sets the value of the instance's `PointerEvent.height`.

`pressure`

A number, defaulting to `0`, that sets the value of the instance's `PointerEvent.pressure`.

`tangentialPressure`

A number, defaulting to `0`, that sets the value of the instance's `PointerEvent.tangentialPressure`.

`tiltX`

A number, defaulting to `0`, that sets the value of the instance's `PointerEvent.tiltX`.

`tiltY`

A number, defaulting to `0`, that sets the value of the instance's `PointerEvent.tiltY`.

`twist`

A number, defaulting to `0`, that sets the value of the instance's `PointerEvent.twist`.

`pointerType`

A string, defaulting to `""` that sets the value of the instance's `PointerEvent.pointerType`.

`isPrimary`

A boolean value, defaulting to `false` that sets the value of the instance's `PointerEvent.isPrimary`.

### Return value

A new `PointerEvent` object.

Examples
--------

```js
const moveEvent = new PointerEvent("pointermove");

const downEvent = new PointerEvent("pointerdown", {
  pointerId: 1,
  bubbles: true,
  cancelable: true,
  pointerType: "touch",
  width: 100,
  height: 100,
  isPrimary: true,
});
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-constructor |

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

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


PointerEvent: twist property - Web APIs

PointerEvent: twist property
============================

 The **`twist`** read-only property of the
 `PointerEvent` interface represents the clockwise rotation of the pointer
 (e.g., pen stylus) around its major axis, in degrees.

Value
-----

 A `long` value representing the amount of twist, in degrees, applied to the
 transducer (pointer). The value is in the range `0` to `359`,
 inclusive. For devices that do not report `twist`, the value is
 `0`.

Examples
--------

 When a `pointerdown` event is fired, different functions are called
 depending on the value of the event's `twist` property.

```js
someElement.addEventListener(
  "pointerdown",
  (event) => {
    if (event.twist === 0) {
      // No twist
      process\_no\_twist(event);
    } else {
      // Default
      process\_twist(event);
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-twist |

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

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

See also
--------

* `Touch.force`


PointerEvent: height property - Web APIs

PointerEvent: height property
=============================

 The **`height`** read-only property of the
 `PointerEvent` interface represents the height of the pointer's contact
 geometry, along the y-axis (in CSS pixels). Depending on the source of the pointer
 device (for example a finger), for a given pointer, each event may produce a different
 value.

 If the input hardware cannot report the contact geometry to the browser, the height
 defaults to `1`.

Value
-----

The height of the event's contact area (in CSS pixels).

Examples
--------

An example of this property is included in the PointerEvent.width example.

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-height |

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

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


PointerEvent: altitudeAngle property - Web APIs

PointerEvent: altitudeAngle property
====================================

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

 The **`altitudeAngle`** read-only property of the `PointerEvent` interface represents the angle between a transducer (a pointer or stylus) axis and the X-Y plane of a device screen.
 The altitude angle describes whether the transducer is perpendicular to the screen, parallel, or at some angle in between.

Depending on the specific hardware and platform, user agents will likely only receive one set of values for the transducer orientation relative to the screen plane — either `tiltX` and `tiltY` or `altitudeAngle` and `azimuthAngle`.

![The azimuth angle of a pointer compared to the altitude angle](/en-US/docs/Web/API/PointerEvent/altitudeAngle/azimuth_altitude_angles.svg)

For an additional illustration of this property, see Figure 4 in the specification.

Value
-----

 An angle in radians between `0` and `π/2` where `0` is parallel to the device surface (X-Y plane), and `π/2` is perpendicular to the surface.
 Defaults to `π/2` (perpendicular to the surface) which differs from the `altitudeAngle` in touch events which defaults to `0` (parallel to the surface).
 For hardware and platforms that do not report tilt or angle, the value is `π/2`.

Example
-------

```js
someElement.addEventListener(
  "pointerdown",
  (event) => {
    process\_angles(event.altitudeAngle, event.azimuthAngle);
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-altitudeangle |

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

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

See also
--------

* `PointerEvent.azimuthAngle`
* `PointerEvent.tiltX`
* `PointerEvent.tiltY`


PointerEvent: tiltX property - Web APIs

PointerEvent: tiltX property
============================

 The **`tiltX`** read-only property of the
 `PointerEvent` interface is the angle (in degrees) between the *Y-Z
plane* of the pointer and the screen. This property is typically only useful for a
 pen/stylus pointer type.

For an illustration of this property see Figure 2 in the specification.

Value
-----

The angle in degrees between the Y-Z plane of the pointer (stylus) and the screen. The range of values is `-90` to `90`, inclusive, where a positive value is a tilt to the right. For devices that do not support this property, the value is `0`.

Examples
--------

 This example illustrates simple accessing of the `tiltX` and
 `tiltY` properties.

```js
someElement.addEventListener(
  "pointerdown",
  (event) => {
    process\_tilt(event.tiltX, event.tiltY);
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-tiltx |

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

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


PointerEvent: pointerType property - Web APIs

PointerEvent: pointerType property
==================================

 The **`pointerType`** read-only property of the
 `PointerEvent` interface indicates the device type (mouse, pen, or touch)
 that caused a given pointer event.

Value
-----

The event's pointer type. The supported values are the following strings:

`"mouse"`

The event was generated by a mouse device.

`"pen"`

The event was generated by a pen or stylus device.

`"touch"`

The event was generated by a touch, such as a finger.

 If the device type cannot be detected by the browser, the value can be an empty string
 (`""`). If the browser supports pointer device types other than those listed
 above, the value should be *vendor-prefixed* to avoid conflicting names for
 different types of devices.

Examples
--------

 This example illustrates using the value of the `pointerType` property to
 call the appropriate pointer type processing function.

```js
targetElement.addEventListener(
  "pointerdown",
  (event) => {
    // Call the appropriate pointer type handler
    switch (event.pointerType) {
      case "mouse":
        process\_pointer\_mouse(event);
        break;
      case "pen":
        process\_pointer\_pen(event);
        break;
      case "touch":
        process\_pointer\_touch(event);
        break;
      default:
        console.log(`pointerType ${event.pointerType} is not supported`);
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-pointertype |

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

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


PointerEvent: tiltY property - Web APIs

PointerEvent: tiltY property
============================

 The **`tiltY`** read-only property of the
 `PointerEvent` interface is the angle (in degrees) between the *X-Z
plane* of the pointer and the screen. This property is typically only useful for a
 pen/stylus pointer type.

For an illustration of this property, see Figure 3 in the specification.

Value
-----

The angle in degrees between the X-Z plane of the pointer (stylus) and the screen. The range of values is `-90` to `90`, inclusive, where a positive value is a tilt towards the user. For devices that do not support this property, the value is `0`.

Examples
--------

 This example illustrates simple accessing of the
 `tiltX` and `tiltY` properties.

```js
someElement.addEventListener(
  "pointerdown",
  (event) => {
    process\_tilt(event.tiltX, event.tiltY);
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-tilty |

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

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


PointerEvent: azimuthAngle property - Web APIs

PointerEvent: azimuthAngle property
===================================

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

The **`azimuthAngle`** read-only property of the `PointerEvent` interface represents the angle between the Y-Z plane and the plane containing both the transducer (pointer or stylus) axis and the Y axis.

Depending on the specific hardware and platform, user agents will likely only receive one set of values for the transducer orientation relative to the screen plane — either `tiltX` and `tiltY` or `altitudeAngle` and `azimuthAngle`.

![The azimuth angle of a pointer compared to the altitude angle](/en-US/docs/Web/API/PointerEvent/azimuthAngle/azimuth_altitude_angles.svg)

For an additional illustration of this property, see Figure 5 in the specification.

Value
-----

An angle in radians between `0` and `2π` where `0` represents a transducer whose cap is pointing in the direction of increasing X values (point to "3 o'clock" if looking straight down) on the X-Y plane, and the values progressively increase when going clockwise (`π/2` at "6 o'clock", `π` at "9 o'clock", `3π/2` at "12 o'clock").

 When the transducer is perpendicular to the surface (`altitudeAngle` of `π/2`), the value is 0.
 For hardware and platforms that do not report tilt or angle, the value is `0`.

Example
-------

```js
someElement.addEventListener(
  "pointerdown",
  (event) => {
    process\_angles(event.altitudeAngle, event.azimuthAngle);
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-azimuthangle |

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

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

See also
--------

* `PointerEvent.altitudeAngle`
* `PointerEvent.tiltX`
* `PointerEvent.tiltY`


PointerEvent: pressure property - Web APIs

PointerEvent: pressure property
===============================

 The **`pressure`** read-only property of the
 `PointerEvent` interface indicates the normalized pressure of the pointer
 input.

Value
-----

The normalized pressure of the pointer input in the range of `0` to `1`, inclusive, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively. For hardware that does not support pressure, such as a mouse, the value is `0.5` when the pointer is active buttons state and `0` otherwise.

Examples
--------

 In this snippet, when a `pointerdown` event is fired, different functions
 are called depending on the value of the event's `pressure` property.

```js
someElement.addEventListener(
  "pointerdown",
  (event) => {
    if (event.pressure === 0) {
      // No pressure
      process\_no\_pressure(event);
    } else if (event.pressure === 1) {
      // Maximum pressure
      process\_max\_pressure(event);
    } else {
      // Default
      process\_pressure(event);
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-pressure |

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

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

See also
--------

* `Touch.force`


PointerEvent: getPredictedEvents() method - Web APIs

PointerEvent: getPredictedEvents() method
=========================================

 The **`getPredictedEvents()`** method of the `PointerEvent` interface returns a sequence of `PointerEvent` instances that are estimated future pointer positions.
 How the predicted positions are calculated depends on the user agent, but they are based on past points, current velocity, and trajectory.

Applications can use the predicted events to "draw ahead" to a predicted position which may reduce perceived latency depending on the application's interpretation of the predicted events and the use case.

For an illustration of predicted events, see Figure 8 in the specification.

Syntax
------

```js
getPredictedEvents()
```

### Parameters

None.

### Return value

A sequence of `PointerEvent` instances.

Example
-------

### HTML

```html
<canvas id="target" width="600" height="300"></canvas>
```

### JavaScript

```js
const canvas = document.getElementById("target");
const ctx = canvas.getContext("2d");

const pointerEvents = [];

function drawCircle(x, y, color) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // draw the last 20 events
  if (pointerEvents.length > 20) {
    pointerEvents.shift();
  }
  pointerEvents.push({ x, y, color });

  for (const pointerEvent of pointerEvents) {
    ctx.beginPath();
    ctx.arc(pointerEvent.x, pointerEvent.y, 10, 0, 2 \* Math.PI);
    ctx.strokeStyle = pointerEvent.color;
    ctx.stroke();
  }
}

canvas.addEventListener("pointermove", (e) => {
  // draw a circle for the current event
  drawCircle(e.clientX, e.clientY, "black");

  const predictedEvents = e.getPredictedEvents();
  for (let predictedEvent of predictedEvents) {
    // give it an offset so we can see the difference and color it red
    drawCircle(predictedEvent.clientX + 20, predictedEvent.clientY + 20, "red");
  }
});
```

### Result

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-getpredictedevents |

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

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


PointerEvent: width property - Web APIs

PointerEvent: width property
============================

 The **`width`** read-only property of the
 `PointerEvent` interface represents the width of the pointer's contact
 geometry along the x-axis, measured in CSS pixels. Depending on the source of the
 pointer device (such as a finger), for a given pointer, each event may produce a
 different value.

 If the input hardware cannot report the contact geometry to the browser, the width
 defaults to `1`.

Value
-----

The width of the event's contact area (in CSS pixels).

Examples
--------

 This example illustrates using the `PointerEvent` interface's
 `width` and
 `height` properties to calculate the contact area.

```js
target.addEventListener(
  "pointerdown",
  (ev) => {
    // Calculate the contact area
    const area = ev.width \* ev.height;
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-width |

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

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


PointerEvent: tangentialPressure property - Web APIs

PointerEvent: tangentialPressure property
=========================================

 The **`tangentialPressure`** read-only property of the
 `PointerEvent` interface represents the normalized tangential pressure of
 the pointer input (also known as barrel pressure or cylinder stress).

Value
-----

 A `float` representing the normalized tangential pressure of the pointer
 input in the range `-1` to `1`, inclusive, where `0` is
 the neutral position of the control.

 Note that some hardware may only support positive values in the range `0` to
 `1`. For hardware that does not support tangential pressure, the value will
 be `0`.

Examples
--------

 In this snippet, when a `pointerdown` event is fired, different functions
 are called depending on the value of the event's `tangentialPressure`
 property.

```js
someElement.addEventListener(
  "pointerdown",
  (event) => {
    if (event.tangentialPressure === 0) {
      // No pressure
      process\_no\_tanPressure(event);
    } else if (event.tangentialPressure === 1) {
      // Maximum pressure
      process\_max\_tanPressure(event);
    } else {
      // Default
      process\_tanPressure(event);
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-tangentialpressure |

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

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

See also
--------

* `Touch.force`


PointerEvent: pointerId property - Web APIs

PointerEvent: pointerId property
================================

 The **`pointerId`** read-only property of the
 `PointerEvent` interface is an identifier assigned to a given pointer
 event. The identifier is unique, being different from the identifiers of all other
 active pointer events. Since the value may be randomly generated, it is not guaranteed
 to convey any particular meaning.

Value
-----

A number.

Examples
--------

 The following code snippet compares a previously saved `pointerId` with the
 one of the `pointerdown` event that was just fired.

```js
let id; // Let's assume that this is a previously saved pointerId

target.addEventListener(
  "pointerdown",
  (event) => {
    // Compare previous event's ID that was cached
    // to current event's ID and handle accordingly
    if (id === event.pointerId) process\_event(event);
  },
  false,
);
```

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

| Specification |
| --- |
| Pointer Events # dom-pointerevent-pointerid |

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

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


XRRigidTransform: matrix property - Web APIs

XRRigidTransform: matrix property
=================================

 The read-only `XRRigidTransform` property
 **`matrix`** returns the transform
 matrix represented by the object. The returned matrix can then be premultiplied with a
 column vector to rotate the
 vector by the 3D rotation specified by the `orientation`, then translate
 it by the `position`.

Value
-----

 A `Float32Array` containing 16 entries which represents the 4x4 transform
 matrix which is described by
 the `position` and
 `orientation` properties.

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

### Matrix format

 All 4x4 transform matrices used in WebGL are stored in 16-element
 `Float32Array`s. The values are stored
 into the array in column-major order; that is, each column is written into the array
 top-down before moving to the
 right one column and writing the next column into the array. Thus, for an array [a0, a1,
 a2, …, a13, a14, a15], the
 matrix looks like this:

[

a0

a4

a8

a12

a1

a5

a9

a13

a2

a6

a10

a14

a3

a7

a11

a15

]

 \begin{bmatrix} a[0] & a[4] & a[8] & a[12]\
 a[1] & a[5] & a[9]
 & a[13]\ a[2] & a[6] & a[10] & a[14]\ a[3] & a[7] &
 a[11] & a[15]\ \end{bmatrix}

On the first request, the `matrix` gets computed. After that, it should be cached for performance reasons.

### Creating the matrix

 In this section, intended for more advanced readers, we cover how the API calculates
 the matrix for the specified
 transform. It begins by allocating a new matrix and writing a 4x4 identity matrix into
 it:

[

1

0

0

0

0

1

0

0

0

0

1

0

0

0

0

1

]

 \begin{bmatrix} 1 & 0 & 0 & 0\ 0 & 1
 & 0 & 0\ 0 & 0 &
 1 & 0\ 0 & 0 & 0 & 1 \end{bmatrix}

 This is a transform that will not change either the orientation or position of any
 point, vector, or object to which
 it's applied.

 Next, the `position` is placed into the right-hand column, like this,
 resulting in a translation matrix
 that will transform a coordinate system by the specified distance in each dimension,
 with no rotational change. Here
 *px*, *py*, and *pz*
 are the values of the
 `x`, `y`, and `z` members of the
 `DOMPointReadOnly`
`position`.

[

1

0

0

p
x

0

1

0

p
y

0

0

1

p
z

0

0

0

1

]

 \begin{bmatrix} 1 & 0 & 0 & x\ 0 & 1
 & 0 & y\ 0 & 0 &
 1 & z\ 0 & 0 & 0 & 1 \end{bmatrix}

 Then a rotation matrix is created by computing a column-vector rotation matrix from the
 unit quaternion specified by
 `orientation`:

[

1
-
2
(

q
y
2

+

q
z
2

)

2
(

q
x

q
y

-

q
z

q
w

)

2
(

q
x

q
z

+

q
y

q
w

)

0

2
(

q
x

q
y

+

q
z

q
w

)

1
-
2
(

q
x
2

+

q
z
2

)

2
(

q
y

q
z

-

q
x

q
w

)

0

2
(

q
x

q
z

-

q
y

q
w

)

2
(

q
y

q
z

+

q
x

q
w

)

1
-
2
(

q
x
2

+

q
y
2

)

0

0

0

0

1

]

 \begin{bmatrix} 1 - 2(q\_y^2 + q\_z^2) & 2(q\_xq\_y -
 q\_zq\_w) & 2(q\_xq\_z + q\_yq\_w)
 & p\_x\ 2(q\_xq\_y + q\_zq\_w) & 1 - 2(q\_x^2 + q\_z^2) & 2(q\_yq\_z - q\_xq\_w)
 & p\_y\ 2(q\_xq\_z -
 q\_yq\_w) & 2(q\_yq\_z + q\_xq\_w) & 1 - 2(q\_x^2 + q\_y^2) & p\_z\ 0 & 0
 & 0 & 1 \end{bmatrix}

 The final transform `matrix` is calculated by multiplying the translation
 matrix by the rotation matrix,
 in the order `(translation * rotation)`. This yields the final transform
 matrix as returned by
 `matrix`:

[

1
-
2
(

q
y
2

+

q
z
2

)

2
(

q
x

q
y

-

q
z

q
w

)

2
(

q
x

q
z

+

q
y

q
w

)

p
x

2
(

q
x

q
y

+

q
z

q
w

)

1
-
2
(

q
x
2

+

q
z
2

)

2
(

q
y

q
z

-

q
x

q
w

)

p
y

2
(

q
x

q
z

-

q
y

q
w

)

2
(

q
y

q
z

+

q
x

q
w

)

1
-
2
(

q
x
2

+

q
y
2

)

p
z

0

0

0

1

]

 \begin{bmatrix} 1 - 2(q\_y^2 + q\_z^2) & 2(q\_xq\_y -
 q\_zq\_w) & 2(q\_xq\_z + q\_yq\_w)
 & p\_x\ 2(q\_xq\_y + q\_zq\_w) & 1 - 2(q\_x^2 + q\_z^2) & 2(q\_yq\_z - q\_xq\_w)
 & p\_y\ 2(q\_xq\_z -
 q\_yq\_w) & 2(q\_yq\_z + q\_xq\_w) & 1 - 2(q\_x^2 + q\_y^2) & p\_z\ 0 & 0
 & 0 & 1 \end{bmatrix}

Examples
--------

 In this example, a transform is created to create a matrix which can be used as a
 transform during rendering of WebGL
 objects, in order to place objects to match a given offset and orientation. The
 `matrix` is then passed
 into a library function that uses WebGL to render an object matching a given name using
 the transform matrix specified
 to position and orient it.

```js
let transform = new XRRigidTransform(
  { x: 0, y: 0.5, z: 0.5 },
  { x: 0, y: -0.5, z: -0.5, w: 1 },
);
drawGLObject("magic-lamp", transform.matrix);
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrrigidtransform-matrix |

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

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


XRRigidTransform: position property - Web APIs

XRRigidTransform: position property
===================================

 The read-only `XRRigidTransform` property
 **`position`** is a `DOMPointReadOnly` object which
 provides the 3D point, specified in meters, describing the translation component of the
 transform.

Value
-----

 A read-only `DOMPointReadOnly` indicating the 3D position component of the
 transform matrix. The units are meters.

**Note:** The `w` component of the point is always 1.0.

Examples
--------

 To create a reference space which can be used to place an object at eye level (assuming
 eye level is 1.5 meters):

```js
function onSessionStarted(xrSession) {
  xrSession.addEventListener("end", onSessionEnded);

  gl = initGraphics(xrSession);

  const glLayer = new XRWebGLLayer(xrSession, gl);
  xrSession.updateRenderState({ baseLayer: glLayer });

  if (immersiveSession) {
    xrSession
      .requestReferenceSpace("bounded-floor")
      .then((refSpace) => {
        refSpaceCreated(refSpace);
      })
      .catch(() => {
        session.requestReferenceSpace("local-floor").then(refSpaceCreated);
      });
  } else {
    session.requestReferenceSpace("viewer").then(refSpaceCreated);
  }
}

function refSpaceCreated(refSpace) {
  xrReferenceSpace = immersiveSession
    ? refSpace
    : refSpace.getOffsetReferenceSpace(new XRRigidTransform({ y: -1.5 }));
  xrSession.requestAnimationFrame(onFrame);
}
```

 After setting up the graphics context for WebXR use, this begins by looking to see if a
 variable `immersiveSession` is `true`; if so, we first request a
 `bounded-floor` reference space. If that fails (probably because
 `bounded-floor` isn't supported), we try requesting a
 `local-floor` reference space.

 If we're not in an immersive session, we instead request a `viewer`
 reference space.

 In all cases, once the space has been obtained, it gets passed into the
 `refSpaceCreated()` function. For immersive spaces, the specified space is
 saved for future use. However, for inline sessions, we know we're in a space not
 automatically adjusted for floor level, so we request an offset reference space to shift
 the viewer's height to 1.5 meters above the presumed floor level of 0 meters. That new
 reference space is used instead of the one initially received.

Finally, an animation frame request is submitted.

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

| Specification |
| --- |
| WebXR Device API # dom-xrrigidtransform-position |

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

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


XRRigidTransform: inverse property - Web APIs

XRRigidTransform: inverse property
==================================

 The read-only **`inverse`** property
 of the `XRRigidTransform` interface returns another
 `XRRigidTransform` object which is the inverse of its owning
 transform. That is, you can always get the inverse of any
 `XRRigidTransform` using its `inverse` property, instead of having
 to explicitly generate it.

Value
-----

 An `XRRigidTransform` which contains the inverse of the
 `XRRigidTransform` on which it's accessed.

 Applying the inverse of a transform to any object previously transformed by the parent
 `XRRigidTransform` always undoes the transformation, resulting in the object
 returning to its previous pose. In other words, its position and orientation both return
 to their prior configurations.

Examples
--------

 In this example, the model view matrix for an object is computed by taking the view
 matrix and multiplying it by the object's pose matrix.

```js
const modelViewMatrix = mat4.create();

for (const view of pose.view) {
  const viewport = glLayer.getViewport(view);
  gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);

  // …

  mat4.multiply(modelViewMatrix, view.transform.inverse.matrix, objectMatrix);
  gl.uniformMatrix4fv(
    programInfo.uniformLocations.modelViewMatrix,
    false,
    modelViewMatrix,
  );

  // …
}
```

 This outline of a renderer's core code shows how the pose's view gets represented by
 taking its transform's inverse's matrix as the model view matrix used to transform
 objects based on the viewer's position and orientation. The inverse's matrix is
 multiplied by the object's matrix to get the model view matrix, which is then passed
 into the shader program by setting a uniform to contain that information.

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

| Specification |
| --- |
| WebXR Device API # dom-xrrigidtransform-inverse |

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

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


XRRigidTransform: orientation property - Web APIs

XRRigidTransform: orientation property
======================================

 The read-only `XRRigidTransform` property
 **`orientation`** is a `DOMPointReadOnly`
 containing a normalized quaternion (also called a **unit
quaternion** or **versor**)
 specifying the rotational component of the transform represented by the object.
 If you specify a quaternion whose length is not exactly 1.0 meters, it will be
 normalized for you.

Value
-----

 A `DOMPointReadOnly` object which contains a unit quaternion providing the
 orientation component of the transform. As a unit quaternion, the length of the returned
 quaternion is always 1.0 meters.

Examples
--------

 To create a reference space which is oriented to look straight up, positioned 2 meters
 off of ground level:

```js
xrReferenceSpace = refSpace.getOffsetReferenceSpace(
  new XRRigidTransform({ y: -2 }, { x: 0.0, y: 1.0, z: 0.0, w: 1.0 }),
);
```

 The unit quaternion specified here is [0.0, 1.0, 0.0, 1.0] to indicate that the object
 should be facing directly along the *y* axis.

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

| Specification |
| --- |
| WebXR Device API # dom-xrrigidtransform-orientation |

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

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

See also
--------

* Movement, orientation, and motion
* Unit quaternions
* Quaternions and spatial rotation


XRRigidTransform: XRRigidTransform() constructor - Web APIs

XRRigidTransform: XRRigidTransform() constructor
================================================

 The
 **`XRRigidTransform()`** constructor creates
 a new `XRRigidTransform` object, representing the position and
 orientation of a point or object. Among other things,
 `XRRigidTransform` is used when providing a transform to translate between
 coordinate systems across spaces.

Syntax
------

```js
new XRRigidTransform()
new XRRigidTransform(position)
new XRRigidTransform(position, orientation)
```

### Parameters

`position` Optional

 An object which specifies the coordinates
 at which the point or object is located. These dimensions are specified in meters. If
 this parameter is left out or is invalid, the
 position used is assumed to be `{x: 0, y: 0, z: 0, w: 1}`. `w`
 must *always* be 1.

`orientation` Optional

 An object which specifies the direction in
 which the object is facing. The default value for `orientation` is
 `{x: 0, y: 0, z: 0, w: 1}`. The specified orientation gets normalized if
 it's not already.

### Return value

 A new `XRRigidTransform` object which has been initialized to represent a
 transform matrix that would adjust the position and orientation of an object from the
 origin to the specified `position` and facing in the direction indicated by
 `orientation`.

### Exceptions

`TypeError`

 Thrown if the value of the `w` coordinate in the specified `position` is
 not 1.0.

Examples
--------

 In this example, the beginning of the animation of a scene is shown, starting with a
 request for a reference space of a given type, then shifting the coordinate system based
 on a transform before requesting the first animation frame.

```js
let animationFrameRequestID = 0;

xrSession.requestReferenceSpace("local-floor").then((refSpace) => {
  xrReferenceSpace = refSpace.getOffsetReferenceSpace(
    new XRRigidTransform(viewerPosition, viewerOrientation),
  );
  animationFrameRequestID = xrSession.requestAnimationFrame(drawFrame);
});
```

 After requesting a reference space of type `local-floor`, the returned
 promise is eventually resolved, at which time we receive a new reference space object,
 `refSpace`. After creating an `XRRigidTransform` from the viewer's
 initial position and orientation, we pass the new transform into
 `getOffsetReferenceSpace()` to
 create *another* reference space, now offset so that its origin is located at the
 same place in space as the coordinates given by `viewerPosition`, with the
 orientation also revised in the same fashion.

 Then `requestAnimationFrame()` is
 called to ask for a new animation frame to draw into. The `drawFrame()`
 callback will be executed when the system is ready to draw the next frame.

You can find more examples in Movement, orientation, and motion.

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

| Specification |
| --- |
| WebXR Device API # dom-xrrigidtransform-xrrigidtransform |

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

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


EventSource: readyState property - Web APIs

EventSource: readyState property
================================

 The **`readyState`** read-only property of the
 `EventSource` interface returns a number representing the state of the
 connection.

Value
-----

A number representing the state of the connection. Possible values are:

* `0` — connecting
* `1` — open
* `2` — closed
Examples
--------

```js
const evtSource = new EventSource("sse.php");
console.log(evtSource.readyState);
```

**Note:** You can find a full example on GitHub — see Simple SSE demo using PHP.

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

| Specification |
| --- |
| HTML Standard # dom-eventsource-readystate-dev |

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

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

See also
--------

* `EventSource`


EventSource: url property - Web APIs

EventSource: url property
=========================

 The **`url`** read-only property of the
 `EventSource` interface returns a string representing the
 URL of the source.

Value
-----

A string representing the URL of the source.

Examples
--------

```js
const evtSource = new EventSource("sse.php");
console.log(evtSource.url);
```

**Note:** You can find a full example on GitHub — see Simple SSE demo using PHP.

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

| Specification |
| --- |
| HTML Standard # dom-eventsource-url-dev |

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

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

See also
--------

* `EventSource`


EventSource: message event - Web APIs

EventSource: message event
==========================

The `message` event of the `EventSource` API is fired when data is received through an event source.

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("message", (event) => {});

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

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

A `MessageEvent`. Inherits from `Event`.

Event

MessageEventEvent properties
----------------

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

`MessageEvent.data` Read only

The data sent by the message emitter.

`MessageEvent.origin` Read only

A string representing the origin of the message emitter.

`MessageEvent.lastEventId` Read only

A string representing a unique ID for the event.

`MessageEvent.source` Read only

A `MessageEventSource` (which can be a WindowProxy, `MessagePort`, or `ServiceWorker` object) representing the message emitter.

`MessageEvent.ports` Read only

An array of `MessagePort` objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).

Examples
--------

In this basic example, an `EventSource` is created to receive events from the server; a page with the name `sse.php` is responsible for generating the events.

```js
const evtSource = new EventSource("sse.php");
const eventList = document.querySelector("ul");

evtSource.addEventListener("message", (e) => {
  const newElement = document.createElement("li");

  newElement.textContent = `message: ${e.data}`;
  eventList.appendChild(newElement);
});
```

### onmessage equivalent

```js
evtSource.onmessage = (e) => {
  const newElement = document.createElement("li");

  newElement.textContent = `message: ${e.data}`;
  eventList.appendChild(newElement);
};
```

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

| Specification |
| --- |
| HTML Standard # event-message |
| HTML Standard # handler-eventsource-onmessage |

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

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

See also
--------

* Using server-sent events
* `open`
* `error`


EventSource: withCredentials property - Web APIs

EventSource: withCredentials property
=====================================

 The **`withCredentials`** read-only property of the
 `EventSource` interface returns a boolean value indicating whether
 the `EventSource` object was instantiated with CORS credentials set.

Value
-----

 A boolean value indicating whether the `EventSource` object was
 instantiated with CORS credentials set (`true`), or not (`false`,
 the default).

Examples
--------

```js
const evtSource = new EventSource("sse.php");
console.log(evtSource.withCredentials);
```

**Note:** You can find a full example on GitHub — see Simple SSE demo using PHP.

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

| Specification |
| --- |
| HTML Standard # dom-eventsource-withcredentials-dev |

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

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

See also
--------

* `EventSource`


EventSource: open event - Web APIs

EventSource: open event
=======================

The `open` event of the `EventSource` API is fired when a connection with an event source is opened.

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("open", (event) => {});

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

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

A generic `Event`.

Examples
--------

```js
const evtSource = new EventSource("sse.php");

// addEventListener version
evtSource.addEventListener("open", (e) => {
  console.log("The connection has been established.");
});

// onopen version
evtSource.onopen = (e) => {
  console.log("The connection has been established.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-open |
| HTML Standard # handler-eventsource-onopen |

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

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

See also
--------

* Using server-sent events
* `open`
* `error`
* `message`


EventSource: close() method - Web APIs

EventSource: close() method
===========================

 The **`close()`** method of the `EventSource`
 interface closes the connection, if one is made, and sets the
 `EventSource.readyState` attribute to `2` (closed).

**Note:** If the connection is already closed, the method does nothing.

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const button = document.querySelector("button");
const evtSource = new EventSource("sse.php");

button.onclick = () => {
  console.log("Connection closed");
  evtSource.close();
};
```

**Note:** You can find a full example on GitHub — see Simple SSE demo using PHP.

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

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

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

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

See also
--------

* `EventSource`


EventSource: EventSource() constructor - Web APIs

EventSource: EventSource() constructor
======================================

 The **`EventSource()`**
 constructor returns a newly-created `EventSource`, which represents a
 remote resource.

Syntax
------

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

### Parameters

`url`

 A string that represents the location of the remote resource
 serving the events/messages.

`options` Optional

Provides options to configure the new connection. The possible entries are:

`withCredentials` Optional

 A boolean value, defaulting to `false`, indicating
 if CORS should be set to `include` credentials.

Examples
--------

```js
const evtSource = new EventSource("sse.php");
const eventList = document.querySelector("ul");

evtSource.onmessage = (e) => {
  const newElement = document.createElement("li");

  newElement.textContent = `message: ${e.data}`;
  eventList.appendChild(newElement);
};
```

**Note:** You can find a full example on GitHub — see Simple SSE demo using PHP.

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

| Specification |
| --- |
| HTML Standard # dom-eventsource-dev |

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

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

See also
--------

* `EventSource`


EventSource: error event - Web APIs

EventSource: error event
========================

The `error` event of the `EventSource` API is fired when a connection with an event source fails to be opened.

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("error", (event) => {});

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

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

A generic `Event`.

Examples
--------

```js
const evtSource = new EventSource("sse.php");

// addEventListener version
evtSource.addEventListener("error", (e) => {
  console.log("An error occurred while attempting to connect.");
});

// onerror version
evtSource.onerror = (e) => {
  console.log("An error occurred while attempting to connect.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-error |
| HTML Standard # handler-eventsource-onerror |

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

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

See also
--------

* Using server-sent events
* `open`
* `message`


HTMLScriptElement: referrerPolicy property - Web APIs

HTMLScriptElement: referrerPolicy property
==========================================

 The **`referrerPolicy`** property of the
 `HTMLScriptElement` interface reflects the HTML
 `referrerpolicy` of the `<script>` element, which defines how the referrer is set when fetching the script and any scripts it imports.

Value
-----

A string; one of the following:

`no-referrer`

 The `Referer` header will be omitted entirely. No referrer
 information is sent along with requests.

`no-referrer-when-downgrade`

 The URL is sent
 as a referrer when the protocol security level stays the same (e.g.HTTP→HTTP,
 HTTPS→HTTPS), but isn't sent to a less secure destination (e.g. HTTPS→HTTP).

`origin`

 Only send the origin of the document as the referrer in all cases.
 The document `https://example.com/page.html` will send the referrer
 `https://example.com/`.

`origin-when-cross-origin`

 Send a full URL when performing a same-origin request, but only send the origin of
 the document for other cases.

`same-origin`

 A referrer will be sent for same-site origins, but
 cross-origin requests will contain no referrer information.

`strict-origin`

 Only send the origin of the document as the referrer when the protocol security
 level stays the same (e.g. HTTPS→HTTPS), but don't send it to a less secure
 destination (e.g. HTTPS→HTTP).

`strict-origin-when-cross-origin` (default)

 This is the user agent's default behavior if no policy is specified. Send a full URL when performing a same-origin request, only send the origin when the
 protocol security level stays the same (e.g. HTTPS→HTTPS), and send no header to a
 less secure destination (e.g. HTTPS→HTTP).

`unsafe-url`

 Send a full URL when performing a same-origin or cross-origin request. This policy
 will leak origins and paths from TLS-protected resources to insecure origins.
 Carefully consider the impact of this setting.

**Note:** An empty string value (`""`) is both the default
 value, and a fallback value if `referrerpolicy` is not supported. If
 `referrerpolicy` is not explicitly specified on the
 `<script>` element, it will adopt a higher-level referrer policy,
 i.e. one set on the whole document or domain. If a higher-level policy is not
 available, the empty string is treated as being equivalent to
 `no-referrer-when-downgrade`.

Examples
--------

```js
const scriptElem = document.createElement("script");
scriptElem.src = "/";
scriptElem.referrerPolicy = "unsafe-url";
document.body.appendChild(scriptElem);
```

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

| Specification |
| --- |
| HTML Standard # dom-script-referrerpolicy |

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

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

See also
--------

* `HTMLIFrameElement.referrerPolicy`


HTMLScriptElement: crossOrigin property - Web APIs

HTMLScriptElement: crossOrigin property
=======================================

The **`crossOrigin`** property of the `HTMLScriptElement` interface reflects the Cross-Origin Resource Sharing settings for the script element. For classic scripts from other origins, this controls if full error information will be exposed. For module scripts, it controls the script itself and any script it imports. See CORS settings attributes for details.

Value
-----

A string of a keyword specifying the CORS mode to use when fetching the resource. Possible values are:

`anonymous` or an empty string (`""`)

Requests sent by the `HTMLScriptElement` will use the `cors` mode and the `same-origin` credentials mode. This means that CORS is enabled and credentials are sent *if* the resource is fetched from the same origin from which the document was loaded.

`use-credentials`

Requests sent by the `HTMLScriptElement` will use the `cors` mode and the `include` credentials mode. All resources requests by the element will use CORS, regardless of which domain the fetch is from.

If the `crossOrigin` property is specified with any other value, it is the same as specifing it as the `anonymous`.

If the `crossOrigin` property is not specified, the resource is fetched without CORS (the `no-cors` mode and the `same-origin` credentials mode).

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

| Specification |
| --- |
| HTML Standard # dom-script-crossorigin |

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

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

See also
--------

* `HTMLImageElement.crossOrigin`
* `HTMLLinkElement.crossOrigin`
* `HTMLMediaElement.crossOrigin`