IDBObjectStore - Web APIs

IDBObjectStore
==============

The **`IDBObjectStore`** interface of the IndexedDB API represents an object store in a database. Records within an object store are sorted according to their keys. This sorting enables fast insertion, look-up, and ordered retrieval.

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

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

`IDBObjectStore.indexNames` Read only

A list of the names of indexes on objects in this object store.

`IDBObjectStore.keyPath` Read only

The key path of this object store. If this attribute is `null`, the application must provide a key for each modification operation.

`IDBObjectStore.name`

The name of this object store.

`IDBObjectStore.transaction` Read only

The `IDBTransaction` object to which this object store belongs.

`IDBObjectStore.autoIncrement` Read only

The value of the auto increment flag for this object store.

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

`IDBObjectStore.add()`

Returns an `IDBRequest` object, and, in a separate thread, creates a structured clone of the `value`, and stores the cloned value in the object store. This is for adding new records to an object store.

`IDBObjectStore.clear()`

Creates and immediately returns an `IDBRequest` object, and clears this object store in a separate thread. This is for deleting all current records out of an object store.

`IDBObjectStore.count()`

Returns an `IDBRequest` object, and, in a separate thread, returns the total number of records that match the provided key or `IDBKeyRange`. If no arguments are provided, it returns the total number of records in the store.

`IDBObjectStore.createIndex()`

Creates a new index during a version upgrade, returning a new `IDBIndex` object in the connected database.

`IDBObjectStore.delete()`

returns an `IDBRequest` object, and, in a separate thread, deletes the store object selected by the specified key. This is for deleting individual records out of an object store.

`IDBObjectStore.deleteIndex()`

Destroys the specified index in the connected database, used during a version upgrade.

`IDBObjectStore.get()`

Returns an `IDBRequest` object, and, in a separate thread, returns the store object store selected by the specified key. This is for retrieving specific records from an object store.

`IDBObjectStore.getKey()`

Returns an `IDBRequest` object, and, in a separate thread retrieves and returns the record key for the object in the object stored matching the specified parameter.

`IDBObjectStore.getAll()`

Returns an `IDBRequest` object retrieves all objects in the object store matching the specified parameter or all objects in the store if no parameters are given.

`IDBObjectStore.getAllKeys()`

Returns an `IDBRequest` object retrieves record keys for all objects in the object store matching the specified parameter or all objects in the store if no parameters are given.

`IDBObjectStore.index()`

Opens an index from this object store after which it can, for example, be used to return a sequence of records sorted by that index using a cursor.

`IDBObjectStore.openCursor()`

Returns an `IDBRequest` object, and, in a separate thread, returns a new `IDBCursorWithValue` object. Used for iterating through an object store by primary key with a cursor.

`IDBObjectStore.openKeyCursor()`

Returns an `IDBRequest` object, and, in a separate thread, returns a new `IDBCursor`. Used for iterating through an object store with a key.

`IDBObjectStore.put()`

Returns an `IDBRequest` object, and, in a separate thread, creates a structured clone of the `value`, and stores the cloned value in the object store. This is for updating existing records in an object store when the transaction's mode is `readwrite`.

Example
-------

This example shows a variety of different uses of object stores, from updating the data structure with `IDBObjectStore.createIndex` inside an `onupgradeneeded` function, to adding a new item to our object store with `IDBObjectStore.add`. For a full working example, see our To-do Notifications app (view example live).

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

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

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

// This event handles the event whereby a new version of
// the database needs to be created Either one has not
// been created before, or a new version number has been
// submitted via the window.indexedDB.open line above
DBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = (event) => {
    note.innerHTML += "<li>Error loading database.</li>";
  };

  // Create an objectStore for this database

  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain

  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });

  objectStore.createIndex("notified", "notified", { unique: false });

  note.innerHTML += "<li>Object store created.</li>";
};

// Create a new item to add in to the object store
const newItem = [
  {
    taskTitle: "Walk dog",
    hours: 19,
    minutes: 30,
    day: 24,
    month: "December",
    year: 2013,
    notified: "no",
  },
];

// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");

// report on the success of the transaction completing, when everything is done
transaction.oncomplete = (event) => {
  note.innerHTML += "<li>Transaction completed.</li>";
};

transaction.onerror = (event) => {
  note.innerHTML +=
    "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};

// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// make a request to add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);

objectStoreRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Request successful .</li>";
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # object-store-interface |

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

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

See also
--------

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


HTMLDataElement - Web APIs

HTMLDataElement
===============

The **`HTMLDataElement`** interface provides special properties (beyond the regular `HTMLElement` interface it also has available to it by inheritance) for manipulating `<data>` elements.

EventTarget

Node

Element

HTMLElement

HTMLDataElementInstance properties
-------------------

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

`HTMLDataElement.value`

A string reflecting the `value` HTML attribute, containing a machine-readable form of the element's value.

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

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

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

| Specification |
| --- |
| HTML Standard # htmldataelement |

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


Device orientation events - Web APIs

Device orientation events
=========================

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

Device orientation events are events that allow you to detect a device's physical orientation, as well as allowing you to detect the device's motion.

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

Mobile devices commonly have sensors such as gyroscopes, compasses, and accelerometers that can enable applications running on the device to detect the device's orientation and motion.

The device orientation events enable you to write web applications that can change their behavior based on the orientation of the user's device, and that can react when the user moves their device.

Some typical features for which you might want to use the device orientation events include:

* in web-based games, to enable the user to control the motion of characters or objects in the game by tilting and moving the device
* in mapping applications, to re-orient a map based on the device's position, or to provide turn-by-turn directions that update with the user's movements
* for gesture recognition — for example, recognizing a "shake" gesture and using it to perform some action such as clearing an input area when the user shakes the device

**Note:** This API is widely supported on mobile browsers. While some desktop-only browsers may have limitations due to hardware differences, these constraints are rarely significant given the API's primary usage on sensor-equipped devices.

Interfaces
----------

`DeviceMotionEvent`

Represents changes in the acceleration of a device, as well as the rotation rate.

`DeviceMotionEventAcceleration`

Represents the amount of acceleration the device is experiencing along all three axes

`DeviceMotionEventRotationRate`

Represents the rate at which the device is rotating around all three axes.

`DeviceOrientationEvent`

Represents changes in the physical orientation of a device.

### Extensions to other interfaces

`devicemotion` event

Fired at a regular interval to indicate the amount of physical force of acceleration the device is receiving at that time, and the rate of rotation of the device.

`deviceorientation` event

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

`deviceorientationabsolute` event

Fired when absolute device orientation changes.

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

| Specification |
| --- |
| DeviceOrientation Event Specification  |

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

### api.Window.deviceorientation\_event

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

### api.Window.devicemotion\_event

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

### api.Window.deviceorientationabsolute\_event

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

### api.DeviceOrientationEvent

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

### api.DeviceMotionEvent

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

### api.DeviceMotionEventAcceleration

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

### api.DeviceMotionEventRotationRate

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

See also
--------

* Device Orientation & Motion at web.dev


MediaKeySession - Web APIs

MediaKeySession
===============

The **`MediaKeySession`** interface of the Encrypted Media Extensions API represents a context for message exchange with a content decryption module (CDM).

EventTarget

MediaKeySessionInstance properties
-------------------

`MediaKeySession.closed` Read only

Returns a `Promise` signaling when a `MediaKeySession` closes. This promise can only be fulfilled and is never rejected. Closing a session means that licenses and keys associated with it are no longer valid for decrypting media data.

`MediaKeySession.expiration` Read only

The time after which the keys in the current session can no longer be used to decrypt media data, or `NaN` if no such time exists. This value is determined by the CDM and measured in milliseconds since January 1, 1970, UTC. This value may change during a session lifetime, such as when an action triggers the start of a window.

`MediaKeySession.keyStatuses` Read only

Contains a reference to a read-only `MediaKeyStatusMap` of the current session's keys and their statuses.

`MediaKeySession.sessionId` Read only

Contains a unique string generated by the CDM for the current media object and its associated keys or licenses.

### Events

`keystatuseschange`

Fires when there has been a change in the keys in a session or their statuses.

`message`

Fires when the content decryption module has generated a message for the session.

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

`MediaKeySession.close()`

Returns a `Promise` after notifying the current media session is no longer needed and that the CDM should release any resources associated with this object and close it.

`MediaKeySession.generateRequest()`

Returns a `Promise` after generating a media request based on initialization data.

`MediaKeySession.load()`

Returns a `Promise` that resolves to a boolean value after loading data for a specified session object.

`MediaKeySession.remove()`

Returns a `Promise` after removing any session data associated with the current object.

`MediaKeySession.update()`

Returns a `Promise` after loading messages and licenses to the CDM.

Examples
--------

```js
// TBD
```

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

| Specification |
| --- |
| Encrypted Media Extensions # mediakeysession-interface |

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

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


GPUCompilationMessage - Web APIs

GPUCompilationMessage
=====================

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

The **`GPUCompilationMessage`** interface of the WebGPU API represents a single informational, warning, or error message generated by the GPU shader module compiler.

An array of `GPUCompilationMessage` objects is available in the `messages` property of the `GPUCompilationInfo` object accessed via `GPUShaderModule.getCompilationInfo()`.

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

`length`
Experimental
 Read only

A number representing the length of the substring that the message corresponds to.

`lineNum`
Experimental
 Read only

A number representing the line number in the shader code that the message corresponds to.

`linePos`
Experimental
 Read only

A number representing the position in the code line that the message corresponds to. This could be an exact point, or the start of the relevant substring.

`message`
Experimental
 Read only

A string representing human-readable message text.

`offset`
Experimental
 Read only

A number representing the offset from the start of the shader code to the exact point, or the start of the relevant substring, that the message corresponds to.

`type`
Experimental
 Read only

An enumerated value representing the type of the message — `"error"`, `"info"`, or `"warning"`.

Examples
--------

See the main `GPUCompilationInfo` page for an example.

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

| Specification |
| --- |
| WebGPU # gpucompilationmessage |

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

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

See also
--------

* The WebGPU API


OVR_multiview2 extension - Web APIs

OVR\_multiview2 extension
=========================

The `OVR_multiview2` extension is part of the WebGL API and adds support for rendering into multiple views simultaneously. This especially useful for virtual reality (VR) and WebXR.

For more information, see also:

* Multiview on WebXR
* Multiview in babylon.js
* Optimizing Virtual Reality: Understanding Multiview
* Multiview WebGL Rendering for Oculus Browser 6.0+

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

**Note:** Support depends on the system's graphics driver (Windows+ANGLE and Android are supported; Windows+GL, Mac, Linux are not supported).

This extension is only available to WebGL 2 contexts as it needs GLSL 3.00 and texture arrays.

Currently, there is no way to use multiview to render to a multisampled backbuffer, so you should create contexts with `antialias: false`. However, the Oculus browser (6+) also supports multisampling using the `OCULUS_multiview` extension. See also this WebGL issue.

Constants
---------

This extension exposes 4 constants that can be used in `getParameter()` or `getFramebufferAttachmentParameter()`.

`FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR`

Number of views of the framebuffer object attachment.

`FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR`

Base view index of the framebuffer object attachment.

`MAX_VIEWS_OVR`

The maximum number of views. Most VR headsets have two views, but there are prototypes of headset with ultra-wide FOV using 4 views which is currently the maximum number of views supported by multiview.

`FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR`

If baseViewIndex is not the same for all framebuffer attachment points where the value of `FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE` is not `NONE`, the framebuffer is considered incomplete. Calling `checkFramebufferStatus` for a framebuffer in this state returns `FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR`.

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

`framebufferTextureMultiviewOVR()`

Simultaneously renders to multiple elements of a 2D texture array.

Examples
--------

This example is taken from the specification.

```js
const gl = document
  .createElement("canvas")
  .getContext("webgl2", { antialias: false });
const ext = gl.getExtension("OVR\_multiview2");
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.DRAW\_FRAMEBUFFER, fb);

const colorTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE\_2D\_ARRAY, colorTex);
gl.texStorage3D(gl.TEXTURE\_2D\_ARRAY, 1, gl.RGBA8, 512, 512, 2);
ext.framebufferTextureMultiviewOVR(
  gl.DRAW\_FRAMEBUFFER,
  gl.COLOR\_ATTACHMENT0,
  colorTex,
  0,
  0,
  2,
);

const depthStencilTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE\_2D\_ARRAY, depthStencilTex);
gl.texStorage3D(gl.TEXTURE\_2D\_ARRAY, 1, gl.DEPTH32F\_STENCIL8, 512, 512, 2);

ext.framebufferTextureMultiviewOVR(
  gl.DRAW\_FRAMEBUFFER,
  gl.DEPTH\_STENCIL\_ATTACHMENT,
  depthStencilTex,
  0,
  0,
  2,
);
gl.drawElements(/\* … \*/); // draw will be broadcasted to the layers of colorTex and depthStencilTex.
```

Shader code

```cpp
#version 300 es
#extension GL\_OVR\_multiview2 : require
precision mediump float;
layout (num_views = 2) in;
in vec4 inPos;
uniform mat4 u_viewMatrices[2];
void main() {
  gl_Position = u_viewMatrices[gl_ViewID_OVR] \* inPos;
}
```

Also, see this three.js demo for a live multiview example.

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

| Specification |
| --- |
| WebGL OVR\_multiview2 Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.getParameter()`
* WebXR


CSSLayerBlockRule - Web APIs

CSSLayerBlockRule
=================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`CSSLayerBlockRule`** represents a `@layer` block rule. It is a grouping at-rule meaning that it can contain other rules, and is associated to a given cascade layer, identified by its *name*.

CSSRule

CSSGroupingRule

CSSLayerBlockRuleInstance properties
-------------------

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

* `CSSLayerBlockRule.name` Read only
    + A string containing the name of the associated cascade layer.
Instance methods
----------------

*Inherits methods from its parent interface, `CSSGroupingRule`.*

Examples
--------

### HTML

```html
<p>I am displayed in <code>color: rebeccapurple</code>.</p>
```

### CSS

```css
@layer special {
  p {
    color: rebeccapurple;
  }
}
```

### JavaScript

```js
const item = document.getElementsByTagName("p")[0];
const rules = document.styleSheets[1].cssRules;
// Note that stylesheet #1 is the stylesheet associated with this embedded example,
// while stylesheet #0 is the stylesheet associated with the whole MDN page

const layer = rules[0]; // A CSSLayerBlockRule

item.textContent = `The CSSLayerBlockRule is for the "${layer.name}" layer`;
```

### Result

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

| Specification |
| --- |
| CSS Cascading and Inheritance Level 5 # csslayerblockrule |

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

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

See also
--------

* `@layer`
* `CSSLayerStatementRule`
* Learn CSS cascade layers


SVGGradientElement - Web APIs

SVGGradientElement
==================

The **`SVGGradient`** interface is a base interface used by `SVGLinearGradientElement` and `SVGRadialGradientElement`.

EventTarget

Node

Element

SVGElement

SVGGradientElementConstants
---------

| Name | Value | Description |
| --- | --- | --- |
| `SVG_SPREADMETHOD_UNKNOWN` | 0 |
 The type is not one of predefined types. It is invalid to attempt to
 define a new value of this type or to attempt to switch an existing
 value to this type.
  |
| `SVG_SPREADMETHOD_PAD` | 1 | Corresponds to value *pad*. |
| `SVG_SPREADMETHOD_REFLECT` | 2 | Corresponds to value *reflect*. |
| `SVG_SPREADMETHOD_REPEAT` | 3 | Corresponds to value *repeat*. |

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

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

`SVGGradientElement.href` Read only

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

`SVGGradientElement.gradientUnits` Read only

An `SVGAnimatedEnumeration` corresponding to the `gradientUnits` attribute on the given element. This property takes one of the constants defined in `SVGUnitTypes`.

`SVGGradientElement.gradientTransform` Read only

An `SVGAnimatedTransformList` corresponding to the `gradientTransform` attribute on the given element.

`SVGGradientElement.spreadMethod` Read only

An `SVGAnimatedEnumeration` corresponding to the `spreadMethod` attribute on the given element. One of the spread method types defined on this interface.

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

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

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

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

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

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


XRInputSourcesChangeEvent - Web APIs

XRInputSourcesChangeEvent
=========================

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

The WebXR Device API interface **`XRInputSourcesChangeEvent`** is used to represent the `inputsourceschange` event sent to an `XRSession` when the set of available WebXR input controllers changes.

Event

XRInputSourcesChangeEventConstructor
-----------

`XRInputSourcesChangeEvent()`

Creates and returns a new `XRInputSourcesChangeEvent` object. The specified type must be `inputsourceschange`, which is the only event that uses this interface.

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

`added` Read only

An array of zero or more `XRInputSource` objects, each representing an input device which has been newly connected or enabled for use.

`removed` Read only

An array of zero or more `XRInputSource` objects representing the input devices newly connected or enabled for use.

`session` Read only

The `XRSession` to which this input source change event is being directed.

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

*While `XRInputSourcesChangeEvent` defines no methods of its own, it inherits methods from its parent interface, `Event`.*

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

`inputsourceschange`

Delivered to the `XRSession` when the set of input devices available to it changes.

Examples
--------

The following example shows how to set up an event handler which uses `inputsourceschange` events to detect newly-available pointing devices and to load their models in preparation to display them in the next animation frame.

```js
xrSession.addEventListener("inputsourceschange", onInputSourcesChange);

function onInputSourcesChange(event) {
  for (const input of event.added) {
    if (input.targetRayMode === "tracked-pointer") {
      loadControllerMesh(input);
    }
  }
}
```

You can also add a handler for `inputsourceschange` events by setting the `oninputsourceschange` event handler:

```js
xrSession.oninputsourceschange = onInputSourcesChange;
```

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

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

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

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


IDBFactory - Web APIs

IDBFactory
==========

The **`IDBFactory`** interface of the IndexedDB API lets applications asynchronously access the indexed databases. The object that implements the interface is `window.indexedDB`. You open — that is, create and access — and delete a database with this object, and not directly with `IDBFactory`.

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

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

`IDBFactory.open`

The current method to request opening a connection to a database.

`IDBFactory.deleteDatabase`

A method to request the deletion of a database.

`IDBFactory.cmp`

A method that compares two keys and returns a result indicating which one is greater in value.

`IDBFactory.databases`

A method that returns a list of all available databases, including their names and versions.

Example
-------

In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. For a full working example, see our To-do Notifications app (view example live).

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

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

DBOpenRequest.onsuccess = (event) => {
  console.info("Database initialized.");

  // store the result of opening the database in the db variable. This is used a lot later on, for opening transactions and suchlike.
  db = DBOpenRequest.result;
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # factory-interface |

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

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

See also
--------

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


GeolocationCoordinates - Web APIs

GeolocationCoordinates
======================

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

 The **`GeolocationCoordinates`** interface represents the position and altitude of the device on Earth, as well as the accuracy with which these properties are calculated.
 The geographic position information is provided in terms of World Geodetic System coordinates (WGS84).

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

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

`GeolocationCoordinates.latitude` Read only

Returns a `double` representing the position's latitude in decimal degrees.

`GeolocationCoordinates.longitude` Read only

Returns a `double` representing the position's longitude in decimal degrees.

`GeolocationCoordinates.altitude` Read only

Returns a `double` representing the position's altitude in meters, relative to nominal sea level. This value can be `null` if the implementation cannot provide the data.

`GeolocationCoordinates.accuracy` Read only

Returns a `double` representing the accuracy of the `latitude` and `longitude` properties, expressed in meters.

`GeolocationCoordinates.altitudeAccuracy` Read only

Returns a `double` representing the accuracy of the `altitude` expressed in meters. This value can be `null` if the implementation cannot provide the data.

`GeolocationCoordinates.heading` Read only

Returns a `double` representing the direction towards which the device is facing. This value, specified in degrees, indicates how far off from heading true north the device is. `0` degrees represents true north, and the direction is determined clockwise (which means that east is `90` degrees and west is `270` degrees). If `speed` is `0`, `heading` is `NaN`. If the device is unable to provide `heading` information, this value is `null`.

`GeolocationCoordinates.speed` Read only

Returns a `double` representing the velocity of the device in meters per second. This value can be `null`.

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

*The `GeolocationCoordinates` interface neither implements, nor inherits any method.*

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

| Specification |
| --- |
| Geolocation API # coordinates\_interface |

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

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

See also
--------

* Using the Geolocation API
* `Geolocation`


HTMLAllCollection - Web APIs

HTMLAllCollection
=================

**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 **`HTMLAllCollection`** interface represents a collection of *all* of the document's elements, accessible by index (like an array) and by the element's `id`. It is returned by the `document.all` property.

`HTMLAllCollection` has a very similar shape to `HTMLCollection`, but there are many subtle behavior differences — for example, `HTMLAllCollection` can be called as a function, and its `item()` method can be called with a string representing an element's `id` or `name` attribute.

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

`HTMLAllCollection.length` Read only

Returns the number of items in the collection.

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

`HTMLAllCollection.item()`

Returns the element located at the specified offset into the collection, or the element with the specified value for its `id` or `name` attribute. Returns `null` if no element is found.

`HTMLAllCollection.namedItem()`

Returns the first element in the collection whose `id` or `name` attribute match the given string name, or `null` if no element matches.

Usage in JavaScript
-------------------

### Indexed access

In addition to the methods above, elements in an `HTMLAllCollection` can be accessed by integer indices and string property names. The HTML `id` attribute may contain `:` and `.` as valid characters, which would necessitate using bracket notation for property access. `collection[i]` is equivalent to `collection.item(i)`, where `i` can be an integer, a string containing an integer, or a string representing an `id`.

### Calling as a function

An `HTMLAllCollection` object is callable. When it's called with no arguments or with `undefined`, it returns `null`. Otherwise, it returns the same value as the `item()` method when given the same arguments.

### Special type conversion behavior

For historical reasons, `document.all` is an object that in the following ways behaves like `undefined`:

* It is loosely equal to `undefined` and `null`.
* It is falsy in boolean contexts.
* Its `typeof` is `"undefined"`.

These special behaviors ensure that code like:

```js
if (document.all) {
  // Assume that we are in IE; provide special logic
}
// Assume that we are in a modern browser
```

Will continue to provide modern behavior even if the code is run in a browser that implements `document.all` for compatibility reasons.

However, in all other contexts, `document.all` remains an object. For example:

* It is not strictly equal to either `undefined` or `null`.
* When used on the left-hand side of the nullish coalescing operator (`??`) or the optional chaining operator (`?.`), it will not cause the expression to short-circuit.
Specifications
--------------

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

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

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

See also
--------

* `HTMLCollection`


Contact Picker API - Web APIs

Contact Picker API
==================

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

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

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

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

Contact Picker API Concepts and Usage
-------------------------------------

Access to contacts has long been a feature available within native applications. The Contacts Picker API brings that functionality to web applications.

Use cases include selecting contacts to message via an email or chat application, selecting a contacts phone number for use with voice over IP (VOIP), or for discovering contacts who have already joined a social platform. User agents can also offer a consistent experience with other applications on a users device.

When calling the `select` method of the `ContactsManager` interface, the user is presented with a contact picker, whereby they can then select contact information to share with the web application. User interaction is required before permission to display the contact picker is granted and access to contacts is not persistent; the user must grant access every time a request is made by the application.

This API is only available from a secure top-level browsing context and very carefully considers the sensitivity and privacy of contact data. The onus is on the user for choosing data to share and only allows specific data for selected contacts, with no access to any data for other contacts.

Interfaces
----------

`ContactAddress`

Represents a physical address.

`ContactsManager`

Provides a way for users to select and share limited details of contacts with a web application.

`Navigator.contacts`

Returns a `ContactsManager` object instance, from which all other functionality can be accessed.

Examples
--------

### Feature Detection

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

```js
const supported = "contacts" in navigator;
```

### 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


HTMLImageElement - Web APIs

HTMLImageElement
================

The **`HTMLImageElement`** interface represents an HTML `<img>` element, providing the properties and methods used to manipulate image elements.

EventTarget

Node

Element

HTMLElement

HTMLImageElementConstructor
-----------

`Image()`

The `Image()` constructor creates and returns a new `HTMLImageElement` object representing an HTML `<img>` element which is not attached to any DOM tree. It accepts optional width and height parameters. When called without parameters, `new Image()` is equivalent to calling `document.createElement('img')`.

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

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

`HTMLImageElement.alt`

A string that reflects the `alt` HTML attribute, thus indicating the alternate fallback content to be displayed if the image has not been loaded.

`HTMLImageElement.complete` Read only

Returns a boolean value that is `true` if the browser has finished fetching the image, whether successful or not. That means this value is also `true` if the image has no `src` value indicating an image to load.

`HTMLImageElement.crossOrigin`

A string specifying the CORS setting for this image element. See CORS settings attributes for further details. This may be `null` if CORS is not used.

`HTMLImageElement.currentSrc` Read only

Returns a string representing the URL from which the currently displayed image was loaded. This may change as the image is adjusted due to changing conditions, as directed by any media queries which are in place.

`HTMLImageElement.decoding`

An optional string representing a hint given to the browser on how it should decode the image. If this value is provided, it must be one of the possible permitted values: `sync` to decode the image synchronously, `async` to decode it asynchronously, or `auto` to indicate no preference (which is the default). Read the `decoding` page for details on the implications of this property's values.

`HTMLImageElement.fetchPriority`

An optional string representing a hint given to the browser on how it should prioritize fetching of the image relative to other images. If this value is provided, it must be one of the possible permitted values: `high` to fetch at a high priority, `low` to fetch at a low priority, or `auto` to indicate no preference (which is the default).

`HTMLImageElement.height`

An integer value that reflects the `height` HTML attribute, indicating the rendered height of the image in CSS pixels.

`HTMLImageElement.isMap`

A boolean value that reflects the `ismap` HTML attribute, indicating that the image is part of a server-side image map. This is different from a client-side image map, specified using an `<img>` element and a corresponding `<map>` which contains `<area>` elements indicating the clickable areas in the image. The image *must* be contained within an `<a>` element; see the `ismap` page for details.

`HTMLImageElement.loading`

A string providing a hint to the browser used to optimize loading the document by determining whether to load the image immediately (`eager`) or on an as-needed basis (`lazy`).

`HTMLImageElement.naturalHeight` Read only

Returns an integer value representing the intrinsic height of the image in CSS pixels, if it is available; else, it shows `0`. This is the height the image would be if it were rendered at its natural full size.

`HTMLImageElement.naturalWidth` Read only

An integer value representing the intrinsic width of the image in CSS pixels, if it is available; otherwise, it will show `0`. This is the width the image would be if it were rendered at its natural full size.

`HTMLImageElement.referrerPolicy`

A string that reflects the `referrerpolicy` HTML attribute, which tells the user agent how to decide which referrer to use in order to fetch the image. Read this article for details on the possible values of this string.

`HTMLImageElement.sizes`

A string reflecting the `sizes` HTML attribute. This string specifies a list of comma-separated conditional sizes for the image; that is, for a given viewport size, a particular image size is to be used. Read the documentation on the `sizes` page for details on the format of this string.

`HTMLImageElement.src`

A string that reflects the `src` HTML attribute, which contains the full URL of the image including base URI. You can load a different image into the element by changing the URL in the `src` attribute.

`HTMLImageElement.srcset`

A string reflecting the `srcset` HTML attribute. This specifies a list of candidate images, separated by commas (`',', U+002C COMMA`). Each candidate image is a URL followed by a space, followed by a specially-formatted string indicating the size of the image. The size may be specified either the width or a size multiple. Read the `srcset` page for specifics on the format of the size substring.

`HTMLImageElement.useMap`

A string reflecting the `usemap` HTML attribute, containing the page-local URL of the `<map>` element describing the image map to use. The page-local URL is a pound (hash) symbol (`#`) followed by the ID of the `<map>` element, such as `#my-map-element`. The `<map>` in turn contains `<area>` elements indicating the clickable areas in the image.

`HTMLImageElement.width`

An integer value that reflects the `width` HTML attribute, indicating the rendered width of the image in CSS pixels.

`HTMLImageElement.x` Read only

An integer indicating the horizontal offset of the left border edge of the image's CSS layout box relative to the origin of the `<html>` element's containing block.

`HTMLImageElement.y` Read only

The integer vertical offset of the top border edge of the image's CSS layout box relative to the origin of the `<html>` element's containing block.

Obsolete properties
-------------------

`HTMLImageElement.align`
Deprecated

A string indicating the alignment of the image with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`. This is obsolete; you should instead use CSS (such as `text-align`, which works with images despite its name) to specify the alignment.

`HTMLImageElement.border`
Deprecated

A string which defines the width of the border surrounding the image. This is deprecated; use the CSS `border` property instead.

`HTMLImageElement.hspace`
Deprecated

An integer value which specifies the amount of space (in pixels) to leave empty on the left and right sides of the image.

`HTMLImageElement.longDesc`
Deprecated

A string specifying the URL at which a long description of the image's contents may be found. This is used to turn the image into a hyperlink automatically. Modern HTML should instead place an `<img>` inside an `<a>` element defining the hyperlink.

`HTMLImageElement.name`
Deprecated

A string representing the name of the element.

`HTMLImageElement.vspace`
Deprecated

An integer value specifying the amount of empty space, in pixels, to leave above and below the image.

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

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

`HTMLImageElement.decode()`

Returns a `Promise` that resolves when the image is decoded and it's safe to append the image to the DOM. This prevents rendering of the next frame from having to pause to decode the image, as would happen if an undecoded image were added to the DOM.

Errors
------

If an error occurs while trying to load or render the image, and an `onerror` event handler has been configured to handle the `error` event, that event handler will get called. This can happen in a number of situations, including:

* The `src` attribute is empty or `null`.
* The specified `src` URL is the same as the URL of the page the user is currently on.
* The specified image is corrupted in some way that prevents it from being loaded.
* The specified image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the `<img>` element's attributes.
* The specified image is in a format not supported by the user agent.
Example
-------

```js
const img1 = new Image(); // Image constructor
img1.src = "image1.png";
img1.alt = "alt";
document.body.appendChild(img1);

const img2 = document.createElement("img"); // Use DOM HTMLImageElement
img2.src = "image2.jpg";
img2.alt = "alt text";
document.body.appendChild(img2);

// using first image in the document
alert(document.images[0].src);
```

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

| Specification |
| --- |
| HTML Standard # htmlimageelement |

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


Pointer Lock API - Web APIs

Pointer Lock API
================

The **Pointer Lock API** (formerly called *Mouse Lock API*) provides input methods based on the movement of the mouse over time (i.e., deltas), not just the absolute position of the mouse cursor in the viewport. It gives you access to raw mouse movement, locks the target of mouse events to a single element, eliminates limits on how far mouse movement can go in a single direction, and removes the cursor from view. It is ideal for first-person 3D games, for example.

More than that, the API is useful for any applications that require significant mouse input to control movements, rotate objects, and change entries, for example allowing users to control the viewing angle by moving the mouse around without any button clicking. The buttons are then freed up for other actions. Other examples include apps for viewing maps or satellite imagery.

Pointer lock lets you access mouse events even when the cursor goes past the boundary of the browser or screen. For example, your users can continue to rotate or manipulate a 3D model by moving the mouse without end. Without Pointer lock, the rotation or manipulation stops the moment the pointer reaches the edge of the browser or screen. Game players can now click buttons and swipe the mouse cursor back and forth without worrying about leaving the game play area and accidentally clicking another application that would take mouse focus away from the game.

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

Pointer lock is related to mouse capture. Mouse capture provides continued delivery of events to a target element while a mouse is being dragged, but it stops when the mouse button is released. Pointer lock is different from mouse capture in the following ways:

* It is persistent: Pointer lock does not release the mouse until an explicit API call is made or the user uses a specific release gesture.
* It is not limited by browser or screen boundaries.
* It continues to send events regardless of mouse button state.
* It hides the cursor.
Method/properties overview
--------------------------

This section provides a brief description of each property and method related to the pointer lock specification.

### requestPointerLock()

The Pointer lock API, similar to the Fullscreen API, extends DOM elements by adding a new method, `requestPointerLock()`. The following example requests pointer lock on a `<canvas>` element:

```js
canvas.addEventListener("click", async () => {
  await canvas.requestPointerLock();
});
```

**Note:** If a user has exited pointer lock via the default unlock gesture, or pointer lock has not previously been entered for this document, an event generated as a result of an engagement gesture must be received by the document before `requestPointerLock` will succeed. (from https://w3c.github.io/pointerlock/#extensions-to-the-element-interface)

Operating systems enable mouse acceleration by default, which is useful when you sometimes want slow precise movement (think about you might use a graphics package), but also want to move great distances with a faster mouse movement (think about scrolling, and selecting several files). For some first-person perspective games however, raw mouse input data is preferred for controlling camera rotation — where the same distance movement, fast or slow, results in the same rotation. This results in a better gaming experience and higher accuracy, according to professional gamers.

To disable OS-level mouse acceleration and access raw mouse input, you can set the `unadjustedMovement` to `true`:

```js
canvas.addEventListener("click", async () => {
  await canvas.requestPointerLock({
    unadjustedMovement: true,
  });
});
```

Handling promise and non-promise versions of requestPointerLock()
-----------------------------------------------------------------

The above code snippet will still work in browsers that do not support the promise-based version of `requestPointerLock()` or the `unadjustedMovement` option — the `await` operator is permitted in front of a function that does not return a promise, and the options object will just be ignored in non-supporting browsers.

However, this could be confusing, and has other potential side-effects (for example, trying to use `requestPointerLock().then()` would throw an error in non-supporting browsers), so you may want to handle this explicitly using code along the following lines:

```js
function requestPointerLockWithUnadjustedMovement() {
  const promise = myTargetElement.requestPointerLock({
    unadjustedMovement: true,
  });

  if (!promise) {
    console.log("disabling mouse acceleration is not supported");
    return;
  }

  return promise
    .then(() => console.log("pointer is locked"))
    .catch((error) => {
      if (error.name === "NotSupportedError") {
        // Some platforms may not support unadjusted movement.
        // You can request again a regular pointer lock.
        return myTargetElement.requestPointerLock();
      }
    });
}
```

### pointerLockElement and exitPointerLock()

The Pointer lock API also extends the `Document` interface, adding a new property and a new method:

* `pointerLockElement` is used for accessing the currently locked element (if any).
* `exitPointerLock()` is used to exit the pointer lock.

The `pointerLockElement` property is useful for determining if any element is currently pointer locked (e.g., for doing a boolean check) and also for obtaining a reference to the locked element, if any.

Here is an example of using `pointerLockElement`:

```js
if (document.pointerLockElement === canvas) {
  console.log("The pointer lock status is now locked");
} else {
  console.log("The pointer lock status is now unlocked");
}
```

The `Document.exitPointerLock()` method is used to exit pointer lock, and like `requestPointerLock`, works asynchronously using the `pointerlockchange` and `pointerlockerror` events, which you'll see more about below.

```js
document.exitPointerLock();
```

pointerlockchange event
-----------------------

When the Pointer lock state changes—for example, when calling `requestPointerLock()` or `exitPointerLock()`, the user pressing the ESC key, etc.—the `pointerlockchange` event is dispatched to the `document`. This is a simple event containing no extra data.

```js
document.addEventListener("pointerlockchange", lockChangeAlert, false);

function lockChangeAlert() {
  if (document.pointerLockElement === canvas) {
    console.log("The pointer lock status is now locked");
    // Do something useful in response
  } else {
    console.log("The pointer lock status is now unlocked");
    // Do something useful in response
  }
}
```

pointerlockerror event
----------------------

When there is an error caused by calling `requestPointerLock()` or `exitPointerLock()`, the `pointerlockerror` event is dispatched to the `document`. This is a simple event containing no extra data.

```js
document.addEventListener("pointerlockerror", lockError, false);

function lockError(e) {
  alert("Pointer lock failed");
}
```

Extensions to mouse events
--------------------------

The Pointer lock API extends the normal `MouseEvent` interface with movement attributes. Two new attributes to mouse events—`movementX` and `movementY`—provide the change in mouse positions. The values of the parameters are the same as the difference between the values of `MouseEvent` properties, `screenX` and `screenY`, which are stored in two subsequent `mousemove` events, `eNow` and `ePrevious`. In other words, the Pointer lock parameter `movementX = eNow.screenX - ePrevious.screenX`.

### Locked state

When Pointer lock is enabled, the standard `MouseEvent` properties `clientX`, `clientY`, `screenX`, and `screenY` are held constant, as if the mouse is not moving. The `movementX` and `movementY` properties continue to provide the mouse's change in position. There is no limit to `movementX` and `movementY` values if the mouse is continuously moving in a single direction. The concept of the mouse cursor does not exist and the cursor cannot move off the window or be clamped by a screen edge.

### Unlocked state

The parameters `movementX` and `movementY` are valid regardless of the mouse lock state, and are available even when unlocked for convenience.

When the mouse is unlocked, the system cursor can exit and re-enter the browser window. If that happens, `movementX` and `movementY` could be set to zero.

Simple example walkthrough
--------------------------

We've written a pointer lock demo (see source code) to show you how to use it to set up a simple control system. This demo uses JavaScript to draw a ball on top of an `<canvas>` element. When you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse. Let's see how this works.

We set initial x and y positions on the canvas:

```js
let x = 50;
let y = 50;
```

Next we set up an event listener to run the `requestPointerLock()` method on the canvas when it is clicked, which initiates pointer lock. The `document.pointerLockElement` check is to see if there is already an active pointer lock — we don't want to keep calling `requestPointerLock()` on the canvas every time we click inside it if we already have pointer lock.

```js
canvas.addEventListener("click", async () => {
  if (!document.pointerLockElement) {
    await canvas.requestPointerLock({
      unadjustedMovement: true,
    });
  }
});
```

**Note:** The above snippet works in browsers that don't support the promise version of `requestPointerLock()`. See Handling promise and non-promise versions of requestPointerLock() for an explanation.

Now for the dedicated pointer lock event listener: `pointerlockchange`. When this occurs, we run a function called `lockChangeAlert()` to handle the change.

```js
document.addEventListener("pointerlockchange", lockChangeAlert, false);
```

This function checks the `pointerLockElement` property to see if it is our canvas. If so, it attached an event listener to handle the mouse movements with the `updatePosition()` function. If not, it removes the event listener again.

```js
function lockChangeAlert() {
  if (document.pointerLockElement === canvas) {
    console.log("The pointer lock status is now locked");
    document.addEventListener("mousemove", updatePosition, false);
  } else {
    console.log("The pointer lock status is now unlocked");
    document.removeEventListener("mousemove", updatePosition, false);
  }
}
```

The `updatePosition()` function updates the position of the ball on the canvas (`x` and `y`), and also includes `if ()` statements to check whether the ball has gone off the edges of the canvas. If so, it makes the ball wrap around to the opposite edge. It also includes a check whether a `requestAnimationFrame()` call has previously been made, and if so, calls it again as required, and calls the `canvasDraw()` function that updates the canvas scene. A tracker is also set up to write out the X and Y values to the screen, for reference.

```js
const tracker = document.getElementById("tracker");

let animation;
function updatePosition(e) {
  x += e.movementX;
  y += e.movementY;
  if (x > canvas.width + RADIUS) {
    x = -RADIUS;
  }
  if (y > canvas.height + RADIUS) {
    y = -RADIUS;
  }
  if (x < -RADIUS) {
    x = canvas.width + RADIUS;
  }
  if (y < -RADIUS) {
    y = canvas.height + RADIUS;
  }
  tracker.textContent = `X position: ${x}, Y position: ${y}`;

  if (!animation) {
    animation = requestAnimationFrame(() => {
      animation = null;
      canvasDraw();
    });
  }
}
```

The `canvasDraw()` function draws the ball in the current `x` and `y` positions:

```js
function canvasDraw() {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#f00";
  ctx.beginPath();
  ctx.arc(x, y, RADIUS, 0, degToRad(360), true);
  ctx.fill();
}
```

IFrame limitations
------------------

Pointer lock can only lock one `<iframe>` at a time. If you lock one `<iframe>`, you can't lock another one and transfer the target to it; pointer lock will error out. To avoid this limitation, first unlock the locked `<iframe>`, and then lock the other.

While `<iframe>` work by default, "sandboxed" `<iframe>`s block Pointer lock. To avoid this limitation, use `<iframe sandbox="allow-pointer-lock">`.

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

| Specification |
| --- |
| Pointer Lock 2.0  |

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

### api.Document.exitPointerLock

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

### api.Element.requestPointerLock

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

See also
--------

* `MouseEvent`
* `Element.requestPointerLock()`


BluetoothRemoteGATTDescriptor - Web APIs

BluetoothRemoteGATTDescriptor
=============================

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

 The `BluetoothRemoteGATTDescriptor` interface of the Web Bluetooth API provides a GATT Descriptor,
 which provides further information about a characteristic's value.

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

`BluetoothRemoteGATTDescriptor.characteristic` Read only
Experimental

 Returns the `BluetoothRemoteGATTCharacteristic` this descriptor belongs
 to.

`BluetoothRemoteGATTDescriptor.uuid` Read only
Experimental

 Returns the UUID of the characteristic descriptor, for
 example '`00002902-0000-1000-8000-00805f9b34fb`' for theClient
 Characteristic Configuration descriptor.

`BluetoothRemoteGATTDescriptor.value` Read only
Experimental

 Returns the currently cached descriptor value. This value gets updated when the
 value of the descriptor is read.

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

`BluetoothRemoteGATTDescriptor.readValue()`
Experimental

 Returns a `Promise` that resolves to
 an `ArrayBuffer` holding a duplicate of the `value` property
 if it is available and supported. Otherwise it throws an error.

`BluetoothRemoteGATTDescriptor.writeValue()`
Experimental

 Sets the value property to the bytes contained in an `ArrayBuffer` and
 returns a `Promise`.

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

| Specification |
| --- |
| Web Bluetooth # bluetoothgattdescriptor-interface |

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

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


HIDDevice - Web APIs

HIDDevice
=========

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

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

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

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

The **`HIDDevice`** interface of the `WebHID API` represents a HID Device. It provides properties for accessing information about the device, methods for opening and closing the connection, and the sending and receiving of reports.

EventTarget

HIDDeviceInstance properties
-------------------

This interface also inherits properties from `EventTarget`.

`HIDDevice.opened` Read only
Experimental

Returns a `boolean`, true if the device has an open connection.

`HIDDevice.vendorId` Read only
Experimental

Returns the vendorId of the HID device.

`HIDDevice.productId` Read only
Experimental

Returns the productID of the HID device.

`HIDDevice.productName` Read only
Experimental

Returns a string containing the product name of the HID device.

`HIDDevice.collections` Read only
Experimental

Returns an array of report formats for the HID device.

### Events

`inputreport`
Experimental

Fires when a report is sent from the device.

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

This interface also inherits methods from `EventTarget`.

`HIDDevice.open()`
Experimental

Opens a connection to this HID device, and returns a `Promise` which resolves once the connection has been successful.

`HIDDevice.close()`
Experimental

Closes the connection to this HID device, and returns a `Promise` which resolves once the connection has been closed.

`HIDDevice.forget()`
Experimental

Closes the connection to this HID device and resets access permission, and returns a `Promise` which resolves once the permission was reset.

`HIDDevice.sendReport()`
Experimental

Sends an output report to this HID Device, and returns a `Promise` which resolves once the report has been sent.

`HIDDevice.sendFeatureReport()`
Experimental

Sends a feature report to this HID device, and returns a `Promise` which resolves once the report has been sent.

`HIDDevice.receiveFeatureReport()`
Experimental

Receives a feature report from this HID device in the form of a `Promise` which resolves with a `DataView`. This allows typed access to the contents of this message.

Examples
--------

The following example demonstrates listening for an `inputreport` event that will allow the application to detect which button is pressed on a Joy-Con Right device.

```js
device.addEventListener("inputreport", (event) => {
  const { data, device, reportId } = event;

  // Handle only the Joy-Con Right device and a specific report ID.
  if (device.productId !== 0x2007 && reportId !== 0x3f) return;

  const value = data.getUint8(0);
  if (value === 0) return;

  const someButtons = { 1: "A", 2: "X", 4: "B", 8: "Y" };
  console.log(`User pressed button ${someButtons[value]}.`);
});
```

In the following example `sendFeatureReport` is used to make a device blink.

```js
const reportId = 1;
for (let i = 0; i < 10; i++) {
  // Turn off
  await device.sendFeatureReport(reportId, Uint32Array.from([0, 0]));
  await waitFor(100);
  // Turn on
  await device.sendFeatureReport(reportId, Uint32Array.from([512, 0]));
  await waitFor(100);
}
```

You can see more examples, and live demos in the article Connecting to uncommon HID devices.

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

| Specification |
| --- |
| WebHID API # dom-hiddevice |

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

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


EcdsaParams - Web APIs

EcdsaParams
===========

The **`EcdsaParams`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm.

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

`name`

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

`hash`

A string. An identifier for the digest algorithm to use. This should be one of the following:

* `SHA-256`: selects the SHA-256 algorithm.
* `SHA-384`: selects the SHA-384 algorithm.
* `SHA-512`: selects the SHA-512 algorithm.

**Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used.

Examples
--------

See the examples for `SubtleCrypto.sign()` or `SubtleCrypto.verify()`.

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

| Specification |
| --- |
| Web Cryptography API # SubtleCrypto-method-sign |
| Web Cryptography API # SubtleCrypto-method-verify |

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

Browsers that support the "ECDSA" algorithm for the `SubtleCrypto.sign()` and `SubtleCrypto.verify()` methods will support this type.

### api.SubtleCrypto.sign

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

### api.SubtleCrypto.verify

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

See also
--------

* `SubtleCrypto.sign()` and `SubtleCrypto.verify()`.


SharedStorageWorkletGlobalScope - Web APIs

SharedStorageWorkletGlobalScope
===============================

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

The **`SharedStorageWorkletGlobalScope`** interface of the Shared Storage API represents the global scope of a `SharedStorageWorklet` module.

WorkletGlobalScope

SharedStorageWorkletGlobalScopeInstance properties
-------------------

`sharedStorage`
Experimental

Contains an instance of the `WorkletSharedStorage` object, representing the shared storage for a particular origin as exposed in a worklet context.

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

`register()`
Experimental

Registers an operation defined inside the current worklet module.

Examples
--------

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

    // Return the group number
    return experimentGroup;
  }
}

register("ab-testing", SelectURLOperation);
```

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

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

| Specification |
| --- |
| Shared Storage API # sharedstorageworkletglobalscope |

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

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

See also
--------

* Shared Storage API


SVGSymbolElement - Web APIs

SVGSymbolElement
================

The **`SVGSymbolElement`** interface corresponds to the `<symbol>` element.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGSymbolElementInstance properties
-------------------

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

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

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

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

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

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

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


WorkerLocation - Web APIs

WorkerLocation
==============

The **`WorkerLocation`** interface defines the absolute location of the script executed by the `Worker`. Such an object is initialized for each worker and is available via the `WorkerGlobalScope.location` property obtained by calling `self.location`.

This interface is only visible from inside a JavaScript script executed in the context of a Web worker.

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

`WorkerLocation.href` Read only

Returns a string containing the serialized `URL` for the worker's location.

`WorkerLocation.protocol` Read only

Returns the `protocol` part of the worker's location.

`WorkerLocation.host` Read only

Returns the `host` part of the worker's location.

`WorkerLocation.hostname` Read only

Returns the `hostname` part of the worker's location.

`WorkerLocation.origin` Read only

Returns the worker's `origin`.

`WorkerLocation.port` Read only

Returns the `port` part of the worker's location.

`WorkerLocation.pathname` Read only

Returns the `pathname` part of the worker's location.

`WorkerLocation.search` Read only

Returns the `search` part of the worker's location.

`WorkerLocation.hash` Read only

Returns the `hash` part of the worker's location.

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

`WorkerLocation.toString()`

Returns a string containing the serialized `URL` for the worker's location. It is a synonym for `WorkerLocation.href`.

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

| Specification |
| --- |
| HTML Standard # worker-locations |

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

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

See also
--------

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


RsaHashedImportParams - Web APIs

RsaHashedImportParams
=====================

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

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

`name`

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

`hash`

A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`.

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

Examples
--------

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

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

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

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

Browsers that support any RSA-based algorithm for the `SubtleCrypto.importKey()` or `SubtleCrypto.unwrapKey()` methods will support this type.

See also
--------

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


HMDVRDevice - Web APIs

HMDVRDevice
===========

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

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

The **`HMDVRDevice`** interface of the WebVR API represents a head mounted display, providing access to information about each eye, and allowing us to modify the current field of view.

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

`HMDVRDevice.getEyeParameters()`
Deprecated

Non-standard

Returns current parameters for the eye specified as its argument ("left" or "right") — such as field of view information — stored in a `VREyeParameters` object.

`HMDVRDevice.setFieldOfView()`
Deprecated

Non-standard

Sets the field of view for both eyes.

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

*This interface doesn't define any properties of its own, but it does inherit the properties of its parent interface, `VRDisplay`.*

`VRDisplay.hardwareUnitId` Read only

Returns the distinct hardware ID for the overall hardware unit that this `VRDevice` is a part of. All devices that are part of the same physical piece of hardware will have the same `hardwareUnitId`.

`VRDisplay.displayId` Read only

Returns the ID for this specific `VRDevice`. The ID shouldn't change across browser restarts, allowing configuration data to be saved based on it.

`VRDisplay.displayName` Read only

A human-readable name to identify the `VRDevice`.

Examples
--------

The following example, taken from the WebVR spec, finds the first available `HMDVRDevice` and its associated `PositionSensorVRDevice`, if it has one.

```js
navigator.getVRDevices().then((devices) => {
  for (const device of devices) {
    if (device instanceof HMDVRDevice) {
      gHMD = device;
      break;
    }
  }

  if (gHMD) {
    for (const device of devices) {
      if (
        device instanceof PositionSensorVRDevice &&
        device.hardwareUnitId === gHMD.hardwareUnitId
      ) {
        gPositionSensor = devices[i];
        break;
      }
    }
  }
});
```

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

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

See also
--------

* WebVR API


CSS - Web APIs

CSS
===

The **`CSS`** interface holds useful CSS-related methods. No objects with this interface are implemented: it contains only static methods and is therefore a utilitarian interface.

Static properties
-----------------

`CSS.highlights`

Provides access to the `HighlightRegistry` used to style arbitrary text ranges using the CSS Custom Highlight API.

`CSS.paintWorklet`
Experimental
 Secure context

Provides access to the Worklet responsible for all the classes related to painting.

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

*The CSS interface is a utility interface and no object of this type can be created: only static properties are defined on it.*

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

*No inherited static methods*.

`CSS.registerProperty()`

Registers `custom properties`, allowing for property type checking, default values, and properties that do or do not inherit their value.

`CSS.supports()`

Returns a boolean value indicating if the pair *property-value*, or the condition, given in parameter is supported.

`CSS.escape()`

Can be used to escape a string mostly for use as part of a CSS selector.

`CSS factory functions`

Can be used to return a new `CSSUnitValue` with a value of the parameter number of the units of the name of the factory function method used.

```js
CSS.em(3); // CSSUnitValue {value: 3, unit: "em"}
```

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

*The CSS interface is a utility interface and no object of this type can be created: only static methods are defined on it.*

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # namespacedef-css |
| CSS Properties and Values API Level 1  |

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

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


CookieStoreManager - Web APIs

CookieStoreManager
==================

**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 **`CookieStoreManager`** interface of the Cookie Store API allows service workers to subscribe to cookie change events. Call `subscribe()` on a particular service worker registration to receive change events.

A `CookieStoreManager` has an associated `ServiceWorkerRegistration`. Each service worker registration has a cookie change subscription list, which is a list of cookie change subscriptions each containing a name and URL. The methods in this interface allow the service worker to add and remove subscriptions from this list, and to get a list of all subscriptions.

To get a `CookieStoreManager`, call `ServiceWorkerRegistration.cookies`.

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

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

`CookieStoreManager.getSubscriptions()`
Experimental

Returns a `Promise` which resolves to a list of the cookie change subscriptions for this service worker registration.

`CookieStoreManager.subscribe()`
Experimental

Subscribes to changes to cookies. It returns a `Promise` which resolves when the subscription is successful.

`CookieStoreManager.unsubscribe()`
Experimental

Unsubscribes the registered service worker from changes to cookies. It returns a `Promise` which resolves when the operation is successful.

Examples
--------

In this example, the `ServiceWorkerRegistration` represented by `registration` is subscribing to change events on the cookie named `"cookie1"` with a scope of `"/path1"`.

```js
const subscriptions = [{ name: "cookie1", url: `/path1` }];
await registration.cookies.subscribe(subscriptions);
```

If the `ServiceWorkerRegistration` has subscribed to any cookies, then `getSubscriptions()` will return a list of cookies represented by objects in the same format as used for the original subscription.

```js
const subscriptions = await self.registration.cookies.getSubscriptions();
```

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

| Specification |
| --- |
| Cookie Store API # cookiestoremanager |

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

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


HTMLUnknownElement - Web APIs

HTMLUnknownElement
==================

The **`HTMLUnknownElement`** interface represents an invalid HTML element and derives from the `HTMLElement` interface, but without implementing any additional properties or methods.

EventTarget

Node

Element

HTMLElement

HTMLUnknownElementInstance properties
-------------------

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

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

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

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

| Specification |
| --- |
| HTML Standard # htmlunknownelement |

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

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


FormData - Web APIs

FormData
========

The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the `fetch()`, `XMLHttpRequest.send()` or `navigator.sendBeacon()` methods. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`.

You can also pass it directly to the `URLSearchParams` constructor if you want to generate query parameters in the way a `<form>` would do if it were using simple `GET` submission.

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

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

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

`FormData()`

Creates a new `FormData` object.

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

`FormData.append()`

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

`FormData.delete()`

Deletes a key/value pair from a `FormData` object.

`FormData.entries()`

Returns an iterator that iterates through all key/value pairs contained in the `FormData`.

`FormData.get()`

Returns the first value associated with a given key from within a `FormData` object.

`FormData.getAll()`

Returns an array of all the values associated with a given key from within a `FormData`.

`FormData.has()`

Returns whether a `FormData` object contains a certain key.

`FormData.keys()`

Returns an iterator iterates through all keys of the key/value pairs contained in the `FormData`.

`FormData.set()`

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

`FormData.values()`

Returns an iterator that iterates through all values contained in the `FormData`.

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

| Specification |
| --- |
| XMLHttpRequest Standard # interface-formdata |

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

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

See also
--------

* Using FormData objects
* `<form>`


BluetoothRemoteGATTCharacteristic - Web APIs

BluetoothRemoteGATTCharacteristic
=================================

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

The `BluetoothRemoteGattCharacteristic` interface of the Web Bluetooth API represents a GATT Characteristic, which is a basic data element that provides further information about a peripheral's service.

EventTarget

BluetoothRemoteGATTCharacteristicInstance properties
-------------------

`BluetoothRemoteGATTCharacteristic.service` Read only
Experimental

Returns the `BluetoothRemoteGATTService` this characteristic belongs to.

`BluetoothRemoteGATTCharacteristic.uuid` Read only
Experimental

Returns a string containing the UUID of the characteristic, for example `'00002a37-0000-1000-8000-00805f9b34fb'` for the Heart Rate Measurement characteristic.

`BluetoothRemoteGATTCharacteristic.properties` Read only
Experimental

Returns the properties of this characteristic.

`BluetoothRemoteGATTCharacteristic.value` Read only
Experimental

The currently cached characteristic value. This value gets updated when the value of the characteristic is read or updated via a notification or indication.

### Events

`oncharacteristicvaluechanged`
Experimental

Event handler for the `characteristicvaluechanged` event.

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

`BluetoothRemoteGATTCharacteristic.getDescriptor()`
Experimental

Returns a `Promise` that resolves to the first `BluetoothRemoteGATTDescriptor` for a given descriptor UUID.

`BluetoothRemoteGATTCharacteristic.getDescriptors()`
Experimental

Returns a `Promise` that resolves to an `Array` of all `BluetoothRemoteGATTDescriptor` objects for a given descriptor UUID.

`BluetoothRemoteGATTCharacteristic.readValue()`
Experimental

Returns a `Promise` that resolves to an `DataView` holding a duplicate of the `value` property if it is available and supported. Otherwise it throws an error.

`BluetoothRemoteGATTCharacteristic.writeValue(value)`
Deprecated

Sets the `value` property to the bytes contained in a given `ArrayBuffer`, calls `WriteCharacteristicValue`(*this*=`this`, *value=value*, *response*=`"optional"`), and returns the resulting `Promise`.

`BluetoothRemoteGATTCharacteristic.writeValueWithResponse(value)`
Experimental

Sets the `value` property to the bytes contained in a given `ArrayBuffer`, calls `WriteCharacteristicValue`(*this*=`this`, *value=value*, *response*=`"required"`), and returns the resulting `Promise`.

`BluetoothRemoteGATTCharacteristic.writeValueWithoutResponse(value)`
Experimental

Sets the `value` property to the bytes contained in a given `ArrayBuffer`, calls `WriteCharacteristicValue`(*this*=`this`, *value=value*, *response*=`"never"`), and returns the resulting `Promise`.

`BluetoothRemoteGATTCharacteristic.startNotifications()`
Experimental

Returns a `Promise` that resolves when `navigator.bluetooth` is added to the active notification context.

`BluetoothRemoteGATTCharacteristic.stopNotifications()`
Experimental

Returns a `Promise` that resolves when `navigator.bluetooth` is removed from the active notification context.

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

| Specification |
| --- |
| Web Bluetooth # bluetoothgattcharacteristic-interface |

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

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


XRHitTestSource - Web APIs

XRHitTestSource
===============

**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 **`XRHitTestSource`** interface of the WebXR Device API handles hit test subscriptions. You can get an `XRHitTestSource` object by using the `XRSession.requestHitTestSource()` method.

This object doesn't itself contain hit test results, but it is used to compute hit tests for each `XRFrame` by calling `XRFrame.getHitTestResults()`, which returns `XRHitTestResult` objects.

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

None.

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

`XRHitTestSource.cancel()`
Experimental

Unsubscribes from the hit test.

Examples
--------

### Getting an `XRHitTestSource` object for a session

Call `XRSession.requestHitTestSource()` to get a hit test source.

```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
  requiredFeatures: ["local", "hit-test"],
});

let hitTestSource = null;

xrSession
  .requestHitTestSource({
    space: viewerSpace, // obtained from xrSession.requestReferenceSpace("viewer");
    offsetRay: new XRRay({ y: 0.5 }),
  })
  .then((viewerHitTestSource) => {
    hitTestSource = viewerHitTestSource;
  });

// frame loop
function onXRFrame(time, xrFrame) {
  let hitTestResults = xrFrame.getHitTestResults(hitTestSource);

  // do things with the hit test results
}
```

### Unsubscribe from hit test

To unsubscribe from a hit test source, call `XRHitTestSource.cancel()`. Since the object will no longer be usable, you can clean up and set the `XRHitTestSource` object to `null`.

```js
hitTestSource.cancel();
hitTestSource = null;
```

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

| Specification |
| --- |
| WebXR Hit Test Module # hit-test-source-interface |

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

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

See also
--------

* `XRTransientInputHitTestSource`


MediaKeyMessageEvent - Web APIs

MediaKeyMessageEvent
====================

The **`MediaKeyMessageEvent`** interface of the Encrypted Media Extensions API contains the content and related data when the content decryption module generates a message for the session.

Event

MediaKeyMessageEventConstructor
-----------

`MediaKeyMessageEvent()`

Creates a new instance of `MediaKeyMessageEvent`.

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

Inherits properties from its parent, `Event`.

`MediaKeyMessageEvent.message` Read only

Returns an `ArrayBuffer` with a message from the content decryption module. Messages vary by key system.

`MediaKeyMessageEvent.messageType` Read only

Indicates the type of message. May be one of `license-request`, `license-renewal`, `license-release`, or `individualization-request`.

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

Inherits methods from its parent, `Event`.

Examples
--------

```js
// TBD
```

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

| Specification |
| --- |
| Encrypted Media Extensions # mediakeymessageevent |

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

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


VREyeParameters - Web APIs

VREyeParameters
===============

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

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

The **`VREyeParameters`** interface of the WebVR API represents all the information required to correctly render a scene for a given eye, including field of view information.

**Note:** This interface was part of the old WebVR API. It has been superseded by the WebXR Device API.

This interface is accessible through the `VRDisplay.getEyeParameters()` method.

**Warning:** The values in this interface should not be used to compute view or projection matrices. In order to ensure the widest possible hardware compatibility use the matrices provided by `VRFrameData`.

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

`VREyeParameters.offset`
Deprecated
 Read only
Non-standard

Represents the offset from the center point between the user's eyes to the center of the eye, measured in meters.

`VREyeParameters.fieldOfView`
Deprecated
 Read only
Non-standard

Describes the current field of view for the eye, which can vary as the user adjusts their interpupillary distance (IPD).

`VREyeParameters.renderWidth`
Deprecated
 Read only
Non-standard

Describes the recommended render target width of each eye viewport, in pixels.

`VREyeParameters.renderHeight`
Deprecated
 Read only
Non-standard

Describes the recommended render target height of each eye viewport, in pixels.

Examples
--------

```js
navigator.getVRDisplays().then((displays) => {
  // If a display is available, use it to present the scene
  vrDisplay = displays[0];
  console.log("Display found");
  // Starting the presentation when the button is clicked:
  // It can only be called in response to a user gesture
  btn.addEventListener("click", () => {
    vrDisplay.requestPresent([{ source: canvas }]).then(() => {
      console.log("Presenting to WebVR display");

      // Set the canvas size to the size of the vrDisplay viewport

      const leftEye = vrDisplay.getEyeParameters("left");
      const rightEye = vrDisplay.getEyeParameters("right");

      canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) \* 2;
      canvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight);

      drawVRScene();
    });
  });
});
```

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

This interface was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


SVGForeignObjectElement - Web APIs

SVGForeignObjectElement
=======================

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

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGForeignObjectElementInstance properties
-------------------

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

`SVGForeignObjectElement.x` Read only

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

`SVGForeignObjectElement.y` Read only

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

`SVGForeignObjectElement.width` Read only

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

`SVGForeignObjectElement.height` Read only

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

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

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

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

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

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

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

See also
--------

* `<foreignObject>`


WEBGL_compressed_texture_s3tc extension - Web APIs

WEBGL\_compressed\_texture\_s3tc extension
==========================================

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

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

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

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

Constants
---------

The compressed texture formats are exposed by four constants and can be used in two functions: `compressedTexImage2D()` and `compressedTexSubImage2D()`.

`ext.COMPRESSED_RGB_S3TC_DXT1_EXT`

A DXT1-compressed image in an RGB image format.

`ext.COMPRESSED_RGBA_S3TC_DXT1_EXT`

A DXT1-compressed image in an RGB image format with a simple on/off alpha value.

`ext.COMPRESSED_RGBA_S3TC_DXT3_EXT`

A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.

`ext.COMPRESSED_RGBA_S3TC_DXT5_EXT`

A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done.

Examples
--------

```js
const ext =
  gl.getExtension("WEBGL\_compressed\_texture\_s3tc") ||
  gl.getExtension("MOZ\_WEBGL\_compressed\_texture\_s3tc") ||
  gl.getExtension("WEBKIT\_WEBGL\_compressed\_texture\_s3tc");

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

gl.compressedTexImage2D(
  gl.TEXTURE\_2D,
  0,
  ext.COMPRESSED\_RGBA\_S3TC\_DXT5\_EXT,
  512,
  512,
  0,
  textureData,
);

gl.texParameteri(gl.TEXTURE\_2D, gl.TEXTURE\_MAG\_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE\_2D, gl.TEXTURE\_MIN\_FILTER, gl.LINEAR);
```

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

| Specification |
| --- |
| WebGL WEBGL\_compressed\_texture\_s3tc Khronos Ratified Extension Specification  |

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

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

See also
--------

* S3 Texture Compression – OpenGL wiki
* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.compressedTexImage2D()`
* `WebGLRenderingContext.compressedTexSubImage2D()`
* `WebGLRenderingContext.getParameter()`