Web Crypto API - Web APIs

Web Crypto API
==============

The **Web Crypto API** is an interface allowing a script to use cryptographic primitives in order to build systems using cryptography.

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

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

**Warning:** The Web Crypto API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle.

Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts.

Errors in security system design and implementation can make the security of the system completely ineffective.

Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The Crypto 101 Course can be a great place to start learning about the design and implementation of secure systems.

Interfaces
----------

Some browsers implemented an interface called `Crypto` without having it well defined or being cryptographically sound. In order to avoid confusion, methods and properties of this interface have been removed from browsers implementing the Web Crypto API, and all Web Crypto API methods are available on a new interface: `SubtleCrypto`. The `Crypto.subtle` property gives access to an object implementing it.

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

| Specification |
| --- |
| Web Cryptography API # crypto-interface |

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

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


Screen - Web APIs

Screen
======

The `Screen` interface represents a screen, usually the one on which the current window is being rendered, and is obtained using `window.screen`.

Note that browsers determine which screen to report as current by detecting which screen has the center of the browser window.

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

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

`Screen.availHeight`

Specifies the height of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the Taskbar on Windows.

`Screen.availWidth`

Returns the amount of horizontal space in pixels available to the window.

`Screen.colorDepth`

Returns the color depth of the screen.

`Screen.height`

Returns the height of the screen in pixels.

`Screen.isExtended`
Experimental
 Secure context

Returns `true` if the user's device has multiple screens, and `false` if not.

`Screen.orientation`

Returns the `ScreenOrientation` instance associated with this screen.

`Screen.pixelDepth`

Gets the bit depth of the screen.

`Screen.width`

Returns the width of the screen.

`Screen.mozEnabled`
Non-standard

Deprecated

Boolean. Setting to false will turn off the device's screen.

`Screen.mozBrightness`
Non-standard

Deprecated

Controls the brightness of a device's screen. A double between 0 and 1.0 is expected.

Non-standard properties
-----------------------

The following properties are specified as part of the Window Management API, which makes them available on the `ScreenDetailed` interface; this is where we have chosen to document them. However, non-standard versions of these properties are available on the `Screen` interface in browsers that don't support that API. See this page's Browser compatibility table for details of the non-standard support.

`Screen.availLeft` Read only
Non-standard

A number representing the x-coordinate (left-hand edge) of the available screen area.

`Screen.availTop` Read only
Non-standard

A number representing the y-coordinate (top edge) of the available screen area.

`Screen.left` Read only
Non-standard

A number representing the x-coordinate (left-hand edge) of the total screen area.

`Screen.top` Read only
Non-standard

Deprecated

A number representing the y-coordinate (top edge) of the total screen area.

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

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

`Screen.lockOrientation`
Deprecated

Lock the screen orientation (only works in fullscreen or for installed apps)

`Screen.unlockOrientation`
Deprecated

Unlock the screen orientation (only works in fullscreen or for installed apps)

Events
------

`change`
Experimental
 Secure context

Fired on a specific screen when it changes in some way — width or height, available width or height, color depth, or orientation.

`orientationchange`
Deprecated

Non-standard

Fires when the screen orientation changes.

Examples
--------

```js
if (screen.colorDepth < 8) {
  // use low-color version of page
} else {
  // use regular, colorful page
}
```

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

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

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

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


TextTrackCue - Web APIs

TextTrackCue
============

**`TextTrackCue`** is an abstract class which is used as the basis for the various derived cue types, such as `VTTCue`; you will instead work with those derived types. These cues represent strings of text presented for some duration of time during the performance of a `TextTrack`. The cue includes the start time (the time at which the text will be displayed) and the end time (the time at which it will be removed from the display), as well as other information.

EventTarget

TextTrackCueInstance properties
-------------------

*This interface also inherits properties from `EventTarget`.*

`TextTrackCue.track` Read only

The `TextTrack` that this cue belongs to, or `null` if it doesn't belong to any.

`TextTrackCue.id`

A string that identifies the cue.

`TextTrackCue.startTime`

A `double` that represents the video time that the cue will start being displayed, in seconds.

`TextTrackCue.endTime`

A `double` that represents the video time that the cue will stop being displayed, in seconds.

`TextTrackCue.pauseOnExit`

A `boolean` for whether the video will pause when this cue stops being displayed.

Events
------

`enter`

Fired when a cue becomes active.

`exit`

Fired when the cue has stopped being active.

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

| Specification |
| --- |
| HTML Standard # texttrackcue |

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

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


EncodedAudioChunk - Web APIs

EncodedAudioChunk
=================

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
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`EncodedAudioChunk`** interface of the WebCodecs API represents a chunk of encoded audio data.

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

`EncodedAudioChunk()`
Experimental

Creates a new `EncodedAudioChunk` object.

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

`EncodedAudioChunk.type` Read only
Experimental

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

`EncodedAudioChunk.timestamp` Read only
Experimental

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

`EncodedAudioChunk.duration` Read only
Experimental

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

`EncodedAudioChunk.byteLength` Read only
Experimental

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

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

`EncodedAudioChunk.copyTo()`
Experimental

Copies the encoded audio data.

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

| Specification |
| --- |
| WebCodecs # encodedaudiochunk-interface |

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

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


PerformanceElementTiming - Web APIs

PerformanceElementTiming
========================

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

The **`PerformanceElementTiming`** interface contains render timing information for image and text node elements the developer annotated with an `elementtiming` attribute for observation.

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

The aim of the Element Timing API is to give web developers or analytics tools the ability to measure rendering timestamps of critical elements on a page.

The API supports timing information on the following elements:

* `<img>` elements,
* `<image>` elements inside an `<svg>`,
* poster images of `<video>` elements,
* elements which have a `background-image`, and
* groups of text nodes, such as a `<p>`.

The author flags an element for observation by adding the `elementtiming` attribute on the element.

`PerformanceElementTiming` inherits from `PerformanceEntry`.

PerformanceEntry

PerformanceElementTimingInstance properties
-------------------

This interface extends the following `PerformanceEntry` properties for event timing performance entry types by qualifying them as follows:

`PerformanceEntry.duration` Read only
Experimental

Always returns `0` as `duration` does not apply to this interface.

`PerformanceEntry.entryType` Read only
Experimental

Always returns `"element"`.

`PerformanceEntry.name` Read only
Experimental

Returns `"image-paint"` for images and `"text-paint"` for text.

`PerformanceEntry.startTime` Read only
Experimental

Returns the value of this entry's `renderTime` if it is not `0`, otherwise the value of this entry's `loadTime`.

This interface also supports the following properties:

`PerformanceElementTiming.element` Read only
Experimental

An `Element` representing the element we are returning information about.

`PerformanceElementTiming.id` Read only
Experimental

A string which is the `id` of the element.

`PerformanceElementTiming.identifier` Read only
Experimental

A string which is the value of the `elementtiming` attribute on the element.

`PerformanceElementTiming.intersectionRect` Read only
Experimental

A `DOMRectReadOnly` which is the rectangle of the element within the viewport.

`PerformanceElementTiming.loadTime` Read only
Experimental

A `DOMHighResTimeStamp` with the loadTime of the element.

`PerformanceElementTiming.naturalHeight` Read only
Experimental

An unsigned 32-bit integer (unsigned long) which is the intrinsic height of the image if this is applied to an image, 0 for text.

`PerformanceElementTiming.naturalWidth` Read only
Experimental

An unsigned 32-bit integer (unsigned long) which is the intrinsic width of the image if this is applied to an image, 0 for text.

`PerformanceElementTiming.renderTime` Read only
Experimental

A `DOMHighResTimeStamp` with the renderTime of the element.

`PerformanceElementTiming.url` Read only
Experimental

A string which is the initial URL of the resources request for images, 0 for text.

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

`PerformanceElementTiming.toJSON()`
Experimental

Returns a JSON representation of the `PerformanceElementTiming` object.

Examples
--------

### Observing render time of specific elements

In this example two elements are being observed by adding the `elementtiming` attribute. A `PerformanceObserver` is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation.

```html
<img src="image.jpg" elementtiming="big-image" />
<p elementtiming="text" id="text-id">text here</p>
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(entry);
  });
});
observer.observe({ type: "element", buffered: true });
```

Two entries will be output to the console. The first containing details of the image, the second with details of the text node.

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

| Specification |
| --- |
| Element Timing API # sec-performance-element-timing |

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

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

See also
--------

* `elementtiming` HTML attribute


Storage - Web APIs

Storage
=======

The **`Storage`** interface of the Web Storage API provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.

To manipulate, for instance, the session storage for a domain, a call to `Window.sessionStorage` is made; whereas for local storage the call is made to `Window.localStorage`.

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

`Storage.length` Read only

Returns an integer representing the number of data items stored in the `Storage` object.

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

`Storage.key()`

When passed a number `n`, this method will return the name of the nth key in the storage.

`Storage.getItem()`

When passed a key name, will return that key's value.

`Storage.setItem()`

When passed a key name and value, will add that key to the storage, or update that key's value if it already exists.

`Storage.removeItem()`

When passed a key name, will remove that key from the storage.

`Storage.clear()`

When invoked, will empty all keys out of the storage.

Examples
--------

Here we access a `Storage` object by calling `localStorage`. We first test whether the local storage contains data items using `!localStorage.getItem('bgcolor')`. If it does, we run a function called `setStyles()` that grabs the data items using `Storage.getItem()` and uses those values to update page styles. If it doesn't, we run another function, `populateStorage()`, which uses `Storage.setItem()` to set the item values, then runs `setStyles()`.

```js
if (!localStorage.getItem("bgcolor")) {
  populateStorage();
} else {
  setStyles();
}

function populateStorage() {
  localStorage.setItem("bgcolor", document.getElementById("bgcolor").value);
  localStorage.setItem("font", document.getElementById("font").value);
  localStorage.setItem("image", document.getElementById("image").value);

  setStyles();
}

function setStyles() {
  const currentColor = localStorage.getItem("bgcolor");
  const currentFont = localStorage.getItem("font");
  const currentImage = localStorage.getItem("image");

  document.getElementById("bgcolor").value = currentColor;
  document.getElementById("font").value = currentFont;
  document.getElementById("image").value = currentImage;

  htmlElem.style.backgroundColor = `#${currentColor}`;
  pElem.style.fontFamily = currentFont;
  imgElem.setAttribute("src", currentImage);
}
```

**Note:** To see this running as a complete working example, see our Web Storage Demo.

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

| Specification |
| --- |
| HTML Standard # storage |

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

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

See also
--------

* Using the Web Storage API
* `Window.localStorage`
* `Window.sessionStorage`
* `CacheStorage`


SVGFEConvolveMatrixElement - Web APIs

SVGFEConvolveMatrixElement
==========================

The **`SVGFEConvolveMatrixElement`** interface corresponds to the `<feConvolveMatrix>` element.

EventTarget

Node

Element

SVGElement

SVGFEConvolveMatrixElementConstants
---------

| Name | Value | Description |
| --- | --- | --- |
| `SVG_EDGEMODE_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.
  |
| `SVG_EDGEMODE_DUPLICATE` | 1 | Corresponds to the `duplicate` value. |
| `SVG_EDGEMODE_WRAP` | 2 | Corresponds to the `wrap` value. |
| `SVG_EDGEMODE_NONE` | 3 | Corresponds to `none` value. |

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

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

`SVGFEConvolveMatrixElement.bias` Read only

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

`SVGFEConvolveMatrixElement.divisor` Read only

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

`SVGFEConvolveMatrixElement.edgeMode` Read only

An `SVGAnimatedEnumeration` corresponding to the `edgeMode` attribute of the given element. Takes one of the `SVG_EDGEMODE_*` constants defined on this interface.

`SVGFEConvolveMatrixElement.height` Read only

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

`SVGFEConvolveMatrixElement.in1` Read only

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

`SVGFEConvolveMatrixElement.kernelMatrix` Read only

An `SVGAnimatedNumberList` corresponding to the `kernelMatrix` attribute of the given element.

`SVGFEConvolveMatrixElement.kernelUnitLengthX` Read only

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

`SVGFEConvolveMatrixElement.kernelUnitLengthY` Read only

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

`SVGFEConvolveMatrixElement.orderX` Read only

An `SVGAnimatedInteger` corresponding to the `order` attribute of the given element.

`SVGFEConvolveMatrixElement.orderY` Read only

An `SVGAnimatedInteger` corresponding to the `order` attribute of the given element.

`SVGFEConvolveMatrixElement.preserveAlpha` Read only

An `SVGAnimatedBoolean` corresponding to the `preserveAlpha` attribute of the given element.

`SVGFEConvolveMatrixElement.result` Read only

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

`SVGFEConvolveMatrixElement.targetX` Read only

An `SVGAnimatedInteger` corresponding to the `targetX` attribute of the given element.

`SVGFEConvolveMatrixElement.targetY` Read only

An `SVGAnimatedInteger` corresponding to the `targetY` attribute of the given element.

`SVGFEConvolveMatrixElement.width` Read only

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

`SVGFEConvolveMatrixElement.x` Read only

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

`SVGFEConvolveMatrixElement.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 # InterfaceSVGFEConvolveMatrixElement |

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

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

See also
--------

* `<feConvolveMatrix>`


Headers - Web APIs

Headers
=======

The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.

A `Headers` object has an associated header list, which is initially empty and consists of zero or more name and value pairs. You can add to this using methods like `append()` (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence.

For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names.

A Headers object also has an associated guard, which takes a value of `immutable`, `request`, `request-no-cors`, `response`, or `none`. This affects whether the `set()`, `delete()`, and `append()` methods will mutate the header. For more information see Guard.

You can retrieve a `Headers` object via the `Request.headers` and `Response.headers` properties, and create a new `Headers` object using the `Headers()` constructor.

An object implementing `Headers` can directly be used in a `for...of` structure, instead of `entries()`: `for (const p of myHeaders)` is equivalent to `for (const p of myHeaders.entries())`.

**Note:** you can find out more about the available headers by reading our HTTP headers reference.

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

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

`Headers()`

Creates a new `Headers` object.

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

`Headers.append()`

Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist.

`Headers.delete()`

Deletes a header from a `Headers` object.

`Headers.entries()`

Returns an `iterator` allowing to go through all key/value pairs contained in this object.

`Headers.forEach()`

Executes a provided function once for each key/value pair in this `Headers` object.

`Headers.get()`

Returns a `String` sequence of all the values of a header within a `Headers` object with a given name.

`Headers.getSetCookie()`

Returns an array containing the values of all `Set-Cookie` headers associated with a response.

`Headers.has()`

Returns a boolean stating whether a `Headers` object contains a certain header.

`Headers.keys()`

Returns an `iterator` allowing you to go through all keys of the key/value pairs contained in this object.

`Headers.set()`

Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.

`Headers.values()`

Returns an `iterator` allowing you to go through all values of the key/value pairs contained in this object.

**Note:** To be clear, the difference between `Headers.set()` and `Headers.append()` is that if the specified header does already exist and does accept multiple values, `Headers.set()` will overwrite the existing value with the new one, whereas `Headers.append()` will append the new value onto the end of the set of values. See their dedicated pages for example code.

**Note:** All of the Headers methods will throw a `TypeError` if you try to pass in a reference to a name that isn't a valid HTTP Header name. The mutation operations will throw a `TypeError` if the header has an immutable Guard. In any other failure case they fail silently.

**Note:** When Header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicate header names are combined.

Examples
--------

In the following snippet, we create a new header using the `Headers()` constructor, add a new header to it using `append()`, then return that header value using `get()`:

```js
const myHeaders = new Headers();

myHeaders.append("Content-Type", "text/xml");
myHeaders.get("Content-Type"); // should return 'text/xml'
```

The same can be achieved by passing an array of arrays or an object literal to the constructor:

```js
let myHeaders = new Headers({
  "Content-Type": "text/xml",
});

// or, using an array of arrays:
myHeaders = new Headers([["Content-Type", "text/xml"]]);

myHeaders.get("Content-Type"); // should return 'text/xml'
```

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

| Specification |
| --- |
| Fetch Standard # headers-class |

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

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

See also
--------

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


SharedStorageSelectURLOperation - Web APIs

SharedStorageSelectURLOperation
===============================

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

The **`SharedStorageSelectURLOperation`** interface of the Shared Storage API represents a URL Selection output gate operation.

SharedStorageOperation

SharedStorageSelectURLOperationInstance methods
----------------

`run()`
Experimental

Defines the structure to which the `run()` method defined inside a URL Selection output gate operation should conform.

Examples
--------

In this example, a class called `SelectURLOperation` is defined in a worklet and is registered using `SharedStorageWorkletGlobalScope.register()` with the name `ab-testing`. `SharedStorageSelectURLOperation` defines the structure to which this class needs to conform, essentially defining the parameters required for the `run()` method. Other than this requirement, the functionality of the class can be defined flexibly.

```js
// ab-testing-worklet.js
class SelectURLOperation {
  async run(urls, data) {
    // Read the user's experiment group from Shared Storage
    const experimentGroup = await this.sharedStorage.get("ab-testing-group");

    // Return the group number
    return experimentGroup;
  }
}

// Register the operation
register("ab-testing", SelectURLOperation);
```

**Note:** It is possible to define and register multiple operations in the same shared storage worklet module script with different names; see `SharedStorageOperation` for an example.

In the main browsing context, the `ab-testing` operation is invoked using the `WindowSharedStorage.selectURL()` method:

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

async function injectContent() {
  // Register the Shared Storage worklet
  await window.sharedStorage.worklet.addModule("ab-testing-worklet.js");

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

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

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

injectContent();
```

For more details about this example and links to other examples, see the Shared Storage API landing page.

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

| Specification |
| --- |
| Shared Storage API # sharedstorageselecturloperation |

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

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

See also
--------

* Shared Storage API


Selection - Web APIs

Selection
=========

A **`Selection`** object represents the range of text selected by the user or the current position of the caret. To obtain a `Selection` object for examination or manipulation, call `window.getSelection()`.

A user may make a selection from left to right (in document order) or right to left (reverse of document order). The ***anchor*** is where the user began the selection and the ***focus*** is where the user ends the selection. If you make a selection with a desktop mouse, the anchor is placed where you pressed the mouse button, and the focus is placed where you released the mouse button.

**Note:** *Anchor* and *focus* should not be confused with the *start* and *end* positions of a selection. The anchor can be placed before the focus or vice versa, depending on the direction you made your selection.

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

`Selection.anchorNode` Read only

Returns the `Node` in which the selection begins. Can return `null` if selection never existed in the document (e.g., an iframe that was never clicked on).

`Selection.anchorOffset` Read only

Returns a number representing the offset of the selection's anchor within the `anchorNode`. If `anchorNode` is a text node, this is the number of characters within anchorNode preceding the anchor. If `anchorNode` is an element, this is the number of child nodes of the `anchorNode` preceding the anchor.

`Selection.focusNode` Read only

Returns the `Node` in which the selection ends. Can return `null` if selection never existed in the document (for example, in an `iframe` that was never clicked on).

`Selection.focusOffset` Read only

Returns a number representing the offset of the selection's anchor within the `focusNode`. If `focusNode` is a text node, this is the number of characters within `focusNode` preceding the focus. If `focusNode` is an element, this is the number of child nodes of the `focusNode` preceding the focus.

`Selection.isCollapsed` Read only

Returns a Boolean indicating whether the selection's start and end points are at the same position.

`Selection.rangeCount` Read only

Returns the number of ranges in the selection.

`Selection.type` Read only

Returns a string describing the type of the current selection.

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

`Selection.addRange()`

A `Range` object that will be added to the selection.

`Selection.collapse()`

Collapses the current selection to a single point.

`Selection.collapseToEnd()`

Collapses the selection to the end of the last range in the selection.

`Selection.collapseToStart()`

Collapses the selection to the start of the first range in the selection.

`Selection.containsNode()`

Indicates if a certain node is part of the selection.

`Selection.deleteFromDocument()`

Deletes the selection's content from the document.

`Selection.extend()`

Moves the focus of the selection to a specified point.

`Selection.getRangeAt()`

Returns a `Range` object representing one of the ranges currently selected.

`Selection.modify()`

Changes the current selection.

`Selection.removeRange()`

Removes a range from the selection.

`Selection.removeAllRanges()`

Removes all ranges from the selection.

`Selection.selectAllChildren()`

Adds all the children of the specified node to the selection.

`Selection.setBaseAndExtent()`

Sets the selection to be a range including all or parts of two specified DOM nodes, and any content located between them.

`Selection.toString()`

Returns a string currently being represented by the selection object, i.e. the currently selected text.

Notes
-----

### String representation of a selection

Calling the `Selection.toString()` method returns the text contained within the selection, e.g.:

```js
const selObj = window.getSelection();
window.alert(selObj);
```

Note that using a selection object as the argument to `window.alert` will call the object's `toString` method.

### Multiple ranges in a selection

A selection object represents the `Range`s that the user has selected. Typically, it holds only one range, accessed as follows:

```js
const selObj = window.getSelection();
const range = selObj.getRangeAt(0);
```

* `selObj` is a Selection object
* `range` is a `Range` object

As the Selection API specification notes, the Selection API was initially created by Netscape and allowed multiple ranges (for instance, to allow the user to select a column from a `<table>`). However, browsers other than Gecko did not implement multiple ranges, and the specification also requires the selection to always have a single range.

### Selection and input focus

Selection and input focus (indicated by `Document.activeElement`) have a complex relationship that varies by browser. In cross-browser compatible code, it's better to handle them separately.

Safari and Chrome (unlike Firefox) currently focus the element containing selection when modifying the selection programmatically; it's possible that this may change in the future (see W3C bug 14383 and Webkit bug 38696).

### Behavior of Selection API in terms of editing host focus changes

The Selection API has a common behavior (i.e., shared between browsers) that governs how focus behavior changes for *editing hosts* after certain methods are called.

The behavior is as follows:

1. An editing host gains focus if the previous selection was outside of it.
2. A Selection API method is called, causing a new selection to be made with the selection range inside the editing host.
3. Focus then moves to the editing host.

**Note:** The Selection API methods may only move focus to an editing host, not to other focusable elements (e.g., `<a>`).

The above behavior applies to selections made using the following methods:

* `Selection.collapse()`
* `Selection.collapseToStart()`
* `Selection.collapseToEnd()`
* `Selection.extend()`
* `Selection.selectAllChildren()`
* `Selection.addRange()`
* `Selection.setBaseAndExtent()`

And when the `Range` is modified using the following methods:

* `Range.setStart()`
* `Range.setEnd()`
* `Range.setStartBefore()`
* `Range.setStartAfter()`
* `Range.setEndBefore()`
* `Range.setEndAfter()`
* `Range.collapse()`
* `Range.selectNode()`
* `Range.selectNodeContents()`
### Glossary

Other key terms used in this section.

`anchor`

The anchor of a selection is the beginning point of the selection. When making a selection with a mouse, the anchor is where in the document the mouse button is initially pressed. As the user changes the selection using the mouse or the keyboard, the anchor does not move.

`editing host`

An editable element (e.g., an HTML element with `contenteditable` set, or the HTML child of a document that has `designMode` enabled).

`focus of a selection`

The *focus* of a selection is the end point of the selection. When making a selection with a mouse, the focus is where in the document the mouse button is released. As the user changes the selection using the mouse or the keyboard, the focus is the end of the selection that moves.

**Note:** This is not the same as the focused *element* of the document, as returned by `document.activeElement`.

`range`

A *range* is a contiguous part of a document. A range can contain entire nodes as well as portions of nodes (such as a portion of a text node). A user will normally only select a single range at a time, but it's possible for a user to select multiple ranges (e.g., by using the `Control` key). A range can be retrieved from a selection as a `range` object. Range objects can also be created via the DOM and programmatically added or removed from a selection.

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

| Specification |
| --- |
| Selection API # selection-interface |

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

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

See also
--------

* `Window.getSelection`, `Document.getSelection`, `Range`
* Selection-related events: `selectionchange` and `selectstart`
* HTML inputs provide simpler helper APIs for working with selection (see `HTMLInputElement.setSelectionRange()`)
* `Document.activeElement`, `HTMLElement.focus`, and `HTMLElement.blur`


CDATASection - Web APIs

CDATASection
============

 The **`CDATASection`** interface represents a CDATA section
 that can be used within XML to include extended portions of unescaped text.
 When inside a CDATA section, the symbols `<` and `&` don't need escaping
 as they normally do.

In XML, a CDATA section looks like:

```xml
<![CDATA[ … ]]>
```

For example:

```html
<foo>
  Here is a CDATA section: <![CDATA[ < > & ]]> with all kinds of unescaped text.
</foo>
```

 The only sequence which is not allowed within a CDATA section is the closing sequence
 of a CDATA section itself, `]]>`.

**Note:** CDATA sections should not be used within HTML they are considered as comments and not displayed.

EventTarget

Node

CharacterData

Text

CDATASectionInstance properties
-------------------

*This interface has no specific properties and implements those of its parent
`Text`.*

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

*This interface has no specific methods and implements those of its parent
`Text`.*

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

| Specification |
| --- |
| DOM Standard # interface-cdatasection |

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

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

See also
--------

* `Document.createCDATASection()`


MediaStreamEvent - Web APIs

MediaStreamEvent
================

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

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

The **`MediaStreamEvent`** interface represents events that occurs in relation to a `MediaStream`. Two events of this type can be thrown: `addstream` and `removestream`.

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

*A `MediaStreamEvent` being an `Event`, this event also implements these properties*.

`MediaStreamEvent.stream` Read only
Deprecated

Non-standard

Contains the `MediaStream` containing the stream associated with the event.

Constructors
------------

`MediaStreamEvent()`
Deprecated

Non-standard

Returns a new `MediaStreamEvent`. It takes two parameters, the first being a string representing the type of the event; the second a dictionary containing the `MediaStream` it refers to.

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

A `MediaStreamEvent` being an `Event`, this event also implements these properties. There is no specific `MediaStreamEvent` method.

Examples
--------

```js
pc.onaddstream = (ev) => {
  alert(`A stream (id: '${ev.stream.id}') has been added to this connection.`);
};
```

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

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

See also
--------

* WebRTC
* Its usual target: `RTCPeerConnection`.


WEBGL_compressed_texture_pvrtc extension - Web APIs

WEBGL\_compressed\_texture\_pvrtc extension
===========================================

The **`WEBGL_compressed_texture_pvrtc`** extension is part of the WebGL API and exposes four PVRTC compressed texture formats.

Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures.

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

**Note:** PVRTC is typically only available on mobile devices with PowerVR chipsets.
 It is used in all generations of the iPhone, iPod Touch and iPad and supported on certain Android devices that use a PowerVR GPU.

This extension is available to both, WebGL1 and WebGL2 contexts.

**Note:** On iOS devices, this extension is named `WEBKIT_WEBGL_compressed_texture_pvrtc`.

Constants
---------

The compressed texture formats are exposed by four constants and can be used in two functions: `compressedTexImage2D()` (where the `height` and `width` parameters must be powers of 2) and `compressedTexSubImage2D()` (where the height and width parameters must equal the current values of the existing texture and the `xoffset` and `yoffset` parameters must be 0).

`ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG`

RGB compression in 4-bit mode. One block for each 4×4 pixels.

`ext.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG`

RGBA compression in 4-bit mode. One block for each 4×4 pixels.

`ext.COMPRESSED_RGB_PVRTC_2BPPV1_IMG`

RGB compression in 2-bit mode. One block for each 8×4 pixels.

`ext.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG`

RGBA compression in 2-bit mode. One block for each 8×4 pixels.

Examples
--------

```js
const ext = gl.getExtension("WEBGL\_compressed\_texture\_pvrtc");

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

gl.compressedTexImage2D(
  gl.TEXTURE\_2D,
  0,
  ext.COMPRESSED\_RGB\_PVRTC\_4BPPV1\_IMG,
  512,
  512,
  0,
  textureData,
);
```

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

| Specification |
| --- |
| WebGL WEBGL\_compressed\_texture\_pvrtc Extension Specification  |

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

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

See also
--------

* PVRTC Texture Compression – Wikipedia
* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.compressedTexImage2D()`
* `WebGLRenderingContext.compressedTexSubImage2D()`
* `WebGLRenderingContext.getParameter()`


Launch Handler API - Web APIs

Launch Handler API
==================

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

The **Launch Handler API** allows developers to control how a progressive web app (PWA) is launched — for example if it uses an existing window or creates a new one, and how the app's target launch URL is handled.

Concepts and usage
------------------

You can specify launch behavior for your app by adding the `launch_handler` field to your web app manifest file. This has one sub-field, `client_mode`, which contains a string value specifying how the app should be launched and navigated to. For example:

```json
"launch\_handler": {
    "client\_mode": "focus-existing"
}
```

If not specified, the default `client_mode` value is `auto`. Available values are:

`focus-existing`

The most recently interacted with browsing context in a web app window is chosen to handle the launch. This will populate the target launch URL in the `targetURL` property of the `LaunchParams` object passed into the `window.launchQueue.setConsumer()`'s callback function. As you'll see below, this allows you to set custom launch handing functionality for your app.

`navigate-existing`

The most recently interacted with browsing context in a web app window is navigated to the target launch URL. The target URL is still made available via `window.launchQueue.setConsumer()` to allow additional custom launch navigation handling to be implemented.

`navigate-new`

A new browsing context is created in a web app window to load the target launch URL. The target URL is still made available via `window.launchQueue.setConsumer()` to allow additional custom launch navigation handling to be implemented.

`auto`

The user agent decides what works best for the platform. For example, `navigate-existing` might make more sense on mobile, where single app instances are commonplace, whereas `navigate-new` might make more sense in a desktop context. This is the default value used if provided values are invalid.

When `focus-existing` is used, you can include code inside the `window.launchQueue.setConsumer()`'s callback function to provide custom handling of the `targetURL`

```js
window.launchQueue.setConsumer((launchParams) => {
  // Do something with launchParams.targetURL
});
```

**Note:** `LaunchParams` also has a `LaunchParams.files` property, which returns a read-only array of `FileSystemHandle` objects representing any files passed along with the launch navigation via the `POST` method. This allows custom file handling to be implemented.

Interfaces
----------

`LaunchParams`

Used when implementing custom launch navigation handling in a PWA. When `window.launchQueue.setConsumer()` is invoked to set up the launch navigation handling functionality, the callback function inside `setConsumer()` is passed a `LaunchParams` object instance.

`LaunchQueue`

When a progressive web app (PWA) is launched with a `launch_handler` `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`, `LaunchQueue` provides access to functionality that allows custom launch navigation handling to be implemented in the PWA. This functionality is controlled by the properties of the `LaunchParams` object passed into the `setConsumer()` callback function.

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

`window.launchQueue`

Provides access to the `LaunchQueue` class, which allows custom launch navigation handling to be implemented in a progressive web app (PWA), with the handling context signified by the `launch_handler` manifest field `client_mode` value.

Examples
--------

```js
if ("launchQueue" in window) {
  window.launchQueue.setConsumer((launchParams) => {
    if (launchParams.targetURL) {
      const params = new URL(launchParams.targetURL).searchParams;

      // Assuming a music player app that gets a track passed to it to be played
      const track = params.get("track");
      if (track) {
        audio.src = track;
        title.textContent = new URL(track).pathname.substr(1);
        audio.play();
      }
    }
  });
}
```

This code is included in the PWA, and executed when the app loads, upon launch. The `window.launchQueue.setConsumer()`'s callback function extracts the search param out of the `LaunchParams.targetURL` and, if it finds a `track` param, uses it to populate an `<audio>` element's `src` and play the audio track that this points to.

See the Musicr 2.0 demo app for full working code.

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

| Specification |
| --- |
| Web App Launch Handler API # launchqueue-interface |

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

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

See also
--------

* Launch Handler API: Control how your app is launched
* Musicr 2.0 demo app


SVGAnimatedNumber - Web APIs

SVGAnimatedNumber
=================

SVG animated number interface
-----------------------------

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

### Interface overview

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

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

| Name | Type | Description |
| --- | --- | --- |
| `baseVal` | float | The base value of the given attribute before applying any animations. |
| `animVal` | float |
 If the given attribute or property is being animated, contains the
 current animated value of the attribute or property. If the given
 attribute or property is not currently being animated, contains the same
 value as `baseVal`.
  |

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

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

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

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


WebGL2RenderingContext - Web APIs

WebGL2RenderingContext
======================

The **WebGL2RenderingContext** interface provides the OpenGL ES 3.0 rendering context for the drawing surface of an HTML `<canvas>` element.

To get an object of this interface, call `getContext()` on a `<canvas>` element, supplying "webgl2" as the argument:

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

**Note:** WebGL 2 is an extension to WebGL 1. The `WebGL2RenderingContext` interface implements all members of the `WebGLRenderingContext` interface. Some methods of the WebGL 1 context can accept additional values when used in a WebGL 2 context. You will find this info noted on the WebGL 1 reference pages.

The WebGL tutorial has more information, examples, and resources on how to get started with WebGL.

Constants
---------

See the WebGL constants page.

State information
-----------------

`WebGL2RenderingContext.getIndexedParameter()`

Returns the indexed value for the given `target`.

Buffers
-------

`WebGL2RenderingContext.bufferData()`

Initializes and creates the buffer object's data store.

`WebGL2RenderingContext.bufferSubData()`

Updates a subset of a buffer object's data store.

`WebGL2RenderingContext.copyBufferSubData()`

Copies part of the data of a buffer to another buffer.

`WebGL2RenderingContext.getBufferSubData()`

Reads data from a buffer and writes them to an `ArrayBuffer` or `SharedArrayBuffer`.

Framebuffers
------------

`WebGL2RenderingContext.blitFramebuffer()`

Transfers a block of pixels from the read framebuffer to the draw framebuffer.

`WebGL2RenderingContext.framebufferTextureLayer()`

Attaches a single layer of a texture to a framebuffer.

`WebGL2RenderingContext.invalidateFramebuffer()`

Invalidates the contents of attachments in a framebuffer.

`WebGL2RenderingContext.invalidateSubFramebuffer()`

Invalidates portions of the contents of attachments in a framebuffer

`WebGL2RenderingContext.readBuffer()`

Selects a color buffer as the source for pixels.

Renderbuffers
-------------

`WebGL2RenderingContext.getInternalformatParameter()`

Returns information about implementation-dependent support for internal formats.

`WebGL2RenderingContext.renderbufferStorageMultisample()`

Creates and initializes a renderbuffer object's data store and allows specifying the number of samples to be used.

Textures
--------

`WebGL2RenderingContext.texStorage2D()`

Specifies all levels of two-dimensional texture storage.

`WebGL2RenderingContext.texStorage3D()`

Specifies all levels of a three-dimensional texture or two-dimensional array texture.

`WebGL2RenderingContext.texImage3D()`

Specifies a three-dimensional texture image.

`WebGL2RenderingContext.texSubImage3D()`

Specifies a sub-rectangle of the current 3D texture.

`WebGL2RenderingContext.copyTexSubImage3D()`

Copies pixels from the current `WebGLFramebuffer` into an existing 3D texture sub-image.

`WebGLRenderingContext.compressedTexImage2D`

Specifies a three-dimensional texture image in a compressed format.

`WebGL2RenderingContext.compressedTexSubImage3D()`

Specifies a three-dimensional sub-rectangle for a texture image in a compressed format.

Programs and shaders
--------------------

`WebGL2RenderingContext.getFragDataLocation()`

Returns the binding of color numbers to user-defined varying out variables.

Uniforms and attributes
-----------------------

`WebGL2RenderingContext.uniform[1234][uif][v]()`

Methods specifying values of uniform variables.

`WebGL2RenderingContext.uniformMatrix[234]x[234]fv()`

Methods specifying matrix values for uniform variables.

`WebGL2RenderingContext.vertexAttribI4[u]i[v]()`

Methods specifying integer values for generic vertex attributes.

`WebGL2RenderingContext.vertexAttribIPointer()`

Specifies integer data formats and locations of vertex attributes in a vertex attributes array.

Drawing buffers
---------------

`WebGL2RenderingContext.vertexAttribDivisor()`

Modifies the rate at which generic vertex attributes advance when rendering multiple instances of primitives with `gl.drawArraysInstanced()` and `gl.drawElementsInstanced()`.

`WebGL2RenderingContext.drawArraysInstanced()`

Renders primitives from array data. In addition, it can execute multiple instances of the range of elements.

`WebGL2RenderingContext.drawElementsInstanced()`

Renders primitives from array data. In addition, it can execute multiple instances of a set of elements.

`WebGL2RenderingContext.drawRangeElements()`

Renders primitives from array data in a given range.

`WebGL2RenderingContext.drawBuffers()`

Specifies a list of color buffers to be drawn into.

`WebGL2RenderingContext.clearBuffer[fiuv]()`

Clears buffers from the currently bound framebuffer.

Query objects
-------------

Methods for working with `WebGLQuery` objects.

`WebGL2RenderingContext.createQuery()`

Creates a new `WebGLQuery` object.

`WebGL2RenderingContext.deleteQuery()`

Deletes a given `WebGLQuery` object.

`WebGL2RenderingContext.isQuery()`

Returns `true` if a given object is a valid `WebGLQuery` object.

`WebGL2RenderingContext.beginQuery()`

Begins an asynchronous query.

`WebGL2RenderingContext.endQuery()`

Marks the end of an asynchronous query.

`WebGL2RenderingContext.getQuery()`

Returns a `WebGLQuery` object for a given target.

`WebGL2RenderingContext.getQueryParameter()`

Returns information about a query.

Sampler objects
---------------

`WebGL2RenderingContext.createSampler()`

Creates a new `WebGLSampler` object.

`WebGL2RenderingContext.deleteSampler()`

Deletes a given `WebGLSampler` object.

`WebGL2RenderingContext.bindSampler()`

Binds a given `WebGLSampler` to a texture unit.

`WebGL2RenderingContext.isSampler()`

Returns `true` if a given object is a valid `WebGLSampler` object.

`WebGL2RenderingContext.samplerParameter[if]()`

Sets sampler parameters.

`WebGL2RenderingContext.getSamplerParameter()`

Returns sampler parameter information.

Sync objects
------------

`WebGL2RenderingContext.fenceSync()`

Creates a new `WebGLSync` object and inserts it into the GL command stream.

`WebGL2RenderingContext.isSync()`

Returns `true` if the passed object is a valid `WebGLSync` object.

`WebGL2RenderingContext.deleteSync()`

Deletes a given `WebGLSync` object.

`WebGL2RenderingContext.clientWaitSync()`

Blocks and waits for a `WebGLSync` object to become signaled or a given timeout to be passed.

`WebGL2RenderingContext.waitSync()`

Returns immediately, but waits on the GL server until the given `WebGLSync` object is signaled.

`WebGL2RenderingContext.getSyncParameter()`

Returns parameter information of a `WebGLSync` object.

Transform feedback
------------------

`WebGL2RenderingContext.createTransformFeedback()`

Creates and initializes `WebGLTransformFeedback` objects.

`WebGL2RenderingContext.deleteTransformFeedback()`

Deletes a given `WebGLTransformFeedback` object.

`WebGL2RenderingContext.isTransformFeedback()`

Returns `true` if the passed object is a valid `WebGLTransformFeedback` object.

`WebGL2RenderingContext.bindTransformFeedback()`

Binds a passed `WebGLTransformFeedback` object to the current GL state.

`WebGL2RenderingContext.beginTransformFeedback()`

Starts a transform feedback operation.

`WebGL2RenderingContext.endTransformFeedback()`

Ends a transform feedback operation.

`WebGL2RenderingContext.transformFeedbackVaryings()`

Specifies values to record in `WebGLTransformFeedback` buffers.

`WebGL2RenderingContext.getTransformFeedbackVarying()`

Returns information about varying variables from `WebGLTransformFeedback` buffers.

`WebGL2RenderingContext.pauseTransformFeedback()`

Pauses a transform feedback operation.

`WebGL2RenderingContext.resumeTransformFeedback()`

Resumes a transform feedback operation.

Uniform buffer objects
----------------------

`WebGL2RenderingContext.bindBufferBase()`

Binds a given `WebGLBuffer` to a given binding point (`target`) at a given `index`.

`WebGL2RenderingContext.bindBufferRange()`

Binds a range of a given `WebGLBuffer` to a given binding point (`target`) at a given `index`.

`WebGL2RenderingContext.getUniformIndices()`

Retrieves the indices of a number of uniforms within a `WebGLProgram`.

`WebGL2RenderingContext.getActiveUniforms()`

Retrieves information about active uniforms within a `WebGLProgram`.

`WebGL2RenderingContext.getUniformBlockIndex()`

Retrieves the index of a uniform block within a `WebGLProgram`.

`WebGL2RenderingContext.getActiveUniformBlockParameter()`

Retrieves information about an active uniform block within a `WebGLProgram`.

`WebGL2RenderingContext.getActiveUniformBlockName()`

Retrieves the name of the active uniform block at a given index within a `WebGLProgram`.

`WebGL2RenderingContext.uniformBlockBinding()`

Assigns binding points for active uniform blocks.

Vertex array objects
--------------------

Methods for working with `WebGLVertexArrayObject` (VAO) objects.

`WebGL2RenderingContext.createVertexArray()`

Creates a new `WebGLVertexArrayObject`.

`WebGL2RenderingContext.deleteVertexArray()`

Deletes a given `WebGLVertexArrayObject`.

`WebGL2RenderingContext.isVertexArray()`

Returns `true` if a given object is a valid `WebGLVertexArrayObject`.

`WebGL2RenderingContext.bindVertexArray()`

Binds a given `WebGLVertexArrayObject` to the buffer.

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

| Specification |
| --- |
| WebGL 2.0 Specification # 3.7 |

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

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

See also
--------

* `HTMLCanvasElement`
* `WebGLRenderingContext`


SVGRectElement - Web APIs

SVGRectElement
==============

The `SVGRectElement` interface provides access to the properties of `<rect>` elements, as well as methods to manipulate them.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGGeometryElement

SVGRectElementInstance properties
-------------------

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

`SVGRectElement.x` Read only

Returns an `SVGAnimatedLength` corresponding to the `x` attribute of the given `<rect>` element.

`SVGRectElement.y` Read only

Returns an `SVGAnimatedLength` corresponding to the `y` attribute of the given `<rect>` element.

`SVGRectElement.width` Read only

Returns an `SVGAnimatedLength` corresponding to the `width` attribute of the given `<rect>` element.

`SVGRectElement.height` Read only

Returns an `SVGAnimatedLength` corresponding to the `height` attribute of the given `<rect>` element.

`SVGRectElement.rx` Read only

Returns an `SVGAnimatedLength` corresponding to the `rx` attribute of the given `<rect>` element.

`SVGRectElement.ry` Read only

Returns an `SVGAnimatedLength` corresponding to the `ry` attribute of the given `<rect>` element.

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

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

Examples
--------

### Changing the color of an SVG rectangle

This example sets the fill color of an `SVGRectElement` to a random value whenever the user clicks it.

#### HTML

```html
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <rect
 width="300"
 height="100"
 id="myrect"
 style="fill:rgb(0 0 255);stroke-width:1;stroke:rgb(0 0 0)" />
  <text x="60" y="40" fill="white" font-size="40">Click Me</text>
</svg>
```

#### JavaScript

```js
const myRect = document.querySelector("#myrect");

myRect.addEventListener("click", () => {
  const r = Math.floor(Math.random() \* 255);
  const g = Math.floor(Math.random() \* 255);
  const b = Math.floor(Math.random() \* 255);
  myRect.style.fill = `rgb(${r} ${g} ${b})`;
});
```

#### Result

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

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

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

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

See also
--------

* `<rect>`


SubmitEvent - Web APIs

SubmitEvent
===========

The **`SubmitEvent`** interface defines the object used to represent an HTML form's `submit` event. This event is fired at the `<form>` when the form's submit action is invoked.

Event

SubmitEventConstructor
-----------

`SubmitEvent()`

Creates and returns a new `SubmitEvent` object whose `type` and other options are configured as specified. Note that currently the only valid `type` for a `SubmitEvent` is `submit`.

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

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

`submitter` Read only

An `HTMLElement` object which identifies the button or other element which was invoked to trigger the form being submitted.

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

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

Examples
--------

In this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. Each of the submit elements' `id` is used to identify which payment processor the button corresponds to.

```js
let form = document.querySelector("form");
form.addEventListener("submit", (event) => {
  let submitter = event.submitter;
  let handler = submitter.id;

  if (handler) {
    processOrder(form, handler);
  } else {
    showAlertMessage(
      "An unknown or unaccepted payment type was selected. Please try again.",
      "OK",
    );
  }
});
```

The handler ID is obtained by using the `submit` event's `submitter` property to get the submit button, from which we then get the ID. With that in hand, we can call a `processOrder()` function to handle the order, passing along the form and the handler ID.

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

| Specification |
| --- |
| HTML Standard # the-submitevent-interface |

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

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


SVGEllipseElement - Web APIs

SVGEllipseElement
=================

The **`SVGEllipseElement`** interface provides access to the properties of `<ellipse>` elements.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGGeometryElement

SVGEllipseElementInstance properties
-------------------

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

`SVGEllipseElement.cx` Read only

This property returns a `SVGAnimatedLength` reflecting the `cx` attribute of the given `<ellipse>` element.

`SVGEllipseElement.cy` Read only

This property returns a `SVGAnimatedLength` reflecting the `cy` attribute of the given `<ellipse>` element.

`SVGEllipseElement.rx` Read only

This property returns a `SVGAnimatedLength` reflecting the `rx` attribute of the given `<ellipse>` element.

`SVGEllipseElement.ry` Read only

This property returns a `SVGAnimatedLength` reflecting the `ry` attribute of the given `<ellipse>` element.

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

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

Example
-------

### SVG

```html
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <ellipse
 cx="100"
 cy="100"
 rx="100"
 ry="60"
 id="ellipse"
 onclick="outputSize();" />
</svg>
```

### JavaScript

```js
function outputSize() {
  const ellipse = document.getElementById("ellipse");

  // Outputs "horizontal radius: 100 vertical radius: 60"
  console.log(
    `horizontal radius: ${ellipse.rx.baseVal.valueAsString}`,
    `vertical radius: ${ellipse.ry.baseVal.valueAsString}`,
  );
}
```

### Result

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

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

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

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

See also
--------

* `<ellipse>` SVG Element


WindowSharedStorage - Web APIs

WindowSharedStorage
===================

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

The **`WindowSharedStorage`** interface of the Shared Storage API represents the shared storage for a particular origin within a standard browsing context.

`WindowSharedStorage` is accessed via `Window.sharedStorage`.

SharedStorage

WindowSharedStorageInstance properties
-------------------

`worklet`
Experimental

Contains the `SharedStorageWorklet` instance representing the shared storage worklet for the current origin. `SharedStorageWorklet` includes the `addModule()` method, which is used to add a module to the shared storage worklet.

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

*`WindowSharedStorage` inherits properties from its parent interface, `SharedStorage`.*

`run()`
Experimental

Executes a Run output gate operation that has been registered in a module added to the `SharedStorageWorklet` of the current origin.

`selectURL()`
Experimental

Executes a URL Selection output gate operation that has been registered in a module added to the `SharedStorageWorklet` of the current origin.

Examples
--------

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

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

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

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

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

injectContent();
```

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

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

| Specification |
| --- |
| Shared Storage API # windowsharedstorage |

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

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

See also
--------

* Shared Storage API


SVGMaskElement - Web APIs

SVGMaskElement
==============

The **`SVGMaskElement`** interface provides access to the properties of `<mask>` elements, as well as methods to manipulate them.

EventTarget

Node

Element

SVGElement

SVGMaskElementInstance properties
-------------------

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

`SVGMaskElement.maskUnits` Read only

An `SVGAnimatedEnumeration` corresponding to the `maskUnits` attribute of the given `<mask>` element. Takes one of the constants defined in `SVGUnitTypes`.

`SVGMaskElement.maskContentUnits` Read only

An `SVGAnimatedEnumeration` corresponding to the `maskContentUnits` attribute of the given `<mask>` element. Takes one of the constants defined in `SVGUnitTypes`.

`SVGMaskElement.x` Read only

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

`SVGMaskElement.y` Read only

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

`SVGMaskElement.width` Read only

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

`SVGMaskElement.height` Read only

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

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

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

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

| Specification |
| --- |
| CSS Masking Module Level 1 # InterfaceSVGMaskElement |

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

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

See also
--------

* `<mask>`


Background Synchronization API - Web APIs

Background Synchronization 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 **Background Synchronization API** enables a web app to defer tasks so that they can be run in a service worker once the user has a stable network connection.

Concepts and usage
------------------

The Background Synchronization API allows web applications to defer server synchronization work to their service worker to handle at a later time, if the device is offline. Uses may include sending requests in the background if they couldn't be sent while the application was being used.

For example, an email client application could let its users compose and send messages at any time, even when the device has no network connection. The application frontend just registers a sync request and the service worker gets alerted when the network is present again and handles the sync.

The `SyncManager` interface is available through `ServiceWorkerRegistration.sync`. A unique tag identifier is set to 'name' the sync event, which can then be listened for within the `ServiceWorker` script. Once the event is received you can then run any functionality available, such as sending requests to the server.

As this API relies on service workers, functionality provided by this API is only available in a secure context.

Interfaces
----------

`SyncManager`
Experimental

Registers tasks to be run in a service worker at a later time with network connectivity. These tasks are referred to as *background sync requests*.

`SyncEvent`
Experimental

Represents a synchronization event, sent to the global scope of a `ServiceWorker`. It provides a way to run tasks in the service worker once the device has network connectivity.

### Extensions to other interfaces

The following additions to the Service Worker API provide an entry point for setting up background synchronization.

`ServiceWorkerRegistration.sync` Read only

Returns a reference to the `SyncManager` interface for registering tasks to run once the device has network connectivity.

`sync` event

An event handler fired whenever a `sync` event occurs. This happens as soon as the network becomes available.

Examples
--------

The following examples show how to use the interface.

### Requesting a background sync

The following asynchronous function registers a background sync from a browsing context:

```js
async function syncMessagesLater() {
  const registration = await navigator.serviceWorker.ready;
  try {
    await registration.sync.register("sync-messages");
  } catch {
    console.log("Background Sync could not be registered!");
  }
}
```

### Verifying a background sync by Tag

This code checks to see if a background sync task with a given tag is registered.

```js
navigator.serviceWorker.ready.then((registration) => {
  registration.sync.getTags().then((tags) => {
    if (tags.includes("sync-messages"))
      console.log("Messages sync already requested");
  });
});
```

### Listening for a background sync within a Service Worker

The following example shows how to respond to a background sync event in the service worker.

```js
self.addEventListener("sync", (event) => {
  if (event.tag === "sync-messages") {
    event.waitUntil(sendOutboxMessages());
  }
});
```

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

| Specification |
| --- |
| Web Background Synchronization  |

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

### api.SyncManager

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

### api.ServiceWorkerGlobalScope.sync\_event

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

See also
--------

* Introducing Background Sync


DecompressionStream - Web APIs

DecompressionStream
===================

The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data.

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

`DecompressionStream()`

Creates a new `DecompressionStream`

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

`DecompressionStream.readable`

Returns the `ReadableStream` instance controlled by this object.

`DecompressionStream.writable`

Returns the `WritableStream` instance controlled by this object.

Examples
--------

In this example a blob is decompressed using gzip compression.

```js
const ds = new DecompressionStream("gzip");
const decompressedStream = blob.stream().pipeThrough(ds);
```

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

| Specification |
| --- |
| Compression Streams # decompression-stream |

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

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


IDBRequest - Web APIs

IDBRequest
==========

The **`IDBRequest`** interface of the IndexedDB API provides access to results of asynchronous requests to databases and database objects using event handler attributes. Each reading and writing operation on a database is done using a request.

The request object does not initially contain any information about the result of the operation, but once information becomes available, an event is fired on the request, and the information becomes available through the properties of the `IDBRequest` instance.

All asynchronous operations immediately return an `IDBRequest` instance. Each request has a `readyState` that is set to the `'pending'` state; this changes to `'done'` when the request is completed or fails. When the state is set to `done`, every request returns a `result` and an `error`, and an event is fired on the request. When the state is still `pending`, any attempt to access the `result` or `error` raises an `InvalidStateError` exception.

In plain words, all asynchronous methods return a request object. If the request has been completed successfully, the result is made available through the `result` property and an event indicating success is fired at the request (`success`). If an error occurs while performing the operation, the exception is made available through the `error` property and an error event is fired (`error`).

The interface `IDBOpenDBRequest` is derived from `IDBRequest`.

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

EventTarget

IDBRequestInstance properties
-------------------

*Also inherits properties from `EventTarget`.*

`IDBRequest.error` Read only

Returns a `DOMException` in the event of an unsuccessful request, indicating what went wrong.

`IDBRequest.result` Read only

Returns the result of the request. If the request is not completed, the result is not available and an `InvalidStateError` exception is thrown.

`IDBRequest.source` Read only

The source of the request, such as an `IDBIndex` or an `IDBObjectStore`. If no source exists (such as when calling `IDBFactory.open`), it returns null.

`IDBRequest.readyState` Read only

The state of the request. Every request starts in the `pending` state. The state changes to `done` when the request completes successfully or when an error occurs.

`IDBRequest.transaction` Read only

The transaction for the request. This property can be null for certain requests, for example those returned from `IDBFactory.open` unless an upgrade is needed. (You're just connecting to a database, so there is no transaction to return).

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

*No methods, but inherits methods from `EventTarget`.*

Events
------

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

`error`

Fired when an error caused a request to fail.

`success`

Fired when an `IDBRequest` succeeds.

Example
-------

In the following code snippet, we open a database asynchronously and make a request; `onerror` and `onsuccess` functions are included to handle the success and error cases. For a full working example, see our To-do Notifications app (view example live.)

```js
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database being
// opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database.
  db = DBOpenRequest.result;
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # request-api |

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


USBDevice - Web APIs

USBDevice
=========

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
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`USBDevice`** interface of the WebUSB API provides access to metadata about a paired USB device and methods for controlling it.

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

`USBDevice.configuration` Read only
Experimental

A `USBConfiguration` object for the currently selected interface for a paired USB device.

`USBDevice.configurations` Read only
Experimental

An `array` of device-specific interfaces for controlling a paired USB device.

`USBDevice.deviceClass` Read only
Experimental

One of three properties that identify USB devices for the purpose of loading a USB driver that will work with that device. The other two properties are `USBDevice.deviceSubclass` and `USBDevice.deviceProtocol`.

`USBDevice.deviceProtocol` Read only
Experimental

One of three properties that identify USB devices for the purpose of loading a USB driver that will work with that device. The other two properties are `USBDevice.deviceClass` and `USBDevice.deviceSubclass`.

`USBDevice.deviceSubclass` Read only
Experimental

One of three properties that identify USB devices for the purpose of loading a USB driver that will work with that device. The other two properties are `USBDevice.deviceClass` and `USBDevice.deviceProtocol`.

`USBDevice.deviceVersionMajor` Read only
Experimental

The major version number of the device in a semantic versioning scheme.

`USBDevice.deviceVersionMinor` Read only
Experimental

The minor version number of the device in a semantic versioning scheme.

`USBDevice.deviceVersionSubminor` Read only
Experimental

The patch version number of the device in a semantic versioning scheme.

`USBDevice.manufacturerName` Read only
Experimental

The name of the organization that manufactured the USB device.

`USBDevice.opened` Read only
Experimental

Indicates whether a session has been started with a paired USB device.

`USBDevice.productId` Read only
Experimental

The manufacturer-defined code that identifies a USB device.

`USBDevice.productName` Read only
Experimental

The manufacturer-defined name that identifies a USB device.

`USBDevice.serialNumber` Read only
Experimental

The manufacturer-defined serial number for the specific USB device.

`USBDevice.usbVersionMajor` Read only
Experimental

One of three properties that declare the USB protocol version supported by the device. The other two properties are `USBDevice.usbVersionMinor` and `USBDevice.usbVersionSubminor`.

`USBDevice.usbVersionMinor` Read only
Experimental

One of three properties that declare the USB protocol version supported by the device. The other two properties are `USBDevice.usbVersionMajor` and `USBDevice.usbVersionSubminor`.

`USBDevice.usbVersionSubminor` Read only
Experimental

One of three properties that declare the USB protocol version supported by the device. The other two properties are `USBDevice.usbVersionMajor` and `USBDevice.usbVersionMinor`.

`USBDevice.vendorId` Read only
Experimental

The official usb.org-assigned vendor ID.

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

`USBDevice.claimInterface()`
Experimental

Returns a `Promise` that resolves when the requested interface is claimed for exclusive access.

`USBDevice.clearHalt()`
Experimental

Returns a `Promise` that resolves when a halt condition is cleared.

`USBDevice.controlTransferIn()`
Experimental

Returns a `Promise` that resolves with a `USBInTransferResult` when a command or status operation has been transmitted to the USB device.

`USBDevice.controlTransferOut()`
Experimental

Returns a `Promise` that resolves with a `USBOutTransferResult` when a command or status operation has been transmitted from the USB device.

`USBDevice.close()`
Experimental

Returns a `Promise` that resolves when all open interfaces are released and the device session has ended.

`USBDevice.forget()`
Experimental

Returns a `Promise` that resolves after all open interfaces are released, the device session has ended, and the permission is reset.

`USBDevice.isochronousTransferIn()`
Experimental

Returns a `Promise` that resolves with a `USBIsochronousInTransferResult` when time sensitive information has been transmitted to the USB device.

`USBDevice.isochronousTransferOut()`
Experimental

Returns a `Promise` that resolves with a `USBIsochronousOutTransferResult` when time sensitive information has been transmitted from the USB device.

`USBDevice.open()`
Experimental

Returns a `Promise` that resolves when a device session has started.

`USBDevice.releaseInterface()`
Experimental

Returns a `Promise` that resolves when a claimed interface is released from exclusive access.

`USBDevice.reset()`
Experimental

Returns a `Promise` that resolves when the device is reset and all app operations canceled and their promises rejected.

`USBDevice.selectAlternateInterface()`
Experimental

Returns a `Promise` that resolves when the specified alternative endpoint is selected.

`USBDevice.selectConfiguration()`
Experimental

Returns a `Promise` that resolves when the specified configuration is selected.

`USBDevice.transferIn()`
Experimental

Returns a `Promise` that resolves with a `USBInTransferResult` when bulk or interrupt data is received from the USB device.

`USBDevice.transferOut()`
Experimental

Returns a `Promise` that resolves with a `USBOutTransferResult` when bulk or interrupt data is sent to the USB device.

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

| Specification |
| --- |
| WebUSB API # device-usage |

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

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


DragEvent - Web APIs

DragEvent
=========

The **`DragEvent`** interface is a `DOM event` that represents a drag and drop interaction. The user initiates a drag by placing a pointer device (such as a mouse) on the touch surface and then dragging the pointer to a new location (such as another DOM element). Applications are free to interpret a drag and drop interaction in an application-specific way.

This interface inherits properties from `MouseEvent` and `Event`.

Event

UIEvent

MouseEvent

DragEventInstance properties
-------------------

`DragEvent.dataTransfer` Read only

The data that is transferred during a drag and drop interaction.

Constructors
------------

Although this interface has a constructor, it is not possible to create a useful DataTransfer object from script, since `DataTransfer` objects have a processing and security model that is coordinated by the browser during drag-and-drops.

`DragEvent()`

Creates a synthetic and untrusted DragEvent.

Event types
-----------

`drag`

This event is fired when an element or text selection is being dragged.

`dragend`

This event is fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key).

`dragenter`

This event is fired when a dragged element or text selection enters a valid drop target.

`dragleave`

This event is fired when a dragged element or text selection leaves a valid drop target.

`dragover`

This event is fired continuously when an element or text selection is being dragged and the mouse pointer is over a valid drop target (every 50 ms WHEN mouse is not moving ELSE much faster between 5 ms (slow movement) and 1ms (fast movement) approximately. This firing pattern is different than `mouseover` ).

`dragstart`

This event is fired when the user starts dragging an element or text selection.

`drop`

This event is fired when an element or text selection is dropped on a valid drop target.

Example
-------

An Example of each property, constructor, event type and global event handlers is included in their respective reference page.

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

| Specification |
| --- |
| HTML Standard # the-dragevent-interface |

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

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

See also
--------

* Drag and drop
* Drag Operations
* Recommended Drag Types
* DataTransfer test - Paste or Drag


ClipboardItem - Web APIs

ClipboardItem
=============

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

The **`ClipboardItem`** interface of the Clipboard API represents a single item format, used when reading or writing clipboard data using `clipboard.read()` and `clipboard.write()` respectively.

The benefit of having the **`ClipboardItem`** interface to represent data, is that it enables developers to cope with the varying scope of file types and data.

**Note:** To work with text see the `Clipboard.readText()` and `Clipboard.writeText()` methods of the `Clipboard` interface.

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

`ClipboardItem()`

Creates a new **`ClipboardItem`** object, with the MIME type as the key and `Blob` as the value.

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

*This interface provides the following properties.*

`types` Read only

Returns an `Array` of MIME types available within the **`ClipboardItem`**.

`presentationStyle` Read only

Returns one of the following: `"unspecified"`, `"inline"` or `"attachment"`.

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

*This interface defines the following methods.*

`getType()`

Returns a `Promise` that resolves with a `Blob` of the requested MIME type, or an error if the MIME type is not found.

Examples
--------

### Writing to the clipboard

Here we're writing a new `ClipboardItem()` to the system clipboard by requesting a PNG image using the `Fetch API`, and in turn, the `responses' blob()` method, to create the new `ClipboardItem`.

```js
async function writeClipImg() {
  try {
    const imgURL = "/myimage.png";
    const data = await fetch(imgURL);
    const blob = await data.blob();

    await navigator.clipboard.write([
      new ClipboardItem({
        [blob.type]: blob,
      }),
    ]);
    console.log("Fetched image copied.");
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

### Reading from the clipboard

 Here we're returning all items on the clipboard via the `clipboard.read()` method.
 Then utilizing the `ClipboardItem.types` property to set the `getType()` argument and return the corresponding blob object.

```js
async function getClipboardContents() {
  try {
    const clipboardItems = await navigator.clipboard.read();

    for (const clipboardItem of clipboardItems) {
      for (const type of clipboardItem.types) {
        const blob = await clipboardItem.getType(type);
        // we can now use blob here
      }
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

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

| Specification |
| --- |
| Clipboard API and events # clipboarditem |

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

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

See also
--------

* Clipboard API
* Image support for Async Clipboard article


SyncEvent - Web APIs

SyncEvent
=========

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

The **`SyncEvent`** interface of the Background Synchronization API represents a sync action that is dispatched on the `ServiceWorkerGlobalScope` of a ServiceWorker.

This interface inherits from the `ExtendableEvent` interface.

Event

ExtendableEvent

SyncEventConstructor
-----------

`SyncEvent()`
Experimental

Creates a new `SyncEvent` object.

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

*Inherits properties from its parent, `ExtendableEvent` and `Event`*.

`SyncEvent.tag` Read only
Experimental

Returns the developer-defined identifier for this `SyncEvent`.

`SyncEvent.lastChance` Read only
Experimental

Returns `true` if the user agent will not make further synchronization attempts after the current attempt.

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

*Inherits methods from its parent, `ExtendableEvent` and `Event`*.

None.

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

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


SVGAnimatedLengthList - Web APIs

SVGAnimatedLengthList
=====================

SVG animated length list interface
----------------------------------

The `SVGAnimatedLengthList` interface is used for attributes of type `SVGLengthList` which can be animated.

### Interface overview

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

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

| Name | Type | Description |
| --- | --- | --- |
| `baseVal` | `SVGLengthList` | The base value of the given attribute before applying any animations. |
| `animVal` | `SVGLengthList` |
 A read only `SVGLengthList` representing the
 current animated value of the given attribute. If the given attribute is
 not currently being animated, then the
 `SVGLengthList` 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 `SVGAnimatedLengthList` interface do not provide any specific methods.

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

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


ChannelSplitterNode - Web APIs

ChannelSplitterNode
===================

The `ChannelSplitterNode` interface, often used in conjunction with its opposite, `ChannelMergerNode`, separates the different channels of an audio source into a set of mono outputs. This is useful for accessing each channel separately, e.g. for performing channel mixing where gain must be separately controlled on each channel.

![Default channel splitter node with a single input splitting to form 6 mono outputs.](/en-US/docs/Web/API/ChannelSplitterNode/webaudiosplitter.png)

If your `ChannelSplitterNode` always has one single input, the amount of outputs is defined by a parameter on its constructor and the call to `AudioContext.createChannelSplitter()`. In the case that no value is given, it will default to `6`. If there are fewer channels in the input than there are outputs, supernumerary outputs are silent.

EventTarget

AudioNode

ChannelSplitterNode

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | variable; default to `6`. |
| Channel count mode | `"explicit"` Older implementations, as per earlier versions
 of the spec use `"max"`.
  |
| Channel count |
 Fixed to the number of outputs. Older implementations, as per earlier
 versions of the spec use `2` (not used in the default count
 mode).
  |
| Channel interpretation | `"discrete"` |

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

`ChannelSplitterNode()`

Creates a new `ChannelSplitterNode` 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.createChannelSplitter()` for example code.

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

| Specification |
| --- |
| Web Audio API # ChannelSplitterNode |

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

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

See also
--------

* Using the Web Audio API


HTMLLabelElement - Web APIs

HTMLLabelElement
================

The **`HTMLLabelElement`** interface gives access to properties specific to `<label>` elements. It inherits methods and properties from the base `HTMLElement` interface.

EventTarget

Node

Element

HTMLElement

HTMLLabelElementInstance properties
-------------------

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

`HTMLLabelElement.control` Read only

A `HTMLElement` representing the control with which the label is associated.

`HTMLLabelElement.form` Read only

A `HTMLFormElement` object representing the form with which the labeled control is associated, or `null` if there is no associated control, or if that control isn't associated with a form. In other words, this is just a shortcut for `HTMLLabelElement.control.form`.

`HTMLLabelElement.htmlFor`

A string containing the ID of the labeled control. This reflects the `for` attribute.

**Note:** To programmatically set the `for` attribute, use `htmlFor`.

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

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

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

| Specification |
| --- |
| HTML Standard # htmllabelelement |

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: `<label>`
* `<form>`
* `HTMLFormElement`


ExtendableCookieChangeEvent - Web APIs

ExtendableCookieChangeEvent
===========================

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

The **`ExtendableCookieChangeEvent`** interface of the Cookie Store API is the event type passed to `cookiechange` event fired at the `ServiceWorkerGlobalScope` when any cookie changes occur which match the service worker's cookie change subscription list. A cookie change event consists of a cookie and a type. (either "changed" or "deleted")

Cookie changes that cause the `ExtendableCookieChangeEvent` to be dispatched are:

* A cookie is newly created and not immediately removed. In this case `type` is "changed".
* A cookie is newly created and immediately removed. In this case `type` is "deleted"
* A cookie is removed. In this case `type` is "deleted".

**Note:** A cookie that is replaced due to the insertion of another cookie with the same name, domain, and path, is ignored and does not trigger a change event.

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

Event

ExtendableEvent

ExtendableCookieChangeEventConstructor
-----------

`ExtendableCookieChangeEvent()`

Creates a new `ExtendableCookieChangeEvent`.

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

*This interface also inherits properties from `ExtendableEvent`.*

`ExtendableCookieChangeEvent.changed` Read only

Returns an array containing the changed cookies.

`ExtendableCookieChangeEvent.deleted` Read only

Returns an array containing the deleted cookies.

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

*This interface also inherits methods from `ExtendableEvent`.*

Examples
--------

In the below example, we use `CookieStoreManager.getSubscriptions()` to get a list of existing subscriptions. (In service workers, a subscription is required in order to listen for events.) We unsubscribe from existing subscriptions using `CookieStoreManager.unsubscribe()`, then subscribe to the cookie with a name of 'COOKIE\_NAME' using `CookieStoreManager.subscribe()`. If that cookie is changed, the event listener logs the event to the console. This will be an `ExtendableCookieChangeEvent` object, with the `changed` or `deleted` property containing the modified cookie.

```js
self.addEventListener("activate", (event) => {
  event.waitUntil(async () => {
    const subscriptions = await self.registration.cookies.getSubscriptions();

    await self.registration.cookies.unsubscribe(subscriptions);

    await self.registration.cookies.subscribe([
      {
        name: "COOKIE\_NAME",
      },
    ]);
  });
});

self.addEventListener("cookiechange", (event) => {
  console.log(event);
});
```

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

| Specification |
| --- |
| Cookie Store API # ExtendableCookieChangeEvent |

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

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


RsaHashedKeyGenParams - Web APIs

RsaHashedKeyGenParams
=====================

The **`RsaHashedKeyGenParams`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.generateKey()`, when generating any RSA-based key pair: that is, when the algorithm is identified as any of RSASSA-PKCS1-v1\_5, RSA-PSS, or RSA-OAEP.

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

`name`

A string. This should be set to `RSASSA-PKCS1-v1_5`, `RSA-PSS`, or `RSA-OAEP`, depending on the algorithm you want to use.

`modulusLength`

A `Number`. The length in bits of the RSA modulus. This should be at least 2048: see for example see SP 800-131A Rev. 2. Some organizations are now recommending that it should be 4096.

`publicExponent`

A `Uint8Array`. The public exponent. Unless you have a good reason to use something else, specify 65537 here (`[0x01, 0x00, 0x01]`).

`hash`

A string representing the name of the digest function to use. You can pass any of `SHA-256`, `SHA-384`, or `SHA-512` here.

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

Examples
--------

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

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

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

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

Browsers that support any RSA-based algorithm for the `SubtleCrypto.generateKey()` method will support this type.

See also
--------

* `SubtleCrypto.generateKey()`.