MutationEvent - Web APIs

MutationEvent
=============

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

The **`MutationEvent`** interface provides event properties that are specific to modifications to the Document Object Model (DOM) hierarchy and nodes.

**Note:** Using *mutation events* is problematic:

* Their design is flawed.
* Adding DOM mutation listeners to a document profoundly degrades the performance of further DOM modifications to that document (making them 1.5 - 7 times slower!). Moreover, removing the listeners does not reverse the damage.
* They have poor cross-browser compatibility: Safari doesn't support `DOMAttrModified` (see WebKit bug 8191) and Firefox doesn't support *mutation name events* (like `DOMElementNameChanged` and `DOMAttributeNameChanged`).

They have been deprecated in favor of mutation observers. **Consider using these instead.**

Event

MutationEventInstance properties
-------------------

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

`MutationEvent.attrChange` Read only
Deprecated

Indicates what kind of change triggered the `DOMAttrModified` event. It can be `MODIFICATION` (`1`), `ADDITION` (`2`) or `REMOVAL` (`3`). It has no meaning for other events and is then set to `0`.

`MutationEvent.attrName` Read only
Deprecated

Indicates the name of the node affected by the `DOMAttrModified` event. It has no meaning for other events and is then set to the empty string (`""`).

`MutationEvent.newValue` Read only
Deprecated

In `DOMAttrModified` events, contains the new value of the modified `Attr` node. In `DOMCharacterDataModified` events, contains the new value of the modified `CharacterData` node. In all other cases, returns the empty string (`""`).

`MutationEvent.prevValue` Read only
Deprecated

In `DOMAttrModified` events, contains the previous value of the modified `Attr` node. In `DOMCharacterDataModified` events, contains previous new value of the modified`CharacterData` node. In all other cases, returns the empty string (`""`).

`MutationEvent.relatedNode` Read only
Deprecated

Indicates the node related to the event, like the changed node inside the subtree for `DOMSubtreeModified`.

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

`MutationEvent.initMutationEvent()`
Deprecated

Constructor method that returns a new `MutationEvent` configured with the parameters given.

Mutation events list
--------------------

The following is a list of all mutation events:

* `DOMAttrModified` (Not supported by Safari)
* `DOMAttributeNameChanged` (Not supported by Firefox)
* `DOMCharacterDataModified`
* `DOMElementNameChanged` (Not supported by Firefox)
* `DOMNodeInserted`
* `DOMNodeInsertedIntoDocument`
* `DOMNodeRemoved`
* `DOMNodeRemovedFromDocument`
* `DOMSubtreeModified`
Examples
--------

You can register a listener for mutation events using `EventTarget.addEventListener()` as follows:

```js
element.addEventListener(
  "DOMNodeInserted",
  (event) => {
    // …
  },
  false,
);
```

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

| Specification |
| --- |
| UI Events # interface-mutationevent |

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

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

See also
--------

* `MutationObserver`


VideoTrackList - Web APIs

VideoTrackList
==============

The **`VideoTrackList`** interface is used to represent a list of the video tracks contained within a `<video>` element, with each track represented by a separate `VideoTrack` object in the list.

Retrieve an instance of this object with `HTMLMediaElement.videoTracks`. The individual tracks can be accessed using array syntax or functions such as `forEach()` for example.

EventTarget

VideoTrackListInstance properties
-------------------

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

`length` Read only

The number of tracks in the list.

`selectedIndex` Read only

The index of the currently selected track, if any, or `−1` otherwise.

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

*This interface also inherits methods from its parent interface, `EventTarget`.*

`getTrackById()`

Returns the `VideoTrack` found within the `VideoTrackList` whose `id` matches the specified string. If no match is found, `null` is returned.

Events
------

`addtrack`

 Fired when a new video track has been added to the media element.
 Also available via the `onaddtrack` property.

`change`

 Fired when a video track has been made active or inactive.
 Also available via the `onchange` property.

`removetrack`

 Fired when a new video track has been removed from the media element.
 Also available via the `onremovetrack` property.

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

In addition to being able to obtain direct access to the video tracks present on a media element, `VideoTrackList` lets you set event handlers on the `addtrack` and `removetrack` events, so that you can detect when tracks are added to or removed from the media element's stream.

Examples
--------

### Getting a media element's video track list

To get a media element's `VideoTrackList`, use its `videoTracks` property.

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

### Monitoring track count changes

In this example, we have an app that displays information about the number of channels available. To keep it up to date, handlers for the `addtrack` and `removetrack` events are set up.

```js
videoTracks.onaddtrack = updateTrackCount;
videoTracks.onremovetrack = updateTrackCount;

function updateTrackCount(event) {
  trackCount = videoTracks.length;
  drawTrackCountIndicator(trackCount);
}
```

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

| Specification |
| --- |
| HTML Standard # audiotracklist-and-videotracklist-objects |

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

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


MerchantValidationEvent - Web APIs

MerchantValidationEvent
=======================

**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.

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

The **`MerchantValidationEvent`** interface of the Payment Request API enables a merchant to verify themselves as allowed to use a particular payment handler.

Learn more about merchant validation.

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

`MerchantValidationEvent()`
Deprecated

Creates a new `MerchantValidationEvent` object describing a `merchantvalidation` event that will be sent to the payment handler to request that it validate the merchant.

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

`MerchantValidationEvent.methodName`
Deprecated

A string providing a unique payment method identifier for the payment handler that's requiring validation. This may be either one of the standard payment method identifier strings or a URL that both identifies and handles requests for the payment handler, such as `https://apple.com/apple-pay`.

`MerchantValidationEvent.validationURL`
Deprecated

A string specifying a URL from which the site or app can fetch payment handler specific validation information. Once this data is retrieved, the data (or a promise resolving to the validation data) should be passed into `complete()` to validate that the payment request is coming from an authorized merchant.

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

`MerchantValidationEvent.complete()`
Deprecated

Pass the data retrieved from the URL specified by `validationURL` into `complete()` to complete the validation process for the `PaymentRequest`.

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

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


ContentIndexEvent - Web APIs

ContentIndexEvent
=================

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

The **`ContentIndexEvent`** interface of the content index defines the object used to represent the `contentdelete` event.

This event is sent to the global scope of a `ServiceWorker`. It contains the id of the indexed content to be removed.

The `contentdelete` event is only fired when the deletion happens due to interaction with the browser's built-in user interface. It is not fired when the `ContentIndex.delete` method is called.

Event

ExtendableEvent

ContentIndexEventConstructor
-----------

`ContentIndexEvent()`
Experimental

Creates and returns a new `ContentIndexEvent` object whose type and other options are configured as specified.

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

*In addition to the properties listed below, this interface inherits the properties of its parent interface, `ExtendableEvent`.*

`id` Read only
Experimental

A `String` which identifies the deleted content index via it's `id`.

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

*While `ContentIndexEvent` offers no methods of its own, it inherits any specified by its parent interface, `ExtendableEvent`.*

Examples
--------

This example shows the service worker script listening for the `contentdelete` event and logs the removed content index id.

```js
self.addEventListener("contentdelete", (event) => {
  console.log(event.id);

  // logs content index id, which can then be used to determine what content to delete from your cache
});
```

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

| Specification |
| --- |
| Content Index # content-index-event |

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

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

See also
--------

* An introductory article on the Content Index API
* An app which uses the Content Index API to list and remove 'save for later' content
* Service Worker API, along with information about Cache and CacheStorage


XRSessionEvent - Web APIs

XRSessionEvent
==============

The WebXR Device API's **`XRSessionEvent`** interface describes an event which indicates the change of the state of an `XRSession`. These events occur, for example, when the session ends or the visibility of its context changes.

Event

XRSessionEventConstructor
-----------

`XRSessionEvent()`

Creates and returns a new `XRSessionEvent` object.

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

*In addition to properties inherited from its parent interface, `Event`, `XRSessionEvent` provides the following:*

`session` Read only

The `XRSession` to which the event refers.

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

*While `XRSessionEvent` defines no methods, it inherits methods from its parent interface, `Event`.*

Session event types
-------------------

*The following events are represented using the `XRSessionEvent` interface, and are permitted values for its `type` property.*

`end`

Fired at the session when it has ended, after being terminated by the application or the user agent.

`visibilitychange`

Fired at the session whenever its visibility state changes.

Examples
--------

This example creates a listener that watches for the visibility state of the session to change. It reacts by calling a function `mySessionVisible()` with a Boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfigure a worker that handles rendering the scene.

```js
xrSession.addEventListener("visibilitystate", (e) => {
  switch (e.session.visibilitystate) {
    case "visible":
    case "visible-blurred":
      mySessionVisible(true);
      break;
    case "hidden":
      mySessionVisible(false);
      break;
  }
});
```

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

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

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

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


Lock - Web APIs

Lock
====

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

 The **`Lock`** interface of the Web Locks API provides the name and mode of a lock.
 This may be a newly requested lock that is received in the callback to `LockManager.request()`, or a record of an active or queued lock returned by `LockManager.query()`.

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

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

`Lock.mode` Read only

 Returns the access mode passed to `LockManager.request()` when the lock was requested.
 The mode is either `"exclusive"` (the default) or `"shared"`.

`Lock.name` Read only

Returns the name passed to `LockManager.request()` when the lock was requested.

Examples
--------

 The following examples show how the mode and name properties are passed in the call to `LockManager.request()`.
 `LockManager` is the object returned by `navigator.locks`.

```js
navigator.locks.request("net\_db\_sync", show_lock_properties);
navigator.locks.request(
  "another\_lock",
  { mode: "shared" },
  show_lock_properties,
);

function show\_lock\_properties(lock) {
  console.log(`The lock name is: ${lock.name}`);
  console.log(`The lock mode is: ${lock.mode}`);
}
```

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

| Specification |
| --- |
| Web Locks API # api-lock |

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

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


Vibration API - Web APIs

Vibration API
=============

Most modern mobile devices include vibration hardware, which lets software code provide physical feedback to the user by causing the device to shake. The **Vibration API** offers Web apps the ability to access this hardware, if it exists, and does nothing if the device doesn't support it.

Describing vibrations
---------------------

Vibration is described as a pattern of on-off pulses, which may be of varying lengths. The pattern may consist of either a single integer, describing the number of milliseconds to vibrate, or an array of integers describing a pattern of vibrations and pauses. Vibration is controlled with a single method: `Navigator.vibrate()`.

### A single vibration

You may pulse the vibration hardware one time by specifying either a single value or an array consisting of only one value:

```js
navigator.vibrate(200);
navigator.vibrate([200]);
```

Both of these examples vibrate the device for 200 ms.

### Vibration patterns

An array of values describes alternating periods in which the device is vibrating and not vibrating. Each value in the array is converted to an integer, then interpreted alternately as the number of milliseconds the device should vibrate and the number of milliseconds it should not be vibrating. For example:

```js
navigator.vibrate([200, 100, 200]);
```

This vibrates the device for 200 ms, then pauses for 100 ms before vibrating the device again for another 200 ms.

You may specify as many vibration/pause pairs as you like, and you may provide either an even or odd number of entries; it's worth noting that you don't have to provide a pause as your last entry since the vibration automatically stops at the end of each vibration period.

### Canceling existing vibrations

Calling `Navigator.vibrate()` with a value of `0`, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern.

### Continued vibrations

Some basic `setInterval` and `clearInterval` action will allow you to create persistent vibration:

```js
let vibrateInterval;

// Starts vibration at passed in level
function startVibrate(duration) {
  navigator.vibrate(duration);
}

// Stops vibration
function stopVibrate() {
  // Clear interval and stop persistent vibrating
  if (vibrateInterval) clearInterval(vibrateInterval);
  navigator.vibrate(0);
}

// Start persistent vibration at given duration and interval
// Assumes a number value is given
function startPersistentVibrate(duration, interval) {
  vibrateInterval = setInterval(() => {
    startVibrate(duration);
  }, interval);
}
```

Of course, the snippet above doesn't take into account the array method of vibration; persistent array-based vibration will require calculating the sum of the array items and creating an interval based on that number (with an additional delay, probably).

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

| Specification |
| --- |
| Vibration API (Second Edition) # dom-navigator-vibrate |

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

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

See also
--------

* `Navigator.vibrate()`


HmacImportParams - Web APIs

HmacImportParams
================

The **`HmacImportParams`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()` or `SubtleCrypto.unwrapKey()`, when generating a key for the HMAC algorithm.

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

`name`

A string. This should be set to `HMAC`.

`hash`

A string representing the name of the digest function to use. The can take a value of `SHA-256`, `SHA-384`, or `SHA-512`.

**Warning:** Although you can technically pass `SHA-1` here, this is strongly discouraged as it is considered vulnerable.

`length` Optional

A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default.

Examples
--------

See the examples for `SubtleCrypto.importKey()`.

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

| Specification |
| --- |
| Web Cryptography API # dfn-HmacImportParams |

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

Browsers that support the "HMAC" algorithm for the `SubtleCrypto.importKey()`, `SubtleCrypto.unwrapKey()` methods will support this type.

See also
--------

* `SubtleCrypto.importKey()`.
* `SubtleCrypto.unwrapKey()`.


Credential Management API - Web APIs

Credential Management API
=========================

The Credential Management API lets a website store and retrieve password, public key, and federated credentials. These capabilities allow users to sign in without typing passwords, see the federated account they used to sign in to a site, and resume a session without the explicit sign-in flow of an expired session.

Credential management concepts and usage
----------------------------------------

This API lets websites interact with a user agent's password system directly so that websites can deal in a uniform way with site credentials and user agents can provide better assistance with the management of their credentials. For example, user agents have a particularly hard time dealing with federated identity providers or esoteric sign-in mechanisms.

To address these problems, the Credential Management API provides ways for a website to store and retrieve different types of credentials. This gives users capabilities such as seeing the federated account they used to sign on to a site, or resuming a session without the explicit sign-in flow of an expired session.

**Note:** This API is restricted to top-level contexts. Calls to `get()` and `store()` within an `<iframe>` element will resolve without effect.

### Subdomain-shared credentials

Later versions of the spec allow credentials to be retrieved from a different subdomain. For example, a password stored in `login.example.com` may be used to log in to `www.example.com`. To take advantage of this, a password must be explicitly stored by calling `CredentialsContainer.store()`. This is sometimes referred to as public suffix list (PSL) matching; however the spec only *recommends* using PSL to determine the effective scope of a credential. It does not require it. Hence browsers may vary in their implementation.

Interfaces
----------

`Credential`

Provides information about an entity as a prerequisite to a trust decision.

`CredentialsContainer`

Exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. This interface is accessible from `navigator.credentials`.

`FederatedCredential`

Provides information about credentials from a federated identity provider, which is an entity that a website trusts to correctly authenticate a user, and which provides an API for that purpose. OpenID Connect is an example of such a framework.

`PasswordCredential`

Provides information about a username/password pair.

`PublicKeyCredential`

Provides a credential for logging in using a more secure system based on asymmetric cryptography instead of a password.

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

| Specification |
| --- |
| Credential Management Level 1 # the-credential-interface |

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

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


USBOutTransferResult - Web APIs

USBOutTransferResult
====================

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

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

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

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

The `USBOutTransferResult` interface of the WebUSB API provides the result from a call to the `transferOut()` and `controlTransferOut()` methods of the `USBDevice` interface. It represents the result from requesting a transfer of data from the USB host to the USB device.

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

`USBOutTransferResult()`
Experimental

Creates a new `USBOutTransferResult` object with the provided `status` and `bytesWritten` fields.

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

`USBOutTransferResult.bytesWritten` Read only
Experimental

Returns the number of bytes from the transfer request that were sent to the device.

`USBOutTransferResult.status` Read only
Experimental

Returns the status of the transfer request, one of:

* `"ok"` - The transfer was successful.
* `"stall"` - The device indicated an error by generating a stall condition on the endpoint. A stall on a bulk or interrupt endpoint must be cleared by calling `clearHalt()` before `transferOut()` can be called again.

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

| Specification |
| --- |
| WebUSB API # usbouttransferresult |

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

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


TransformStream - Web APIs

TransformStream
===============

The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain *transform stream* concept.

 It may be passed to the `ReadableStream.pipeThrough()` method in order to transform a stream of data from one format into another.
 For example, it might be used to decode (or encode) video frames, decompress data, or convert the stream from XML to JSON.

 A transformation algorithm may be provided as an optional argument to the object constructor.
 If not supplied, data is not modified when piped through the stream.

`TransformStream` is a transferable object.

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

`TransformStream()`

Creates and returns a transform stream object, optionally specifying a transformation object and queuing strategies for the streams.

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

`TransformStream.readable` Read only

The `readable` end of a `TransformStream`.

`TransformStream.writable` Read only

The `writable` end of a `TransformStream`.

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

None

Examples
--------

### Anything-to-uint8array stream

In the following example, a transform stream passes through all chunks it receives as `Uint8Array` values.

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

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

### Polyfilling TextEncoderStream and TextDecoderStream

Note that this is deprecated by the native constructors. This is intended as a polyfill for unsupported platforms.

```js
const tes = {
  start() {
    this.encoder = new TextEncoder();
  },
  transform(chunk, controller) {
    controller.enqueue(this.encoder.encode(chunk));
  },
};

let _jstes_wm = new WeakMap(); /\* info holder \*/
class JSTextEncoderStream extends TransformStream {
  constructor() {
    let t = { ...tes };

    super(t);
    _jstes_wm.set(this, t);
  }
  get encoding() {
    return _jstes_wm.get(this).encoder.encoding;
  }
}
```

Similarly, `TextDecoderStream` can be written as such:

```js
const tds = {
  start() {
    this.decoder = new TextDecoder(this.encoding, this.options);
  },
  transform(chunk, controller) {
    controller.enqueue(this.decoder.decode(chunk, { stream: true }));
  },
};

let _jstds_wm = new WeakMap(); /\* info holder \*/
class JSTextDecoderStream extends TransformStream {
  constructor(encoding = "utf-8", { ...options } = {}) {
    let t = { ...tds, encoding, options };

    super(t);
    _jstds_wm.set(this, t);
  }
  get encoding() {
    return _jstds_wm.get(this).decoder.encoding;
  }
  get fatal() {
    return _jstds_wm.get(this).decoder.fatal;
  }
  get ignoreBOM() {
    return _jstds_wm.get(this).decoder.ignoreBOM;
  }
}
```

### Chaining multiple ReadableStreams together

This is a useful one, where multiple streams can be conjoined. Examples include building a PWA with progressive loading and progressive streaming.

```js
let responses = [
  /\* conjoined response tree \*/
];
let { readable, writable } = new TransformStream();

responses.reduce(
  (a, res, i, arr) =>
    a.then(() => res.pipeTo(writable, { preventClose: i + 1 !== arr.length })),
  Promise.resolve(),
);
```

Note that this is not resilient to other influences.

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

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

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

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

See also
--------

* WHATWG Stream Visualizer, for a basic visualization of readable, writable, and transform streams.
* Streams—The Definitive Guide


XRPose - Web APIs

XRPose
======

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

`XRPose` is a WebXR API interface representing a position and orientation in the 3D space, relative to the `XRSpace` within which it resides. The `XRSpace`—which is either an `XRReferenceSpace` or an `XRBoundedReferenceSpace`—defines the coordinate system used for the pose and, in the case of an `XRViewerPose`, its underlying views.

To obtain the `XRPose` for the `XRSpace` used as the local coordinate system of an object, call `XRFrame.getPose()`, specifying that local `XRSpace` and the space to which you wish to convert:

```js
thePose = xrFrame.getPose(localSpace, baseSpace);
```

The pose for a viewer (or camera) is represented by the `XRViewerPose` subclass of `XRPose`. This is obtained using `XRFrame.getViewerPose()` instead of `getPose()`, specifying a reference space which has been adjusted to position and orient the node to provide the desired viewing position and angle:

```js
viewerPose = xrFrame.getViewerPose(adjReferenceSpace);
```

Here, `adjReferenceSpace` is a reference space which has been updated using the base frame of reference for the frame and any adjustments needed to position the viewer based on movement or rotation which is being supplied from a source other than the XR device, such as keyboard or mouse inputs.

See the article Movement, orientation, and motion for further details and an example with thorough explanations of what's going on.

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

`XRPose.angularVelocity` Read only

A `DOMPointReadOnly` describing the angular velocity in radians per second relative to the base `XRSpace`.

`XRPose.emulatedPosition` Read only

A Boolean value which is `false` if the position and orientation given by `transform` is obtained directly from a full six degree of freedom (6DoF) XR device (that is, a device which tracks not only the pitch, yaw, and roll of the head but also the forward, backward, and side-to-side motion of the viewer). If any component of the `transform` is computed or created artificially (such as by using mouse or keyboard controls to move through space), this value is instead `true`, indicating that the `transform` is in part emulated in software.

`XRPose.linearVelocity` Read only

A `DOMPointReadOnly` describing the linear velocity in meters per second relative to the base `XRSpace`.

`XRPose.transform` Read only

A `XRRigidTransform` which provides the position and orientation of the pose relative to the base `XRSpace`.

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

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

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

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

See also
--------

* WebXR Device API
* `XRFrame.getPose()`
* `XRViewerPose`


WGSLLanguageFeatures - Web APIs

WGSLLanguageFeatures
====================

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

The **`WGSLLanguageFeatures`** interface of the WebGPU API is a setlike object that reports the WGSL language extensions supported by the WebGPU implementation.

The `WGSLLanguageFeatures` object is accessed via the `GPU.wgslLanguageFeatures` property.

**Note:** Not all WGSL language extensions are available to WebGPU in all browsers that support the API. We recommend you thoroughly test any extensions you choose to use.

Available features
------------------

The available WGSL language extensions can vary across implementations and physical devices and may also change over time; we have therefore not listed them here. For a complete list, refer to WGSL language extensions in the WGSL specification.

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

The following property is available to all read-only setlike objects:

`size`
Experimental

Returns the number of values in the set.

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

The following methods are available to all read-only setlike objects:

`has()`
Experimental

Returns a boolean asserting whether or not an element with the given value is present in the set.

`values()`
Experimental

Returns a new iterator object that yields **values** for each element in the set in insertion order.

`keys()`
Experimental

An alias for `values()`.

`entries()`
Experimental

Returns a new iterator object that contains **an array of `[value, value]`** for each element in the set in insertion order.

`forEach()`
Experimental

Calls the provided callback function once for each value present in the set in insertion order.

Examples
--------

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

const wgslFeatures = navigator.gpu.wgslLanguageFeatures;

// Return the size of the set
console.log(wgslFeatures.size);

// Iterate through all the set values using values()
const valueIterator = wgslFeatures.values();
for (const value of valueIterator) {
  console.log(value);
}

// ...
```

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

| Specification |
| --- |
| WebGPU # gpuwgsllanguagefeatures |

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

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

See also
--------

* WebGPU API


InputDeviceCapabilities API - Web APIs

InputDeviceCapabilities API
===========================

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

The InputDeviceCapabilities API provides details about the underlying sources of input events. The API attempts to describe how the device behaves rather than what it is. For example, the first version of the API indicates whether a device fires touch events rather than whether it is a touch screen.

Input device capabilities concepts and usage
--------------------------------------------

Because DOM events abstract device input, they provide no way to learn what device or type of device fired an event. This can lead to instances where the same action triggers multiple event handlers. To deal with this, developers make assumptions and use heuristics to normalize behavior on web pages.

The InputDeviceCapabilities API addresses this problem by abstracting the capabilities of input devices. For example, let's say we have a web page that implements both a `touchstart` and a `mousedown` event. We can assume that if the touchstart event is triggered that the user's device has a touch interface. What about when the mousedown event is triggered? It would be useful to know if a `touchstart` event were also triggered so that we don't take the same action twice. We can do this by checking the sourceCapabilities property of the `UIEvent`.

```js
myButton.addEventListener("mousedown", (e) => {
  // Touch event case handled above, don't change the style again on tap.
  if (!e.sourceCapabilities.firesTouchEvents) myButton.classList.add("pressed");
});
```

Interfaces
----------

`InputDeviceCapabilities`
Experimental

Provides logical information about an input device.

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

`UIEvent.sourceCapabilities`
Experimental
 Read only

Returns an instance of the `InputDeviceCapabilities` interface, which provides information about the physical device responsible for generating a touch event.

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

| Specification |
| --- |
| Input Device Capabilities # dom-inputdevicecapabilities |

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

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


TextTrackCueList - Web APIs

TextTrackCueList
================

The **`TextTrackCueList`** array-like object represents a dynamically updating list of `TextTrackCue` objects.

This interface has no constructor. Retrieve an instance of this object with `TextTrack.cues` which returns all of the cues in a `TextTrack` object.

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

`TextTrackCueList.length` Read only

An `unsigned long` that is the number of cues in the list.

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

`TextTrackCueList.getCueById()`

Returns the first `TextTrackCue` object with the identifier passed to it.

Examples
--------

The `HTMLMediaElement.textTracks` property returns a `TextTrackList` object listing all of the `TextTrack` objects, one for each text track linked to the media. The `TextTrack.cues` property then returns a `TextTrackCueList` containing the cues for that particular track.

```js
const video = document.getElementById("video");
video.onplay = () => {
  console.log(video.textTracks[0].cues);
};
```

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

| Specification |
| --- |
| HTML Standard # texttrackcuelist |

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

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


SVGFEPointLightElement - Web APIs

SVGFEPointLightElement
======================

The **`SVGFEPointLightElement`** interface corresponds to the `<fePointLight>` element.

EventTarget

Node

Element

SVGElement

SVGFEPointLightElementInstance properties
-------------------

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

`SVGFEPointLightElement.x` Read only

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

`SVGFEPointLightElement.y` Read only

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

`SVGFEPointLightElement.z` Read only

An `SVGAnimatedNumber` corresponding to the `z` attribute of the given element.

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

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

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

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

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

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

See also
--------

* `<fePointLight>`


ReadableStream - Web APIs

ReadableStream
==============

The `ReadableStream` interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a `ReadableStream` through the `body` property of a `Response` object.

`ReadableStream` is a transferable object.

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

`ReadableStream()`

Creates and returns a readable stream object from the given handlers.

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

`ReadableStream.locked` Read only

Returns a boolean indicating whether or not the readable stream is locked to a reader.

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

`ReadableStream.from()`
Experimental

Returns `ReadableStream` from a provided iterable or async iterable object, such as an array, a set, an async generator, and so on.

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

`ReadableStream.cancel()`

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

`ReadableStream.getReader()`

Creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.

`ReadableStream.pipeThrough()`

Provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair.

`ReadableStream.pipeTo()`

Pipes the current ReadableStream to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered.

`ReadableStream.tee()`

The `tee` method tees this readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. Each of those streams receives the same incoming data.

Async iteration
---------------

`ReadableStream` implements the async iterable protocol.
 This enables asynchronous iteration over the chunks in a stream using the `for await...of` syntax:

```js
const stream = new ReadableStream(getSomeSource());

for await (const chunk of stream) {
  // Do something with each 'chunk'
}
```

 The async iterator consumes the stream until it runs out of data or otherwise terminates.
 The loop can also exit early due to a `break`, `throw`, or `return` statement.

 While iterating, the stream is locked to prevent other consumers from acquiring a reader (attempting to iterate over a stream that is already locked will throw a `TypeError`).
 This lock is released when the loop exits.

 By default, exiting the loop will also cancel the stream, so that it can no longer be used.
 To continue to use a stream after exiting the loop, pass `{ preventCancel: true }` to the stream's `values()` method:

```js
for await (const chunk of stream.values({ preventCancel: true })) {
  // Do something with 'chunk'
  break;
}
// Acquire a reader for the stream and continue reading ...
```

Examples
--------

### Fetch stream

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

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

```js
fetch("https://www.example.org")
  .then((response) => response.body)
  .then((rb) => {
    const reader = rb.getReader();

    return new ReadableStream({
      start(controller) {
        // The following function handles each data chunk
        function push() {
          // "done" is a Boolean and value a "Uint8Array"
          reader.read().then(({ done, value }) => {
            // If there is no more data to read
            if (done) {
              console.log("done", done);
              controller.close();
              return;
            }
            // Get the data and send it to the browser via the controller
            controller.enqueue(value);
            // Check chunks by logging to the console
            console.log(done, value);
            push();
          });
        }

        push();
      },
    });
  })
  .then((stream) =>
    // Respond with our stream
    new Response(stream, { headers: { "Content-Type": "text/html" } }).text(),
  )
  .then((result) => {
    // Do things with result
    console.log(result);
  });
```

### Convert an iterator or async iterator to a stream

The `from()` static method can convert an iterator, such as an `Array` or `Map`, or an (async) iterator to a readable stream:

```js
const myReadableStream = ReadableStream.from(iteratorOrAsyncIterator);
```

On browsers that don't support the `from()` method you can instead create your own custom readable stream to achieve the same result:

```js
function iteratorToStream(iterator) {
  return new ReadableStream({
    async pull(controller) {
      const { value, done } = await iterator.next();

      if (done) {
        controller.close();
      } else {
        controller.enqueue(value);
      }
    },
  });
}
```

### Async iteration of a stream using for await...of

This example shows how you can process the `fetch()` response using a `for await...of` loop to iterate through the arriving chunks.

```js
const response = await fetch("https://www.example.org");
let total = 0;

// Iterate response.body (a ReadableStream) asynchronously
for await (const chunk of response.body) {
  // Do something with each chunk
  // Here we just accumulate the size of the response.
  total += chunk.length;
}

// Do something with the total
console.log(total);
```

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

| Specification |
| --- |
| Streams Standard # rs-class |

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

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

See also
--------

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


WebGLShader - Web APIs

WebGLShader
===========

The **WebGLShader** is part of the WebGL API and can either be a vertex or a fragment shader. A `WebGLProgram` requires both types of shaders.

WebGLObject

WebGLShaderDescription
-----------

To create a **WebGLShader** use `WebGLRenderingContext.createShader`, then hook up the GLSL source code using `WebGLRenderingContext.shaderSource()`, and finally invoke `WebGLRenderingContext.compileShader()` to finish and compile the shader. At this point the **WebGLShader** is still not in a usable form and must still be attached to a `WebGLProgram`.

```js
function createShader(gl, sourceCode, type) {
  // Compiles either a shader of type gl.VERTEX\_SHADER or gl.FRAGMENT\_SHADER
  const shader = gl.createShader(type);
  gl.shaderSource(shader, sourceCode);
  gl.compileShader(shader);

  if (!gl.getShaderParameter(shader, gl.COMPILE\_STATUS)) {
    const info = gl.getShaderInfoLog(shader);
    throw `Could not compile WebGL program. \n\n${info}`;
  }
  return shader;
}
```

See `WebGLProgram` for information on attaching the shaders.

Examples
--------

### Creating a vertex shader

Note that there are many other strategies for writing and accessing shader source code strings. These example are for illustration purposes only.

```js
const vertexShaderSource =
  "attribute vec4 position;\n" +
  "void main() {\n" +
  " gl\_Position = position;\n" +
  "}\n";

//Use the createShader function from the example above
const vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX\_SHADER);
```

### Creating a fragment shader

```js
const fragmentShaderSource =
  "void main() {\n" + " gl\_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n" + "}\n";

//Use the createShader function from the example above
const fragmentShader = createShader(
  gl,
  fragmentShaderSource,
  gl.FRAGMENT\_SHADER,
);
```

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

| Specification |
| --- |
| WebGL Specification # 5.8 |

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

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

See also
--------

* `WebGLProgram`
* `WebGLRenderingContext.attachShader()`
* `WebGLRenderingContext.bindAttribLocation()`
* `WebGLRenderingContext.compileShader()`
* `WebGLRenderingContext.createProgram()`
* `WebGLRenderingContext.createShader()`
* `WebGLRenderingContext.deleteProgram()`
* `WebGLRenderingContext.deleteShader()`
* `WebGLRenderingContext.detachShader()`
* `WebGLRenderingContext.getAttachedShaders()`
* `WebGLRenderingContext.getProgramParameter()`
* `WebGLRenderingContext.getProgramInfoLog()`
* `WebGLRenderingContext.getShaderParameter()`
* `WebGLRenderingContext.getShaderPrecisionFormat()`
* `WebGLRenderingContext.getShaderInfoLog()`
* `WebGLRenderingContext.getShaderSource()`
* `WebGLRenderingContext.isProgram()`
* `WebGLRenderingContext.isShader()`
* `WebGLRenderingContext.linkProgram()`
* `WebGLRenderingContext.shaderSource()`
* `WebGLRenderingContext.useProgram()`
* `WebGLRenderingContext.validateProgram()`


MediaQueryList - Web APIs

MediaQueryList
==============

A **`MediaQueryList`** object stores information on a media query applied to a document, with support for both immediate and event-driven matching against the state of the document.

You can create a `MediaQueryList` by calling `matchMedia()` on the `window` object. The resulting object handles sending notifications to listeners when the media query state changes (i.e. when the media query test starts or stops evaluating to `true`).

This is very useful for adaptive design, since this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, and allows you to programmatically make changes to a document based on media query status.

EventTarget

MediaQueryListInstance properties
-------------------

*The `MediaQueryList` interface inherits properties from its parent interface, `EventTarget`.*

`matches` Read only

A boolean value that returns `true` if the `document` currently matches the media query list, or `false` if not.

`media` Read only

A string representing a serialized media query.

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

*The `MediaQueryList` interface inherits methods from its parent interface, `EventTarget`.*

`addListener()`
Deprecated

Adds to the `MediaQueryList` a callback which is invoked whenever the media query status—whether or not the document matches the media queries in the list—changes. This method exists primarily for backward compatibility; if possible, you should instead use `addEventListener()` to watch for the `change` event.

`removeListener()`
Deprecated

Removes the specified listener callback from the callbacks to be invoked when the `MediaQueryList` changes media query status, which happens any time the document switches between matching and not matching the media queries listed in the `MediaQueryList`. This method has been kept for backward compatibility; if possible, you should generally use `removeEventListener()` to remove change notification callbacks (which should have previously been added using `addEventListener()`).

Events
------

*The following events are delivered to `MediaQueryList` objects:*

`change`

Sent to the `MediaQueryList` when the result of running the media query against the document changes. For example, if the media query is `(min-width: 400px)`, the `change` event is fired any time the width of the document's viewport changes such that its width moves across the 400px boundary in either direction.

Examples
--------

This simple example creates a `MediaQueryList` and then sets up a listener to detect when the media query status changes, running a custom function when it does to change the appearance of the page.

```js
const para = document.querySelector("p");
const mql = window.matchMedia("(max-width: 600px)");

function screenTest(e) {
  if (e.matches) {
    /\* the viewport is 600 pixels wide or less \*/
    para.textContent = "This is a narrow screen — less than 600px wide.";
    document.body.style.backgroundColor = "red";
  } else {
    /\* the viewport is more than 600 pixels wide \*/
    para.textContent = "This is a wide screen — more than 600px wide.";
    document.body.style.backgroundColor = "blue";
  }
}

mql.addEventListener("change", screenTest);
```

**Note:** You can find this example on GitHub (see the source code, and also see it running live).

You can find other examples on the individual property and method pages.

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

| Specification |
| --- |
| CSSOM View Module # the-mediaquerylist-interface |

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

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

See also
--------

* Media queries
* Using media queries from code
* `window.matchMedia()`
* `MediaQueryListEvent`
* The article `Window.devicePixelRatio` also has a useful example


HTMLOptGroupElement - Web APIs

HTMLOptGroupElement
===================

The **`HTMLOptGroupElement`** interface provides special properties and methods (beyond the regular `HTMLElement` object interface they also have available to them by inheritance) for manipulating the layout and presentation of `<optgroup>` elements.

EventTarget

Node

Element

HTMLElement

HTMLOptGroupElementInstance properties
-------------------

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

`HTMLOptGroupElement.disabled`

A boolean value representing whether or not the whole list of children `<option>` is disabled (true) or not (false).

`HTMLOptGroupElement.label`

A string representing the label for the group.

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

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

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

| Specification |
| --- |
| HTML Standard # htmloptgroupelement |

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

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

See also
--------

* The HTML element implementing this interface: `<optgroup>`.


Media Source API - Web APIs

Media Source API
================

The **Media Source API**, formally known as **Media Source Extensions** (**MSE**), provides functionality enabling plugin-free web-based streaming media. Using MSE, media streams can be created via JavaScript, and played using `<audio>` and `<video>` elements.

Media Source Extensions concepts and usage
------------------------------------------

Playing video and audio has been available in web applications without plugins for a few years now, but the basic features offered have really only been useful for playing single whole tracks. We can't, for example, combine/split arraybuffers. Streaming media has up until recently been the domain of Flash, with technologies like Flash Media Server serving video streams using the RTMP protocol.

### The MSE standard

With Media Source Extensions (MSE), this is changing. MSE allows us to replace the usual single progressive `src` URI fed to media elements with a reference to a `MediaSource` object, which is a container for information like the ready state of the media for being played, and references to multiple `SourceBuffer` objects that represent the different chunks of media that make up the entire stream. MSE gives us finer-grained control over how much and how often content is fetched, and some control over memory usage details, such as when buffers are evicted. It lays the groundwork for adaptive bitrate streaming clients (such as those using DASH or HLS) to be built on its extensible API.

Creating assets that work with MSE in modern browsers is a laborious process, taking significant time, computing power, and energy. The usage of external utilities to massage the content into a suitable format is required. While browser support for the various media containers with MSE is spotty, usage of the H.264 video codec, AAC audio codec, and MP4 container format is a common baseline. MSE also provides an API for runtime detection of container and codec support.

If you do not require explicit control of video quality over time, the rate at which content is fetched, or the rate at which memory is evicted, then the `<video>` and `<source>` tags may well be a simple and adequate solution.

### DASH

Dynamic Adaptive Streaming over HTTP (DASH) is a protocol for specifying how adaptive content should be fetched. It is effectively a layer built on top of MSE for building adaptive bitrate streaming clients. While there are other protocols available (such as HTTP Live Streaming (HLS)), DASH has the most platform support.

DASH moves lots of logic out of the network protocol and into the client side application logic, using the simpler HTTP protocol to fetch files. Indeed, one can support DASH with a simple static file server, which is also great for CDNs. This is in direct contrast with previous streaming solutions that required expensive licenses for proprietary non-standard client/server protocol implementations.

The two most common use cases for DASH involve watching content "on demand" or "live." On demand allows a developer to take their time transcoding the assets into multiple resolutions of various quality.

Live profile content can introduce latency due to its transcoding and broadcasting, so DASH is not suitable for real time communication like WebRTC is. It can however support significantly more client connections than WebRTC.

There are numerous available free and open source tools for transcoding content and preparing it for use with DASH, DASH file servers, and DASH client libraries written in JavaScript.

### Availability in workers

Starting with Chrome 108, MSE features are available in dedicated web workers, which allows for improved performance when manipulating `MediaSource`s and `SourceBuffer`s. To play back the media, the `MediaSource.handle` property is used to get a reference to a `MediaSourceHandle` object, a proxy for the `MediaSource` that can be transferred back to the main thread and attached to a media element via its `HTMLMediaElement.srcObject` property.

See MSE-in-Workers Demo by Matt Wolenetz for a live example.

Interfaces
----------

`MediaSource`

Represents a media source to be played via an `HTMLMediaElement` object.

`SourceBuffer`

Represents a chunk of media to be passed into an `HTMLMediaElement` via a `MediaSource` object.

`SourceBufferList`

A simple container list for multiple `SourceBuffer` objects.

`VideoPlaybackQuality`

Contains information about the quality of video being played by a `<video>` element, such as number of dropped or corrupted frames. Returned by the `HTMLVideoElement.getVideoPlaybackQuality()` method.

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

`URL.createObjectURL()`

Creates an object URL pointing to a `MediaSource` object that can then be specified as the `src` value of an HTML media element to play a media stream.

`HTMLMediaElement.seekable`

When a `MediaSource` object is played by an HTML media element, this property will return a `TimeRanges` object that contains the time ranges that the user is able to seek to.

`HTMLVideoElement.getVideoPlaybackQuality()`

Returns a `VideoPlaybackQuality` object for the currently played video.

`AudioTrack.sourceBuffer`, `VideoTrack.sourceBuffer`, `TextTrack.sourceBuffer`

Returns the `SourceBuffer` that created the track in question.

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

| Specification |
| --- |
| Media Source Extensions™  |

See also
--------

* Transcoding assets for Media Source Extensions
* Using MSE to create a basic streaming service (TBD)
* Using MPEG DASH to create a streaming application (TBD)
* The `<audio>` and `<video>` elements.
* `HTMLMediaElement`, `HTMLVideoElement`, `HTMLAudioElement`.


Broadcast Channel API - Web APIs

Broadcast Channel API
=====================

Baseline 2022
-------------

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

* Learn more
* See full compatibility
* Report feedback
The **Broadcast Channel API** allows basic communication between browsing contexts (that is, *windows*, *tabs*, *frames*, or *iframes*) and workers on the same origin.

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

By creating a `BroadcastChannel` object, you can receive any messages that are posted to it. You don't have to maintain a reference to the frames or workers you wish to communicate with: they can "subscribe" to a particular channel by constructing their own `BroadcastChannel` with the same name, and have bi-directional communication between all of them.

![The principle of the Broadcast Channel API](/en-US/docs/Web/API/Broadcast_Channel_API/broadcastchannel.png)

Broadcast Channel interface
---------------------------

### Creating or joining a channel

A client joins a broadcast channel by creating a `BroadcastChannel` object. Its constructor takes one single parameter: the *name* of the channel. If it is the first to connect to that broadcast channel name, the underlying channel is created.

```js
// Connection to a broadcast channel
const bc = new BroadcastChannel("test\_channel");
```

### Sending a message

It is enough to call the `postMessage()` method on the created `BroadcastChannel` object, which takes any object as an argument. An example string message:

```js
// Example of sending of a very simple message
bc.postMessage("This is a test message.");
```

Data sent to the channel is serialized using the structured clone algorithm. That means you can send a broad variety of data objects safely without having to serialize them yourself.

The API doesn't associate any semantics to messages, so it is up to the code to know what kind of messages to expect and what to do with them.

### Receiving a message

When a message is posted, a `message` event is dispatched to each `BroadcastChannel` object connected to this channel. A function can be run for this event using the `onmessage` event handler:

```js
// A handler that only logs the event to the console:
bc.onmessage = (event) => {
  console.log(event);
};
```

### Disconnecting a channel

To leave a channel, call the `close()` method on the object. This disconnects the object from the underlying channel, allowing garbage collection.

```js
// Disconnect the channel
bc.close();
```

Conclusion
----------

The Broadcast Channel API's self-contained interface allows cross-context communication. It can be used to detect user actions in other tabs within a same origin, like when the user logs in or out.

The messaging protocol is not defined and the different browsing contexts need to implement it themselves; there is no negotiation nor requirement from the specification.

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

| Specification |
| --- |
| HTML Standard # broadcasting-to-other-browsing-contexts |

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

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

See also
--------

* `BroadcastChannel`, the interface implementing it.


DeviceMotionEvent - Web APIs

DeviceMotionEvent
=================

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

The **`DeviceMotionEvent`** interface of the Device Orientation Events provides web developers with information about the speed of changes for the device's position and orientation.

**Warning:** Currently, Firefox and Chrome do not handle the coordinates the same way. Take care about this while using them.

Event

DeviceMotionEventConstructor
-----------

`DeviceMotionEvent()`

Creates a new `DeviceMotionEvent`.

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

`DeviceMotionEvent.acceleration` Read only

An object giving the acceleration of the device on the three axis X, Y and Z. Acceleration is expressed in m/s².

`DeviceMotionEvent.accelerationIncludingGravity` Read only

An object giving the acceleration of the device on the three axis X, Y and Z with the effect of gravity. Acceleration is expressed in m/s².

`DeviceMotionEvent.rotationRate` Read only

An object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma. Rotation rate is expressed in degrees per seconds.

`DeviceMotionEvent.interval` Read only

A number representing the interval of time, in milliseconds, at which data is obtained from the device.

Example
-------

```js
window.addEventListener("devicemotion", (event) => {
  console.log(`${event.acceleration.x} m/s2`);
});
```

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

| Specification |
| --- |
| DeviceOrientation Event Specification # devicemotion |

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

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

See also
--------

* Detecting device orientation
* Orientation and motion data explained
* `DeviceOrientationEvent`
* `deviceorientation` event
* `deviceorientationabsolute` event
* `devicemotion` event
* `Accelerometer`
* `LinearAccelerationSensor`


ReportingObserver - Web APIs

ReportingObserver
=================

The `ReportingObserver` interface of the Reporting API allows you to collect and access reports.

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

`ReportingObserver()`

Creates a new `ReportingObserver` object instance, which can be used to collect and access reports.

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

*This interface has no properties defined on it.*

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

`ReportingObserver.disconnect()`

Stops a reporting observer that had previously started observing from collecting reports.

`ReportingObserver.observe()`

Instructs a reporting observer to start collecting reports in its report queue.

`ReportingObserver.takeRecords()`

Returns the current list of reports contained in the observer's report queue, and empties the queue.

Events
------

*This interface has no events that fire on it.*

Examples
--------

In our deprecation\_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page:

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

const observer = new ReportingObserver((reports, observer) => {
  reportBtn.onclick = () => displayReports(reports);
}, options);
```

We then tell it to start observing reports using `ReportingObserver.observe()`; this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor:

```js
observer.observe();
```

Later on in the example we deliberately use the deprecated version of `MediaDevices.getUserMedia()`:

```js
if (navigator.mozGetUserMedia) {
  navigator.mozGetUserMedia(constraints, success, failure);
} else {
  navigator.getUserMedia(constraints, success, failure);
}
```

This causes a deprecation report to be generated; because of the event handler we set up inside the `ReportingObserver()` constructor, we can now click the button to display the report details.

![image of a jolly bearded man with various stats displayed below it about a deprecated feature](/en-US/docs/Web/API/ReportingObserver/reporting_api_example.png)

**Note:** If you look at the complete source code, you'll notice that we actually call the deprecated `getUserMedia()` method twice. After the first time we call `ReportingObserver.takeRecords()`, which returns the first generated report and empties the queue. Because of this, when the button is pressed only the second report is listed.

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

| Specification |
| --- |
| Reporting API # interface-reporting-observer |

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

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

See also
--------

* Reporting API


SVGDefsElement - Web APIs

SVGDefsElement
==============

The **`SVGDefsElement`** interface corresponds to the `<defs>` element.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGDefsElementInstance properties
-------------------

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

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

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

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

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

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

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


XRCompositionLayer - Web APIs

XRCompositionLayer
==================

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

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

The **`XRCompositionLayer`** interface of the WebXR Device API is a base class that defines a set of common properties and behaviors for WebXR layer types. It is not constructable on its own.

Several layer types inherit from `XRCompositionLayer`:

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

`XRCompositionLayer` itself inherits from the general `XRLayer` class (which inherits from `EventTarget`).

EventTarget

XRLayer

XRCompositionLayerInstance properties
-------------------

`XRCompositionLayer.blendTextureSourceAlpha`
Experimental

A boolean enabling the layer's texture alpha channel.

`XRCompositionLayer.layout` Read only
Experimental

The layout type of the layer.

`XRCompositionLayer.mipLevels` Read only
Experimental

The number of mip levels in the color and texture data for the layer.

`XRCompositionLayer.needsRedraw` Read only
Experimental

A boolean signaling that the layer should be re-rendered in the next frame.

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

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

`XRCompositionLayer.destroy()`
Experimental

Deletes the underlying layer attachments.

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

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

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

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

See also
--------

* `XRLayer`
* `EventTarget`
* `XREquirectLayer`
* `XRCubeLayer`
* `XRCylinderLayer`
* `XRProjectionLayer`
* `XRQuadLayer`


FragmentDirective - Web APIs

FragmentDirective
=================

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

The **`FragmentDirective`** interface is an object exposed for feature detectability, that is, whether or not a browser supports text fragments.

It is accessed via the `Document.fragmentDirective` property.

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

None.

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

None.

Examples
--------

Try running the following in a supporting browser's devtools, in a tab with one or more matched text fragments:

```js
document.fragmentDirective;
// returns an empty FragmentDirective object, if supported
// undefined otherwise
```

This functionality is mainly intended for feature detection at present. In the future, the `FragmentDirective` object could include additional information.

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

| Specification |
| --- |
| URL Fragment Text Directives # fragmentdirective |

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

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

See also
--------

* Text fragments
* `::target-text`


isSecureContext global property - Web APIs

isSecureContext global property
===============================

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

 The global **`isSecureContext`** read-only property returns a boolean indicating whether
 the current context is secure
 (`true`) or not (`false`).

Value
-----

Boolean `true` or `false`.

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

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

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

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

See also
--------

* Secure contexts


HTMLStyleElement - Web APIs

HTMLStyleElement
================

The **`HTMLStyleElement`** interface represents a `<style>` element. It inherits properties and methods from its parent, `HTMLElement`.

This interface doesn't allow to manipulate the CSS it contains (in most case). To manipulate CSS, see Using dynamic styling information for an overview of the objects used to manipulate specified CSS properties using the DOM.

EventTarget

Node

Element

HTMLElement

HTMLStyleElementInstance properties
-------------------

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

`HTMLStyleElement.media`

A string reflecting the HTML attribute representing the intended destination medium for style information.

`HTMLStyleElement.type`
Deprecated

A string reflecting the HTML attribute representing the type of style being applied by this statement.

`HTMLStyleElement.disabled`

A boolean value indicating whether or not the associated stylesheet is disabled.

`HTMLStyleElement.sheet` Read only

Returns the `CSSStyleSheet` object associated with the given element, or `null` if there is none.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlstyleelement |

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

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

See also
--------

* The HTML element implementing this interface: `<style>`.
* Using dynamic styling information to see how to manipulate CSS.


SharedStorageWorklet - Web APIs

SharedStorageWorklet
====================

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

The **`SharedStorageWorklet`** interface of the Shared Storage API represents the shared storage worklet for the current origin.

`SharedStorageWorklet` does not have its own properties or methods. Rather, it inherits the `addModule()` method from the `Worklet` interface. This method is used for adding a module.

Unlike a regular `Worklet`:

* If the calling site has not included the Shared Storage API in a privacy sandbox enrollment process, calls to `sharedStorageWorklet.addModule()` will be rejected.
* `SharedStorageWorklet` allows only a single module to be added, for privacy reasons. Even with a successful enrollment, repeated calls to `addModule()` on the same shared storage worklet will be rejected.

`SharedStorageWorklet` is accessed via `WindowSharedStorage.worklet`.

Worklet

SharedStorageWorkletExamples
--------

```js
// Randomly assigns a user to a group 0 or 1
function getExperimentGroup() {
  return Math.round(Math.random());
}

async function injectContent() {
  // Add the module to the shared storage worklet
  await window.sharedStorage.worklet.addModule("ab-testing-worklet.js");

  // Assign user to a random group (0 or 1) and store it in shared storage
  window.sharedStorage.set("ab-testing-group", getExperimentGroup(), {
    ignoreIfPresent: true,
  });

  // Run the URL selection operation
  const fencedFrameConfig = await window.sharedStorage.selectURL(
    "ab-testing",
    [
      { url: `https://your-server.example/content/default-content.html` },
      { url: `https://your-server.example/content/experiment-content-a.html` },
    ],
    {
      resolveToConfig: true,
    },
  );

  // Render the chosen URL into a fenced frame
  document.getElementById("content-slot").config = fencedFrameConfig;
}

injectContent();
```

See the Shared Storage API landing page for a walkthrough of this example and links to other examples.

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

| Specification |
| --- |
| Shared Storage API # sharedstorageworklet |

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

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

See also
--------

* Shared Storage API


GPURenderPassEncoder - Web APIs

GPURenderPassEncoder
====================

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

The **`GPURenderPassEncoder`** interface of the WebGPU API encodes commands related to controlling the vertex and fragment shader stages, as issued by a `GPURenderPipeline`. It forms part of the overall encoding activity of a `GPUCommandEncoder`.

A render pipeline renders graphics to `GPUTexture` attachments, typically intended for display in a `<canvas>` element, but it could also render to textures used for other purposes that never appear onscreen. It has two main stages:

* A vertex stage, in which a vertex shader takes positioning data fed into the GPU and uses it to position a series of vertices in 3D space by applying specified effects like rotation, translation, or perspective. The vertices are then assembled into primitives such as triangles (the basic building block of rendered graphics) and rasterized by the GPU to figure out what pixels each one should cover on the drawing canvas.
* A fragment stage, in which a fragment shader computes the color for each pixel covered by the primitives produced by the vertex shader. These computations frequently use inputs such as images (in the form of textures) that provide surface details and the position and color of virtual lights.

A `GPURenderPassEncoder` object instance is created via the `GPUCommandEncoder.beginRenderPass()` property.

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

`label`
Experimental

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

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

`beginOcclusionQuery()`
Experimental

Begins an occlusion query at the specified index of the relevant `GPUQuerySet` (provided as the value of the `occlusionQuerySet` descriptor property when invoking `GPUCommandEncoder.beginRenderPass()` to run the render pass).

`draw()`
Experimental

Draw primitives based on the vertex buffers provided by `setVertexBuffer()`.

`drawIndexed()`
Experimental

Draw indexed primitives based on the vertex and index buffers provided by `setVertexBuffer()` and `setIndexBuffer()`

`drawIndirect()`
Experimental

Draw primitives using parameters read from a `GPUBuffer`.

`drawIndexedIndirect()`
Experimental

Draw indexed primitives using parameters read from a `GPUBuffer`.

`end()`
Experimental

Completes recording of the current render pass command sequence.

`endOcclusionQuery()`
Experimental

Ends an active occlusion query previously started with `beginOcclusionQuery()`.

`executeBundles()`
Experimental

Executes commands previously recorded into the referenced `GPURenderBundle`s, as part of this render pass.

`insertDebugMarker()`
Experimental

Marks a specific point in a series of encoded commands with a label.

`popDebugGroup()`
Experimental

Ends a debug group, which is begun with a `pushDebugGroup()` call.

`pushDebugGroup()`
Experimental

Begins a debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a `popDebugGroup()` method is invoked.

`setBindGroup()`
Experimental

Sets the `GPUBindGroup` to use for subsequent render commands, for a given index.

`setBlendConstant()`
Experimental

Sets the constant blend color and alpha values used with `"constant"` and `"one-minus-constant"` blend factors (as set in the descriptor of the `GPUDevice.createRenderPipeline()` method, in the `blend` property).

`setIndexBuffer()`
Experimental

Sets the current `GPUBuffer` that will provide index data for subsequent drawing commands.

`setPipeline()`
Experimental

Sets the `GPURenderPipeline` to use for this render pass.

`setScissorRect()`
Experimental

Sets the scissor rectangle used during the rasterization stage. After transformation into viewport coordinates any fragments that fall outside the scissor rectangle will be discarded.

`setStencilReference()`
Experimental

Sets the stencil reference value using during stencil tests with the `"replace"` stencil operation (as set in the descriptor of the `GPUDevice.createRenderPipeline()` method, in the properties defining the various stencil operations).

`setVertexBuffer()`
Experimental

Sets or unsets the current `GPUBuffer` that will provide vertex data for subsequent drawing commands.

`setViewport()`
Experimental

Sets the viewport used during the rasterization stage to linearly map from normalized device coordinates to viewport coordinates.

Examples
--------

In our basic render demo, several commands are recorded via a `GPUCommandEncoder`. Most of these commands originate from the `GPURenderPassEncoder` created via `GPUCommandEncoder.beginRenderPass()`.

```js
// ...

const renderPipeline = device.createRenderPipeline(pipelineDescriptor);

// Create GPUCommandEncoder to issue commands to the GPU
// Note: render pass descriptor, command encoder, etc. are destroyed after use, fresh one needed for each frame.
const commandEncoder = device.createCommandEncoder();

// Create GPURenderPassDescriptor to tell WebGPU which texture to draw into, then initiate render pass
const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear",
      storeOp: "store",
      view: context.getCurrentTexture().createView(),
    },
  ],
};

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

// Draw the triangle
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

// End the render pass
passEncoder.end();

// End frame by passing array of command buffers to command queue for execution
device.queue.submit([commandEncoder.finish()]);

// ...
```

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

| Specification |
| --- |
| WebGPU # gpurenderpassencoder |

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

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

See also
--------

* The WebGPU API


FileSystemSync - Web APIs

FileSystemSync
==============

**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.

**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.

In the File and Directory Entries API, a `FileSystemSync` object represents a file system. It has two properties.

**Warning:** This interface is deprecated and is no more on the standard track.
 *Do not use it anymore.* Use the File and Directory Entries API instead.

Basic concepts
--------------

The `FileSystemSync` object is your gateway to the entire API and you will use it a lot. So once you have a reference, cache the object in a global variable or class property.

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

`name` Read only
Non-standard

Deprecated

A string that represents the name of the file system. The name must be unique across the list of exposed file systems.

`root` Read only
Non-standard

Deprecated

A `DirectoryEntry` that is the root directory of the file system.

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

This feature is not part of any specification anymore. It is no longer on track to become a standard.

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

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

See also
--------

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


HTMLMapElement - Web APIs

HTMLMapElement
==============

The **`HTMLMapElement`** interface provides special properties and methods (beyond those of the regular object `HTMLElement` interface it also has available to it by inheritance) for manipulating the layout and presentation of map elements.

EventTarget

Node

Element

HTMLElement

HTMLMapElementInstance properties
-------------------

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

`HTMLMapElement.name`

A string representing the `<map>` element for referencing it other context. If the `id` attribute is set, this must have the same value; and it cannot be `null` or empty.

`HTMLMapElement.areas` Read only

A live `HTMLCollection` representing the `<area>` elements associated to this `<map>`.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlmapelement |

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

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

See also
--------

* HTML element implementing this interface: `<map>`.


Document Object Model (DOM) - Web APIs

Document Object Model (DOM)
===========================

The **Document Object Model** (**DOM**) connects web pages to scripts or programming languages by representing the structure of a document—such as the HTML representing a web page—in memory. Usually it refers to JavaScript, even though modeling HTML, SVG, or XML documents as objects are not part of the core JavaScript language.

The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content.

Nodes can also have event handlers attached to them. Once an event is triggered, the event handlers get executed.

To learn more about what the DOM is and how it represents documents, see our article Introduction to the DOM.

DOM interfaces
--------------

* `AbortController`
* `AbortSignal`
* `AbstractRange`
* `Attr`
* `CDATASection`
* `CharacterData`
* `Comment`
* `CustomEvent`
* `Document`
* `DocumentFragment`
* `DocumentType`
* `DOMError`
Deprecated
* `DOMException`
* `DOMImplementation`
* `DOMParser`
* `DOMPoint`
* `DOMPointReadOnly`
* `DOMRect`
* `DOMTokenList`
* `Element`
* `Event`
* `EventTarget`
* `HTMLCollection`
* `MutationObserver`
* `MutationRecord`
* `NamedNodeMap`
* `Node`
* `NodeIterator`
* `NodeList`
* `ProcessingInstruction`
* `Range`
* `StaticRange`
* `Text`
* `TextDecoder`
* `TextEncoder`
* `TimeRanges`
* `TreeWalker`
* `XMLDocument`
### Obsolete DOM interfaces

The Document Object Model has been highly simplified. To achieve this, the following interfaces in the different DOM level 3 or earlier specifications have been removed. They are no longer available to web developers.

* `DOMConfiguration`
* `DOMErrorHandler`
* `DOMImplementationList`
* `DOMImplementationRegistry`
* `DOMImplementationSource`
* `DOMLocator`
* `DOMObject`
* `DOMSettableTokenList`
* `DOMUserData`
* `ElementTraversal`
* `Entity`
* `EntityReference`
* `NameList`
* `Notation`
* `TypeInfo`
* `UserDataHandler`
HTML DOM
--------

A document containing HTML is described using the `Document` interface, which is extended by the HTML specification to include various HTML-specific features. In particular, the `Element` interface is enhanced to become `HTMLElement` and various subclasses, each representing one of (or a family of closely related) elements.

The HTML DOM API provides access to various browser features such as tabs and windows, CSS styles and stylesheets, browser history, etc. These interfaces are discussed further in the HTML DOM API documentation.

SVG DOM
-------

Similarly, a document containing SVG is also described using the `Document` interface, which is extended by the SVG specification to include various SVG-specific features. In particular, the `Element` interface is enhanced to become `SVGElement` and various subclasses, each representing an element or a family of closely related elements. These interfaces are discussed further in the SVG API documentation.

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

| Specification |
| --- |
| DOM Standard  |

See also
--------

* DOM Examples
* CSS Object Model (CSSOM)


SVGLength - Web APIs

SVGLength
=========

SVG length interface
--------------------

The `SVGLength` interface correspond to the <length> basic data type.

An `SVGLength` object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown.

### Interface overview

|  |  |
| --- | --- |
| Also implement | None |
| Methods | * `void **newValueSpecifiedUnits**(in unsigned short
unitType, in float
valueInSpecifiedUnits)`
* `void **convertToSpecifiedUnits**(in unsigned short
unitType)`
 |
| Properties | * readonly unsigned short `unitType`
* float `value`
* float `valueInSpecifiedUnits`
* string `valueAsString`
 |
| Constants | * `SVG_LENGTHTYPE_UNKNOWN` = `0`
* `SVG_LENGTHTYPE_NUMBER` = `1`
* `SVG_LENGTHTYPE_PERCENTAGE` = `2`
* `SVG_LENGTHTYPE_EMS` = `3`
* `SVG_LENGTHTYPE_EXS` = `4`
* `SVG_LENGTHTYPE_PX` = `5`
* `SVG_LENGTHTYPE_CM` = `6`
* `SVG_LENGTHTYPE_MM` = `7`
* `SVG_LENGTHTYPE_IN` = `8`
* `SVG_LENGTHTYPE_PT` = `9`
* `SVG_LENGTHTYPE_PC` = `10`
 |
| Normative document | SVG 1.1 (2nd Edition) |

Example
-------

```xml
<svg height="200" onload="start();" version="1.1" width="200" xmlns="http://www.w3.org/2000/svg">
  <script><![CDATA[
function start() {
 const rect = document.getElementById("myRect");
 const val = rect.x.baseVal;

 // read x in pixel and cm units
 console.log("value: " + val.value +
 ", valueInSpecifiedUnits: " + val.unitType + ": " + val.valueInSpecifiedUnits +
 ", valueAsString: " + val.valueAsString);

 // set x = 20pt and read it out in pixel and pt units
 val.newValueSpecifiedUnits(SVGLength.SVG\_LENGTHTYPE\_PT, 20);
 console.log("value: " + val.value +
 ", valueInSpecifiedUnits " + val.unitType + ": " + val.valueInSpecifiedUnits +
 ", valueAsString: " + val.valueAsString);

 // convert x = 20pt to inches and read out in pixel and inch units
 val.convertToSpecifiedUnits(SVGLength.SVG\_LENGTHTYPE\_IN);
 console.log("value: " + val.value +
 ", valueInSpecifiedUnits " + val.unitType + ": " + val.valueInSpecifiedUnits +
 ", valueAsString: " + val.valueAsString);
}
]]></script>
  <rect id="myRect"
 x="1cm" y="1cm"
 fill="green" stroke="black" stroke-width="1"
 width="1cm" height="1cm"
 />
</svg>
```

Results on a desktop monitor (pixel units will be dpi-dependent):
```

value: 37.7952766418457, valueInSpecifiedUnits: 6: 1, valueAsString: 1cm
value: 26.66666603088379, valueInSpecifiedUnits 9: 20, valueAsString: 20pt
value: 26.66666603088379, valueInSpecifiedUnits 8: 0.277777761220932, valueAsString: 0.277778in
```

Constants
---------

| Name | Value | Description |
| --- | --- | --- |
| `SVG_LENGTHTYPE_UNKNOWN` | `0` |
 The unit type is not one of predefined unit types. It is invalid to
 attempt to define a new value of this type or to attempt to switch an
 existing value to this type.
  |
| `SVG_LENGTHTYPE_NUMBER` | `1` |
 No unit type was provided (i.e., a unitless value was specified), which
 indicates a value in user units.
  |
| `SVG_LENGTHTYPE_PERCENTAGE` | `2` | A percentage value was specified. |
| `SVG_LENGTHTYPE_EMS` | `3` | A value was specified using the em units defined in CSS2. |
| `SVG_LENGTHTYPE_EXS` | `4` | A value was specified using the ex units defined in CSS2. |
| `SVG_LENGTHTYPE_PX` | `5` | A value was specified using the px units defined in CSS2. |
| `SVG_LENGTHTYPE_CM` | `6` | A value was specified using the cm units defined in CSS2. |
| `SVG_LENGTHTYPE_MM` | `7` | A value was specified using the mm units defined in CSS2. |
| `SVG_LENGTHTYPE_IN` | `8` | A value was specified using the in units defined in CSS2. |
| `SVG_LENGTHTYPE_PT` | `9` | A value was specified using the pt units defined in CSS2. |
| `SVG_LENGTHTYPE_PC` | `10` | A value was specified using the pc units defined in CSS2. |

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

| Name | Type | Description |
| --- | --- | --- |
| `unitType` | unsigned short |
 The type of the value as specified by one of the
 `SVG_LENGTHTYPE_*` constants defined on this interface.
  |
| `value` | float |
 The value as a floating point value, in user units. Setting this
 attribute will cause `valueInSpecifiedUnits` and
 `valueAsString` to be updated automatically to reflect this
 setting.

**Exceptions on setting:** a
 `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the length
 corresponds to a read only attribute or when the object itself is read
 only.
  |
| `valueInSpecifiedUnits` | float |
 The value as a floating point value, in the units expressed by
 `unitType`. Setting this attribute will cause
 `value` and `valueAsString` to be updated
 automatically to reflect this setting.

**Exceptions on setting:** a
 `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the length
 corresponds to a read only attribute or when the object itself is read
 only.
  |
| `valueAsString` | string |
 The value as a string value, in the units expressed by
 `unitType`. Setting this attribute will cause
 `value`, `valueInSpecifiedUnits`, and
 `unitType` to be updated automatically to reflect this
 setting.

**Exceptions on setting:*** a `DOMException` with code
 `SYNTAX_ERR` is raised if the assigned string cannot be
 parsed as a valid
 <length>.
* a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the length
 corresponds to a read only attribute or when the object itself is
 read only.
 |

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

| Name & Arguments | Return | Description |
| --- | --- | --- |
| `**newValueSpecifiedUnits**(in unsigned short
unitType, in float valueInSpecifiedUnits)` | void |
 Reset the value as a number with an associated unitType, thereby
 replacing the values for all of the attributes on the object.

**Exceptions:*** a `DOMException` with code
 `NOT_SUPPORTED_ERR` is raised if `unitType` is
 `SVG_LENGTHTYPE_UNKNOWN` or not a valid unit type
 constant (one of the other `SVG_LENGTHTYPE_*` constants
 defined on this interface).
* a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the length
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**convertToSpecifiedUnits**(in unsigned short
unitType)` | void |
 Preserve the same underlying stored value, but reset the stored unit
 identifier to the given `unitType`. Object attributes `unitType`,
 `valueInSpecifiedUnits`, and `valueAsString` might
 be modified as a result of this method. For example, if the original
 value were `"0.5cm"` and the method was invoked to convert to
 millimeters, then the `unitType` would be changed to
 `SVG_LENGTHTYPE_MM`, `valueInSpecifiedUnits` would
 be changed to the numeric value `5` and
 `valueAsString` would be changed to `"5mm"`.
  |

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

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


SVGFontFaceUriElement - Web APIs

SVGFontFaceUriElement
=====================

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

The **`SVGFontFaceUriElement`** interface corresponds to the `<font-face-uri>` elements.

Object-oriented access to the attributes of the `<font-face-uri>` element via the SVG DOM is not possible.

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

*This interface has no properties but inherits properties from its parent, `SVGElement`.*

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

*This interface has no methods but inherits methods from its parent, `SVGElement`.*

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

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 1.1 (Second Edition) # InterfaceSVGFontFaceUriElement |

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

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

See also
--------

* `<font-face-uri>`


SVGAnimationElement - Web APIs

SVGAnimationElement
===================

The **`SVGAnimationElement`** interface is the base interface for all of the animation element interfaces: `SVGAnimateElement`, `SVGSetElement`, `SVGAnimateColorElement`, `SVGAnimateMotionElement` and `SVGAnimateTransformElement`.

EventTarget

Node

Element

SVGElement

SVGAnimationElementInstance properties
-------------------

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

`SVGAnimationElement.requiredExtensions` Read only

An `SVGStringList` reflecting the `requiredExtensions` attribute of the given element.

`SVGAnimationElement.systemLanguage` Read only

An `SVGStringList` reflecting the `systemLanguage` attribute of the given element.

`SVGAnimationElement.targetElement` Read only

An `SVGElement` representing the element which is being animated. If no target element is being animated (for example, because the `href` specifies an unknown element) the value returned is `null`.

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

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

`SVGAnimationElement.getStartTime()`

Returns a float representing the begin time, in seconds, for this animation element's current interval, if it exists, regardless of whether the interval has begun yet. If there is no current interval, then a `DOMException` with code `INVALID_STATE_ERR` is thrown.

`SVGAnimationElement.getCurrentTime()`

Returns a float representing the current time in seconds relative to time zero for the given time container.

`SVGAnimationElement.getSimpleDuration()`

Returns a float representing the number of seconds for the simple duration for this animation. If the simple duration is undefined (e.g., the end time is indefinite), then a `DOMException` with code `NOT_SUPPORTED_ERR` is raised.

`SVGAnimationElement.beginElement()`

Creates a begin instance time for the current time. The new instance time is added to the begin instance times list. The behavior of this method is equivalent to `beginElementAt(0)`.

`SVGAnimationElement.beginElementAt()`

Creates a begin instance time for the current time plus the specified offset. The new instance time is added to the begin instance times list.

`SVGAnimationElement.endElement()`

Creates an end instance time for the current time. The new instance time is added to the end instance times list. The behavior of this method is equivalent to `endElementAt(0)`.

`SVGAnimationElement.endElementAt()`

Creates an end instance time for the current time plus the specified offset. The new instance time is added to the end instance times list.

Events
------

Listen to these events using `addEventListener()` or by assigning an event listener to the `on...` handler property of this interface.

`beginEvent`

Fired when the element local timeline begins to play.

`endEvent`

Fired when at the active end of the animation is reached.

`repeatEvent`

Fired when the element's local timeline repeats. It will be fired each time the element repeats, after the first iteration.

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

| Specification |
| --- |
| SVG Animations Level 2 # InterfaceSVGAnimationElement |

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

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