HTMLAnchorElement - Web APIs

HTMLAnchorElement
=================

The **`HTMLAnchorElement`** interface represents hyperlink elements and provides special properties and methods (beyond those of the regular `HTMLElement` object interface that they inherit from) for manipulating the layout and presentation of such elements. This interface corresponds to `<a>` element; not to be confused with `<link>`, which is represented by `HTMLLinkElement`.

EventTarget

Node

Element

HTMLElement

HTMLAnchorElementInstance properties
-------------------

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

`HTMLAnchorElement.download`

A string indicating that the linked resource is intended to be downloaded rather than displayed in the browser. The value represent the proposed name of the file. If the name is not a valid filename of the underlying OS, browser will adapt it.

`HTMLAnchorElement.hash`

A string representing the fragment identifier, including the leading hash mark ('`#`'), if any, in the referenced URL.

`HTMLAnchorElement.host`

A string representing the hostname and port (if it's not the default port) in the referenced URL.

`HTMLAnchorElement.hostname`

A string representing the hostname in the referenced URL.

`HTMLAnchorElement.href`

A string that is the result of parsing the `href` HTML attribute relative to the document, containing a valid URL of a linked resource.

`HTMLAnchorElement.hreflang`

A string that reflects the `hreflang` HTML attribute, indicating the language of the linked resource.

`HTMLAnchorElement.origin` Read only

Returns a string containing the origin of the URL, that is its scheme, its domain and its port.

`HTMLAnchorElement.password`

A string containing the password specified before the domain name.

`HTMLAnchorElement.pathname`

A string containing an initial `'/'` followed by the path of the URL, not including the query string or fragment.

`HTMLAnchorElement.port`

A string representing the port component, if any, of the referenced URL.

`HTMLAnchorElement.protocol`

A string representing the protocol component, including trailing colon ('`:`'), of the referenced URL.

`HTMLAnchorElement.referrerPolicy`

A string that reflects the `referrerpolicy` HTML attribute indicating which referrer to use.

`HTMLAnchorElement.rel`

A string that reflects the `rel` HTML attribute, specifying the relationship of the target object to the linked object.

`HTMLAnchorElement.relList` Read only

Returns a `DOMTokenList` that reflects the `rel` HTML attribute, as a list of tokens.

`HTMLAnchorElement.search`

A string representing the search element, including leading question mark ('`?`'), if any, of the referenced URL.

`HTMLAnchorElement.target`

A string that reflects the `target` HTML attribute, indicating where to display the linked resource.

`HTMLAnchorElement.text`

A string being a synonym for the `Node.textContent` property.

`HTMLAnchorElement.type`

A string that reflects the `type` HTML attribute, indicating the MIME type of the linked resource.

`HTMLAnchorElement.username`

A string containing the username specified before the domain name.

### Obsolete properties

`HTMLAnchorElement.charset`
Deprecated

A string representing the character encoding of the linked resource.

`HTMLAnchorElement.coords`
Deprecated

A string representing a comma-separated list of coordinates.

`HTMLAnchorElement.name`
Deprecated

A string representing the anchor name.

`HTMLAnchorElement.rev`
Deprecated

A string representing that the `rev` HTML attribute, specifying the relationship of the link object to the target object.

**Note:** Currently the W3C HTML 5.2 spec states that `rev` is no longer obsolete, whereas the WHATWG living standard still has it labeled obsolete. Until this discrepancy is resolved, you should still assume it is obsolete.

`HTMLAnchorElement.shape`
Deprecated

A string representing the shape of the active area.

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

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

`HTMLAnchorElement.toString()`

Returns a string containing the whole URL. It is a synonym for `HTMLAnchorElement.href`, though it can't be used to modify the value.

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

| Specification |
| --- |
| HTML Standard # htmlanchorelement |

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: `<a>`


HTMLFieldSetElement - Web APIs

HTMLFieldSetElement
===================

The **`HTMLFieldSetElement`** interface provides special properties and methods (beyond the regular `HTMLElement` interface it also has available to it by inheritance) for manipulating the layout and presentation of `<fieldset>` elements.

EventTarget

Node

Element

HTMLElement

HTMLFieldSetElementInstance properties
-------------------

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

`HTMLFieldSetElement.disabled`

A boolean value reflecting the `disabled` HTML attribute, indicating whether the user can interact with the control.

`HTMLFieldSetElement.elements` Read only

The elements belonging to this field set. The type of this property depends on the version of the spec that is implemented by the browser.

`HTMLFieldSetElement.form` Read only

 An `HTMLFormControlsCollection` or `HTMLCollection` referencing the containing form element, if this element is in a form.
 If the field set is not a descendant of a form element, then the attribute can be the ID of any form element in the same document it is related to, or the `null` value if none matches.

`HTMLFieldSetElement.name`

A string reflecting the `name` HTML attribute, containing the name of the field set. This can be used when accessing the field set in JavaScript. It is *not* part of the data which is sent to the server.

`HTMLFieldSetElement.type` Read only

The string "`fieldset`".

`HTMLFieldSetElement.validationMessage`

A string representing a localized message that describes the validation constraints that the element does not satisfy (if any). This is the empty string if the element is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints.

`HTMLFieldSetElement.validity`

A `ValidityState` representing the validity states that this element is in.

`HTMLFieldSetElement.willValidate`

A boolean value `false`, because `<fieldset>` objects are never candidates for constraint validation.

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

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

`HTMLFieldSetElement.checkValidity()`

Always returns `true` because `<fieldset>` objects are never candidates for constraint validation.

`HTMLFieldSetElement.reportValidity()`

Always returns `true` because `<fieldset>` objects are never candidates for constraint validation.

`HTMLFieldSetElement.setCustomValidity()`

Sets a custom validity message for the field set. If this message is not the empty string, then the field set is suffering from a custom validity error, and does not validate.

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

| Specification |
| --- |
| HTML Standard # htmlfieldsetelement |

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


NavigatorUAData - Web APIs

NavigatorUAData
===============

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

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

The **`NavigatorUAData`** interface of the `User-Agent Client Hints API` returns information about the browser and operating system of a user.

An instance of this object is returned by calling `Navigator.userAgentData`. Therefore, this interface has no constructor.

**Note:** The terms *high entropy* and *low entropy* refer to the amount of information these values reveal about the browser. The values returned as properties are deemed low entropy, and unlikely to identify a user. The values returned by `NavigatorUAData.getHighEntropyValues()` could potentially reveal more information. These values are therefore retrieved via a `Promise`, allowing time for the browser to request user permission, or make other checks.

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

`NavigatorUAData.brands` Read only
Experimental

Returns an array of brand information containing the browser name and version.

`NavigatorUAData.mobile` Read only
Experimental

Returns `true` if the user-agent is running on a mobile device.

`NavigatorUAData.platform` Read only
Experimental

Returns the platform brand the user-agent is running on.

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

`NavigatorUAData.getHighEntropyValues()`
Experimental

Returns a `Promise` that resolves with a dictionary object containing the *high entropy* values the user-agent returns.

`NavigatorUAData.toJSON()`
Experimental

A *serializer* that returns a JSON representation of the *low entropy* properties of the `NavigatorUAData` object.

Examples
--------

### Getting the brands

The following example prints the value of `NavigatorUAData.brands` to the console.

```js
console.log(navigator.userAgentData.brands);
```

### Returning high entropy values

In the following value a number of hints are requested using the `NavigatorUAData.getHighEntropyValues()` method. When the promise resolves, this information is printed to the console.

```js
navigator.userAgentData
  .getHighEntropyValues([
    "architecture",
    "model",
    "platform",
    "platformVersion",
    "fullVersionList",
  ])
  .then((ua) => {
    console.log(ua);
  });
```

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

| Specification |
| --- |
| User-Agent Client Hints # navigatoruadata |

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

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

See also
--------

* Improving user privacy and developer experience with User-Agent Client Hints


XRCylinderLayer - Web APIs

XRCylinderLayer
===============

**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 **`XRCylinderLayer`** interface of the WebXR Device API is a layer that takes up a curved rectangular space in the virtual environment. Only the front of the layer is visible.

`XRCylinderLayer` requires the `layers` feature to be enabled for the `XRSession`. You can request it in `XRSystem.requestSession()`.

To create a new `XRCylinderLayer`, call either:

* `XRWebGLBinding.createCylinderLayer()` for a WebGL opaque texture layer, or
* `XRMediaBinding.createCylinderLayer()` for an HTML `<video>` playback layer.

To present layers to the XR device, add them to the `layers` render state using `XRSession.updateRenderState()`.

EventTarget

XRLayer

XRCompositionLayer

XRCylinderLayerInstance properties
-------------------

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

`XRCylinderLayer.aspectRatio`
Experimental

A number indicating the ratio of the visible cylinder section. It is the ratio of the width of the visible section of the cylinder divided by its height. The width is calculated by multiplying the `radius` with the `centralAngle`.

`XRCylinderLayer.centralAngle`
Experimental

A number indicating the angle in radians of the visible section of the cylinder.

`XRCylinderLayer.radius`
Experimental

A number indicating the radius of the cylinder.

`XRCylinderLayer.space`
Experimental

An `XRSpace` representing the layer's spatial relationship with the user's physical environment.

`XRCylinderLayer.transform`
Experimental

An `XRRigidTransform` representing the offset and orientation relative to `space`.

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

*Inherits methods from its parents, `XRCompositionLayer` and `EventTarget`*.

Events
------

`redraw`
Experimental

Sent to the `XRCylinderLayer` object when the underlying resources of the layer are lost or when the XR Compositor can no longer reproject the layer. If this event is sent, authors should redraw the content of the layer in the next XR animation frame.

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

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

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

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

See also
--------

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


URLSearchParams - Web APIs

URLSearchParams
===============

The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL.

An object implementing `URLSearchParams` can directly be used in a `for...of` structure to iterate over key/value pairs in the same order as they appear in the query string, for example the following two lines are equivalent:

```js
for (const [key, value] of mySearchParams) {
}
for (const [key, value] of mySearchParams.entries()) {
}
```

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

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

`URLSearchParams()`

Returns a `URLSearchParams` object instance.

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

`size` Read only

Indicates the total number of search parameter entries.

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

`URLSearchParams.[@@iterator]()`

Returns an `iterator` allowing iteration through all key/value pairs contained in this object in the same order as they appear in the query string.

`URLSearchParams.append()`

Appends a specified key/value pair as a new search parameter.

`URLSearchParams.delete()`

Deletes search parameters that match a name, and optional value, from the list of all search parameters.

`URLSearchParams.entries()`

Returns an `iterator` allowing iteration through all key/value pairs contained in this object in the same order as they appear in the query string.

`URLSearchParams.forEach()`

Allows iteration through all values contained in this object via a callback function.

`URLSearchParams.get()`

Returns the first value associated with the given search parameter.

`URLSearchParams.getAll()`

Returns all the values associated with a given search parameter.

`URLSearchParams.has()`

Returns a boolean value indicating if a given parameter, or parameter and value pair, exists.

`URLSearchParams.keys()`

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

`URLSearchParams.set()`

Sets the value associated with a given search parameter to the given value. If there are several values, the others are deleted.

`URLSearchParams.sort()`

Sorts all key/value pairs, if any, by their keys.

`URLSearchParams.toString()`

Returns a string containing a query string suitable for use in a URL.

`URLSearchParams.values()`

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

Examples
--------

```js
const paramsString = "q=URLUtils.searchParams&topic=api";
const searchParams = new URLSearchParams(paramsString);

// Iterating the search parameters
for (const p of searchParams) {
  console.log(p);
}

console.log(searchParams.has("topic")); // true
console.log(searchParams.has("topic", "fish")); // false
console.log(searchParams.get("topic") === "api"); // true
console.log(searchParams.getAll("topic")); // ["api"]
console.log(searchParams.get("foo") === null); // true
console.log(searchParams.append("topic", "webdev"));
console.log(searchParams.toString()); // "q=URLUtils.searchParams&topic=api&topic=webdev"
console.log(searchParams.set("topic", "More webdev"));
console.log(searchParams.toString()); // "q=URLUtils.searchParams&topic=More+webdev"
console.log(searchParams.delete("topic"));
console.log(searchParams.toString()); // "q=URLUtils.searchParams"
```

```js
// Search parameters can also be an object
const paramsObj = { foo: "bar", baz: "bar" };
const searchParams = new URLSearchParams(paramsObj);

console.log(searchParams.toString()); // "foo=bar&baz=bar"
console.log(searchParams.has("foo")); // true
console.log(searchParams.get("foo")); // "bar"
```

### Duplicate search parameters

```js
const paramStr = "foo=bar&foo=baz";
const searchParams = new URLSearchParams(paramStr);

console.log(searchParams.toString()); // "foo=bar&foo=baz"
console.log(searchParams.has("foo")); // true
console.log(searchParams.get("foo")); // bar, only returns the first value
console.log(searchParams.getAll("foo")); // ["bar", "baz"]
```

### No URL parsing

The `URLSearchParams` constructor does *not* parse full URLs. However, it will strip an initial leading `?` off of a string, if present.

```js
const paramsString1 = "http://example.com/search?query=%40";
const searchParams1 = new URLSearchParams(paramsString1);

console.log(searchParams1.has("query")); // false
console.log(searchParams1.has("http://example.com/search?query")); // true

console.log(searchParams1.get("query")); // null
console.log(searchParams1.get("http://example.com/search?query")); // "@" (equivalent to decodeURIComponent('%40'))

const paramsString2 = "?query=value";
const searchParams2 = new URLSearchParams(paramsString2);
console.log(searchParams2.has("query")); // true

const url = new URL("http://example.com/search?query=%40");
const searchParams3 = new URLSearchParams(url.search);
console.log(searchParams3.has("query")); // true
```

### Preserving plus signs

The `URLSearchParams` constructor interprets plus signs (`+`) as spaces, which might cause problems. In the example below, we use hexadecimal escape sequences to mimic a string containing binary data (where every byte carries information) that needs to be stored in the URL search params. Note how the encoded string produced by `btoa()` contains `+` and isn't preserved by `URLSearchParams`.

```js
const rawData = "\x13à\x17@\x1F\x80";
const base64Data = btoa(rawData); // 'E+AXQB+A'

const searchParams = new URLSearchParams(`bin=${base64Data}`); // 'bin=E+AXQB+A'
const binQuery = searchParams.get("bin"); // 'E AXQB A', '+' is replaced by spaces

console.log(atob(binQuery) === rawData); // false
```

You can avoid this by encoding the data with the `encodeURIComponent()`.

```js
const rawData = "\x13à\x17@\x1F\x80";
const base64Data = btoa(rawData); // 'E+AXQB+A'
const encodedBase64Data = encodeURIComponent(base64Data); // 'E%2BAXQB%2BA'

const searchParams = new URLSearchParams(`bin=${encodedBase64Data}`); // 'bin=E%2BAXQB%2BA'
const binQuery = searchParams.get("bin"); // 'E+AXQB+A'

console.log(atob(binQuery) === rawData); // true
```

### Empty value vs. no value

`URLSearchParams` doesn't distinguish between a parameter with nothing after the `=`, and a parameter that doesn't have a `=` altogether.

```js
const emptyVal = new URLSearchParams("foo=&bar=baz");
console.log(emptyVal.get("foo")); // returns ''
const noEquals = new URLSearchParams("foo&bar=baz");
console.log(noEquals.get("foo")); // also returns ''
console.log(noEquals.toString()); // 'foo=&bar=baz'
```

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

| Specification |
| --- |
| URL Standard # urlsearchparams |

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

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

See also
--------

* Polyfill of `URLSearchParams` in `core-js`
* The `URL` interface.
* Google Developers: Easy URL manipulation with URLSearchParams


WebGLSampler - Web APIs

WebGLSampler
============

The **`WebGLSampler`** interface is part of the WebGL 2 API and stores sampling parameters for `WebGLTexture` access inside of a shader.

WebGLObject

WebGLSampler
When working with `WebGLSampler` objects, the following methods of the `WebGL2RenderingContext` are useful:

* `WebGL2RenderingContext.createSampler()`
* `WebGL2RenderingContext.deleteSampler()`
* `WebGL2RenderingContext.isSampler()`
* `WebGL2RenderingContext.bindSampler()`
* `WebGL2RenderingContext.getSamplerParameter()`
Examples
--------

### Creating a `WebGLSampler` object

in this example, `gl` must be a `WebGL2RenderingContext`. `WebGLSampler` objects are not available in WebGL 1.

```js
const sampler = gl.createSampler();
```

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

| Specification |
| --- |
| WebGL 2.0 Specification # 3.3 |

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

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


Insertable Streams for MediaStreamTrack API - Web APIs

Insertable Streams for MediaStreamTrack API
===========================================

The **Insertable Streams for MediaStreamTrack API** provides a method of adding new components to a `MediaStreamTrack`.

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

When processing video or audio, you sometimes want to insert additional elements or otherwise process the stream. For example, an application might include two tracks that need to be combined, such as a weather map and video of a presenter explaining the map. Or, you may want to do processing on a track to blur backgrounds, remove background noise, or introduce other elements (such as adding funny hats to people, and so on). This API provides a method to do this by giving direct access to the stream, thus allowing it to be manipulated.

Interfaces
----------

`MediaStreamTrackGenerator`

Creates a `WritableStream` that acts as a `MediaStreamTrack` source.

`MediaStreamTrackProcessor`

Consumes a `MediaStreamTrack` object's source and generates a stream of media frames.

Examples
--------

The following example is from the article Insertable streams for MediaStreamTrack, and demonstrates a barcode scanner application that highlights a barcode in a video stream. This transforms the stream accessed via `MediaStreamTrackProcessor.readable`.

```js
const stream = await getUserMedia({ video: true });
const videoTrack = stream.getVideoTracks()[0];

const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });

const transformer = new TransformStream({
  async transform(videoFrame, controller) {
    const barcodes = await detectBarcodes(videoFrame);
    const newFrame = highlightBarcodes(videoFrame, barcodes);
    videoFrame.close();
    controller.enqueue(newFrame);
  },
});

trackProcessor.readable
  .pipeThrough(transformer)
  .pipeTo(trackGenerator.writable);
```


WebTransportDatagramDuplexStream - Web APIs

WebTransportDatagramDuplexStream
================================

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

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

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

The **`WebTransportDatagramDuplexStream`** interface of the WebTransport API represents a duplex stream that can be used for unreliable transport of datagrams between client and server. Provides access to a `ReadableStream` for reading incoming datagrams, a `WritableStream` for writing outgoing datagrams, and various settings and statistics related to the stream.

This is accessed via the `WebTransport.datagrams` property.

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

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

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

`incomingHighWaterMark`

Gets or sets the high water mark for incoming chunks of data — this is the maximum size, in chunks, that the incoming `ReadableStream`'s internal queue can reach before it is considered full. See Internal queues and queuing strategies for more information.

`incomingMaxAge`

Gets or sets the maximum age for incoming datagrams, in milliseconds. Returns `null` if no maximum age has been set.

`maxDatagramSize` Read only

Returns the maximum allowable size of outgoing datagrams, in bytes, that can be written to `writable`.

`outgoingHighWaterMark`

Gets or sets the high water mark for outgoing chunks of data — this is the maximum size, in chunks, that the outgoing `WritableStream`'s internal queue can reach before it is considered full. See Internal queues and queuing strategies for more information.

`outgoingMaxAge`

Gets or sets the maximum age for outgoing datagrams, in milliseconds. Returns `null` if no maximum age has been set.

`readable` Read only

Returns a `ReadableStream` instance that can be used to read incoming datagrams from the stream.

`writable` Read only

Returns a `WritableStream` instance that can be used to write outgoing datagrams to the stream.

Examples
--------

### Writing outgoing datagrams

The `writable` property returns a `WritableStream` object that you can write data to using a writer, for transmission to the server:

```js
const writer = transport.datagrams.writable.getWriter();
const data1 = new Uint8Array([65, 66, 67]);
const data2 = new Uint8Array([68, 69, 70]);
writer.write(data1);
writer.write(data2);
```

### Reading incoming datagrams

The `readable` property returns a `ReadableStream` object that you can use to receive data from the server:

```js
async function readData() {
  const reader = transport.datagrams.readable.getReader();
  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break;
    }
    // value is a Uint8Array.
    console.log(value);
  }
}
```

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

| Specification |
| --- |
| WebTransport # duplex-stream |

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

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

See also
--------

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


HTMLHRElement - Web APIs

HTMLHRElement
=============

The **`HTMLHRElement`** interface provides special properties (beyond those of the `HTMLElement` interface it also has available to it by inheritance) for manipulating `<hr>` elements.

EventTarget

Node

Element

HTMLElement

HTMLHRElementInstance properties
-------------------

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

`HTMLHRElement.align`
Deprecated

A string, an enumerated attribute indicating alignment of the rule with respect to the surrounding context.

`HTMLHRElement.color`
Deprecated

A string representing the name of the color of the rule.

`HTMLHRElement.noshade`
Deprecated

A boolean value that sets the rule to have no shading.

`HTMLHRElement.size`
Deprecated

A string representing the height of the rule.

`HTMLHRElement.width`
Deprecated

A string representing the width of the rule on the page.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlhrelement |

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: `<hr>`


DOMPointReadOnly - Web APIs

DOMPointReadOnly
================

The **`DOMPointReadOnly`** interface specifies the coordinate and perspective fields used by `DOMPoint` to define a 2D or 3D point in a coordinate system.

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

There are two ways to create a new `DOMPointReadOnly` instance. First, you can use its constructor, passing in the values of the parameters for each dimension and, optionally, the perspective:

```js
/\* 2D \*/
const point2D = new DOMPointReadOnly(50, 50);

/\* 3D \*/
const point3D = new DOMPointReadOnly(50, 50, 25);

/\* 3D with perspective \*/
const point3DPerspective = new DOMPointReadOnly(100, 100, 100, 1.0);
```

The other option is to use the static `DOMPointReadOnly.fromPoint()` method:

```js
const point = DOMPointReadOnly.fromPoint({ x: 100, y: 100, z: 50, w: 1.0 });
```

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

`DOMPointReadOnly()`

Creates a new `DOMPointReadOnly` object given the values of its coordinates and perspective. To create a point using an object, you can instead use `DOMPointReadOnly.fromPoint()`.

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

`DOMPointReadOnly.x` Read only

The point's horizontal coordinate, `x`.

`DOMPointReadOnly.y` Read only

The point's vertical coordinate, `y`.

`DOMPointReadOnly.z` Read only

The point's depth coordinate, `z`.

`DOMPointReadOnly.w` Read only

The point's perspective value, `w`.

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

`DOMPointReadOnly.fromPoint()`

A static method that creates a new `DOMPointReadOnly` object given the coordinates provided in the specified object.

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

`matrixTransform()`

Applies a matrix transform specified as an object to the `DOMPointReadOnly` object.

`toJSON()`

Returns a JSON representation of the `DOMPointReadOnly` object.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # DOMPoint |

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

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

See also
--------

* `DOMPoint`
* `DOMRect`
* `DOMMatrix`


Window - Web APIs

Window
======

The **`Window`** interface represents a window containing a DOM document; the `document` property points to the DOM document loaded in that window.

A window for a given document can be obtained using the `document.defaultView` property.

A global variable, `window`, representing the window in which the script is running, is exposed to JavaScript code.

The `Window` interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the `Window` interface is a suitable place to include these items that need to be globally available. Many of these are documented in the JavaScript Reference and the DOM Reference.

In a tabbed browser, each tab is represented by its own `Window` object; the global `window` seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as `resizeTo()` and `innerHeight`. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.

EventTarget

WindowInstance properties
-------------------

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

Note that properties which are objects (e.g., for overriding the prototype of built-in elements) are listed in a separate section below.

`Window.caches` Read only

Returns the `CacheStorage` object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.

`Window.clientInformation` Read only

An alias for `Window.navigator`.

`Window.closed` Read only

This property indicates whether the current window is closed or not.

`Window.console` Read only

Returns a reference to the console object which provides access to the browser's debugging console.

`Window.cookieStore` Read only
Experimental

Returns a reference to the `CookieStore` object for the current document context.

`Window.credentialless` Read only
Experimental

Returns a boolean that indicates whether the current document was loaded inside a credentialless `<iframe>`. See IFrame credentialless for more details.

`Window.crossOriginIsolated` Read only

Returns a boolean value that indicates whether the website is in a cross-origin isolation state.

`Window.crypto` Read only

Returns the browser crypto object.

`Window.customElements` Read only

Returns a reference to the `CustomElementRegistry` object, which can be used to register new custom elements and get information about previously registered custom elements.

`Window.devicePixelRatio` Read only

Returns the ratio between physical pixels and device independent pixels in the current display.

`Window.document` Read only

Returns a reference to the document that the window contains.

`Window.documentPictureInPicture` Read only
Experimental

Returns a reference to the document Picture-in-Picture window for the current document context.

`Window.frameElement` Read only

Returns the element in which the window is embedded, or null if the window is not embedded.

`Window.frames` Read only

Returns an array of the subframes in the current window.

`Window.fullScreen`
Non-standard

This property indicates whether the window is displayed in full screen or not.

`Window.history` Read only

Returns a reference to the history object.

`Window.indexedDB` Read only

Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an `IDBFactory` object.

`Window.innerHeight` Read only

Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.

`Window.innerWidth` Read only

Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.

`Window.isSecureContext` Read only

Returns a boolean indicating whether the current context is secure (`true`) or not (`false`).

`Window.launchQueue` Read only
Experimental

When a progressive web app (PWA) is launched with a `launch_handler` `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`, the `launchQueue` provides access to the `LaunchQueue` class, which allows custom launch navigation handling to be implemented for the PWA.

`Window.length` Read only

Returns the number of frames in the window. See also `window.frames`.

`Window.localStorage` Read only

Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.

`Window.location`

Gets/sets the location, or current URL, of the window object.

`Window.locationbar` Read only

Returns the locationbar object.

`Window.menubar` Read only

Returns the menubar object.

`Window.mozInnerScreenX` Read only
Non-standard

Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See `mozScreenPixelsPerCSSPixel` in `nsIDOMWindowUtils` for a conversion factor to adapt to screen pixels if needed.

`Window.mozInnerScreenY` Read only
Non-standard

Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See `mozScreenPixelsPerCSSPixel` for a conversion factor to adapt to screen pixels if needed.

`Window.name`

Gets/sets the name of the window.

`Window.navigation` Read only
Experimental

Returns the current `window`'s associated `Navigation` object. The entry point for the `Navigation API`.

`Window.navigator` Read only

Returns a reference to the navigator object.

`Window.opener`

Returns a reference to the window that opened this current window.

`Window.origin` Read only

Returns the global object's origin, serialized as a string.

`Window.originAgentCluster` Read only
Experimental

Returns `true` if this window belongs to an origin-keyed agent cluster.

`Window.outerHeight` Read only

Gets the height of the outside of the browser window.

`Window.outerWidth` Read only

Gets the width of the outside of the browser window.

`Window.pageXOffset` Read only

An alias for `window.scrollX`.

`Window.pageYOffset` Read only

An alias for `window.scrollY`.

`Window.parent` Read only

Returns a reference to the parent of the current window or subframe.

`Window.performance` Read only

Returns a `Performance` object, which includes the `timing` and `navigation` attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.

`Window.personalbar` Read only

Returns the personalbar object.

`Window.scheduler` Read only

Returns the `Scheduler` object associated with the current context. This is the entry point for using the Prioritized Task Scheduling API.

`Window.screen` Read only

Returns a reference to the screen object associated with the window.

`Window.screenX` and `Window.screenLeft` Read only

Both properties return the horizontal distance from the left border of the user's browser viewport to the left side of the screen.

`Window.screenY` and `Window.screenTop` Read only

Both properties return the vertical distance from the top border of the user's browser viewport to the top side of the screen.

`Window.scrollbars` Read only

Returns the scrollbars object.

`Window.scrollMaxX`
Non-standard
 Read only

The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.

`Window.scrollMaxY`
Non-standard
 Read only

The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).

`Window.scrollX` Read only

Returns the number of pixels that the document has already been scrolled horizontally.

`Window.scrollY` Read only

Returns the number of pixels that the document has already been scrolled vertically.

`Window.self` Read only

Returns an object reference to the window object itself.

`Window.sessionStorage`

Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.

`Window.sharedStorage` Read only
Experimental

Returns the `WindowSharedStorage` object for the current origin. This is the main entry point for writing data to shared storage using the Shared Storage API.

`Window.speechSynthesis` Read only

Returns a `SpeechSynthesis` object, which is the entry point into using Web Speech API speech synthesis functionality.

`Window.statusbar` Read only

Returns the statusbar object.

`Window.toolbar` Read only

Returns the toolbar object.

`Window.top` Read only

Returns a reference to the topmost window in the window hierarchy. This property is read only.

`Window.visualViewport` Read only

Returns a `VisualViewport` object which represents the visual viewport for a given window.

`Window.window` Read only

Returns a reference to the current window.

`window[0]`, `window[1]`, etc.

Returns a reference to the `window` object in the frames. See `Window.frames` for more details.

### Deprecated properties

`Window.event`
Deprecated
 Read only

Returns the **current event**, which is the event currently being handled by the JavaScript code's context, or `undefined` if no event is currently being handled. The `Event` object passed directly to event handlers should be used instead whenever possible.

`Window.external`
Deprecated
 Read only

Returns an object with functions for adding external search providers to the browser.

`Window.orientation`
Deprecated
 Read only

Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.

`Window.sidebar`
Deprecated

Non-standard
 Read only

Returns a reference to the window object of the sidebar

`Window.status`
Deprecated

Gets/sets the text in the statusbar at the bottom of the browser.

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

*This interface inherits methods from the `EventTarget` interface.*

`Window.atob()`

Decodes a string of data which has been encoded using base-64 encoding.

`Window.alert()`

Displays an alert dialog.

`Window.blur()`

Sets focus away from the window.

`Window.btoa()`

Creates a base-64 encoded ASCII string from a string of binary data.

`Window.cancelAnimationFrame()`

Enables you to cancel a callback previously scheduled with `Window.requestAnimationFrame`.

`Window.cancelIdleCallback()`

Enables you to cancel a callback previously scheduled with `Window.requestIdleCallback`.

`Window.clearInterval()`

Cancels the repeated execution set using `setInterval()`.

`Window.clearTimeout()`

Cancels the delayed execution set using `setTimeout()`.

`Window.close()`

Closes the current window.

`Window.confirm()`

Displays a dialog with a message that the user needs to respond to.

`Window.createImageBitmap()`

Accepts a variety of different image sources, and returns a `Promise` which resolves to an `ImageBitmap`. Optionally the source is cropped to the rectangle of pixels originating at *(sx, sy)* with width sw, and height sh.

`Window.dump()`
Non-standard

Writes a message to the console.

`Window.fetch()`

Starts the process of fetching a resource from the network.

`Window.find()`
Non-standard

Searches for a given string in a window.

`Window.focus()`

Sets focus on the current window.

`Window.getComputedStyle()`

Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.

`Window.getDefaultComputedStyle()`
Non-standard

Gets default computed style for the specified element, ignoring author stylesheets.

`Window.getScreenDetails()`
Experimental
 Secure context

Returns a `Promise` that fulfills with a `ScreenDetails` object instance representing the details of all the screens available to the user's device.

`Window.getSelection()`

Returns the selection object representing the selected item(s).

`Window.matchMedia()`

Returns a `MediaQueryList` object representing the specified media query string.

`Window.moveBy()`

Moves the current window by a specified amount.

`Window.moveTo()`

Moves the window to the specified coordinates.

`Window.open()`

Opens a new window.

`Window.postMessage()`

Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.

`Window.print()`

Opens the Print Dialog to print the current document.

`Window.prompt()`

Returns the text entered by the user in a prompt dialog.

`Window.queryLocalFonts()`
Experimental

Returns a `Promise` that fulfills with an array of `FontData` objects representing the font faces available locally.

`Window.queueMicrotask()`

Queues a microtask to be executed at a safe time prior to control returning to the browser's event loop.

`Window.reportError()`

Reports an error in a script, emulating an unhandled exception.

`Window.requestAnimationFrame()`

Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.

`Window.requestIdleCallback()`

Enables the scheduling of tasks during a browser's idle periods.

`Window.resizeBy()`

Resizes the current window by a certain amount.

`Window.resizeTo()`

Dynamically resizes window.

`Window.scroll()`

Scrolls the window to a particular place in the document.

`Window.scrollBy()`

Scrolls the document in the window by the given amount.

`Window.scrollByLines()`
Non-standard

Scrolls the document by the given number of lines.

`Window.scrollByPages()`
Non-standard

Scrolls the current document by the specified number of pages.

`Window.scrollTo()`

Scrolls to a particular set of coordinates in the document.

`Window.setInterval()`

Schedules a function to execute every time a given number of milliseconds elapses.

`Window.setTimeout()`

Schedules a function to execute in a given amount of time.

`Window.showDirectoryPicker()`
Experimental

Displays a directory picker which allows the user to select a directory.

`Window.showOpenFilePicker()`
Experimental

Shows a file picker that allows a user to select a file or multiple files.

`Window.showSaveFilePicker()`
Experimental

Shows a file picker that allows a user to save a file.

`Window.sizeToContent()`
Non-standard

Sizes the window according to its content.

`Window.stop()`

This method stops window loading.

`Window.structuredClone()`

Creates a deep clone of a given value using the structured clone algorithm.

`Window.updateCommands()`
Non-standard

Updates the state of commands of the current chrome window (UI).

### Deprecated methods

`Window.back()`
Non-standard

Deprecated

Moves back one in the window history. This method is deprecated; you should instead use `history.back()`.

`Window.captureEvents()`
Deprecated

Registers the window to capture all events of the specified type.

`Window.clearImmediate()`
Non-standard

Deprecated

Cancels the repeated execution set using `setImmediate()`.

`Window.forward()`
Non-standard

Deprecated

Moves the window one document forward in the history. This method is deprecated; you should instead use `history.forward()`.

`Window.releaseEvents()`
Deprecated

Releases the window from trapping events of a specific type.

`Window.requestFileSystem()`
Non-standard

Deprecated

Lets a website or app gain access to a sandboxed file system for its own use.

`Window.setImmediate()`
Non-standard

Deprecated

Executes a function after the browser has finished other heavy tasks.

`Window.setResizable()`
Non-standard

Does nothing (no-op). Kept for backward compatibility with Netscape 4.x.

`Window.showModalDialog()`
Non-standard

Deprecated

Displays a modal dialog.

`Window.webkitConvertPointFromNodeToPage()`
Non-standard

Deprecated

Transforms a `WebKitPoint` from the node's coordinate system to the page's coordinate system.

`Window.webkitConvertPointFromPageToNode()`
Non-standard

Deprecated

Transforms a `WebKitPoint` from the page's coordinate system to the node's coordinate system.

Events
------

Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface. In addition to the events listed below, many events can bubble from the `Document` contained in the window object.

`error`

Fired when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.

`languagechange`

Fired at the global scope object when the user's preferred language changes.

`resize`

Fired when the window has been resized.

`storage`

Fired when a storage area (`localStorage` or `sessionStorage`) has been modified in the context of another document.

### Clipboard events

`copy`

 Fired when the user initiates a copy action through the browser's user interface.
 Also available via the `oncopy` property.

`cut`

 Fired when the user initiates a cut action through the browser's user interface.
 Also available via the `oncut` property.

`paste`

 Fired when the user initiates a paste action through the browser's user interface.
 Also available via the `onpaste` property.

### Connection events

`offline`

Fired when the browser has lost access to the network and the value of `navigator.onLine` has switched to `false`.

`online`

Fired when the browser has gained access to the network and the value of `navigator.onLine` has switched to `true`.

### Device orientation events

`devicemotion`

Fired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available.

`deviceorientation`

Fired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame.

`deviceorientationabsolute`

Fired when fresh data is available from the magnetometer orientation sensor about the current absolute orientation of the device as compared to the Earth coordinate frame.

### Focus events

`blur`

Fired when an element has lost focus.

`focus`

Fired when an element has gained focus.

### Gamepad events

`gamepadconnected`

Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.

`gamepaddisconnected`

Fired when the browser detects that a gamepad has been disconnected.

### History events

`hashchange`

Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol).

`pagehide`

Sent when the browser hides the current document while in the process of switching to displaying in its place a different document from the session's history. This happens, for example, when the user clicks the Back button or when they click the Forward button to move ahead in session history.

`pageshow`

Sent when the browser makes the document visible due to navigation tasks, including not only when the page is first loaded, but also situations such as the user navigating back to the page after having navigated to another within the same tab.

`popstate`

Fired when the active history entry changes.

### Load & unload events

`beforeunload`

Fired when the window, the document and its resources are about to be unloaded.

`load`

Fired when the whole page has loaded, including all dependent resources such as stylesheets images.

`unload`
Deprecated

Fired when the document or a child resource is being unloaded.

### Manifest events

`appinstalled`

Fired when the browser has successfully installed a page as an application.

`beforeinstallprompt`

Fired when a user is about to be prompted to install a web application.

### Messaging events

`message`

Fired when the window receives a message, for example from a call to `Window.postMessage()` from another browsing context.

`messageerror`

Fired when a `Window` object receives a message that can't be deserialized.

### Print events

`afterprint`

Fired after the associated document has started printing or the print preview has been closed.

`beforeprint`

Fired when the associated document is about to be printed or previewed for printing.

### Promise rejection events

`rejectionhandled`

Sent every time a JavaScript `Promise` is rejected, regardless of whether or not there is a handler in place to catch the rejection.

`unhandledrejection`

Sent when a JavaScript `Promise` is rejected but there is no handler in place to catch the rejection.

### Deprecated events

`orientationchange`
Deprecated

Fired when the orientation of the device has changed.

`vrdisplayactivate`
Deprecated

Non-standard

Fired when a display is able to be presented to.

`vrdisplayconnect`
Deprecated

Non-standard

Fired when a compatible VR device has been connected to the computer.

`vrdisplaydisconnect`
Deprecated

Non-standard

Fired when a compatible VR device has been disconnected from the computer.

`vrdisplaydeactivate`
Deprecated

Non-standard

Fired when a display can no longer be presented to.

`vrdisplaypresentchange`
Deprecated

Non-standard

Fired when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa.

Interfaces
----------

See DOM Reference.

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

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

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

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


MimeTypeArray - Web APIs

MimeTypeArray
=============

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

The **`MimeTypeArray`** interface returns an array of `MimeType` instances, each of which contains information about a supported browser plugins. This object is returned by `Navigator.mimeTypes`.

**Note:** This interface was an attempt to create an unmodifiable list and only continues to be supported to not break code that's already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).

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

`MimeTypeArray.length`
Deprecated

The number of items in the array.

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

`MimeTypeArray.item()`
Deprecated

Returns the `MimeType` object with the specified index.

`MimeTypeArray.namedItem()`
Deprecated

Returns the `MimeType` object with the specified name.

Example
-------

The following example tests whether a plugin is available for the 'application/pdf' mime type and if so, logs its description.

```js
const mimeTypes = navigator.mimeTypes;
const pdf = mimeTypes.namedItem("application/pdf");

if (pdf) {
  console.log(pdf.description);
}
```

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

| Specification |
| --- |
| HTML Standard # mimetypearray |

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

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


ServiceWorkerContainer - Web APIs

ServiceWorkerContainer
======================

The **`ServiceWorkerContainer`** interface of the Service Worker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.

Most importantly, it exposes the `ServiceWorkerContainer.register()` method used to register service workers, and the `ServiceWorkerContainer.controller` property used to determine whether or not the current page is actively controlled.

EventTarget

ServiceWorkerContainerInstance properties
-------------------

`ServiceWorkerContainer.controller` Read only

Returns a `ServiceWorker` object if its state is `activating` or `activated` (the same object returned by `ServiceWorkerRegistration.active`). This property returns `null` during a force-refresh request (*Shift* + refresh) or if there is no active worker.

`ServiceWorkerContainer.ready` Read only

Provides a way of delaying code execution until a service worker is active. It returns a `Promise` that will never reject, and which waits indefinitely until the `ServiceWorkerRegistration` associated with the current page has an `ServiceWorkerRegistration.active` worker. Once that condition is met, it resolves with the `ServiceWorkerRegistration`.

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

`ServiceWorkerContainer.getRegistration()`

Gets a `ServiceWorkerRegistration` object whose scope matches the provided document URL. The method returns a `Promise` that resolves to a `ServiceWorkerRegistration` or `undefined`.

`ServiceWorkerContainer.getRegistrations()`

Returns all `ServiceWorkerRegistration` objects associated with a `ServiceWorkerContainer` in an array. The method returns a `Promise` that resolves to an array of `ServiceWorkerRegistration`.

`ServiceWorkerContainer.register()`

Creates or updates a `ServiceWorkerRegistration` for the given `scriptURL`.

`ServiceWorkerContainer.startMessages()`

explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via `Client.postMessage()`). This can be used to react to sent messages earlier, even before that page's content has finished loading.

Events
------

`controllerchange`

Occurs when the document's associated `ServiceWorkerRegistration` acquires a new `active` worker.

`error`
Deprecated

Non-standard

Fired whenever an error occurs in the associated service workers.

`message`

Occurs when incoming messages are received by the `ServiceWorkerContainer` object (e.g. via a `MessagePort.postMessage()` call).

`messageerror`

Occurs when incoming messages can not deserialized by the `ServiceWorkerContainer` object (e.g. via a `MessagePort.postMessage()` call).

Examples
--------

The example below first checks to see if the browser supports service workers. If supported, the code registers the service worker and determines if the page is actively controlled by the service worker. If it isn't, it prompts the user to reload the page so the service worker can take control. The code also reports any registration failures.

```js
if ("serviceWorker" in navigator) {
  // Register a service worker hosted at the root of the
  // site using the default scope.
  navigator.serviceWorker
    .register("/sw.js")
    .then((registration) => {
      console.log("Service worker registration succeeded:", registration);

      // At this point, you can optionally do something
      // with registration. See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
    })
    .catch((error) => {
      console.error(`Service worker registration failed: ${error}`);
    });

  // Independent of the registration, let's also display
  // information about whether the current page is controlled
  // by an existing service worker, and when that
  // controller changes.

  // First, do a one-off check if there's currently a
  // service worker in control.
  if (navigator.serviceWorker.controller) {
    console.log(
      "This page is currently controlled by:",
      navigator.serviceWorker.controller,
    );
  }

  // Then, register a handler to detect when a new or
  // updated service worker takes control.
  navigator.serviceWorker.oncontrollerchange = () => {
    console.log(
      "This page is now controlled by",
      navigator.serviceWorker.controller,
    );
  };
} else {
  console.log("Service workers are not supported.");
}
```

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

| Specification |
| --- |
| Service Workers # serviceworkercontainer-interface |

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

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

See also
--------

* Using Service Workers
* Service workers basic code example
* Using web workers


WebOTP API - Web APIs

WebOTP API
==========

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

The **WebOTP API** provides a streamlined user experience for web apps to verify that a phone number belongs to a user when using it as a sign-in factor. WebOTP is an extension of the Credential Management API.

The verification is done via a two-step process:

1. The app client requests a one-time password (OTP), which is obtained from a specially-formatted SMS message sent by the app server.
2. JavaScript is used to enter the OTP into a validation form on the app client and it is submitted back to the server to verify that it matches what was originally sent in the SMS.
WebOTP concepts and usage
-------------------------

Phone numbers are often used as a way to identify the user of an app. An SMS is frequently deployed to verify that the number belongs to the user. The SMS typically contains an OTP that the user is required to copy and paste into a form in the app to verify that they own the number. This is a somewhat clunky user experience.

OTP use cases include:

* Improving sign-in security by using a phone number as an extra factor (i.e. for two-factor authentication (2FA) or multifactor authentication (MFA)).
* Verifying sensitive actions such as payments.

The WebOTP API allows web apps to expedite this validation process by copying the OTP from the SMS and passing it to the app automatically after the user has provided consent (most native platforms have an equivalent API).

Note that an OTP is bound to the sending domain. This is a useful security constraint for verifying that the OTP is coming from the right source, which can mitigate the risk of phishing attacks during day-to-day reauthentication.

### Security concerns with SMS OTPs

SMS OTPs are useful for verifying phone numbers, and using SMS for a second factor is certainly better than having no second factor. In some regions, other identifiers such as email addresses and authenticators are not widely-used, so SMS OTPs are very common.

However, SMSes aren't that secure. Attackers can spoof an SMS and hijack a person's phone number. Carriers can recycle phone numbers to new users after an account is closed.

You are, therefore, recommended to use a stronger form of authentication if possible, such as a Web Authentication API-based solution involving a password and security key or a passkey.

How does the WebOTP API work?
-----------------------------

The process works like so:

1. At the point where phone number verification is required, an app client will ask a user to enter their phone number into a form, which is then submitted to the app server.
2. The app client then invokes `navigator.credentials.get()` with an `otp` option specifying a `transport` type of `"sms"`. This triggers a request for an OTP from the underlying system, the source of which will be a specially-formatted SMS message (containing the OTP and the app's domain) received from the app server. The `get()` call is `Promise`-based and waits for the SMS message to be received.
3. The app server sends the SMS message to the specified phone number. This must be done just after Step 2 has occurred.
4. When the SMS is received on the device, provided it contains the app's domain, the browser will ask the user if they consent to the OTP being retrieved/used. Chrome, for example, displays a dialog asking them for their permission to retrieve the OTP from the SMS; other browsers may handle it differently. If they do consent, the `get()` call will fulfill with an `OTPCredential` object containing the OTP.
5. You can then use the OTP in any way you wish. Typical usage would be to set it as the value of the validation form on the app client and then submit the form, making the process as seamless as possible.
6. The app server will then verify that the OTP sent back to it matches what it originally sent in the SMS and, if so, complete the process (for example, sign the user in).
### SMS message format

A typical SMS message looks like so:
```

Your verification code is 123456.

@www.example.com #123456
```

* The first line and second blank line are optional and are for human readability.
* The last line is mandatory. It must be the last line if there are others present, and must consist of:
    + The domain part of the URL of the website that invoked the API, preceded by a `@`.
    + Followed by a space.
    + Followed by the OTP, preceded by a pound sign (`#`).

**Note:** The provided domain value must not include a URL schema, port, or other URL features not shown above.

If the `get()` method is invoked by a third-party site embedded in an `<iframe>`, the SMS structure should be:
```

Your verification code is 123456.

@top-level.example.com #123456 @embedded.com
```

In this case, the last line must consist of:

* The domain part of the top-level domain, preceded by a `@`.
* Followed by a space.
* Followed by the OTP, preceded by a pound sign (`#`).
* Followed by a space.
* Followed by the domain part of the embedded domain, preceded by a `@`.
Controlling access to the API
-----------------------------

The availability of WebOTP can be controlled using a Permissions Policy specifying a `otp-credentials` directive. This directive has a default allowlist value of `"self"`, meaning that by default, these methods can be used in top-level document contexts.

You could specify a directive allowing the use of WebOTP in a specific cross-origin domain (i.e., inside an `<iframe>`) like this:

```http
Permissions-Policy: otp-credentials=(self "https://embedded.com")
```

Or you could specify it directly on the `<iframe>` like this:

```html
<iframe src="https://embedded.com/..." allow="otp-credentials"> ... </iframe>
```

**Note:** Where a policy forbids use of WebOTP `get()`, `promises` returned by it will reject with a `SecurityError` `DOMException`.

Interfaces
----------

`OTPCredential`

Returned when a WebOTP `get()` call fulfills; includes a `code` property that contains the retrieved OTP.

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

`CredentialsContainer.get()`, the `otp` option

Calling `get()` with an `otp` option instructs the user agent to attempt to retrieve an OTP from the underlying system's SMS app.

Examples
--------

In this example, when an SMS message arrives and the user grants permission, an `OTPCredential` object is returned with an OTP. This password is then prefilled into the verification form field, and the form is submitted.

Try this demo using a phone.

The form field includes an `autocomplete` attribute with the value of `one-time-code`. This is not needed for the WebOTP API to work, but it is worth including. As a result, Safari will prompt the user to autofill this field with the OTP when a correctly-formatted SMS is received, even though the WebOTP API isn't fully supported in Safari.

```html
<input type="text" autocomplete="one-time-code" inputmode="numeric" />
```

The JavaScript is as follows:

```js
// Detect feature support via OTPCredential availability
if ("OTPCredential" in window) {
  window.addEventListener("DOMContentLoaded", (e) => {
    const input = document.querySelector('input[autocomplete="one-time-code"]');
    if (!input) return;
    // Set up an AbortController to use with the OTP request
    const ac = new AbortController();
    const form = input.closest("form");
    if (form) {
      // Abort the OTP request if the user attempts to submit the form manually
      form.addEventListener("submit", (e) => {
        ac.abort();
      });
    }
    // Request the OTP via get()
    navigator.credentials
      .get({
        otp: { transport: ["sms"] },
        signal: ac.signal,
      })
      .then((otp) => {
        // When the OTP is received by the app client, enter it into the form
        // input and submit the form automatically
        input.value = otp.code;
        if (form) form.submit();
      })
      .catch((err) => {
        console.error(err);
      });
  });
}
```

Another good use for the `AbortController` is to cancel the `get()` request after a certain amount of time:

```js
setTimeout(() => {
  // abort after 30 seconds
  ac.abort();
}, 30 \* 1000);
```

If the user becomes distracted or navigates somewhere else, it is good to cancel the request so that they don't get presented with a permission prompt that is no longer relevant to them.

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

| Specification |
| --- |
| WebOTP API  |

See also
--------

* Verify phone numbers on the web with WebOTP on developer.chrome.com (2023)
* Fill OTP forms within cross-origin iframes with WebOTP API


PresentationConnectionList - Web APIs

PresentationConnectionList
==========================

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

`PresentationConnectionList` is the collection of incoming presentation connections.

EventTarget

PresentationConnectionListInstance properties
-------------------

`PresentationConnectionList.connections` Read only
Experimental

Returns the non-terminated set of `PresentationConnection`s in the set of presentation controllers.

### Event Handlers

`PresentationConnectionList.onconnectionavailable`
Experimental

Fired whenever a new presentation connection becomes available.

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

| Specification |
| --- |
| Presentation API # interface-presentationconnectionlist |

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

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


XMLHttpRequestUpload - Web APIs

XMLHttpRequestUpload
====================

The **`XMLHttpRequestUpload`** interface represents the upload process for a specific `XMLHttpRequest`. It is an *opaque* object that represents the underlying, browser-dependent, upload process. It is an `XMLHttpRequestEventTarget` and can be obtained by calling `XMLHttpRequest.upload`.

**Note:** This feature is available in Web Workers, except for Service Workers

EventTarget

XMLHttpRequestEventTarget

XMLHttpRequestUploadInstance properties
-------------------

*This interface has no specific property, but inherits the properties of `XMLHttpRequestEventTarget` and of `EventTarget`.*

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

*This interface has no specific method, but inherits the methods of `XMLHttpRequestEventTarget` and of `EventTarget`.*

Events
------

`abort`

 Fired when a request has been aborted, for example because the program called `XMLHttpRequest.abort()`.
 Also available via the `onabort` event handler property.

`error`

 Fired when the request encountered an error.
 Also available via the `onerror` event handler property.

`load`

 Fired when a request transaction completes successfully.
 Also available via the `onload` event handler property.

`loadend`

 Fired when a request has completed, whether successfully (after `load`) or unsuccessfully (after `abort` or `error`).
 Also available via the `onloadend` event handler property.

`loadstart`

 Fired when a request has started to load data.
 Also available via the `onloadstart` event handler property.

`progress`

 Fired periodically when a request receives more data.
 Also available via the `onprogress` event handler property.

`timeout`

 Fired when progress is terminated due to preset time expiring.
 Also available via the `ontimeout` event handler property.

Examples
--------

### Uploading a file with a timeout

This allows you to upload a file to a server; it displays a progress bar while the upload is happening as well as a message with the progress and the results, success or failure. An abort button allows to stop an upload.

#### HTML

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>XMLHttpRequestUpload test</title>
    <link rel="stylesheet" href="xhrupload\_test.css" />
    <script src="xhrupload\_test.js"></script>
  </head>
  <body>
    <main>
      <h1>Upload a file</h1>
      <p>
        <label for="file">File to upload</label><input type="file" id="file" />
      </p>
      <p>
        <progress />
      </p>
      <p>
        <output></output>
      </p>
      <p>
        <button disabled id="abort">Abort</button>
      </p>
    </main>
  </body>
</html>
```

#### CSS

```css
body {
  background-color: lightblue;
}

main {
  margin: 50px auto;
  text-align: center;
}

#file {
  display: none;
}

label[for="file"] {
  background-color: lightgrey;
  padding: 10px 10px;
}

progress {
  display: none;
}

progress.visible {
  display: inline;
}
```

#### JavaScript

```js
addEventListener("DOMContentLoaded", () => {
  const fileInput = document.getElementById("file");
  const progressBar = document.querySelector("progress");
  const log = document.querySelector("output");
  const abortButton = document.getElementById("abort");

  fileInput.addEventListener("change", () => {
    const xhr = new XMLHttpRequest();
    xhr.timeout = 2000; // 2 seconds

    // Link abort button
    abortButton.addEventListener(
      "click",
      () => {
        xhr.abort();
      },
      { once: true },
    );

    // When the upload starts, we display the progress bar
    xhr.upload.addEventListener("loadstart", (event) => {
      progressBar.classList.add("visible");
      progressBar.value = 0;
      progressBar.max = event.total;
      log.textContent = "Uploading (0%)…";
      abortButton.disabled = false;
    });

    // Each time a progress event is received, we update the bar
    xhr.upload.addEventListener("progress", (event) => {
      progressBar.value = event.loaded;
      log.textContent = `Uploading (${(
 (event.loaded / event.total) \*
 100
 ).toFixed(2)}%)…`;
    });

    // When the upload is finished, we hide the progress bar.
    xhr.upload.addEventListener("loadend", (event) => {
      progressBar.classList.remove("visible");
      if (event.loaded !== 0) {
        log.textContent = "Upload finished.";
      }
      abortButton.disabled = true;
    });

    // In case of an error, an abort, or a timeout, we hide the progress bar
    // Note that these events can be listened to on the xhr object too
    function errorAction(event) {
      progressBar.classList.remove("visible");
      log.textContent = `Upload failed: ${event.type}`;
    }
    xhr.upload.addEventListener("error", errorAction);
    xhr.upload.addEventListener("abort", errorAction);
    xhr.upload.addEventListener("timeout", errorAction);

    // Build the payload
    const fileData = new FormData();
    fileData.append("file", fileInput.files[0]);

    // Theoretically, event listeners could be set after the open() call
    // but browsers are buggy here
    xhr.open("POST", "upload\_test.php", true);

    // Note that the event listener must be set before sending (as it is a preflighted request)
    xhr.send(fileData);
  });
});
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # xmlhttprequestupload |

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

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

See also
--------

* `XMLHttpRequest`


AuthenticatorResponse - Web APIs

AuthenticatorResponse
=====================

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

The **`AuthenticatorResponse`** interface of the Web Authentication API is the base interface for interfaces that provide a cryptographic root of trust for a key pair. The child interfaces include information from the browser such as the challenge origin and either may be returned from `PublicKeyCredential.response`.

Interfaces based on AuthenticatorResponse
-----------------------------------------

Below is a list of interfaces based on the AuthenticatorResponse interface.

* `AuthenticatorAssertionResponse`
* `AuthenticatorAttestationResponse`
Instance properties
-------------------

`AuthenticatorResponse.clientDataJSON`

A JSON string in an `ArrayBuffer`, representing the client data that was passed to `CredentialsContainer.create()` or `CredentialsContainer.get()`.

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

None.

Examples
--------

### Getting an AuthenticatorAssertionResponse

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

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

### Getting an AuthenticatorAttestationResponse

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

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

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

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

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

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

See also
--------

* `AuthenticatorAttestationResponse`
* `AuthenticatorAssertionResponse`
* `PublicKeyCredential.response`


XRWebGLDepthInformation - Web APIs

XRWebGLDepthInformation
=======================

**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 **`XRWebGLDepthInformation`** interface contains depth information from the GPU/WebGL (returned by `XRWebGLBinding.getDepthInformation()`).

XRDepthInformation

XRWebGLDepthInformation
This interface inherits properties from its parent, `XRDepthInformation`.

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

`XRDepthInformation.height` Read only

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

`XRDepthInformation.normDepthBufferFromNormView` Read only

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

`XRDepthInformation.rawValueToMeters` Read only

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

`XRWebGLDepthInformation.texture` Read only
Experimental

A `WebGLTexture` containing depth buffer information as an opaque texture.

`XRDepthInformation.width` Read only

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

Examples
--------

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

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

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

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

See also
--------

* `XRDepthInformation`
* `XRCPUDepthInformation`
* `XRWebGLBinding.getDepthInformation()`


MediaStreamTrack - Web APIs

MediaStreamTrack
================

The **`MediaStreamTrack`** interface of the Media Capture and Streams API represents a single media track within a stream; typically, these are audio or video tracks, but other track types may exist as well.

Some user agents subclass this interface to provide more precise information or functionality, such as `CanvasCaptureMediaStreamTrack`.

EventTarget

MediaStreamTrackInstance properties
-------------------

In addition to the properties listed below, `MediaStreamTrack` has constrainable properties which can be set using `applyConstraints()` and accessed using `getConstraints()` and `getSettings()`. See Capabilities, constraints, and settings to learn how to correctly work with constrainable properties. Not doing so correctly will result in your code being unreliable.

`MediaStreamTrack.contentHint`

A string that may be used by the web application to provide a hint as to what type of content the track contains to guide how it should be treated by API consumers.

`MediaStreamTrack.enabled`

A Boolean whose value of `true` if the track is enabled, that is allowed to render the media source stream; or `false` if it is disabled, that is not rendering the media source stream but silence and blackness. If the track has been disconnected, this value can be changed but has no more effect.

**Note:** You can implement standard "mute" functionality by setting `enabled` to `false`. The `muted` property refers to a condition in which there's no media because of a technical issue.

`MediaStreamTrack.id` Read only

Returns a string containing a unique identifier (GUID) for the track; it is generated by the browser.

`MediaStreamTrack.kind` Read only

Returns a string set to `"audio"` if the track is an audio track and to `"video"`, if it is a video track. It doesn't change if the track is disassociated from its source.

`MediaStreamTrack.label` Read only

Returns a string containing a user agent-assigned label that identifies the track source, as in `"internal microphone"`. The string may be left empty and is empty as long as no source has been connected. When the track is disassociated from its source, the label is not changed.

`MediaStreamTrack.muted` Read only

Returns a Boolean value indicating whether the track is unable to provide media data due to a technical issue.

**Note:** You can implement standard "mute" functionality by setting `enabled` to `false`, and unmute the media by setting it back to `true` again.

`MediaStreamTrack.readyState` Read only

Returns an enumerated string giving the status of the track. This will be one of the following values:

* `"live"` which indicates that an input is connected and does its best-effort in providing real-time data. In that case, the output of data can be switched on or off using the `enabled` attribute.
* `"ended"` which indicates that the input is not giving any more data and will never provide new data.

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

`MediaStreamTrack.applyConstraints()`

Lets the application specify the ideal and/or ranges of acceptable values for any number of the available constrainable properties of the `MediaStreamTrack`.

`MediaStreamTrack.clone()`

Returns a duplicate of the `MediaStreamTrack`.

`MediaStreamTrack.getCapabilities()`

Returns the a list of constrainable properties available for the `MediaStreamTrack`.

`MediaStreamTrack.getConstraints()`

Returns a `MediaTrackConstraints` object containing the currently set constraints for the track; the returned value matches the constraints last set using `applyConstraints()`.

`MediaStreamTrack.getSettings()`

Returns a `MediaTrackSettings` object containing the current values of each of the `MediaStreamTrack`'s constrainable properties.

`MediaStreamTrack.stop()`

Stops playing the source associated to the track, both the source and the track are disassociated. The track state is set to `ended`.

Events
------

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

`ended`

Sent when playback of the track ends (when the value `readyState` changes to `ended`).

`mute`

Sent to the `MediaStreamTrack` when the value of the `muted` property is changed to `true`, indicating that the track is unable to provide data temporarily (such as when the network is experiencing a service malfunction).

`unmute`

Sent to the track when data becomes available again, ending the `muted` state.

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

| Specification |
| --- |
| Media Capture and Streams # mediastreamtrack |

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

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

See also
--------

* Media Capture and Streams API
* `MediaStream`


SpeechGrammarList - Web APIs

SpeechGrammarList
=================

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

The **`SpeechGrammarList`** interface of the Web Speech API represents a list of `SpeechGrammar` objects containing words or patterns of words that we want the recognition service to recognize.

Grammar is defined using JSpeech Grammar Format (**JSGF**.) Other formats may also be supported in the future.

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

`SpeechGrammarList()`
Experimental

Creates a new `SpeechGrammarList` object.

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

`SpeechGrammarList.length` Read only
Experimental

Returns the number of `SpeechGrammar` objects contained in the `SpeechGrammarList`.

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

`SpeechGrammarList.item()`
Experimental

Standard getter — allows individual `SpeechGrammar` objects to be retrieved from the `SpeechGrammarList` using array syntax.

`SpeechGrammarList.addFromURI()`
Experimental

Takes a grammar present at a specific URI and adds it to the `SpeechGrammarList` as a new `SpeechGrammar` object.

`SpeechGrammarList.addFromString()`
Experimental

Adds a grammar in a string to the `SpeechGrammarList` as a new `SpeechGrammar` object.

Examples
--------

In our simple Speech color changer example, we create a new `SpeechRecognition` object instance using the `SpeechRecognition()` constructor, create a new `SpeechGrammarList`, add our grammar string to it using the `SpeechGrammarList.addFromString` method, and set it to be the grammar that will be recognized by the `SpeechRecognition` instance using the `SpeechRecognition.grammars` property.

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
```

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

| Specification |
| --- |
| Web Speech API # speechgrammarlist |

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

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

See also
--------

* Web Speech API


Selection API - Web APIs

Selection API
=============

**Note:** This API is *not available* in Web Workers (not exposed via `WorkerNavigator`).

The **Selection API** enables developers to access and manipulate the portion of a document selected by the user.

The `Window.getSelection()` and `Document.getSelection()` methods return a `Selection` object representing the portion of the document selected by the user. A `Selection` object provides methods to:

* access the currently selected nodes
* modify the current selection, expanding or collapsing it or selecting an entirely different part of the document
* delete parts of the current selection from the DOM.

The Selection API also provides two events, both firing on `Document`:

* the `selectstart` event is fired when the user starts to make a new selection
* the `selectionchange` event is fired when the current selection changes.
Interfaces
----------

`Selection`

An interface which represents the part of the document selected by the user or the current position of the caret.

`Document.getSelection()`

A method returning a `Selection` object representing the current selection or current position of the caret.

`Window.getSelection()`

A method returning a `Selection` object representing the current selection or current position of the caret.

`Document.selectionchange`

An event which is fired when the current selection is changed.

`Node.selectstart`

An event which is fired when a user starts a new selection.

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

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


ContactsManager - Web APIs

ContactsManager
===============

**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 **`ContactsManager`** interface of the `Contact Picker API` allows users to select entries from their contact list and share limited details of the selected entries with a website or application.

The `ContactsManager` is available through the global `navigator.contacts` property.

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

`select()`
Experimental

Returns a `Promise` which, when resolved, presents the user with a contact picker which allows them to select contact(s) they wish to share.

`getProperties()`
Experimental

Returns a `Promise` which resolves with an `Array` of `strings` indicating which contact properties are available.

Examples
--------

### Feature Detection

The following code checks whether the Contact Picker API is supported.

```js
const supported = "contacts" in navigator && "ContactsManager" in window;
```

### Checking for Supported Properties

The following asynchronous function uses the `getProperties` method to check for supported properties.

```js
async function checkProperties() {
  const supportedProperties = await navigator.contacts.getProperties();
  if (supportedProperties.includes("name")) {
    // run code for name support
  }
  if (supportedProperties.includes("email")) {
    // run code for email support
  }
  if (supportedProperties.includes("tel")) {
    // run code for telephone number support
  }
  if (supportedProperties.includes("address")) {
    // run code for address support
  }
  if (supportedProperties.includes("icon")) {
    // run code for avatar support
  }
}
```

### Selecting Contacts

The following example sets an array of properties to be retrieved for each contact, as well as setting an options object to allow for multiple contacts to be selected.

An asynchronous function is then defined which uses the `select()` method to present the user with a contact picker interface and handle the chosen results.

```js
const props = ["name", "email", "tel", "address", "icon"];
const opts = { multiple: true };

async function getContacts() {
  try {
    const contacts = await navigator.contacts.select(props, opts);
    handleResults(contacts);
  } catch (ex) {
    // Handle any errors here.
  }
}
```

`handleResults()` is a developer defined function.

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

| Specification |
| --- |
| Contact Picker API # contacts-manager |

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

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

See also
--------

* A Contact Picker for the Web
* A Contact Picker demo on glitch


XPathExpression - Web APIs

XPathExpression
===============

This interface is a compiled XPath expression that can be evaluated on a document or specific node to return information from its DOM tree.

This is useful when an expression will be reused in an application, because it is just compiled once and all namespace prefixes which occur within the expression are preresolved.

Objects of this type are created by calling `XPathEvaluator.createExpression()`.

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

`XPathExpression.evaluate()`

Evaluates the XPath expression on the given node or document.

Example
-------

The following example shows the use of the `XPathExpression` interface.

### HTML

```html
<div>XPath example</div>
<div>Number of <div>s: <output></output></div>
```

### JavaScript

```js
const xpath = "//div";
const evaluator = new XPathEvaluator();
const expression = evaluator.createExpression(xpath);
const result = expression.evaluate(
  document,
  XPathResult.ORDERED\_NODE\_SNAPSHOT\_TYPE,
);
document.querySelector("output").textContent = result.snapshotLength;
```

### Result

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

| Specification |
| --- |
| DOM Standard # interface-xpathexpression |

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

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

See also
--------

* `document.createExpression()`
* `XPathResult`


CSSImageValue - Web APIs

CSSImageValue
=============

The **`CSSImageValue`** interface of the CSS Typed Object Model API represents values for properties that take an image, for example `background-image`, `list-style-image`, or `border-image-source`.

The CSSImageValue object represents an `<image>` that involves a URL, such as `url()` or `image()`, but not `linear-gradient()` or `element()`.

CSSStyleValue

CSSImageValueInstance properties
-------------------

None.

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

*Inherits methods from `CSSStyleValue`.*

Examples
--------

We create an element

```html
<button>Magic Wand</button>
```

We add some CSS, including a background image requesting a binary file:

```css
button {
  display: inline-block;
  min-height: 100px;
  min-width: 100px;
  background: no-repeat 5% center url(magicwand.png) aqua;
}
```

We get the element's style map. We then get() the background-image from the stylemap and stringify it:

```js
// get the element
const button = document.querySelector("button");

// Retrieve all computed styles with computedStyleMap()
const allComputedStyles = button.computedStyleMap();

// Return the CSSImageValue Example
console.log(allComputedStyles.get("background-image"));
console.log(allComputedStyles.get("background-image").toString());
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # imagevalue-objects |

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

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

See also
--------

* `CSSKeywordValue`
* `CSSNumericValue`
* `CSSPositionValue`
* `CSSTransformValue`
* `CSSUnparsedValue`


SVGStopElement - Web APIs

SVGStopElement
==============

The **`SVGStopElement`** interface corresponds to the `<stop>` element.

EventTarget

Node

Element

SVGElement

SVGStopElementInstance properties
-------------------

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

`SVGStopElement.offset` Read only

An `SVGAnimatedNumber` corresponding to the `offset` of the given element.

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

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

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

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

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

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


VideoFrame - Web APIs

VideoFrame
==========

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

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

* Learn more
* See full compatibility
* Report feedback
The **`VideoFrame`** interface of the Web Codecs API represents a frame of a video.

`VideoFrame` is a transferable object.

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

A `VideoFrame` object can be created or accessed in a number of ways. The `MediaStreamTrackProcessor` breaks a media track into individual `VideoFrame` objects.

 A `VideoFrame` is an image source and has a constructor that accepts any other canvas source (
 an `SVGImageElement`,
 an `HTMLVideoElement`,
 an `HTMLCanvasElement`,
 an `ImageBitmap`,
 an `OffscreenCanvas`,
 or another `VideoFrame`).
 This means that a frame can be created from an image or video element.

A second constructor enables the creation of a `VideoFrame` from its binary pixel representation in an `ArrayBuffer`, a `TypedArray`, or a `DataView`.

Created frames may then turned into a media track, for example with the `MediaStreamTrackGenerator` interface that creates a media track from a stream of frames.

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

`VideoFrame()`

Creates a new `VideoFrame` object.

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

`VideoFrame.format` Read only

Returns the pixel format of the `VideoFrame`.

`VideoFrame.codedWidth` Read only

Returns the width of the `VideoFrame` in pixels, potentially including non-visible padding, and prior to considering potential ratio adjustments.

`VideoFrame.codedHeight` Read only

Returns the height of the `VideoFrame` in pixels, potentially including non-visible padding, and prior to considering potential ratio adjustments.

`VideoFrame.codedRect` Read only

Returns a `DOMRectReadOnly` with the width and height matching `codedWidth` and `codedHeight`.

`VideoFrame.visibleRect` Read only

Returns a `DOMRectReadOnly` describing the visible rectangle of pixels for this `VideoFrame`.

`VideoFrame.displayWidth` Read only

Returns the width of the `VideoFrame` when displayed after applying aspect ratio adjustments.

`VideoFrame.displayHeight` Read only

Returns the height of the `VideoFrame` when displayed after applying aspect ratio adjustments.

`VideoFrame.duration` Read only

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

`VideoFrame.timestamp` Read only

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

`VideoFrame.colorSpace` Read only

Returns a `VideoColorSpace` object.

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

`VideoFrame.allocationSize()`

Returns the number of bytes required to hold the `VideoFrame` as filtered by options passed into the method.

`VideoFrame.copyTo()`

Copies the contents of the `VideoFrame` to an `ArrayBuffer`.

`VideoFrame.clone()`

Creates a new `VideoFrame` object with reference to the same media resource as the original.

`VideoFrame.close()`

Clears all states and releases the reference to the media resource.

Examples
--------

In the following example frames are returned from a `MediaStreamTrackProcessor`, then encoded. See the full example and read more about it in the article Video processing with WebCodecs.

```js
let frame_counter = 0;

const track = stream.getVideoTracks()[0];
const media_processor = new MediaStreamTrackProcessor(track);

const reader = media_processor.readable.getReader();
while (true) {
  const result = await reader.read();
  if (result.done) break;

  let frame = result.value;
  if (encoder.encodeQueueSize > 2) {
    // Too many frames in flight, encoder is overwhelmed
    // let's drop this frame.
    frame.close();
  } else {
    frame_counter++;
    const insert_keyframe = frame_counter % 150 === 0;
    encoder.encode(frame, { keyFrame: insert_keyframe });
    frame.close();
  }
}
```

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

| Specification |
| --- |
| WebCodecs # videoframe-interface |

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

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

See also
--------

* Video processing with WebCodecs
* WebCodecs examples