KHR_parallel_shader_compile extension - Web APIs

KHR\_parallel\_shader\_compile extension
========================================

The **`KHR_parallel_shader_compile`** extension is part of the WebGL API and enables a non-blocking poll operation, so that compile/link status availability (`COMPLETION_STATUS_KHR`) can be queried without potentially incurring stalls. In other words you can check the status of your shaders compiling without blocking the runtime.

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

Constants
---------

`ext.COMPLETION_STATUS_KHR`

A GLenum.

Examples
--------

Enable the extension:

```js
const ext = gl.getExtension("KHR\_parallel\_shader\_compile");
```

In general, best practice with or without the extension is:

```js
// Assuming lists of `shaders` and `programs`:
for (const x of shaders) gl.compileShader(x); // Never check compile status unless subsequent linking fails.
for (const x of programs) gl.linkProgram(x);
```

With the extension, apps would be able to poll whether programs have linked without janking, but these are likely to take the same total wall time to link:

```js
// Generator yielding a progress ratio [0.0, 1.0].
// Without the extension, this will jank and only check one program per generation.
function\* linkingProgress(programs) {
  const ext = gl.getExtension("KHR\_parallel\_shader\_compile");
  let todo = programs.slice();
  while (todo.length) {
    if (ext) {
      todo = todo.filter(
        (x) => !gl.getProgramParameter(x, ext.COMPLETION\_STATUS\_KHR),
      );
    } else {
      const x = todo.pop();
      gl.getProgramParameter(x, gl.LINK\_STATUS);
    }
    if (!todo.length) return;
    yield 1.0 - todo.length / programs.length;
  }
}
```

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

| Specification |
| --- |
| WebGL KHR\_parallel\_shader\_compile Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`


WorkerNavigator - Web APIs

WorkerNavigator
===============

The **`WorkerNavigator`** interface represents a subset of the `Navigator` interface allowed to be accessed from a `Worker`. Such an object is initialized for each worker and is available via the `self.navigator` property.

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

*The `WorkerNavigator` interface doesn't inherit any property.*

`WorkerNavigator.appCodeName`
Deprecated
 Read only

Always returns `'Mozilla'`, in any browser. This property is kept only for compatibility purposes.

`WorkerNavigator.appName`
Deprecated
 Read only

Returns the official name of the browser. Do not rely on this property to return the correct value.

`WorkerNavigator.appVersion`
Deprecated
 Read only

Returns the version of the browser as a string. Do not rely on this property to return the correct value.

`WorkerNavigator.connection` Read only

Provides a `NetworkInformation` object containing information about the network connection of a device.

`WorkerNavigator.deviceMemory` Read only

Returns the amount of device memory in gigabytes. This value is an approximation given by rounding to the nearest power of 2 and dividing that number by 1024.

`WorkerNavigator.globalPrivacyControl` Read only
Experimental

Non-standard

Returns a boolean indicating a user's consent to their information being shared or sold.

`WorkerNavigator.gpu` Read only
Experimental

Returns the `GPU` object for the current worker context. The entry point for the WebGPU API.

`WorkerNavigator.hardwareConcurrency` Read only

Returns the number of logical processor cores available.

`WorkerNavigator.language` Read only

Returns a string representing the preferred language of the user, usually the language of the browser UI. The `null` value is returned when this is unknown.

`WorkerNavigator.languages` Read only

Returns an array of strings representing the languages known to the user, by order of preference.

`WorkerNavigator.locks` Read only

Returns a `LockManager` object which provides methods for requesting a new `Lock` object and querying for an existing `Lock` object.

`WorkerNavigator.mediaCapabilities` Read only

Returns a `MediaCapabilities` object that can expose information about the decoding and encoding capabilities for a given format and output capabilities.

`WorkerNavigator.onLine` Read only

Returns a boolean value indicating whether the browser is online.

`WorkerNavigator.permissions` Read only

Returns a `Permissions` object that can be used to query and update permission status of APIs covered by the Permissions API.

`WorkerNavigator.platform`
Deprecated
 Read only

Returns a string representing the platform of the browser. Do not rely on this property to return the correct value.

`WorkerNavigator.product`
Deprecated
 Read only

Always returns `'Gecko'`, on any browser. This property is kept only for compatibility purposes.

`WorkerNavigator.serial` Read only
Experimental

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

`WorkerNavigator.serviceWorker` Read only

Returns a `ServiceWorkerContainer` object, which provides access to registration, removal, upgrade, and communication with the `ServiceWorker` objects for the associated document.

`WorkerNavigator.storage` Read only

Returns a `StorageManager` interface for managing persistence permissions and estimating available storage.

`WorkerNavigator.usb` Read only

Returns a `USB` object for the current document, providing access to WebUSB API functionality.

`WorkerNavigator.userAgent` Read only

Returns the user agent string for the current browser.

`WorkerNavigator.userAgentData` Read only
Experimental

Returns a `NavigatorUAData` object, which gives access to information about the browser and operating system of the user.

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

*The `WorkerNavigator` interface doesn't inherit any method.*

`Navigator.clearAppBadge()`

Clears a badge on the current app's icon and returns a `Promise` that resolves with `undefined`.

`Navigator.setAppBadge()`

Sets a badge on the icon associated with this app and returns a `Promise` that resolves with `undefined`.

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

| Specification |
| --- |
| HTML Standard # the-workernavigator-object |

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

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

See also
--------

* Other Worker-related interfaces: `Worker`, `WorkerLocation`, and `WorkerGlobalScope`
* Using web workers


LinearAccelerationSensor - Web APIs

LinearAccelerationSensor
========================

The **`LinearAccelerationSensor`** interface of the Sensor APIs provides on each reading the acceleration applied to the device along all three axes, but without the contribution of gravity.

To use this sensor, the user must grant permission to the `'accelerometer'` device sensor through the Permissions API. In addition, this feature may be blocked by a Permissions Policy set on your server.

EventTarget

Sensor

Accelerometer

LinearAccelerationSensorConstructor
-----------

`LinearAccelerationSensor()`

Creates a new `LinearAccelerationSensor` object.

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

*Inherits properties from its ancestors, `Accelerometer`, `Sensor`, and `EventTarget`.*

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

*`LinearAccelerationSensor` doesn't have own methods. However, it inherits methods from its parent interfaces, `Sensor` and `EventTarget`.*

Events
------

*`LinearAccelerationSensor` doesn't have own events. However, it inherits events from its parent interface, `Sensor`.*

Example
-------

Linear acceleration is typically read in the `reading` event callback. In the example below this occurs sixty times a second.

```js
let laSensor = new LinearAccelerationSensor({ frequency: 60 });

laSensor.addEventListener("reading", (e) => {
  console.log(`Linear acceleration along the X-axis ${laSensor.x}`);
  console.log(`Linear acceleration along the Y-axis ${laSensor.y}`);
  console.log(`Linear acceleration along the Z-axis ${laSensor.z}`);
});
laSensor.start();
```

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

| Specification |
| --- |
| Accelerometer # linearaccelerationsensor-interface |

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

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


FileReaderSync - Web APIs

FileReaderSync
==============

The **`FileReaderSync`** interface allows to read `File` or `Blob` objects synchronously. This interface is only available in workers as it enables synchronous I/O that could potentially block.

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

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

`FileReaderSync()`

Returns a new `FileReaderSync` object.

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

This interface does not have any properties.

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

`FileReaderSync.readAsArrayBuffer()`

This method converts a specified `Blob` or a `File` into an `ArrayBuffer` representing the input data as a binary string.

`FileReaderSync.readAsBinaryString()`
Deprecated

This method converts a specified `Blob` or a `File` into a string representing the input data as a binary string. This method is deprecated, consider using `readAsArrayBuffer()` instead.

`FileReaderSync.readAsText()`

This method converts a specified `Blob` or a `File` into a string representing the input data as a text string. The optional **`encoding`** parameter indicates the encoding to be used (e.g., iso-8859-1 or UTF-8). If not present, the method will apply a detection algorithm for it.

`FileReaderSync.readAsDataURL()`

This method converts a specified `Blob` or a `File` into a string representing the input data as a data URL.

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

| Specification |
| --- |
| File API # FileReaderSync |

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

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

See also
--------

* `FileReader`
* `Blob`
* `File`


EXT_blend_minmax extension - Web APIs

EXT\_blend\_minmax extension
============================

The **`EXT_blend_minmax`** extension is part of the WebGL API and extends blending capabilities by adding two new blend equations: the minimum or maximum color components of the source and destination colors.

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

**Note:** This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. The constants in WebGL2 are `gl.MIN` and `gl.MAX`.

Constants
---------

This extension adds two new constants, which can be used in `WebGLRenderingContext.blendEquation()` and `WebGLRenderingContext.blendEquationSeparate()`:

`ext.MIN_EXT`

Produces the minimum color components of the source and destination colors.

`ext.MAX_EXT`

Produces the maximum color components of the source and destination colors.

Examples
--------

```js
const ext = gl.getExtension("EXT\_blend\_minmax");

gl.blendEquation(ext.MIN\_EXT);
gl.blendEquation(ext.MAX\_EXT);

gl.blendEquationSeparate(ext.MIN\_EXT, ext.MAX\_EXT);
```

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

| Specification |
| --- |
| WebGL EXT\_blend\_minmax Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.blendEquation()`
* `WebGLRenderingContext.blendEquationSeparate()`


WakeLockSentinel - Web APIs

WakeLockSentinel
================

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

The **`WakeLockSentinel`** interface of the Screen Wake Lock API can be used to monitor the status of the platform screen wake lock, and manually release the lock when needed.

The screen wake lock prevents device screens from dimming or locking when an application needs to keep running.

A screen wake lock is requested using the `navigator.wakeLock.request()` method, which returns a `Promise` that fulfills with a `WakeLockSentinel` object if the lock is granted.

 An acquired screen wake lock can be released manually via the `release()` method, or automatically via the platform screen wake lock. The latter may occur if the document becomes inactive or loses visibility, if the device is low on power, or if the user turns on a power save mode.
 Releasing all `WakeLockSentinel` instances of a given wake lock type will cause the underlying platform wake lock to be released.

An event is fired at the `WakeLockSentinel` if the platform lock is released, allowing applications to configure their UI, and re-request the lock if needed.

EventTarget

WakeLockSentinelInstance properties
-------------------

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

`released` Read only

Returns a boolean indicating whether the `WakeLockSentinel` has been released.

`type` Read only

 Returns a string representation of the currently acquired `WakeLockSentinel` type.
 Return values are:

* `screen`: A screen wake lock.
 Prevents devices from dimming or locking the screen.

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

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

`release()`

Releases the `WakeLockSentinel`, returning a `Promise` that is resolved once the sentinel has been successfully released.

Events
------

`release`

Fired when the `release()` method is called or the wake lock is released by the user agent.

Examples
--------

 In this example, we create an asynchronous function that requests a `WakeLockSentinel`.
 Once the screen wake lock is acquired we listen for the `release` event, which can be used to give appropriate UI feedback.
 The sentinel can be acquired or released via appropriate interactions.

```js
// create a reference for the wake lock
let wakeLock = null;

// create an async function to request a wake lock
const requestWakeLock = async () => {
  try {
    wakeLock = await navigator.wakeLock.request("screen");

    // listen for our release event
    wakeLock.addEventListener("release", () => {
      // if wake lock is released alter the UI accordingly
    });
  } catch (err) {
    // if wake lock request fails - usually system related, such as battery
  }
};

wakeLockOnButton.addEventListener("click", () => {
  requestWakeLock();
});

wakeLockOffButton.addEventListener("click", () => {
  if (wakeLock !== null) {
    wakeLock.release().then(() => {
      wakeLock = null;
    });
  }
});
```

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

| Specification |
| --- |
| Screen Wake Lock API # the-wakelocksentinel-interface |

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

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

See also
--------

* Stay awake with the Screen Wake Lock API


SVGElement - Web APIs

SVGElement
==========

All of the SVG DOM interfaces that correspond directly to elements in the SVG language derive from the `SVGElement` interface.

EventTarget

Node

Element

SVGElementInstance properties
-------------------

*Also inherits properties from the `Element` interface.*

`SVGElement.attributeStyleMap` Read only

A `StylePropertyMap` representing the declarations of the element's `style` attribute.

`HTMLElement.dataset` Read only

A `DOMStringMap` object which provides a list of key/value pairs of named data attributes which correspond to custom data attributes attached to the element. These can also be defined in SVG using attributes of the form `data-\*`, where `*` is the key name for the pair. This works just like HTML's `HTMLElement.dataset` property and HTML's `data-*` global attribute.

`SVGElement.className`
Deprecated
 Read only

An `SVGAnimatedString` that reflects the value of the `class` attribute on the given element, or the empty string if `class` is not present. This attribute is deprecated and may be removed in a future version of this specification. Authors are advised to use `Element.classList` instead.

`SVGElement.nonce`

Returns the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed.

`SVGElement.ownerSVGElement` Read only

An `SVGSVGElement` referring to the nearest ancestor `<svg>` element. `null` if the given element is the outermost `<svg>` element.

`SVGElement.style`

A `CSSStyleDeclaration` representing the declarations of the element's `style` attribute.

`SVGElement.tabIndex`

The position of the element in the tabbing order.

`SVGElement.viewportElement` Read only

The `SVGElement` which established the current viewport. Often the nearest ancestor `<svg>` element. `null` if the given element is the outermost `<svg>` element.

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

*This interface has no methods, but inherits methods from `Element`.*

Events
------

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

`abort`

Fired when page loading is stopped before an SVG element has been allowed to load completely.

`error`

Fired when an SVG element does not load properly or when an error occurs during script execution.

`load`

Fires on an `SVGElement` when it is loaded in the browser.

`resize`

Fired when an SVG document is being resized.

`scroll`

Fired when an SVG document view is being shifted along the X and/or Y axes.

`unload`

Fired when the DOM implementation removes an SVG document from a window or frame.

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

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

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

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

See also
--------

* HTML `data-*` attribute
* SVG `data-\*` attribute
* Using custom data attributes in HTML


WindowControlsOverlay - Web APIs

WindowControlsOverlay
=====================

**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 **`WindowControlsOverlay`** interface of the Window Controls Overlay API exposes information about the geometry
 of the title bar area in desktop Progressive Web Apps, and an event to know whenever it changes. This interface is accessible from `Navigator.windowControlsOverlay`.

EventTarget

WindowControlsOverlayInstance properties
-------------------

`WindowControlsOverlay.visible` Read only
Experimental

A Boolean that indicates whether the window controls overlay is visible or not.

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

`WindowControlsOverlay.getTitlebarAreaRect()`
Experimental

Returns the size and position of the title bar.

Events
------

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

`geometrychange`
Experimental

Fired when the geometry of the title bar area changes.

Examples
--------

```js
if ("windowControlsOverlay" in navigator) {
  navigator.windowControlsOverlay.addEventListener(
    "geometrychange",
    (event) => {
      if (event.visible) {
        const rect = event.titlebarAreaRect;
        // Do something with the coordinates of the title bar area.
      }
    },
  );
}
```

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

| Specification |
| --- |
| Window Controls Overlay # windowcontrolsoverlay-interface |

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

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


ProcessingInstruction - Web APIs

ProcessingInstruction
=====================

The **`ProcessingInstruction`** interface represents a processing instruction; that is, a `Node` which embeds an instruction targeting a specific application but that can be ignored by any other applications which don't recognize the instruction.

**Warning:** `ProcessingInstruction` nodes are only supported in XML documents, not in HTML documents. In these, a process instruction will be considered as a comment and be represented as a `Comment` object in the tree.

A processing instruction may be different than the XML declaration.

**Note:** User-defined processing instructions cannot begin with "`xml`", as `xml`-prefixed processing-instruction target names are reserved by the XML specification for particular, standard uses (see, for example, `<?xml-stylesheet ?>`.

For example:

```html
<?xml version="1.0"?>
```

is a processing instruction whose `target` is `xml`.

EventTarget

Node

CharacterData

ProcessingInstructionInstance properties
-------------------

*This interface also inherits properties from its parent interfaces, `CharacterData`, `Node`, and `EventTarget`.*

`ProcessingInstruction.sheet` Read only

Returns the associated `StyleSheet` object, if any; or `null` if none.

`ProcessingInstruction.target` Read only

A name identifying the application to which the instruction is targeted.

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

*This interface doesn't have any specific method, but inherits methods from its parent interfaces, `CharacterData`, `Node`, and `EventTarget`.*

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

| Specification |
| --- |
| DOM Standard # interface-processinginstruction |

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

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

See also
--------

* document.createProcessingInstruction()
* The DOM API


WebUSB API - Web APIs

WebUSB API
==========

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

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

The **WebUSB API** provides a way to expose non-standard Universal Serial Bus (USB) compatible devices services to the web, to make USB safer and easier to use.

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

USB is the de-facto standard for wired peripherals. The USB devices that you connect to your computer are typically grouped into a number of device classes—such as keyboards, mice, video devices, and so on. These are supported using the operating system's class driver. Many of these are also web accessible via the `WebHID API`.

In addition to these standardized devices, there are a large number of devices that don't fit into any class. These need custom drivers, and are inaccessible from the web due to the native code required to take advantage of them. Installing one of these devices often involves searching on a manufacturer's website for drivers and, should you wish to use the device on another computer, repeating the process again.

WebUSB provides a way for these non-standardized USB device services to be exposed to the web. This means that hardware manufacturers will be able to provide a way for their device to be accessed from the web, without having to provide their own API.

When connecting a new WebUSB-compatible device, the browser displays a notification providing a link to the manufacturer's website. On arriving at the site the browser prompts for permission to connect to the device, then the device is ready for use. No drivers need be downloaded and installed.

Interfaces
----------

`USB`

Provides attributes and methods for finding and connecting USB devices from a web page.

`USBConnectionEvent`

The event type passed to `USB` `connect` or `disconnect` events when the user agent detects a new USB device has been connected to, or disconnected from the host.

`USBDevice`

Provides access to metadata about a paired USB device and methods for controlling it.

`USBInTransferResult`

Represents the result from requesting a transfer of data from the USB device to the USB host.

`USBOutTransferResult`

Represents the result from requesting a transfer of data from the USB host to the USB device.

`USBIsochronousInTransferPacket`

Represents the status of an individual packet from a request to transfer data from the USB device to the USB host over an isochronous endpoint.

`USBIsochronousInTransferResult`

Represents the result from requesting a transfer of data from the USB device to the USB host.

`USBIsochronousOutTransferPacket`

Represents the status of an individual packet from a request to transfer data from the USB host to the USB device over an isochronous endpoint.

`USBIsochronousOutTransferResult`

Represents the result from requesting a transfer of data from the USB host to the USB device.

`USBConfiguration`

Provides information about a particular configuration of a USB device and the interfaces that it supports.

`USBInterface`

Provides information about an interface provided by the USB device.

`USBAlternateInterface`

Provides information about a particular configuration of an interface provided by the USB device.

`USBEndPoint`

Provides information about an endpoint provided by the USB device.

Examples
--------

### Accessing a connected device

The following example demonstrates how to access a connected Arduino device using `USB.requestDevice()`, which has a vendorId of `0x2341`.

```js
navigator.usb
  .requestDevice({ filters: [{ vendorId: 0x2341 }] })
  .then((device) => {
    console.log(device.productName); // "Arduino Micro"
    console.log(device.manufacturerName); // "Arduino LLC"
  })
  .catch((error) => {
    console.error(error);
  });
```

### Finding all connected devices

You can find all connected devices with `USB.getDevices()`. In the following example, with the Arduino device connected, product and manufacturer name are printed to the console.

```js
navigator.usb.getDevices().then((devices) => {
  devices.forEach((device) => {
    console.log(device.productName); // "Arduino Micro"
    console.log(device.manufacturerName); // "Arduino LLC"
  });
});
```

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

| Specification |
| --- |
| WebUSB API  |

See also
--------

* Access USB Devices on the Web


ReadableStreamDefaultController - Web APIs

ReadableStreamDefaultController
===============================

The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a `ReadableStream`'s state and internal queue. Default controllers are for streams that are not byte streams.

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

None. `ReadableStreamDefaultController` instances are created automatically during `ReadableStream` construction.

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

`ReadableStreamDefaultController.desiredSize` Read only

Returns the desired size required to fill the stream's internal queue.

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

`ReadableStreamDefaultController.close()`

Closes the associated stream.

`ReadableStreamDefaultController.enqueue()`

Enqueues a given chunk in the associated stream.

`ReadableStreamDefaultController.error()`

Causes any future interactions with the associated stream to error.

Examples
--------

In the following simple example, a custom `ReadableStream` is created using a constructor (see our Simple random stream example for the full code). The `start()` function generates a random string of text every second and enqueues it into the stream. A `cancel()` function is also provided to stop the generation if `ReadableStream.cancel()` is called for any reason.

Note that a `ReadableStreamDefaultController` object is provided as the parameter of the `start()` and `pull()` functions.

When a button is pressed, the generation is stopped, the stream is closed using `ReadableStreamDefaultController.close()`, and another function is run, which reads the data back out of the stream.

```js
let interval;
const stream = new ReadableStream({
  start(controller) {
    interval = setInterval(() => {
      let string = randomChars();

      // Add the string to the stream
      controller.enqueue(string);

      // show it on the screen
      let listItem = document.createElement("li");
      listItem.textContent = string;
      list1.appendChild(listItem);
    }, 1000);

    button.addEventListener("click", () => {
      clearInterval(interval);
      fetchStream();
      controller.close();
    });
  },
  pull(controller) {
    // We don't really need a pull in this example
  },
  cancel() {
    // This is called if the reader cancels,
    // so we should stop generating strings
    clearInterval(interval);
  },
});
```

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

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

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

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

See also
--------

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


SVGTextPathElement - Web APIs

SVGTextPathElement
==================

The **`SVGTextPathElement`** interface corresponds to the `<textPath>` element.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGTextContentElement

SVGTextPathElementConstants
---------

### Method types

| Name | Value | Description |
| --- | --- | --- |
| `TEXTPATH_METHODTYPE_UNKNOWN` | 0 |
 The type is not one of predefined types. It is invalid to attempt to
 define a new value of this type or to attempt to switch an existing
 value to this type.
  |
| `TEXTPATH_METHODTYPE_ALIGN` | 1 | Corresponds to the value `align`. |
| `TEXTPATH_METHODTYPE_STRETCH` | 2 | Corresponds to the value `stretch`. |

### Spacing types

| Name | Value | Description |
| --- | --- | --- |
| `TEXTPATH_SPACINGTYPE_UNKNOWN` | 0 |
 The type is not one of predefined types. It is invalid to attempt to
 define a new value of this type or to attempt to switch an existing
 value to this type.
  |
| `TEXTPATH_SPACINGTYPE_AUTO` | 1 | Corresponds to the value `auto`. |
| `TEXTPATH_SPACINGTYPE_EXACT` | 2 | Corresponds to the value `exact`. |

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

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

`SVGTextPathElement.href` Read only

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

`SVGTextPathElement.startOffset` Read only

An `SVGAnimatedLength` corresponding to the X component of the `startOffset` attribute of the given element.

`SVGTextPathElement.method` Read only

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

`SVGTextPathElement.spacing` Read only

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

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

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

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

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

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

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

See also
--------

* `<textPath>`


SVGFEMergeElement - Web APIs

SVGFEMergeElement
=================

The **`SVGFEMergeElement`** interface corresponds to the `<feMerge>` element.

EventTarget

Node

Element

SVGElement

SVGFEMergeElementInstance properties
-------------------

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

`SVGFEMergeElement.height` Read only

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

`SVGFEMergeElement.result` Read only

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

`SVGFEMergeElement.width` Read only

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

`SVGFEMergeElement.x` Read only

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

`SVGFEMergeElement.y` Read only

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

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

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

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

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

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

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

See also
--------

* `<feMerge>`


MediaStreamAudioSourceNode - Web APIs

MediaStreamAudioSourceNode
==========================

The **`MediaStreamAudioSourceNode`** interface is a type of `AudioNode` which operates as an audio source whose media is received from a `MediaStream` obtained using the WebRTC or Media Capture and Streams APIs.

This media could be from a microphone (through `getUserMedia()`) or from a remote peer on a WebRTC call (using the `RTCPeerConnection`'s audio tracks).

A `MediaStreamAudioSourceNode` has no inputs and exactly one output, and is created using the `AudioContext.createMediaStreamSource()` method.

The `MediaStreamAudioSourceNode` takes the audio from the *first* `MediaStreamTrack` whose `kind` attribute's value is `audio`. See Track ordering for more information about the order of tracks.

The number of channels output by the node matches the number of tracks found in the selected audio track.

EventTarget

AudioNode

MediaStreamAudioSourceNode

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |
| Channel count | 2 (but note that `AudioNode.channelCount` is only used for up-mixing and down-mixing `AudioNode` inputs, and `MediaStreamAudioSourceNode` doesn't have any input) |

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

`new MediaStreamAudioSourceNode()`

Creates a new `MediaStreamAudioSourceNode` object instance with the specified options.

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

*In addition to the following properties, `MediaStreamAudioSourceNode` inherits the properties of its parent, `AudioNode`.*

`mediaStream` Read only

The `MediaStream` used when constructing this `MediaStreamAudioSourceNode`.

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

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

Exceptions
----------

`InvalidStateError` `DOMException`

Thrown if the stream specified by the `mediaStream` parameter does not contain any audio tracks.

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

### Track ordering

For the purposes of the `MediaStreamTrackAudioSourceNode` interface, the order of the audio tracks on the stream is determined by taking the tracks whose `kind` is `audio`, then sorting the tracks by their `id` property's values, in Unicode code point order (essentially, in alphabetical or lexicographical order, for IDs which are simple alphanumeric strings).

The **first** track, then, is the track whose `id` comes first when the tracks' IDs are all sorted by Unicode code point.

However, it's important to note that the rule establishing this ordering was added long after this interface was first introduced into the Web Audio API. As such, you can't easily rely on the order matching between any two browsers or browser versions.

The `MediaStreamTrackAudioSourceNode` interface is similar to `MediaStreamAudioSourceNode`, but avoids this problem by letting you specify which track you want to use.

Example
-------

See `AudioContext.createMediaStreamSource()` for example code that uses this object.

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

| Specification |
| --- |
| Web Audio API # MediaStreamAudioSourceNode |

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

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

See also
--------

* Using the Web Audio API
* WebRTC API
* Media Capture and Streams API (Media Streams)
* `MediaStreamTrackAudioSourceNode`


AuthenticatorAttestationResponse - Web APIs

AuthenticatorAttestationResponse
================================

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

The **`AuthenticatorAttestationResponse`** interface of the Web Authentication API is the result of a WebAuthn credential registration. It contains information about the credential that the server needs to perform WebAuthn assertions, such as its credential ID and public key.

An `AuthenticatorAttestationResponse` object instance is available in the `response` property of a `PublicKeyCredential` object returned by a successful `CredentialsContainer.create()` call.

This interface inherits from `AuthenticatorResponse`.

AuthenticatorResponse

AuthenticatorAttestationResponse

**Note:** This interface is restricted to top-level contexts. Use of its features from within an `<iframe>` element will not have any effect.

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

*Also inherits properties from its parent, `AuthenticatorResponse`.*

`AuthenticatorAttestationResponse.attestationObject` Read only

An `ArrayBuffer` containing authenticator data and an attestation statement for a new key pair generated by the authenticator.

`AuthenticatorResponse.clientDataJSON` Read only

Inherited from `AuthenticatorResponse`, this property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential — i.e., when `CredentialsContainer.create()` is called with a `publicKey` option. This data contains some information from the options passed into the `create()` call, and some information controlled by the browser.

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

`AuthenticatorAttestationResponse.getAuthenticatorData()`

Returns an `ArrayBuffer` containing the authenticator data contained within the `AuthenticatorAttestationResponse.attestationObject` property.

`AuthenticatorAttestationResponse.getPublicKey()`

Returns an `ArrayBuffer` containing the DER `SubjectPublicKeyInfo` of the new credential (see Subject Public Key Info), or `null` if this is not available.

`AuthenticatorAttestationResponse.getPublicKeyAlgorithm()`

Returns a number that is equal to a COSE Algorithm Identifier, representing the cryptographic algorithm used for the new credential.

`AuthenticatorAttestationResponse.getTransports()`

Returns an array of strings describing which transport methods (e.g., `usb`, `nfc`) are believed to be supported with the authenticator. The array may be empty if the information is not available.

Examples
--------

See Creating a public key credential using the WebAuthn API for a detailed example.

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

| Specification |
| --- |
| Web Authentication: An API for accessing Public Key Credentials - Level 3 # authenticatorattestationresponse |

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

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

See also
--------

* `AuthenticatorAssertionResponse`: the interface for the type of response given when retrieving an existing credential
* `AuthenticatorResponse`: the parent interface


AudioWorkletProcessor - Web APIs

AudioWorkletProcessor
=====================

The **`AudioWorkletProcessor`** interface of the Web Audio API represents an audio processing code behind a custom `AudioWorkletNode`. It lives in the `AudioWorkletGlobalScope` and runs on the Web Audio rendering thread. In turn, an `AudioWorkletNode` based on it runs on the main thread.

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

**Note:** The `AudioWorkletProcessor` and classes that derive from it cannot be instantiated directly from a user-supplied code. Instead, they are created only internally by the creation of an associated `AudioWorkletNode`s. The constructor of the deriving class is getting called with an options object, so you can perform a custom initialization procedures — see constructor page for details.

`AudioWorkletProcessor()`

Creates a new instance of an `AudioWorkletProcessor` object.

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

`port` Read only

Returns a `MessagePort` used for bidirectional communication between the processor and the `AudioWorkletNode` which it belongs to. The other end is available under the `port` property of the node.

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

*The `AudioWorkletProcessor` interface does not define any methods of its own. However, you must provide a `process()` method, which is called in order to process the audio stream.*

Events
------

*The `AudioWorkletProcessor` interface doesn't respond to any events.*

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

### Deriving classes

To define custom audio processing code you have to derive a class from the `AudioWorkletProcessor` interface. Although not defined on the interface, the deriving class must have the `process` method. This method gets called for each block of 128 sample-frames and takes input and output arrays and calculated values of custom `AudioParam`s (if they are defined) as parameters. You can use inputs and audio parameter values to fill the outputs array, which by default holds silence.

Optionally, if you want custom `AudioParam`s on your node, you can supply a `parameterDescriptors` property as a *static getter* on the processor. The array of `AudioParamDescriptor`-based objects returned is used internally to create the `AudioParam`s during the instantiation of the `AudioWorkletNode`.

The resulting `AudioParam`s reside in the `parameters` property of the node and can be automated using standard methods such as `linearRampToValueAtTime`. Their calculated values will be passed into the `process()` method of the processor for you to shape the node output accordingly.

### Processing audio

An example algorithm of creating a custom audio processing mechanism is:

1. Create a separate file;
2. In the file:
    1. Extend the `AudioWorkletProcessor` class (see "Deriving classes" section) and supply your own `process()` method in it;
    2. Register the processor using `AudioWorkletGlobalScope.registerProcessor()` method;
3. Load the file using `addModule()` method on your audio context's `audioWorklet` property;
4. Create an `AudioWorkletNode` based on the processor. The processor will be instantiated internally by the `AudioWorkletNode` constructor.
5. Connect the node to the other nodes.
Examples
--------

In the example below we create a custom `AudioWorkletNode` that outputs white noise.

First, we need to define a custom `AudioWorkletProcessor`, which will output white noise, and register it. Note that this should be done in a separate file.

```js
// white-noise-processor.js
class WhiteNoiseProcessor extends AudioWorkletProcessor {
  process(inputs, outputs, parameters) {
    const output = outputs[0];
    output.forEach((channel) => {
      for (let i = 0; i < channel.length; i++) {
        channel[i] = Math.random() \* 2 - 1;
      }
    });
    return true;
  }
}

registerProcessor("white-noise-processor", WhiteNoiseProcessor);
```

Next, in our main script file we'll load the processor, create an instance of `AudioWorkletNode`, passing it the name of the processor, then connect the node to an audio graph.

```js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("white-noise-processor.js");
const whiteNoiseNode = new AudioWorkletNode(
  audioContext,
  "white-noise-processor",
);
whiteNoiseNode.connect(audioContext.destination);
```

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

| Specification |
| --- |
| Web Audio API # AudioWorkletProcessor |

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

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

See also
--------

* Web Audio API
* Using the Web Audio API
* Using AudioWorklet


SVGGraphicsElement - Web APIs

SVGGraphicsElement
==================

The **`SVGGraphicsElement`** interface represents SVG elements whose primary purpose is to directly render graphics into a group.

EventTarget

Node

Element

SVGElement

SVGGraphicsElementInstance properties
-------------------

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

`SVGGraphicsElement.requiredExtensions` Read only

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

`SVGGraphicsElement.systemLanguage` Read only

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

`SVGGraphicsElement.transform` Read only

An `SVGAnimatedTransformList` reflecting the computed value of the `transform` property and its corresponding `transform` attribute of the given element.

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

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

`SVGGraphicsElement.getBBox()`

Returns a `DOMRect` representing the computed bounding box of the current element.

`SVGGraphicsElement.getCTM()`

Returns a `DOMMatrix` representing the matrix that transforms the current element's coordinate system to its SVG viewport's coordinate system.

`SVGGraphicsElement.getScreenCTM()`

Returns a `DOMMatrix` representing the matrix that transforms the current element's coordinate system to the coordinate system of the SVG viewport for the SVG document fragment.

Events
------

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

`copy`

Fired when the user initiates a copy action through the browser's user interface.

`cut`

Fired when the user has initiated a "cut" action through the browser's user interface.

`paste`

Fires when the user has initiated a "paste" action through the browser's user interface.

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

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

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

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


EncodedVideoChunk - Web APIs

EncodedVideoChunk
=================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`EncodedVideoChunk`** interface of the WebCodecs API represents a chunk of encoded video data.

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

`EncodedVideoChunk()`

Creates a new `EncodedVideoChunk` object.

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

`EncodedVideoChunk.type` Read only

Returns a string indicating whether this chunk of data is a key chunk.

`EncodedVideoChunk.timestamp` Read only

Returns an integer representing the timestamp of the video in microseconds.

`EncodedVideoChunk.duration` Read only

Returns an integer representing the duration of the video in microseconds.

`EncodedVideoChunk.byteLength` Read only

Returns an integer representing the length of the video in bytes.

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

`EncodedVideoChunk.copyTo()`

Copies the encoded video data.

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

| Specification |
| --- |
| WebCodecs # encodedvideochunk-interface |

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

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


AesGcmParams - Web APIs

AesGcmParams
============

The **`AesGcmParams`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.encrypt()`, `SubtleCrypto.decrypt()`, `SubtleCrypto.wrapKey()`, or `SubtleCrypto.unwrapKey()`, when using the AES-GCM algorithm.

For details of how to supply appropriate values for this parameter, see the specification for AES-GCM: NIST SP800-38D, in particular section 5.2.1.1 on Input Data.

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

`name`

A string. This should be set to `AES-GCM`.

`iv`

An `ArrayBuffer`, a `TypedArray`, or a `DataView` with the initialization vector. This must be unique for every encryption operation carried out with a given key. Put another way: never reuse an IV with the same key. The AES-GCM specification recommends that the IV should be 96 bits long, and typically contains bits from a random number generator. Section 8.2 of the specification outlines methods for constructing IVs. Note that the IV does not have to be secret, just unique: so it is OK, for example, to transmit it in the clear alongside the encrypted message.

`additionalData` Optional

An `ArrayBuffer`, a `TypedArray`, or a `DataView`. This contains additional data that will not be encrypted but will be authenticated along with the encrypted data. If `additionalData` is given here then the same data must be given in the corresponding call to `decrypt()`: if the data given to the `decrypt()` call does not match the original data, the decryption will throw an exception. This gives you a way to authenticate associated data without having to encrypt it.

The bit length of `additionalData` must be smaller than `2^64 - 1`.

The `additionalData` property is optional and may be omitted without compromising the security of the encryption operation.

`tagLength` Optional

A `Number`. This determines the size in bits of the authentication tag generated in the encryption operation and used for authentication in the corresponding decryption.

According to the Web Crypto specification this must have one of the following values: 32, 64, 96, 104, 112, 120, or 128. The AES-GCM specification recommends that it should be 96, 104, 112, 120 or 128, although 32 or 64 bits may be acceptable in some applications: Appendix C of the specification provides additional guidance here.

`tagLength` is optional and defaults to 128 if it is not specified.

Examples
--------

See the examples for `SubtleCrypto.encrypt()` and `SubtleCrypto.decrypt()`.

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

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

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

Browsers that support the "AES-GCM" algorithm for the `SubtleCrypto.encrypt()`, `SubtleCrypto.decrypt()`, `SubtleCrypto.wrapKey()`, or `SubtleCrypto.unwrapKey()` methods will support this type.

See also
--------

* `SubtleCrypto.encrypt()`.
* `SubtleCrypto.decrypt()`.
* `SubtleCrypto.wrapKey()`.
* `SubtleCrypto.unwrapKey()`.


PresentationAvailability - Web APIs

PresentationAvailability
========================

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

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

A **`PresentationAvailability`** object is associated with available presentation displays and represents the *presentation display availability* for a presentation request. If the controlling user agent can monitor the list of available presentation displays in the background (without a pending request to `start()`), the `PresentationAvailability` object *MUST* be implemented in a controlling browsing context.

The `value` attribute *MUST* return the last value it was set to. The value is updated by the monitor the list of available presentation displays algorithm.

The `onchange` attribute is an event handler whose corresponding event handler event type is `change`.

EventTarget

PresentationAvailabilityInstance properties
-------------------

`PresentationAvailability.value` Read only
Experimental

A boolean value indicating whether the given presentation display is available. The `value` attribute *MUST* return the last value it was set to.

### Event

`change`
Experimental

Indicates that the availability of the presentation display has changed.

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

None.

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

| Specification |
| --- |
| Presentation API # interface-presentationavailability |

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

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


SVGAnimatedAngle - Web APIs

SVGAnimatedAngle
================

SVG animated angle interface
----------------------------

The `SVGAnimatedAngle` interface is used for attributes of basic type <angle> which can be animated.

### Interface overview

|  |  |
| --- | --- |
| Also implement | *None* |
| Methods | *None* |
| Properties | * readonly `SVGAngle` `baseVal`
* readonly `SVGAngle` `animVal`
 |
| Normative document | SVG 1.1 (2nd Edition) |

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

| Name | Type | Description |
| --- | --- | --- |
| `baseVal` | `SVGAngle` | The base value of the given attribute before applying any animations. |
| `animVal` | `SVGAngle` |
 A read only `SVGAngle` representing the current
 animated value of the given attribute. If the given attribute is not
 currently being animated, then the `SVGAngle` will
 have the same contents as `baseVal`. The object referenced by
 `animVal` will always be distinct from the one referenced by
 `baseVal`, even when the attribute is not animated.
  |

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

The `SVGAnimatedAngle` interface do not provide any specific methods.

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

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


IDBCursorWithValue - Web APIs

IDBCursorWithValue
==================

The **`IDBCursorWithValue`** interface of the IndexedDB API represents a cursor for traversing or iterating over multiple records in a database. It is the same as the `IDBCursor`, except that it includes the `value` property.

The cursor has a source that indicates which index or object store it is iterating over. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. The cursor enables an application to asynchronously process all the records in the cursor's range.

You can have an unlimited number of cursors at the same time. You always get the same `IDBCursorWithValue` object representing a given cursor. Operations are performed on the underlying index or object store.

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

IDBCursor

IDBCursorWithValueInstance methods
----------------

Inherits methods from its parent interface, `IDBCursor`.

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

Inherits properties from its parent interface, `IDBCursor`.

`IDBCursorWithValue.value` Read only

Returns the value of the current cursor.

Example
-------

In this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our IDBCursor example (view example live.)

```js
function displayData() {
  const transaction = db.transaction(["rushAlbumList"], "readonly");
  const objectStore = transaction.objectStore("rushAlbumList");

  objectStore.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
      list.appendChild(listItem);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-idbcursorwithvalue② |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


Web Locks API - Web APIs

Web Locks API
=============

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

The **Web Locks API** allows scripts running in one tab or worker to asynchronously acquire a lock, hold it while work is performed, then release it. While held, no other script executing in the same origin can acquire the same lock, which allows a web app running in multiple tabs or workers to coordinate work and the use of resources.

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

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

A lock is an abstract concept representing some potentially shared resource, identified by a name chosen by the web app. For example, if a web app running in multiple tabs wants to ensure that only one tab is syncing data between the network and Indexed DB, each tab could try to acquire a "my\_net\_db\_sync" lock, but only one tab will succeed (the leader election pattern.)

The API is used as follows:

1. The lock is requested.
2. Work is done while holding the lock in an asynchronous task.
3. The lock is automatically released when the task completes.

```js
navigator.locks.request("my\_resource", async (lock) => {
  // The lock has been acquired.
  await do\_something();
  await do\_something\_else();
  // Now the lock will be released.
});
```

While a lock is held, requests for the same lock from this execution context, or from other tabs/workers, will be queued. The first queued request will be granted only when the lock is released.

The API provides optional functionality that may be used as needed, including:

* returning values from the asynchronous task
* shared and exclusive lock modes
* conditional acquisition
* diagnostics to query the state of locks in an origin
* an escape hatch to protect against deadlocks

Locks are scoped to origins; the locks acquired by a tab from `https://example.com` have no effect on the locks acquired by a tab from `https://example.org:8080` as they are separate origins.

The main entry point is `navigator.locks.request()` which requests a lock. It takes a lock name, an optional set of options, and a callback. The callback is invoked when the lock is granted. The lock is automatically released when the callback returns, so usually the callback is an *async function*, which causes the lock to be released only when the async function has completely finished.

 The `request()` method itself returns a promise which resolves once the lock has been released;
 within an async function, a script can `await` the call to make the asynchronous code flow linearly.
 For example:

```js
await do\_something\_without\_lock();

// Request the lock.
await navigator.locks.request("my\_resource", async (lock) => {
  // The lock has been acquired.
  await do\_something\_with\_lock();
  await do\_something\_else\_with\_lock();
  // Now the lock will be released.
});
// The lock has been released.

await do\_something\_else\_without\_lock();
```

### Options

Several options can be passed when requesting a lock:

* `mode`: The default mode is "exclusive", but "shared" can be specified. There can be only one "exclusive" holder of a lock, but multiple "shared" requests can be granted at the same time. This can be used to implement the readers-writer pattern.
* `ifAvailable`: If specified, the lock request will fail if the lock cannot be granted immediately without waiting. The callback is invoked with `null`.
* `steal`: If specified, then any held locks with the same name will be released, and the request will be granted, preempting any queued requests for it.
* `signal`: An `AbortSignal` can be passed in, allowing a lock request to be aborted. This can be used to implement a timeout on requests.
### Monitoring

The `navigator.locks.query()` method can be used by scripts to introspect the state of the lock manager for the origin. This can be useful when debugging, for example, identifying why a lock could not be acquired. The results are a snapshot of the lock manager state, which identifies held and requested locks and some additional data (e.g. mode) about each, at the time the snapshot was taken.

### Advanced use

For more complicated cases, such as holding the lock for an arbitrary amount of time, the callback can return a promise explicitly resolved by the script:

```js
// Capture promise control functions:
let resolve, reject;
const p = new Promise((res, rej) => {
  resolve = res;
  reject = rej;
});

// Request the lock:
navigator.locks.request(
  "my\_resource",
  // Lock is acquired.
  (lock) => p, // Now lock will be held until either resolve() or reject() is called.
);
```

### Deadlocks

A deadlock occurs when a process can no longer make progress because each part is waiting on a request that cannot be satisfied. This can occur with this API in complex use-cases, for example, if multiple locks are requested out-of-order. If tab 1 holds lock A and tab 2 holds lock B, then tab 1 attempts to also acquire lock B and tab 2 attempts to also acquire lock A, neither request can be granted. Web applications can avoid this through several strategies, such as ensuring lock requests are not nested, or are always well ordered, or have timeouts. Note that such deadlocks only affect the locks themselves and code depending on them; the browser, other tabs, and other script in the page is not affected.

Interfaces
----------

`Lock`

Provides the name and mode of a previously requested lock, which is received in the callback to `LockManager.request()`.

`LockManager`

Provides methods for requesting a new `Lock` object and querying for an existing `Lock` object. To get an instance of `LockManager`, call `navigator.locks`.

### Extensions to other interfaces

`Navigator.locks` Read only

Returns a `LockManager` object that provides methods for requesting a new `Lock` object and querying for an existing `Lock` object.

`WorkerNavigator.locks` Read only

Returns a `LockManager` object which provides methods for requesting a new `Lock` object and querying for an existing `Lock` object.

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

| Specification |
| --- |
| Web Locks API  |

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

### api.LockManager

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

### api.Lock

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


EXT_color_buffer_half_float extension - Web APIs

EXT\_color\_buffer\_half\_float extension
=========================================

The **`EXT_color_buffer_half_float`** extension is part of the WebGL API and adds the ability to render to 16-bit floating-point color buffers.

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

**Note:** This extension is available to both, WebGL1 and WebGL2 contexts. On WebGL 2, it's an alternative to using the `EXT_color_buffer_float` extension on platforms that support 16-bit floating point render targets but not 32-bit floating point render targets.

The `OES_texture_half_float` extension implicitly enables this extension.

Constants
---------

`ext.RGBA16F_EXT`

RGBA 16-bit floating-point color-renderable format.

`ext.RGB16F_EXT`

RGB 16-bit floating-point color-renderable format.

`ext.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT`

?

`ext.UNSIGNED_NORMALIZED_EXT`

?

Extended methods
----------------

This extension extends `WebGLRenderingContext.renderbufferStorage()`:

* The `internalformat` parameter now accepts `ext.RGBA16F_EXT` and `ext.RGBA16F_EXT`.
Examples
--------

```js
const ext = gl.getExtension("EXT\_color\_buffer\_half\_float");

gl.renderbufferStorage(gl.RENDERBUFFER, ext.RGBA16F\_EXT, 256, 256);
```

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

| Specification |
| --- |
| WebGL EXT\_color\_buffer\_half\_float Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.renderbufferStorage()`
* `OES_texture_half_float`


XRDepthInformation - Web APIs

XRDepthInformation
==================

**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 **`XRDepthInformation`** interface contains information about the distance from the user's device to the real-world geometry in the user's environment.

This interface is the parent of:

`XRCPUDepthInformation`

Depth information from the CPU (returned by `XRFrame.getDepthInformation()`).

`XRWebGLDepthInformation`

Depth information from WebGL (returned by `XRWebGLBinding.getDepthInformation()`).

You will usually interact with these child interfaces. However, `XRDepthInformation` provides some useful properties that are inherited:

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

`XRDepthInformation.height` Read only
Experimental

Contains the height of the depth buffer (number of rows).

`XRDepthInformation.normDepthBufferFromNormView` Read only
Experimental

An `XRRigidTransform` that needs to be applied when indexing into the depth buffer. The transformation that the matrix represents changes the coordinate system from normalized view coordinates to normalized depth-buffer coordinates that can then be scaled by depth buffer's `width` and `height` to obtain the absolute depth-buffer coordinates.

`XRDepthInformation.rawValueToMeters` Read only
Experimental

Contains the scale factor by which the raw depth values must be multiplied in order to get the depths in meters.

`XRDepthInformation.width` Read only
Experimental

Contains the width of the depth buffer (number of columns).

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

None.

Examples
--------

See `XRCPUDepthInformation` and `XRWebGLDepthInformation` for code examples.

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

| Specification |
| --- |
| WebXR Depth Sensing Module # xrdepthinformation |

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

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

See also
--------

* `XRCPUDepthInformation`
* `XRWebGLDepthInformation`
* `XRFrame.getDepthInformation()`


ChannelMergerNode - Web APIs

ChannelMergerNode
=================

The `ChannelMergerNode` interface, often used in conjunction with its opposite, `ChannelSplitterNode`, reunites different mono inputs into a single output. Each input is used to fill a channel of the output. This is useful for accessing each channels separately, e.g. for performing channel mixing where gain must be separately controlled on each channel.

![Default channel merger node with six mono inputs combining to form a single output.](/en-US/docs/Web/API/ChannelMergerNode/webaudiomerger.png)

If `ChannelMergerNode` has one single output, but as many inputs as there are channels to merge; the number of inputs is defined as a parameter of its constructor and the call to `AudioContext.createChannelMerger()`. In the case that no value is given, it will default to `6`.

Using a `ChannelMergerNode`, it is possible to create outputs with more channels than the rendering hardware is able to process. In that case, when the signal is sent to the `AudioContext.listener` object, supernumerary channels will be ignored.

EventTarget

AudioNode

ChannelMergerNode

|  |  |
| --- | --- |
| Number of inputs | variable; default to `6`. |
| Number of outputs | `1` |
| Channel count mode | `"explicit"` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `"speakers"` |

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

`ChannelMergerNode()`

Creates a new `ChannelMergerNode` object instance.

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

*No specific property; inherits properties from its parent, `AudioNode`*.

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

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

Example
-------

See `BaseAudioContext.createChannelMerger()` for example code.

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

| Specification |
| --- |
| Web Audio API # ChannelMergerNode |

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

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

See also
--------

* Using the Web Audio API


HTMLTitleElement - Web APIs

HTMLTitleElement
================

The **`HTMLTitleElement`** interface is implemented by a document's `<title>`. This element inherits all of the properties and methods of the `HTMLElement` interface.

EventTarget

Node

Element

HTMLElement

HTMLTitleElementInstance properties
-------------------

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

`HTMLTitleElement.text`

A string representing the text of the document's title.

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

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

Example
-------

Do not confuse: `document.title` with `document.querySelector('title')`

The former is just a setter/getter method to set or get the inner text value of the document title, while the latter is the `HTMLTitleElement` object. So you cannot write: `document.title.text = "Hello world!";`

Instead, you can simply write: `document.title = "Hello world!";` which is an equivalent to `document.querySelector('title').text = "Hello world!";`

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

| Specification |
| --- |
| HTML Standard # htmltitleelement |

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: `<title>`.


HighlightRegistry - Web APIs

HighlightRegistry
=================

 The **`HighlightRegistry`** interface of the CSS Custom Highlight API is used to register `Highlight` objects to be styled using the API.
 It is accessed via `CSS.highlights`.

A `HighlightRegistry` instance is a `Map`-like object, in which each key is the name string for a custom highlight, and the corresponding value is the associated `Highlight` object.

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

*The `HighlightRegistry` interface doesn't inherit any properties.*

`HighlightRegistry.size` Read only

Returns the number of `Highlight` objects currently registered.

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

*The `HighlightRegistry` interface doesn't inherit any methods*.

`HighlightRegistry.clear()`

Remove all `Highlight` objects from the registry.

`HighlightRegistry.delete()`

Remove the named `Highlight` object from the registry.

`HighlightRegistry.entries()`

Returns a new iterator object that contains each `Highlight` object in the registry, in insertion order.

`HighlightRegistry.forEach()`

Calls the given callback once for each `Highlight` object in the registry, in insertion order.

`HighlightRegistry.get()`

Gets the named `Highlight` object from the registry.

`HighlightRegistry.has()`

Returns a boolean asserting whether a `Highlight` object is present the registry or not.

`HighlightRegistry.keys()`

An alias for `HighlightRegistry.values()`.

`HighlightRegistry.set()`

Adds the given `Highlight` object to the registry with the given name, or updates the named `Highlight` object, if it already exists in the registry.

`HighlightRegistry.values()`

Returns a new iterator object that yields the `Highlight` objects in the registry, in insertion order.

Examples
--------

### Registering a highlight

The following example demonstrates how to create ranges, instantiate a new `Highlight` object for them, and register the highlight using the `HighlightRegistry`, to style it on the page:

#### HTML

```html
<p id="foo">CSS Custom Highlight API</p>
```

#### CSS

```css
::highlight(my-custom-highlight) {
  background-color: peachpuff;
}
```

#### JavaScript

```js
const text = document.getElementById("foo").firstChild;

if (!CSS.highlights) {
  text.textContent =
    "The CSS Custom Highlight API is not supported in this browser!";
}

// Create a couple of ranges.
const range1 = new Range();
range1.setStart(text, 0);
range1.setEnd(text, 3);

const range2 = new Range();
range2.setStart(text, 21);
range2.setEnd(text, 24);

// Create a custom highlight for these ranges.
const highlight = new Highlight(range1, range2);

// Register the ranges in the HighlightRegistry.
CSS.highlights.set("my-custom-highlight", highlight);
```

#### Result

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

| Specification |
| --- |
| CSS Custom Highlight API Module Level 1 # highlight-registry |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


EXT_float_blend extension - Web APIs

EXT\_float\_blend extension
===========================

The WebGL API's `EXT_float_blend` extension allows blending and draw buffers with 32-bit floating-point components.

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

**Note:** This extension is available to both, WebGL1 and WebGL2 contexts. However, to use it, you need to enable the use of 32-bit floating-point draw buffers by enabling the extension `WEBGL_color_buffer_float` (for WebGL1) or `EXT_color_buffer_float` (for WebGL2). Doing so automatically enables `EXT_float_blend` as well, if and only if `EXT_float_blend` is also supported. Support for `EXT_color_buffer_float` does not imply support for `EXT_float_blend`.

With this extension enabled, calling `drawArrays()` or `drawElements()` with blending enabled and a draw buffer with 32-bit floating-point components will no longer result in an `INVALID_OPERATION` error.

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

On devices that support the `EXT_float_blend` extension, it is automatically, implicitly, enabled when any one or more of `EXT_color_buffer_float`, `OES_texture_float`, or `WEBGL_color_buffer_float` are enabled. This ensures that content written before `EXT_float_blend` was exposed by WebGL will function as expected.

Examples
--------

```js
const gl = canvas.getContext("webgl2");

// enable necessary extensions
gl.getExtension("EXT\_color\_buffer\_float");
gl.getExtension("EXT\_float\_blend");

const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE\_2D, tex);

// use floating point format
gl.texImage2D(gl.TEXTURE\_2D, 0, gl.RGBA32F, 1, 1, 0, gl.RGBA, gl.FLOAT, null);

const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(
  gl.FRAMEBUFFER,
  gl.COLOR\_ATTACHMENT0,
  gl.TEXTURE\_2D,
  tex,
  0,
);

// enable blending
gl.enable(gl.BLEND);

gl.drawArrays(gl.POINTS, 0, 1);
// won't throw gl.INVALID\_OPERATION with the extension enabled
```

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

| Specification |
| --- |
| WebGL EXT\_float\_blend Extension Specification  |

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

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

See also
--------

* WebGL API
* Using WebGL extensions
* WebGL tutorial
* `WebGLRenderingContext.getExtension()`
* `EXT_color_buffer_float`
* `WEBGL_color_buffer_float`
* `WebGLRenderingContext.drawArrays()`
* `WebGLRenderingContext.drawElements()`


Ink - Web APIs

Ink
===

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

The **`Ink`** interface of the Ink API provides access to `InkPresenter` objects for the application to use to render ink strokes.

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

`requestPresenter()`
Experimental

Returns a `Promise` that fulfills with an `InkPresenter` object to handle rendering strokes.

Example
-------

```js
async function inkInit() {
  const ink = navigator.ink;
  let presenter = await ink.requestPresenter({ presentationArea: canvas });

  //...
}
```

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

| Specification |
| --- |
| Ink API # ink-interface |

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

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

See also
--------

* Enhancing Inking on the Web


WebGLActiveInfo - Web APIs

WebGLActiveInfo
===============

The **WebGLActiveInfo** interface is part of the WebGL API and represents the information returned by calling the `WebGLRenderingContext.getActiveAttrib()` and `WebGLRenderingContext.getActiveUniform()` methods.

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

`WebGLActiveInfo.name`

The read-only name of the requested variable.

`WebGLActiveInfo.size`

The read-only size of the requested variable.

`WebGLActiveInfo.type`

The read-only type of the requested variable.

Examples
--------

A `WebGLActiveInfo` object is returned by:

* `WebGLRenderingContext.getActiveAttrib()`
* `WebGLRenderingContext.getActiveUniform()` or
* `WebGL2RenderingContext.getTransformFeedbackVarying()`
Specifications
--------------

| Specification |
| --- |
| WebGL Specification # 5.11 |

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

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

See also
--------

* `WebGLRenderingContext.getActiveAttrib()`
* `WebGLRenderingContext.getActiveUniform()`


CSSMathProduct - Web APIs

CSSMathProduct
==============

The **`CSSMathProduct`** interface of the CSS\_Object\_Model#css\_typed\_object\_model represents the result obtained by calling `add()`, `sub()`, or `toSum()` on `CSSNumericValue`. It inherits properties and methods from its parent `CSSNumericValue`.

CSSStyleValue

CSSNumericValue

CSSMathValue

CSSMathProductConstructor
-----------

`CSSMathProduct()`
Experimental

Creates a new `CSSMathProduct` object.

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

`CSSMathProduct.values`

Returns a `CSSNumericArray` object which contains one or more `CSSNumericValue` objects.

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

*The interface may also inherit methods from its parent interface, `CSSMathValue`.*

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

*The interface may also inherit methods from its parent interface, `CSSMathValue`.*

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

| Specification |
| --- |
| CSS Typed OM Level 1 # cssmathproduct |

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

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


WheelEvent - Web APIs

WheelEvent
==========

The **`WheelEvent`** interface represents events that occur due to the user moving a mouse wheel or similar input device.

**Note:** This is the standard wheel event interface to use. Old versions of browsers implemented the non-standard and non-cross-browser-compatible `MouseWheelEvent` and `MouseScrollEvent` interfaces. Use this interface and avoid the non-standard ones.

**Note:** Do not confuse the `wheel` event with the `scroll` event. The default action of a `wheel` event is implementation-defined. Thus, a `wheel` event doesn't necessarily dispatch a `scroll` event. Even when it does, that doesn't mean that the `delta*` values in the `wheel` event necessarily reflect the content's scrolling direction. Therefore, do not rely on `delta*` properties to get the content's scrolling direction. Instead, detect value changes to `scrollLeft` and `scrollTop` of the target in the `scroll` event.

Event

UIEvent

MouseEvent

WheelEventConstructor
-----------

`WheelEvent()`

Creates a `WheelEvent` object.

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

*This interface inherits properties from its ancestors, `MouseEvent`, `UIEvent`, and `Event`.*

`WheelEvent.deltaX` Read only

Returns a `double` representing the horizontal scroll amount.

`WheelEvent.deltaY` Read only

Returns a `double` representing the vertical scroll amount.

`WheelEvent.deltaZ` Read only

Returns a `double` representing the scroll amount for the z-axis.

`WheelEvent.deltaMode` Read only

Returns an `unsigned long` representing the unit of the `delta*` values' scroll amount. Permitted values are:

| Constant | Value | Description |
| --- | --- | --- |
| `WheelEvent.DOM_DELTA_PIXEL` | `0x00` | The `delta*` values are specified in pixels. |
| `WheelEvent.DOM_DELTA_LINE` | `0x01` | The `delta*` values are specified in lines. Each mouse click scrolls a line of content, where the method used to calculate line height is browser dependent. |
| `WheelEvent.DOM_DELTA_PAGE` | `0x02` | The `delta*` values are specified in pages. Each mouse click scrolls a page of content. |

`WheelEvent.wheelDelta` Read only
Deprecated

Non-standard

Returns an integer (32-bit) representing the distance in pixels.

`WheelEvent.wheelDeltaX` Read only
Deprecated

Non-standard

Returns an integer representing the horizontal scroll amount.

`WheelEvent.wheelDeltaY` Read only
Deprecated

Non-standard

Returns an integer representing the vertical scroll amount.

**Note:** Element: mousewheel event has additional documentation about the deprecated properties `wheelDelta`, `wheelDeltaX`, `wheelDeltaY`.

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

*This interface doesn't define any specific methods, but inherits methods from its ancestors, `MouseEvent`, `UIEvent`, and `Event`.*

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

| Specification |
| --- |
| UI Events # interface-wheelevent |

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

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

See also
--------

* `wheel` event
* Interfaces replaced by this one:
    + Gecko's legacy mouse wheel event object: `MouseScrollEvent`


HTMLVideoElement - Web APIs

HTMLVideoElement
================

Implemented by the `<video>` element, the **`HTMLVideoElement`** interface provides special properties and methods for manipulating video objects. It also inherits properties and methods of `HTMLMediaElement` and `HTMLElement`.

The list of supported media formats varies from one browser to the other. You should either provide your video in a single format that all the relevant browsers supports, or provide multiple video sources in enough different formats that all the browsers you need to support are covered.

EventTarget

Node

Element

HTMLElement

HTMLMediaElement

HTMLVideoElementInstance properties
-------------------

*Inherits properties from its parent interface, `HTMLMediaElement`, and `HTMLElement`.*

`HTMLVideoElement.disablePictureInPicture`

Indicates if the user agent should suggest the picture-in-picture to users, or not.

`HTMLVideoElement.height`

A string that reflects the `height` HTML attribute, which specifies the height of the display area, in CSS pixels.

`HTMLVideoElement.poster`

A string that reflects the `poster` HTML attribute, which specifies an image to show while no video data is available.

`HTMLVideoElement.videoHeight` Read only

Returns an unsigned integer value indicating the intrinsic height of the resource in CSS pixels, or 0 if no media is available yet.

`HTMLVideoElement.videoWidth` Read only

Returns an unsigned integer value indicating the intrinsic width of the resource in CSS pixels, or 0 if no media is available yet.

`HTMLVideoElement.width`

A string that reflects the `width` HTML attribute, which specifies the width of the display area, in CSS pixels.

### Gecko-specific properties

`HTMLVideoElement.mozParsedFrames`
Non-standard
 Read only
Deprecated

Returns an `unsigned long` with the count of video frames that have been parsed from the media resource.

`HTMLVideoElement.mozDecodedFrames`
Non-standard
 Read only
Deprecated

Returns an `unsigned long` with the count of parsed video frames that have been decoded into images.

`HTMLVideoElement.mozPresentedFrames`
Non-standard
 Read only
Deprecated

Returns an `unsigned long` with the count of decoded frames that have been presented to the rendering pipeline for painting.

`HTMLVideoElement.mozPaintedFrames`
Non-standard
 Read only
Deprecated

Returns an `unsigned long` with the count of presented frames which were painted on the screen.

`HTMLVideoElement.mozFrameDelay`
Non-standard
 Read only
Deprecated

Returns an `double` with the time which the last painted video frame was late by, in seconds.

`HTMLVideoElement.mozHasAudio`
Non-standard
 Read only
Deprecated

Returns a boolean indicating if there is some audio associated with the video.

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

*Inherits methods from its parent interface, `HTMLMediaElement`, and `HTMLElement`.*

`HTMLVideoElement.getVideoPlaybackQuality()`

Returns a `VideoPlaybackQuality` object that contains the current playback metrics. This information includes things like the number of dropped or corrupted frames, as well as the total number of frames.

`HTMLVideoElement.requestPictureInPicture()`

Requests that the user agent make video enters picture-in-picture mode

Events
------

*Inherits events from its parent interface, `HTMLMediaElement`, and `HTMLElement`.*

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

`enterpictureinpicture`

Fired when the `HTMLVideoElement` enters picture-in-picture mode successfully.

`leavepictureinpicture`

Fired when the `HTMLVideoElement` leaves picture-in-picture mode successfully.

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

| Specification |
| --- |
| HTML Standard # htmlvideoelement |

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

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

See also
--------

* HTML element implementing this interface: `<video>`.
* Supported media formats


SpeechRecognitionAlternative - Web APIs

SpeechRecognitionAlternative
============================

The **`SpeechRecognitionAlternative`** interface of the Web Speech API represents a single word that has been recognized by the speech recognition service.

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

`SpeechRecognitionAlternative.transcript` Read only

Returns a string containing the transcript of the recognized word.

`SpeechRecognitionAlternative.confidence` Read only

Returns a numeric estimate between 0 and 1 of how confident the speech recognition system is that the recognition is correct.

Examples
--------

 This code is excerpted from our
 Speech color changer example.

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

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

| Specification |
| --- |
| Web Speech API # speechreco-alternative |

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

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

See also
--------

* Web Speech API


createImageBitmap() global function - Web APIs

createImageBitmap() global function
===================================

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

 The **`createImageBitmap()`** method creates a bitmap from a
 given source, optionally cropped to contain only a portion of that source. The method
 exists on the global scope in both windows and workers. It accepts a variety of
 different image sources, and returns a `Promise` which resolves to an
 `ImageBitmap`.

Syntax
------

```js
createImageBitmap(image)
createImageBitmap(image, options)
createImageBitmap(image, sx, sy, sw, sh)
createImageBitmap(image, sx, sy, sw, sh, options)
```

### Parameters

`image`

An image source, which can be any one of the following:

* `HTMLImageElement`
* `SVGImageElement`
* `HTMLVideoElement`
* `HTMLCanvasElement`
* `Blob`
* `ImageData`
* `ImageBitmap`
* `OffscreenCanvas`

`sx`

 The x coordinate of the reference point of the rectangle from which the
 `ImageBitmap` will be extracted.

`sy`

 The y coordinate of the reference point of the rectangle from which the
 `ImageBitmap` will be extracted.

`sw`

 The width of the rectangle from which the `ImageBitmap` will be
 extracted. This value can be negative.

`sh`

 The height of the rectangle from which the `ImageBitmap` will be
 extracted. This value can be negative.

`options` Optional

An object that sets options for the image's extraction. The available options are:

`imageOrientation`

 Specifies whether the image should be presented
 as is or flipped vertically. Either `none` (default) or
 `flipY`.

`premultiplyAlpha`

 Specifies whether the bitmap's color channels
 should be premultiplied by the alpha channel. One of `none`,
 `premultiply`, or `default` (default).

`colorSpaceConversion`

 Specifies whether the image should be decoded
 using color space conversion. Either `none` or `default`
 (default). The value `default` indicates that implementation-specific
 behavior is used.

`resizeWidth`

A long integer that indicates the output width.

`resizeHeight`

A long integer that indicates the output height.

`resizeQuality`

 Specifies the algorithm to be used for resizing the
 input to match the output dimensions. One of `pixelated`,
 `low` (default), `medium`, or `high`.

### Return value

 A `Promise` which resolves to an `ImageBitmap` object
 containing bitmap data from the given rectangle.

Examples
--------

### Creating sprites from a sprite sheet

 This example loads a sprite sheet, extracts individual sprites, and then renders each
 sprite to the canvas. A sprite sheet is an image containing multiple smaller images,
 each of which you want to be able to render separately.

```js
const canvas = document.getElementById("myCanvas"),
  ctx = canvas.getContext("2d"),
  image = new Image();

// Wait for the sprite sheet to load
image.onload = () => {
  Promise.all([
    // Cut out two sprites from the sprite sheet
    createImageBitmap(image, 0, 0, 32, 32),
    createImageBitmap(image, 32, 0, 32, 32),
  ]).then((sprites) => {
    // Draw each sprite onto the canvas
    ctx.drawImage(sprites[0], 0, 0);
    ctx.drawImage(sprites[1], 32, 32);
  });
};

// Load the sprite sheet from an image file
image.src = "sprites.png";
```

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

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

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

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

See also
--------

* `CanvasRenderingContext2D.drawImage()`
* `ImageData`


PublicKeyCredential - Web APIs

PublicKeyCredential
===================

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

The **`PublicKeyCredential`** interface provides information about a public key / private key pair, which is a credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password. It inherits from `Credential`, and is part of the Web Authentication API extension to the Credential Management API.

Credential

PublicKeyCredential

**Note:** This API is restricted to top-level contexts. Use from within an `<iframe>` element will not have any effect.

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

`PublicKeyCredential.authenticatorAttachment` Read only

A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes.

`PublicKeyCredential.id` Read only

Inherited from `Credential` and overridden to be the base64url encoding of `PublicKeyCredential.rawId`.

`PublicKeyCredential.rawId` Read only

An `ArrayBuffer` that holds the globally unique identifier for this `PublicKeyCredential`. This identifier can be used to look up credentials for future calls to `navigator.credentials.get()`.

`PublicKeyCredential.response` Read only

An instance of an `AuthenticatorResponse` object. It is either of type `AuthenticatorAttestationResponse` if the `PublicKeyCredential` was the results of a `navigator.credentials.create()` call, or of type `AuthenticatorAssertionResponse` if the `PublicKeyCredential` was the result of a `navigator.credentials.get()` call.

`PublicKeyCredential.type` Read only

Inherited from `Credential`. Always set to `public-key` for `PublicKeyCredential` instances.

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

`PublicKeyCredential.isConditionalMediationAvailable()`

Returns a `Promise` which resolves to `true` if conditional mediation is available.

`PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()`

Returns a `Promise` which resolves to `true` if an authenticator bound to the platform is capable of *verifying* the user.

`PublicKeyCredential.parseCreationOptionsFromJSON()`
Experimental

Convenience method for deserializing server-sent credential registration data when registering a user with credentials.

`PublicKeyCredential.parseRequestOptionsFromJSON()`
Experimental

Convenience method for deserializing server-sent credential request data when authenticating a (registered) user.

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

`PublicKeyCredential.getClientExtensionResults()`

If any extensions were requested, this method will return the results of processing those extensions.

`PublicKeyCredential.toJSON()`
Experimental

Convenience method for creating a JSON string representation of a `PublicKeyCredential` for sending to the server when registering a user with credentials and authenticating a registered user.

Examples
--------

### Creating a new instance of PublicKeyCredential

Here, we use `navigator.credentials.create()` to generate a new credential.

```js
const createCredentialOptions = {
  challenge: new Uint8Array([
    21, 31, 105 /\* 29 more random bytes generated by the server \*/,
  ]),
  rp: {
    name: "Example CORP",
    id: "login.example.com",
  },
  user: {
    id: new Uint8Array(16),
    name: "canand@example.com",
    displayName: "Carina Anand",
  },
  pubKeyCredParams: [
    {
      type: "public-key",
      alg: -7,
    },
  ],
};

navigator.credentials
  .create({ createCredentialOptions })
  .then((newCredentialInfo) => {
    const response = newCredentialInfo.response;
    const clientExtensionsResults =
      newCredentialInfo.getClientExtensionResults();
  })
  .catch((err) => {
    console.error(err);
  });
```

### Getting an existing instance of PublicKeyCredential

Here, we fetch an existing credential from an authenticator, using `navigator.credentials.get()`.

```js
const requestCredentialOptions = {
  challenge: new Uint8Array([
    /\* bytes sent from the server \*/
  ]),
};

navigator.credentials
  .get({ requestCredentialOptions })
  .then((credentialInfoAssertion) => {
    // send assertion response back to the server
    // to proceed with the control of the credential
  })
  .catch((err) => {
    console.error(err);
  });
```

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

| Specification |
| --- |
| Web Authentication: An API for accessing Public Key Credentials - Level 3 # iface-pkcredential |

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

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

See also
--------

* The parent interface `Credential`


clearTimeout() global function - Web APIs

clearTimeout() global function
==============================

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

 The global **`clearTimeout()`** method cancels a timeout previously established
 by calling `setTimeout()`.

 If the parameter provided does not identify a previously established action,
 this method does nothing.

Syntax
------

```js
clearTimeout(timeoutID)
```

### Parameters

`timeoutID`

 The identifier of the timeout you want to cancel. This ID was returned by the
 corresponding call to `setTimeout()`.

 It's worth noting that the pool of IDs used by
 `setTimeout()` and
 `setInterval()` are shared, which
 means you can technically use `clearTimeout()` and
 `clearInterval()`
 interchangeably. However, for clarity, you should avoid doing so.

### Return value

None (`undefined`).

Examples
--------

 Run the script below in the context of a web page and click on the page once. You'll
 see a message popping up in a second. If you click the page multiple times in
 one second, the alert only appears once.

```js
const alarm = {
  remind(aMessage) {
    alert(aMessage);
    this.timeoutID = undefined;
  },

  setup() {
    if (typeof this.timeoutID === "number") {
      this.cancel();
    }

    this.timeoutID = setTimeout(
      (msg) => {
        this.remind(msg);
      },
      1000,
      "Wake up!",
    );
  },

  cancel() {
    clearTimeout(this.timeoutID);
  },
};
window.addEventListener("click", () => alarm.setup());
```

Notes
-----

 Passing an invalid ID to `clearTimeout()` silently does nothing; no
 exception is thrown.

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

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

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

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

See also
--------

* `setTimeout()`
* `setInterval()`
* `clearInterval()`
* `Window.requestAnimationFrame()`


SVGAnimatedLength - Web APIs

SVGAnimatedLength
=================

The **`SVGAnimatedLength`** interface represents attributes of type <length> which can be animated.

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

`baseVal` Read only

A `SVGLength` representing the base value of the given attribute before applying any animations.

`animVal` Read only

 If the given attribute or property is being animated,
 a `SVGLength` containing the current animated value of the attribute or property.
 If the given attribute or property is not currently being animated,
 a `SVGLength` containing the same value as `baseVal`.

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

*This interface does not implement any specific methods.*

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

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

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

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

See also
--------

* `SVGLength`