XRCPUDepthInformation: getDepthInMeters() method - Web APIs

XRCPUDepthInformation: getDepthInMeters() method
================================================

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

The **`getDepthInMeters()`** method of the `XRCPUDepthInformation` interface returns the depth in meters at (x, y) in normalized view coordinates (origin in the top left corner).

Syntax
------

```js
getDepthInMeters(x, y)
```

### Parameters

`x`

X coordinate (origin at the left, grows to the right).

`y`

Y coordinate (origin at the top, grows downward).

### Return value

None (`undefined`).

### Exceptions

* A `RangeError` is thrown if `x` or `y` are greater than 1.0 or less than 0.0.
Examples
--------

```js
const distance = depthInfo.getDepthInMeters(x, y);
```

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

| Specification |
| --- |
| WebXR Depth Sensing Module # dom-xrcpudepthinformation-getdepthinmeters |

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

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


GamepadButton: touched property - Web APIs

GamepadButton: touched property
===============================

 The **`touched`** property of the
 `GamepadButton` interface returns a `boolean` indicating whether
 a button capable of detecting touch is currently touched (`true`) or not touched (`false`).

If the button is not capable of detecting touch but can return an analog value, the property will be `true` if the value is greater than `0`, and `false` otherwise. If the button is not capable of detecting touch and can only report a digital value, then it should mirror the `GamepadButton.pressed` property.

Value
-----

A `Boolean`. True if touched.

Examples
--------

```js
let gp = navigator.getGamepads()[0]; // Get the first gamepad object

if (gp.buttons[0].touched) {
  // respond to button being touched
}
```

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

| Specification |
| --- |
| Gamepad # dom-gamepadbutton-touched |

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

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

See also
--------

* Using the Gamepad API


GamepadButton: value property - Web APIs

GamepadButton: value property
=============================

 The **`GamepadButton.value`** property of the
 `GamepadButton` interface returns a double value used to represent the
 current state of analog buttons on many modern gamepads, such as the triggers.

 The values are normalized to the range `0.0` — `1.0`, with
 `0.0` representing a button that is not pressed, and 1.0 representing a
 button that is fully pressed.

Examples
--------

```js
let gp = navigator.getGamepads()[0];

if (gp.buttons[0].value > 0) {
  // respond to analog button being pressed in
}
```

Value
-----

A double.

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

| Specification |
| --- |
| Gamepad # dom-gamepadbutton-value |

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

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

See also
--------

Using the Gamepad API


GamepadButton: pressed property - Web APIs

GamepadButton: pressed property
===============================

 The **`GamepadButton.pressed`** property of the
 `GamepadButton` interface returns a `boolean` indicating whether
 the button is currently pressed (`true`) or unpressed (`false`).

Examples
--------

```js
let gp = navigator.getGamepads()[0]; // Get the first gamepad object

if (gp.buttons[0].pressed) {
  // respond to button being pressed
}
```

Value
-----

A boolean value.

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

| Specification |
| --- |
| Gamepad # dom-gamepadbutton-pressed |

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

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

See also
--------

* Using the Gamepad API


SVGElement: style property - Web APIs

SVGElement: style property
==========================

The read-only **`style`** property of the `SVGElement` returns the *inline* style of an element in the form of a live `CSSStyleDeclaration` object that contains a list of all styles properties for that element with values assigned only for the attributes that are defined in the element's inline `style` attribute.

Shorthand properties are expanded. If you set `style="border-top: 1px solid black"`, the longhand properties (`border-top-color`, `border-top-style`, and `border-top-width`) are set instead.

This property is read-only, meaning it is not possible to assign a `CSSStyleDeclaration` object to it. Nevertheless, it is possible to set an inline style by assigning a *string* directly to the `style` property. In this case the string is forwarded to `CSSStyleDeclaration.cssText`. Using `style` in this manner will completely overwrite all inline styles on the element.

Therefore, to add specific styles to an element without altering other style values, it is generally preferable to set individual properties on the `CSSStyleDeclaration` object. For example, you can write `element.style.backgroundColor = "red"`.

A style declaration is reset by setting it to `null` or an empty string, e.g., `elt.style.color = null`.

**Note:** CSS property names are converted to JavaScript identifier with these rules:

* If the property is made of one word, it remains as it is: `height` stays as is (in lowercase).
* If the property is made of several words, separated by dashes, the dashes are removed and it is converted to camel case: `background-attachment` becomes `backgroundAttachment`.
* The property `float`, being a reserved JavaScript keyword, is converted to `cssFloat`.

The `style` property has the same priority in the CSS cascade as an inline style declaration set via the `style` attribute.

Value
-----

A live `CSSStyleDeclaration` object.

Examples
--------

### Getting style information

The following code snippet demonstrates how the `style` attribute is translated into a list of entries in `CSSStyleDeclaration` :

```html
<svg
 width="50"
 height="50"
 xmlns="http://www.w3.org/2000/svg"
 viewBox="0 0 250 250"
 width="250"
 height="250">
  <circle
 cx="100"
 cy="100"
 r="50"
 id="circle"
 style="fill: red; stroke: black; stroke-width: 2px;" />
</svg>
<pre id="out"></pre>
```

```js
const element = document.querySelector("circle");
const out = document.getElementById("out");
const elementStyle = element.style;

// We loop through all styles (for…of doesn't work with CSStyleDeclaration)
for (const prop in elementStyle) {
  if (Object.hasOwn(elementStyle, prop)) {
    out.textContent += `${
 elementStyle[prop]
 } = '${elementStyle.getPropertyValue(elementStyle[prop])}'\n`;
  }
}
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-elementcssinlinestyle-style |

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

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

See also
--------

* Using dynamic styling information
* `HTMLElement.style`


SVGElement: load event - Web APIs

SVGElement: load event
======================

The `load` event fires on an `SVGElement` when it is loaded in the browser, e.g. in the DOM in the case of an embedded `<svg>`. It is basically the same as the standard `load` DOM event.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("load", (event) => {});

onload = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

```js
svgElem.addEventListener("load", () => {
  console.log("SVG loaded.");
});
```

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

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

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

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


SVGElement: error event - Web APIs

SVGElement: error event
=======================

The `error` event is fired when an SVG element does not load properly or when an error occurs during script execution.

This basically implements the standard `error` DOM event.

This event is not cancelable.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("error", (event) => {});

onerror = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

```js
svgElem.addEventListener("error", () => {
  console.log("SVG not loaded properly.");
});
```

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

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

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

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


VRDisplayCapabilities: canPresent property - Web APIs

VRDisplayCapabilities: canPresent property
==========================================

**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 **`canPresent`** read-only property of the `VRDisplayCapabilities` interface returns a boolean value stating whether the VR display is capable of presenting content (e.g. through an HMD).

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

This is useful for identifying "magic window" devices that are capable of 6DoF tracking but for which `VRDisplay.requestPresent()` is not meaningful. If `canPresent` is `false`, calls to `VRDisplay.requestPresent()` will fail, and `VRDisplay.getEyeParameters()` will return `null`.

Value
-----

A boolean value.

Examples
--------

See `VRDisplayCapabilities` for example code.

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

This property 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


VRDisplayCapabilities: hasPosition property - Web APIs

VRDisplayCapabilities: hasPosition property
===========================================

**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 **`hasPosition`** read-only property of the `VRDisplayCapabilities` interface returns `true` if the VR display can track and return position information.

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

Value
-----

A boolean value.

Examples
--------

See `VRDisplayCapabilities` for example code.

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

This property 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


VRDisplayCapabilities: hasOrientation property - Web APIs

VRDisplayCapabilities: hasOrientation property
==============================================

**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 **`hasOrientation`** read-only property of the `VRDisplayCapabilities` interface returns `true` if the VR display can track and return orientation information.

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

Value
-----

A boolean value.

Examples
--------

See `VRDisplayCapabilities` for example code.

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

This property 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


VRDisplayCapabilities: hasExternalDisplay property - Web APIs

VRDisplayCapabilities: hasExternalDisplay property
==================================================

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

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

The **`hasExternalDisplay`** read-only property of the `VRDisplayCapabilities` interface returns `true` if the VR display is separate from the device's primary display.

**Note:** If presenting VR content would obscure other content on the device, this will return `false`, in which case the application should not attempt to mirror VR content or update non-VR UI because that content will not be visible.

Value
-----

A boolean value.

Examples
--------

See `VRDisplayCapabilities` for example code.

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

This property 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


VRDisplayCapabilities: maxLayers property - Web APIs

VRDisplayCapabilities: maxLayers property
=========================================

**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 **`maxLayers`** read-only property of the `VRDisplayCapabilities` interface returns a number indicating the maximum number of `VRLayerInit`s that the VR display can present at once (e.g. the maximum length of the array that `VRDisplay.requestPresent()` can accept.)

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

Value
-----

A number, which must be 1 if `VRDisplayCapabilities.canPresent` is `true`, or 0 otherwise.

Examples
--------

See `VRDisplayCapabilities` for example code.

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

This property 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


GPUOutOfMemoryError: GPUOutOfMemoryError() constructor - Web APIs

GPUOutOfMemoryError: GPUOutOfMemoryError() constructor
======================================================

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

 The **`GPUOutOfMemoryError()`** constructor creates a new
 `GPUOutOfMemoryError` object instance.

Syntax
------

```js
new GPUOutOfMemoryError(message)
```

### Parameters

`message`

A string providing a human-readable message that explains why the error occurred.

Examples
--------

A developer would not manually use the constructor to create a `GPUOutOfMemoryError` object. The user agent uses this constructor to create an appropriate object when an out-of-memory error is surfaced by `GPUDevice.popErrorScope` or the `uncapturederror` event.

See the main `GPUOutOfMemoryError` page for a specific example involving a `GPUOutOfMemoryError` object instance.

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

| Specification |
| --- |
| WebGPU # dom-gpuoutofmemoryerror-gpuoutofmemoryerror |

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

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

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices


XRCubeLayer: redraw event - Web APIs

XRCubeLayer: redraw event
=========================

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

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

See also the `XRCompositionLayer.needsRedraw` property which is also available to `XRCubeLayer` objects through inheritance from `XRCompositionLayer`.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("redraw", (event) => {});

onredraw = (event) => {};
```

Event type
----------

An `XRLayerEvent`. Inherits from `Event`.

Event properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`layer` Read only

The `XRLayer` which generated the event.

Examples
--------

### Using the `redraw` event

You can pass `redraw` to `addEventListener()`:

```js
cubeLayer.addEventListener("redraw", (event) => {
  // redraw the layer
});
```

Alternatively, you can use the `onredraw` event handler property to establish a handler for the `redraw` event:

```js
cubeLayer.onredraw = (event) => {
  // redraw the layer
};
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # eventdef-xrlayer-redraw |

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

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

See also
--------

* `XRCompositionLayer.needsRedraw`


XRCubeLayer: space property - Web APIs

XRCubeLayer: space property
===========================

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

The **`space`** property of the `XRCubeLayer` interface represents the layer's spatial relationship with the user's physical environment.

Value
-----

An `XRSpace`.

Examples
--------

### Updating the cube layer's space

The `XRWebGLBinding.createCubeLayer()` method creates a cube layer and requires a `space` property to be provided. The `XRCubeLayer.space` property can be used after layer creation to get the space used or to set it to a new one.

```js
const cubeLayer = xrGlBinding.createCubeLayer({
  space: xrReferenceSpace,
  viewPixelWidth: 512,
  viewPixelHeight: 512,
});

cubeLayer.space = someOtherSpace;
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrcubelayer-space |

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

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

See also
--------

* `XRSpace`
* `XRWebGLBinding.createCubeLayer()`


XRCubeLayer: orientation property - Web APIs

XRCubeLayer: orientation property
=================================

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

The **`orientation`** property of the `XRCubeLayer` interface represents the orientation relative to the `space` property.

Value
-----

A `DOMPointReadOnly`.

Examples
--------

### Updating the cube layer's orientation

The `XRWebGLBinding.createCubeLayer()` method creates a cube layer and allows specifying an `orientation`. The `XRCubeLayer.orientation` property can be used after layer creation to get the current orientation or to set it to a new one.

```js
const cubeLayer = xrGlBinding.createCubeLayer({
  space: xrReferenceSpace,
  viewPixelWidth: 512,
  viewPixelHeight: 512,
  orientation: DOMPointReadOnly.fromPoint({ x: 0.0, y: 0.0, z: 0.0, w: 1.0 }),
});

cubeLayer.orientation = someOtherPoint;
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrcubelayer-orientation |

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

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

See also
--------

* `DOMPointReadOnly`
* `XRSpace`
* `XRWebGLBinding.createCubeLayer()`


LinearAccelerationSensor: LinearAccelerationSensor() constructor - Web APIs

LinearAccelerationSensor: LinearAccelerationSensor() constructor
================================================================

 The **`LinearAccelerationSensor()`**
 constructor creates a new `LinearAccelerationSensor` object which
 provides on each reading the acceleration applied to the device along all three axes,
 but without the contribution of gravity.

Syntax
------

```js
new LinearAccelerationSensor()
new LinearAccelerationSensor(options)
```

### Parameters

`options` Optional

Options are as follows:

`frequency`

 The desired number of times per second a sample should
 be taken, meaning the number of times per second that the
 `reading` event will be called. A whole number or decimal may be
 used, the latter for frequencies less than a second. The actual reading frequency
 depends on device hardware and consequently may be less than requested.

`referenceFrame`

 Either `'device'` or
 `'screen'`. The default is `'device'`.

### Exceptions

`SecurityError` `DOMException`

Use of this feature was blocked by a Permissions Policy.

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

| Specification |
| --- |
| Accelerometer # dom-linearaccelerationsensor-linearaccelerationsensor |

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

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

See also
--------

* `reading` event


TrackEvent: track property - Web APIs

TrackEvent: track property
==========================

 The read-only **`track`** property of
 the `TrackEvent` interface specifies the media track object to which the
 event applies.

 The media track will be an `AudioTrack`,
 `VideoTrack`, or `TextTrack` object.

Value
-----

 An object which is one of the types `AudioTrack`,
 `VideoTrack`, or `TextTrack`, depending on the type of media
 represented by the track. This identifies the track to which the event applies.

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

| Specification |
| --- |
| HTML Standard # dom-trackevent-track-dev |

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

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


TrackEvent: TrackEvent() constructor - Web APIs

TrackEvent: TrackEvent() constructor
====================================

 The **`TrackEvent()`** constructor
 creates and returns a new `TrackEvent` object describing an event which
 occurred on a list of tracks (`AudioTrackList`,
 `VideoTrackList`, or `TextTrackList`).

Syntax
------

```js
new TrackEvent(type)
new TrackEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers set it to `addtrack` or `removetrack`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`track` Optional

 The track to which the event refers; this is `null` by default, but
 should be set to a `VideoTrack`, `AudioTrack`, or
 `TextTrack` as appropriate given the type of track.

### Return value

 A new `TrackEvent` object, initialized as described by the
 inputs to the constructor.

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

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

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

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


StylePropertyMapReadOnly: forEach() method - Web APIs

StylePropertyMapReadOnly: forEach() method
==========================================

 The **`StylePropertyMapReadOnly.forEach()`** method executes a
 provided function once for each element of `StylePropertyMapReadOnly`.

Syntax
------

```js
forEach(callbackFn)
forEach(callbackFn, thisArg)
```

### Parameters

`callbackFn`

The function to execute for each element, taking three arguments:

`currentValue`

The value of the current element being processed.

`index` Optional

The index of the current element being processed.

`array` Optional

The StylePropertyMapReadOnly that `forEach()` is being called on.

`thisArg` Optional

 Value to use as **`this`** (i.e., the reference
 `Object`) when executing `callback`.

### Return value

None (`undefined`).

Examples
--------

 Here is an example of using `forEach()` on a retrieved
 `Element.computedStyleMap()`.

```js
// get a button element
const buttonEl = document.querySelector(".example");

// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();

// forEach will allow us to run code over each prop/val pair
allComputedStyles.forEach((elem, index, arr) => {
  // code to run for each pair
});
```

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

#### No specification found

No specification data found for `api.StylePropertyMapReadOnly.forEach`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


StylePropertyMapReadOnly: entries() method - Web APIs

StylePropertyMapReadOnly: entries() method
==========================================

 The **`StylePropertyMapReadOnly.entries()`** method returns an
 array of a given object's own enumerable property `[key, value]` pairs, in
 the same order as that provided by a `for...in` loop
 (the difference being that a for-in loop enumerates properties in the prototype chain as
 well).

Syntax
------

```js
entries()
```

### Parameters

None.

### Return value

 An array of the given `StylePropertyMapReadOnly` object's own enumerable
 property `[key, value]` pairs.

Examples
--------

 Here shows an example of using `StylePropertyMapReadOnly.entries()` method
 on an elements computed styles.

```js
// grab a DOM element
const buttonEl = document.querySelector("button");

// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();

// entries returns an iterable of the items
const iterableStyles = allComputedStyles.entries();

// returns a two item array with align-content as the first item and CSSStyleValue as the second
console.log(iterableStyles.next().value);
```

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

#### No specification found

No specification data found for `api.StylePropertyMapReadOnly.entries`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


StylePropertyMapReadOnly: keys() method - Web APIs

StylePropertyMapReadOnly: keys() method
=======================================

 The **`StylePropertyMapReadOnly.keys()`** method returns a new
 *array iterator* containing the keys for each item
 in `StylePropertyMapReadOnly`

Syntax
------

```js
keys()
```

### Parameters

None.

### Return value

A new `Array`.

Examples
--------

 In this example we use the `keys()` method to be able to access the
 properties within our `Element.computedStyleMap()`.

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

// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();

// keys returns an iterable list of properties
const props = allComputedStyles.keys();
console.log(props.next().value); // returns align-content
```

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

#### No specification found

No specification data found for `api.StylePropertyMapReadOnly.keys`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


StylePropertyMapReadOnly: size property - Web APIs

StylePropertyMapReadOnly: size property
=======================================

 The **`size`** read-only property of the
 `StylePropertyMapReadOnly` interface returns an unsigned long integer
 containing the size of the `StylePropertyMapReadOnly` object.

Value
-----

An unsigned long integer.

Examples
--------

 Here we use the size property to return the total entries within the button elements
 `computedStyleMap`.

```js
// grab our element
const buttonEl = document.querySelector("button");

// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();

// use size to get the total styles within the map
const amountStyles = allComputedStyles.size;
console.log(amountStyles); // logs 338
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-stylepropertymapreadonly-size |

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

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


StylePropertyMapReadOnly: get() method - Web APIs

StylePropertyMapReadOnly: get() method
======================================

 The **`get()`** method of the
 `StylePropertyMapReadOnly` interface returns a `CSSStyleValue`
 object for the first value of the specified property.

Syntax
------

```js
get(property)
```

### Parameters

`property`

The name of the property to retrieve the value of.

### Return value

A `CSSStyleValue` object.

Examples
--------

 Let's get just a few properties and values. Let's start by creating a link inside a
 paragraph in our HTML, and adding a definition list which we will populate with
 JavaScript:

```html
<p>
  <a href="https://example.com">Link</a>
</p>
<dl id="results"></dl>
```

We add a bit of CSS, including a custom property and an inheritable property:

```css
p {
  font-weight: bold;
}
a {
  --color: red;
  color: var(--color);
}
```

 We use the Element's
 `computedStyleMap()`
 to return a *StylePropertyMapReadOnly* object. We create an array of properties
 of interest and use the StylePropertyMapReadOnly's `get()` method to get only
 those values.

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

// Retrieve all computed styles with computedStyleMap()
const styleMap = myElement.computedStyleMap();

// get the <dl> we'll be populating
const stylesList = document.querySelector("#results");

// array of properties we're interested in
const ofInterest = ["font-weight", "border-left-color", "color", "--color"];

// iterate over our properties of interest
for (const property of ofInterest) {
  // properties
  const cssProperty = document.createElement("dt");
  cssProperty.innerText = property;
  stylesList.appendChild(cssProperty);

  // values
  const cssValue = document.createElement("dd");
  // use get() to find the value
  cssValue.innerText = styleMap.get(property);
  stylesList.appendChild(cssValue);
}
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-stylepropertymapreadonly-get |

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

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

See also
--------

* CSS Typed Object Model API
* Learning Houdini: the CSS Typed Object Model


StylePropertyMapReadOnly: has() method - Web APIs

StylePropertyMapReadOnly: has() method
======================================

 The **`has()`** method of the
 `StylePropertyMapReadOnly` interface indicates whether the specified
 property is in the `StylePropertyMapReadOnly` object.

Syntax
------

```js
has(property)
```

### Parameters

`property`

The name of a property.

### Return value

A boolean value.

Examples
--------

 Here we use the `has()` method to see if the padding-top property is present
 within the button elements style attribute.

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

// find what's in the style attribute with attributeStyleMap and has()
const hasPadTop = buttonEl.attributeStyleMap.has("padding-top");

console.log(hasPadTop); // logs true if padding-top is present in style attribute
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-stylepropertymapreadonly-has |

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

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


StylePropertyMapReadOnly: values() method - Web APIs

StylePropertyMapReadOnly: values() method
=========================================

 The **`StylePropertyMapReadOnly.values()`** method returns a
 new *array iterator* containing the values for each index in the
 `StylePropertyMapReadOnly` object.

Syntax
------

```js
values()
```

### Parameters

None.

### Return value

A new `Array`.

Examples
--------

 In this example we use the `values()` method to be able to access the values
 within our `Element.computedStyleMap()`.

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

// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();

// values returns an iterable list of the CSS values
const vals = allComputedStyles.values();
console.log(vals.next().value); // returns a CSSStyleValue
```

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

#### No specification found

No specification data found for `api.StylePropertyMapReadOnly.values`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


StylePropertyMapReadOnly: getAll() method - Web APIs

StylePropertyMapReadOnly: getAll() method
=========================================

 The **`getAll()`** method of the
 `StylePropertyMapReadOnly` interface returns an array of
 `CSSStyleValue` objects containing the values for the provided property.

Syntax
------

```js
getAll(property)
```

### Parameters

`property`

The name of the property to retrieve all values of.

### Return value

An array of `CSSStyleValue` objects.

Examples
--------

 The following example uses `getAll()` with the
 `background-image` property. An `Array` is returned which
 contains an item for each background image declared.

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

// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();

// use getAll() with the background image property
const allBkImages = allComputedStyles.getAll("background-image");
console.log(allBkImages); // logs an array with each background image as an item
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-stylepropertymapreadonly-getall |

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

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


WheelEvent: deltaZ property - Web APIs

WheelEvent: deltaZ property
===========================

 The **`WheelEvent.deltaZ`** read-only property is a
 `double` representing the scroll amount along the z-axis, in the
 `WheelEvent.deltaMode` unit.

Value
-----

A number.

Examples
--------

```js
const syntheticEvent = new WheelEvent("syntheticWheel", {
  deltaZ: 4,
  deltaMode: 0,
});

console.log(syntheticEvent.deltaZ);
```

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

| Specification |
| --- |
| UI Events # dom-wheelevent-deltaz |

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

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

See also
--------

* `wheel`
* `WheelEvent`


WheelEvent: deltaY property - Web APIs

WheelEvent: deltaY property
===========================

 The **`WheelEvent.deltaY`** read-only property is a
 `double` representing the vertical scroll amount in the
 `WheelEvent.deltaMode` unit.

Value
-----

A number.

Examples
--------

```js
const syntheticEvent = new WheelEvent("syntheticWheel", {
  deltaY: 4,
  deltaMode: 0,
});

console.log(syntheticEvent.deltaY);
```

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

| Specification |
| --- |
| UI Events # dom-wheelevent-deltay |

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

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

See also
--------

* `wheel`
* `WheelEvent`


WheelEvent: deltaX property - Web APIs

WheelEvent: deltaX property
===========================

 The **`WheelEvent.deltaX`** read-only property is a
 `double` representing the horizontal scroll amount in the
 `WheelEvent.deltaMode` unit.

Value
-----

A number.

Examples
--------

```js
const syntheticEvent = new WheelEvent("syntheticWheel", {
  deltaX: 4,
  deltaMode: 0,
});

console.log(syntheticEvent.deltaX);
```

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

| Specification |
| --- |
| UI Events # dom-wheelevent-deltax |

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

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

See also
--------

* `wheel`
* `WheelEvent`


WheelEvent: WheelEvent() constructor - Web APIs

WheelEvent: WheelEvent() constructor
====================================

The **`WheelEvent()`** constructor returns a new `WheelEvent` object.

**Note:** If you construct a synthetic event using this constructor, that event will not be *trusted*, for security reasons.
 Only browser-generated `WheelEvent` objects are trusted and only trusted events trigger default actions.

Syntax
------

```js
new WheelEvent(type)
new WheelEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `wheel`.

`options` Optional

An object that, *in addition of the properties defined in `MouseEvent()`*, can have the following properties:

`deltaX` Optional

 A floating number representing the horizontal scroll amount in the `deltaMode` unit.
 It defaults to `0.0`.

`deltaY` Optional

 A floating number representing the vertical scroll amount in the `deltaMode` unit.
 It defaults to `0.0`.

`deltaZ` Optional

 A floating number representing the scroll amount for the z-axis scroll amount in the `deltaMode` unit.
 It defaults to `0.0`.

`deltaMode` Optional

An integer representing the unit of the delta values scroll amount. It defaults to `0x00`. Permitted values are:

| Constant | Value | Description |
| --- | --- | --- |
| `DOM_DELTA_PIXEL` | `0x00` | The delta values are specified in pixels. |
| `DOM_DELTA_LINE` | `0x01` | The delta values are specified in lines. |
| `DOM_DELTA_PAGE` | `0x02` | The delta values are specified in pages. |

### Return value

A new `WheelEvent` object.

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

| Specification |
| --- |
| UI Events # dom-wheelevent-wheelevent |

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

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

See also
--------

* The `WheelEvent` interface it belongs to.


WheelEvent: deltaMode property - Web APIs

WheelEvent: deltaMode property
==============================

 The **`WheelEvent.deltaMode`** read-only property returns an
 `unsigned long` representing the unit of the delta values scroll amount.
 Permitted values are:

| Constant | Value | Description |
| --- | --- | --- |
| `DOM_DELTA_PIXEL` | `0x00` | The delta values are specified in pixels. |
| `DOM_DELTA_LINE` | `0x01` | The delta values are specified in lines. |
| `DOM_DELTA_PAGE` | `0x02` | The delta values are specified in pages. |

Value
-----

An `unsigned long`.

Examples
--------

```js
const syntheticEvent = new WheelEvent("syntheticWheel", {
  deltaX: 4,
  deltaMode: 0,
});

console.log(syntheticEvent.deltaMode);
```

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

| Specification |
| --- |
| UI Events # dom-wheelevent-deltamode |

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

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

See also
--------

* `wheel`
* `WheelEvent`


PerformanceEventTiming: processingEnd property - Web APIs

PerformanceEventTiming: processingEnd property
==============================================

The read-only **`processingEnd`** property returns the time the last event handler finished executing.

It's equal to `PerformanceEventTiming.processingStart` when there are no such event handlers.

Value
-----

A `DOMHighResTimeStamp` timestamp.

Examples
--------

### Using the processingEnd property

The `processingEnd` property can be used when observing event-timing entries (`PerformanceEventTiming`). For example, to calculate input delay or event processing times.

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    // Full duration
    const duration = entry.duration;
    // Input delay (before processing event)
    const delay = entry.processingStart - entry.startTime;
    // Synchronous event processing time
    // (between start and end dispatch)
    const time = entry.processingEnd - entry.processingStart;
  });
});
// Register the observer for events
observer.observe({ type: "event", buffered: true });
```

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

| Specification |
| --- |
| Event Timing API # dom-performanceeventtiming-processingend |

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

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

See also
--------

* `PerformanceEventTiming.processingStart`


PerformanceEventTiming: target property - Web APIs

PerformanceEventTiming: target property
=======================================

The read-only **`target`** property returns the associated event's last `target` which is the node onto which the event was last dispatched.

Value
-----

A `Node` onto which the event was last dispatched.

Or `null` if the `Node` is disconnected from the document's DOM or is in the shadow DOM.

Examples
--------

### Observing events with a specific last target

The `target` property can be used when observing event-timing entries (`PerformanceEventTiming`). For example, to log and measure events for a given last target only.

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.target && entry.target.id === "myNode") {
      const delay = entry.processingStart - entry.startTime;
      console.log(entry.name, delay);
    }
  });
});

// Register the observer for events
observer.observe({ type: "event", buffered: true });
```

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

| Specification |
| --- |
| Event Timing API # dom-performanceeventtiming-target |

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

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


PerformanceEventTiming: toJSON() method - Web APIs

PerformanceEventTiming: toJSON() method
=======================================

The **`toJSON()`** method of the `PerformanceEventTiming` interface is a serializer; it returns a JSON representation of the `PerformanceEventTiming` object.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A `JSON` object that is the serialization of the `PerformanceEventTiming` object.

The JSON doesn't contain the `target` property because it is of type `Node`, which doesn't provide a `toJSON()` operation.

Examples
--------

### Using the toJSON method

In this example, calling `entry.toJSON()` returns a JSON representation of the `PerformanceEventTiming` object.

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(entry.toJSON());
  });
});

observer.observe({ type: "event", buffered: true });
```

This would log a JSON object like so:

```json
{
  "name": "dragover",
  "entryType": "event",
  "startTime": 67090751.599999905,
  "duration": 128,
  "processingStart": 67090751.70000005,
  "processingEnd": 67090751.900000095,
  "cancelable": true
}
```

To get a JSON string, you can use `JSON.stringify(entry)` directly; it will call `toJSON()` automatically.

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

| Specification |
| --- |
| Event Timing API # dom-performanceeventtiming-tojson |

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

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

See also
--------

* `JSON`


PerformanceEventTiming: processingStart property - Web APIs

PerformanceEventTiming: processingStart property
================================================

The read-only **`processingStart`** property returns the time at which event dispatch started. This is when event handlers are about to be executed.

Value
-----

A `DOMHighResTimeStamp` timestamp.

Examples
--------

### Using the processingStart property

The `processingStart` property can be used when observing event timing entries (`PerformanceEventTiming`). For example, to calculate input delay or event processing times.

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    // Full duration
    const duration = entry.duration;
    // Input delay (before processing event)
    const delay = entry.processingStart - entry.startTime;
    // Synchronous event processing time
    // (between start and end dispatch)
    const time = entry.processingEnd - entry.processingStart;
  });
});
// Register the observer for events
observer.observe({ type: "event", buffered: true });
```

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

| Specification |
| --- |
| Event Timing API # dom-performanceeventtiming-processingstart |

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

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

See also
--------

* `PerformanceEventTiming.processingEnd`


PerformanceEventTiming: interactionId property - Web APIs

PerformanceEventTiming: interactionId property
==============================================

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

The read-only **`interactionId`** property returns an ID that uniquely identifies a user interaction which triggered a series of associated events.

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

When a user interacts with a web page, a user interaction (for example a click) usually triggers a sequence of events, such as `pointerdown`, `pointerup`, and `click` events. To measure the latency of this series of events, the events share the same `interactionId`.

An `interactionId` is only computed for the following event types belonging to a user interaction. It is `0` otherwise.

| Event types | User interaction |
| --- | --- |
| `pointerdown`, `pointerup`, `click` | click / tap / drag |
| `keydown`, `keyup` | key press |

Value
-----

A number.

Examples
--------

### Using interactionId

The following example collects event duration for all events corresponding to an interaction. The `eventLatencies` map can then be used to find events with maximum duration for a user interaction, for example.

```js
// The key is the interaction ID.
let eventLatencies = {};

const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.interactionId > 0) {
      const interactionId = entry.interactionId;
      if (!eventLatencies.has(interactionId)) {
        eventLatencies[interactionId] = [];
      }
      eventLatencies[interactionId].push(entry.duration);
    }
  });
});

observer.observe({ type: "event", buffered: true });

// Log events with maximum event duration for a user interaction
Object.entries(eventLatencies).forEach(([k, v]) => {
  console.log(Math.max(...v));
});
```

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

| Specification |
| --- |
| Event Timing API # dom-performanceeventtiming-interactionid |

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

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


PerformanceEventTiming: cancelable property - Web APIs

PerformanceEventTiming: cancelable property
===========================================

The read-only **`cancelable`** property returns the associated event's `cancelable` property, indicating whether the event can be canceled.

Value
-----

A boolean. `true` if the associated event is cancelable, `false` otherwise.

Examples
--------

### Observing non-cancelable events

The `cancelable` property can be used when observing event-timing entries (`PerformanceEventTiming`). For example, to log and measure non-cancelable events only.

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (!entry.cancelable) {
      const delay = entry.processingStart - entry.startTime;
      console.log(entry.name, delay);
    }
  });
});

// Register the observer for events
observer.observe({ type: "event", buffered: true });
```

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

| Specification |
| --- |
| Event Timing API # dom-performanceeventtiming-cancelable |

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

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


VideoTrack: kind property - Web APIs

VideoTrack: kind property
=========================

 The **`kind`** property contains a
 string indicating the category of video contained in the
 **`VideoTrack`**.

 The `kind` can be used
 to determine the scenarios in which specific tracks should be enabled or disabled. See
 Video track kind strings for a list of the kinds available for video tracks.

Value
-----

 A string specifying the type of content the media represents. The
 string is one of those found in Video track kind strings below.

Video track kind strings
------------------------

The kinds available for video tracks are:

`"alternative"`

 A potential alternative to the main track, such as a different video take or a
 version of the soundtrack with only the music and no dialogue.

`"captions"`

A version of the main video track with captions burnt in.

`"main"`

The primary video track.

`"sign"`

A sign-language interpretation of an audio track.

`"subtitles"`

A version of the main video track with subtitles burnt in.

`"commentary"`

 A video track containing a commentary. This might be used to contain the director's
 commentary track on a movie, for example.

`""` (empty string)

 The track doesn't have an explicit kind, or the kind provided by the track's
 metadata isn't recognized by the user agent.

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

| Specification |
| --- |
| HTML Standard # dom-videotrack-kind-dev |

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

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


VideoTrack: id property - Web APIs

VideoTrack: id property
=======================

 The **`id`** property contains a
 string which uniquely identifies the track represented by the
 **`VideoTrack`**.

 This ID can be used with the
 `VideoTrackList.getTrackById()` method to locate a specific track within
 the media associated with a media element.

 The track ID can also be used as the fragment of a URL that loads the specific track
 (if the media supports media fragments).

Value
-----

 A string which identifies the track, suitable for use when calling
 `getTrackById()` on an
 `VideoTrackList` such as the one specified by a media element's
 `videoTracks` property.

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

| Specification |
| --- |
| HTML Standard # dom-videotrack-id-dev |

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

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


VideoTrack: selected property - Web APIs

VideoTrack: selected property
=============================

 The **`VideoTrack`** property
 **`selected`** controls whether or not a particular video
 track is active.

Value
-----

 The `selected` property is a Boolean whose value is `true` if the
 track is active. Only a single video track can be active at any given time, so setting
 this property to `true` for one track while another track is active will make
 that other track inactive.

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

| Specification |
| --- |
| HTML Standard # dom-videotrack-selected-dev |

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

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


VideoTrack: language property - Web APIs

VideoTrack: language property
=============================

 The read-only **`VideoTrack`**
 property **`language`** returns a string identifying the
 language used in the video track.

 For tracks that include multiple languages
 (such as a movie in English in which a few lines are spoken in other languages), this
 should be the video's primary language.

Value
-----

 A string specifying the BCP 47 (RFC 5646) format language tag of
 the primary language used in the video track, or an empty string (`""`) if
 the language is not specified or known, or if the track doesn't contain speech.

 For example, if the primary language used in the track is United States English, this
 value would be `"en-US"`. For Brazilian Portuguese, the value would be
 `"pt-BR"`.

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

| Specification |
| --- |
| HTML Standard # dom-videotrack-language-dev |

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

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


VideoTrack: sourceBuffer property - Web APIs

VideoTrack: sourceBuffer property
=================================

 The read-only **`VideoTrack`**
 property **`sourceBuffer`** returns the
 `SourceBuffer` that created the track, or null if the track was not
 created by a `SourceBuffer` or the `SourceBuffer` has been
 removed from the `MediaSource.sourceBuffers` attribute of its parent
 media source.

Value
-----

A `SourceBuffer` or null.

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

| Specification |
| --- |
| Media Source Extensions™ # dom-videotrack-sourcebuffer |

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

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


VideoTrack: label property - Web APIs

VideoTrack: label property
==========================

 The read-only **`VideoTrack`**
 property **`label`** returns a string specifying the video
 track's human-readable label, if one is available; otherwise, it returns an empty
 string.

Value
-----

 A string specifying the track's human-readable label, if one is
 available in the track metadata. Otherwise, an empty string (`""`) is
 returned.

 For example, a track whose `kind` is
 `"sign"` might have a `label` such as
 `"A sign-language interpretation."`.

Examples
--------

 This example returns an array of track kinds and labels for potential use in a user
 interface to select video tracks for a specified media element. The list is filtered to
 only allow certain track kinds through.

```js
function getTrackList(el) {
  const trackList = [];
  const wantedKinds = ["main", "alternative", "commentary"];

  el.videoTracks.forEach((track) => {
    if (wantedKinds.includes(track.kind)) {
      trackList.push({
        id: track.id,
        kind: track.kind,
        label: track.label,
      });
    }
  });
  return trackList;
}
```

 The resulting `trackList` contains an array of video tracks whose
 `kind` is one of those in the array `wantedKinds`, with each entry
 providing the track's `id`, `kind`, and `label`.

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

| Specification |
| --- |
| HTML Standard # dom-videotrack-label-dev |

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

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


RTCStatsReport: size property - Web APIs

RTCStatsReport: size property
=============================

The **`size`** read-only property of the `RTCStatsReport` interface returns the number of items in the current report.

Note that each item consists of a key-value pair, where the keys are unique `id` values for monitored statistics objects from which the statistics are derived, and the associated values are statistics dictionary objects.

This property is otherwise the same as `Map.prototype.size`.

Value
-----

 An integer indicating the number of items in this report.
 The value is zero if the report is empty.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcstatsreport |

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

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

See also
--------

* `Map`


RTCStatsReport: values() method - Web APIs

RTCStatsReport: values() method
===============================

The **`values()`** method of the `RTCStatsReport` interface returns a new *iterator* object that can be used to iterate through the values for each element in the `RTCStatsReport` object, in insertion order.

The values are statistics dictionary objects.

The method is otherwise the same as `Map.prototype.values()`.

Syntax
------

```js
values()
```

### Return value

A new iterable iterator object.

Examples
--------

This example shows how to iterate through a `RTCStatsReport` using the iterator returned by `values()`.

 Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code calls `getStats()` with `await` to wait for the statistics report.
 It then uses a for...of loop, with the iterator returned by `values()`, to iterate through the dictionary objects in the report.
 The properties of statistics objects with the `type` of `outbound-rtp` are logged to the console (other objects are discarded).

```js
const stats = await myPeerConnection.getStats();

for (const stat of stats.values()) {
  if (stat.type != "outbound-rtp") continue;
  Object.keys(stat).forEach((statName) => {
    console.log(`${statName}: ${report[statName]}`);
  });
}
```

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

#### No specification found

No specification data found for `api.RTCStatsReport.values`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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

See also
--------

* `Map.prototype.values()`
* `RTCStatsReport.keys()`
* `RTCStatsReport.entries()`


RTCStatsReport: keys() method - Web APIs

RTCStatsReport: keys() method
=============================

The **`keys()`** method of the `RTCStatsReport` interface returns a new *iterator* object that can be used to iterate through the keys for each element in the `RTCStatsReport` object, in insertion order.

The keys in the `RTCStatsReport` are unique string `id` values, which represent the monitored statistics objects from which the statistics are derived.

The method is otherwise the same as `Map.prototype.keys()`.

Syntax
------

```js
keys()
```

### Return value

A new iterable iterator object.

Examples
--------

This example shows how to iterate through a `RTCStatsReport` using the iterator returned by `keys()`.

 Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code calls `getStats()` with `await` to wait for the statistics report.
 It then uses a for...of loop, with the iterator returned by `keys()`, to iterate through the IDs.
 Each ID is used to get the corresponding statistics dictionary.
 The properties of statistics objects with the `type` of `outbound-rtp` are logged to the console (other objects are discarded).

```js
const stats = await myPeerConnection.getStats();

for (const id of stats.keys()) {
  // Get dictionary associated with key (id)
  const stat = stats.get(id);
  if (stat.type != "outbound-rtp") continue;
  Object.keys(stat).forEach((statName) => {
    console.log(`${statName}: ${report[statName]}`);
  });
}
```

 Note that this examples is somewhat contrived.
 You could more easily iterate with `entries()` or `values()` and not have to map the ID to a value.
 You can even iterate the `RTCStatsReport` itself, as it has the `@@iterator` method!

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcstatsreport |

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

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

See also
--------

* `Map.prototype.keys()`
* `RTCStatsReport.values()`
* `RTCStatsReport.entries()`


RTCStatsReport: entries() method - Web APIs

RTCStatsReport: entries() method
================================

The **`entries()`** method of the `RTCStatsReport` interface returns a new iterator object that can be used to iterate through the key/value pairs for each element in the `RTCStatsReport` object, in insertion order.

The keys are unique `id` values for monitored statistics objects from which the statistics are derived, and the associated values are statistics dictionary objects.

The method is otherwise the same as `Map.prototype.entries()`.

Syntax
------

```js
entries()
```

### Parameters

None.

### Return value

A new iterable iterator object.

Examples
--------

This example shows how to iterate through a `RTCStatsReport` using the iterator returned by `entries()`.

 Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code calls `getStats()` with `await` to wait for the statistics report.
 It then uses a for...of loop, with the iterator returned by `entries()`, to iterate through the entries.
 The properties of statistics objects with the `type` of `outbound-rtp` are logged to the console (other objects are discarded).

```js
const stats = await myPeerConnection.getStats();

for (const stat of stats.entries()) {
  if (stat.type != "outbound-rtp") continue;
  Object.keys(stat).forEach((statName) => {
    console.log(`${statName}: ${report[statName]}`);
  });
}
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcstatsreport |

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

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

See also
--------

* `Map.prototype.entries()`
* `RTCStatsReport.values()`
* `RTCStatsReport.keys()`


RTCStatsReport: get() method - Web APIs

RTCStatsReport: get() method
============================

The **`get()`** method of the `RTCStatsReport` interface returns a specified element from an `RTCStatsReport`.

 Elements in the `RTCStatsReport` are identified by unique `id` values, which represent the monitored statistics objects from which the statistics are derived.
 The element returned will be an instance of one of the statistics dictionary objects, and it will contain statistics for the object with the given `id`.
 The fetched value is a reference to the statistics dictionary, and any change made to that object will effectively modify it inside the `RTCStatsReport` object.

The method is otherwise the same as `Map.prototype.get()`.

Syntax
------

```js
get(id)
```

### Parameters

`id`

 A string indicating the ID of the element to return from the `RTCStatsReport` object.
 IDs are unique strings that identify the monitored object from which the corresponding statistics are derived.

### Return value

The element associated with the specified `id` key, or `undefined` if the key can't be found in the `Map` object.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcstatsreport |

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

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

See also
--------

* `Map.prototype.get()`


RTCStatsReport: [@@iterator]() method - Web APIs

RTCStatsReport: [@@iterator]() method
=====================================

 The **`[@@iterator]()`** method of the `RTCStatsReport` interface implements the iterable protocol and allows statistics reports to be consumed by most syntaxes expecting iterables, such as the spread syntax and `for...of` loops.
 It returns an iterator object that yields the key-value pairs of the report in insertion order.

The initial value of this property is the same function object as the initial value of the `RTCStatsReport.entries()` method.

The method is otherwise the same as `Map.prototype[@@iterator]()`.

Syntax
------

```js
RTCStatsReport[Symbol.iterator]()
```

### Return value

 The same return value as `RTCStatsReport.entries()`.
 This is a new iterable iterator object that yields the key-value (`id`-"statistics dictionary") pairs of the report.

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

#### No specification found

No specification data found for `api.RTCStatsReport.@@iterator`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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

See also
--------

* `RTCStatsReport.entries()`
* `Map.prototype[@@iterator]()`


RTCStatsReport: has() method - Web APIs

RTCStatsReport: has() method
============================

The **`has()`** method of the `RTCStatsReport` interface returns a boolean indicating whether a report contains a statistics dictionary with the specified id.

The method is otherwise the same as `Map.prototype.has()`.

Syntax
------

```js
has(id)
```

### Parameters

`id`

A string containing the ID of a statistics object that might be present in this `RTCStatsReport`.

### Return value

`true` if an element with the specified `id` exists in the `RTCStatsReport` object; otherwise `false`.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcstatsreport |

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

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

See also
--------

* `Map`
* `Map.prototype.set()`
* `Map.prototype.get()`


RTCStatsReport: forEach() method - Web APIs

RTCStatsReport: forEach() method
================================

The **`forEach()`** method of the `RTCStatsReport` interface executes a provided function once for each key/value pair in the `RTCStatsReport` object, in insertion order.

The keys are unique `id` values for the monitored statistics objects from which the statistics are derived, and the associated values are statistics dictionary objects.

The method is otherwise the same as `Map.prototype.forEach()`.

Syntax
------

```js
forEach(callbackFn)
forEach(callbackFn, thisArg)
```

### Parameters

`callbackFn`

 A function to execute for each entry in the report.
 The function is called with the following arguments:

`report`

 Statistics report for each iteration.
 This can be any of the statistics dictionary types.

`id`

A unique string identifying the monitored object from which the statistics are derived.

`map`

The report being iterated.

`thisArg` Optional

A value to use as `this` when executing `callbackFn`.

### Return value

`undefined`.

Examples
--------

 Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code calls `getStats()` with `await` to wait for the statistics report.
 It then iterates the report using `RTCStatsReport.forEach()`, and filters the dictionaries for just those reports that have the `type` of `inbound-rtp` and `kind` of `video`.
 For matching dictionaries it logs the `framesPerSecond` property of the inbound video.

```js
const stats = await myPeerConnection.getStats();

stats.forEach((report) => {
  if (report.type === "inbound-rtp" && report.kind === "video") {
    // Log the frame rate
    console.log(report.framesPerSecond);
  }
});
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcstatsreport |

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

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

See also
--------

* `Map.prototype.forEach()`


Scheduling: isInputPending() method - Web APIs

Scheduling: isInputPending() method
===================================

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

The **`isInputPending()`** method of the `Scheduling` interface allows you to check whether there are pending input events in the event queue, indicating that the user is attempting to interact with the page.

This feature is useful in situations where you have a queue of tasks to run, and you want to yield to the main thread regularly to allow user interaction to occur so that the app is kept as responsive and performant as possible. `isInputPending()` allows you to yield only when there is input pending, rather than having to do it at arbitrary intervals.

`isInputPending()` is called using `navigator.scheduling.isInputPending()`.

Syntax
------

```js
isInputPending()
isInputPending(options)
```

### Parameters

`options` Optional

An object providing options. Currently, the only option is:

`includeContinuous` Optional

A boolean, which is `false` by default. If set to `true`, it indicates that continuous events should be considered when checking for pending input. Continuous events are trusted events (events dispatched by the browser) that are fired successively, such as `mousemove`, `wheel`, `touchmove`, `drag`, `pointermove`, and `pointerrawupdate`.

### Return value

A boolean that indicates whether there are pending input events in the event queue (`true`) or not (`false`).

Examples
--------

We can use `isInputPending()` inside a task runner structure to run the `yield()` function only when the user is attempting to interact with the page:

```js
function yield() {
  return new Promise((resolve) => {
    setTimeout(resolve, 0);
  });
}

async function main() {
  // Create an array of functions to run
  const tasks = [a, b, c, d, e];

  while (tasks.length > 0) {
    // Yield to a pending user input
    if (navigator.scheduling.isInputPending()) {
      await yield();
    } else {
      // Shift the first task off the tasks array
      const task = tasks.shift();

      // Run the task
      task();
    }
  }
}
```

This allows you to avoid blocking the main thread when the user is actively interacting with the page, potentially providing a smoother user experience. However, by only yielding when necessary, we can continue running the current task when there are no user inputs to process. This also avoids tasks being placed at the back of the queue behind other non-essential browser-initiated tasks that were scheduled after the current one.

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

| Specification |
| --- |
| Early detection of input events # dom-scheduling-isinputpending |

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

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

See also
--------

* Faster input events with Facebook's first browser API contribution on engineering.fb.com (2019)
* Better JS scheduling with isInputPending() on developer.chrome.com (2020)
* Optimizing long tasks on web.dev (2022)


ServiceWorkerGlobalScope: activate event - Web APIs

ServiceWorkerGlobalScope: activate event
========================================

The **`activate`** event of the `ServiceWorkerGlobalScope` interface is fired when a `ServiceWorkerRegistration` acquires a new `ServiceWorkerRegistration.active` worker.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("activate", (event) => {});

onactivate = (event) => {};
```

Event type
----------

An `ExtendableEvent`. Inherits from `Event`.

Event

ExtendableEventEvent properties
----------------

*Doesn't implement any specific properties, but inherits properties from its parent, `Event`.*

Examples
--------

The following snippet shows how you could use an `activate` event handler to upgrade a cache.

```js
self.addEventListener("activate", (event) => {
  const cacheAllowlist = ["v2"];

  event.waitUntil(
    caches.forEach((cache, cacheName) => {
      if (!cacheAllowlist.includes(cacheName)) {
        return caches.delete(cacheName);
      }
    }),
  );
});
```

You can also set up the event handler using the `onactivate` property:

```js
self.onactivate = (event) => {
  // ...
};
```

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

| Specification |
| --- |
| Service Workers # service-worker-global-scope-activate-event |
| Service Workers # dom-serviceworkerglobalscope-onactivate |

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

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

See also
--------

* `install` event
* `ServiceWorkerGlobalScope`
* Service Worker API


ServiceWorkerGlobalScope: cookiechange event - Web APIs

ServiceWorkerGlobalScope: cookiechange event
============================================

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

The **`cookiechange`** event of the `ServiceWorkerGlobalScope` interface is fired when a cookie change occurs that matches the service worker's cookie change subscription list.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("cookiechange", (event) => {});

oncookiechange = (event) => {};
```

Event type
----------

An `ExtendableCookieChangeEvent`. Inherits from `ExtendableEvent`.

Event

ExtendableEvent

ExtendableCookieChangeEventSpecifications
--------------

| Specification |
| --- |
| Cookie Store API # dom-serviceworkerglobalscope-oncookiechange |

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

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


ServiceWorkerGlobalScope: backgroundfetchclick event - Web APIs

ServiceWorkerGlobalScope: backgroundfetchclick event
====================================================

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

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

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`backgroundfetchclick`** event of the `ServiceWorkerGlobalScope` interface is fired when the user clicks on the UI that the browser provides to show the user the progress of the background fetch operation.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("backgroundfetchclick", (event) => {});

onbackgroundfetchclick = (event) => {};
```

Event type
----------

A `BackgroundFetchEvent`.

Event

ExtendableEvent

BackgroundFetchEventEvent properties
----------------

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

`BackgroundFetchEvent.registration`

Returns the `BackgroundFetchRegistration` whose progress dialog the user clicked on.

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

When a background fetch operation starts, the browser shows a UI element to the user to indicate the progress of the operation. If the user clicks this element, the browser starts the service worker, if necessary, and fires the `backgroundfetchclick` event in the service worker's global scope.

A common task for the handler in this situation is to open a window giving the user more details about the fetch operation.

Examples
--------

### Opening a window with more details

This event handler uses the global `clients` property to open a window giving the user more details about the fetch. It opens a different window depending on whether the fetch has completed or not.

```js
addEventListener("backgroundfetchclick", (event) => {
  const registration = event.registration;

  if (registration.result === "success") {
    clients.openWindow("/play-movie");
  } else {
    clients.openWindow("/movie-download-progress");
  }
});
```

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

| Specification |
| --- |
| Background Fetch # dom-serviceworkerglobalscope-onbackgroundfetchclick |

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

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

See also
--------

* Background Fetch API


ServiceWorkerGlobalScope: backgroundfetchfail event - Web APIs

ServiceWorkerGlobalScope: backgroundfetchfail event
===================================================

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

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

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`backgroundfetchfail`** event of the `ServiceWorkerGlobalScope` interface is fired when a background fetch operation has failed: that is, when at least one network request in the fetch has failed to complete successfully.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("backgroundfetchfail", (event) => {});

onbackgroundfetchfail = (event) => {};
```

Event type
----------

A `BackgroundFetchUpdateUIEvent`.

Event

ExtendableEvent

BackgroundFetchEvent

BackgroundFetchUpdateUIEventEvent properties
----------------

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

`BackgroundFetchUpdateUIEvent.updateUI()`

Updates the UI of the element that the browser displays to show the progress of the fetch operation.

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

When a background fetch operation fails (meaning that at least one of the individual network requests has not completed successfully), the browser starts the service worker, if necessary, and fires the `backgroundfetchfail` event in the service worker's global scope.

In the background fetch API, the browser shows a UI element to the user to indicate the progress of the operation. In the `backgroundfetchfail` handler, the service worker can update that UI to show that the operation has failed. To do this, the handler calls the event's `updateUI()` method, passing in a new title and/or icons.

In the handler for this `backgroundfetchfail`, the service worker can also clean up any related data for the operation. It can also retrieve and store any successful responses (for example, using the `Cache` API). To access the response data, the service worker uses the event's `registration` property.

Examples
--------

### Updating UI

This event handler updates the UI to let the user know that the operation failed.

```js
addEventListener("backgroundfetchfail", (event) => {
  event.updateUI({ title: "Could not complete download" });
});
```

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

| Specification |
| --- |
| Background Fetch # dom-serviceworkerglobalscope-onbackgroundfetchfail |

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

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

See also
--------

* Background Fetch API


ServiceWorkerGlobalScope: install event - Web APIs

ServiceWorkerGlobalScope: install event
=======================================

The **`install`** event of the `ServiceWorkerGlobalScope` interface is fired when a `ServiceWorkerRegistration` acquires a new `ServiceWorkerRegistration.installing` worker.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("install", (event) => {});

oninstall = (event) => {};
```

Event type
----------

An `ExtendableEvent`. Inherits from `Event`.

Event

ExtendableEventEvent properties
----------------

*Doesn't implement any specific properties, but inherits properties from its parent, `Event`.*

Examples
--------

The following snippet shows how an `install` event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline:

```js
self.addEventListener("install", (event) => {
  event.waitUntil(
    caches
      .open("v1")
      .then((cache) =>
        cache.addAll([
          "/",
          "/index.html",
          "/style.css",
          "/app.js",
          "/image-list.js",
          "/star-wars-logo.jpg",
          "/gallery/",
          "/gallery/bountyHunters.jpg",
          "/gallery/myLittleVader.jpg",
          "/gallery/snowTroopers.jpg",
        ]),
      ),
  );
});
```

You can also set up the event handler using the `oninstall` property:

```js
self.oninstall = (event) => {
  // ...
};
```

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

| Specification |
| --- |
| Service Workers # dom-serviceworkerglobalscope-oninstall |

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

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

See also
--------

* `activate` event
* `ServiceWorkerGlobalScope`
* Service Worker API


ServiceWorkerGlobalScope: clients property - Web APIs

ServiceWorkerGlobalScope: clients property
==========================================

 The **`clients`** read-only property of the
 `ServiceWorkerGlobalScope` interface returns the `Clients`
 object associated with the service worker.

Value
-----

The `Clients` object associated with the specific worker.

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

| Specification |
| --- |
| Service Workers # service-worker-global-scope-clients |

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

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

See also
--------

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


ServiceWorkerGlobalScope: canmakepayment event - Web APIs

ServiceWorkerGlobalScope: canmakepayment event
==============================================

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

The **`canmakepayment`** event of the `ServiceWorkerGlobalScope` interface is fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls `new PaymentRequest()`.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("canmakepayment", (event) => {});

oncanmakepayment = (event) => {};
```

Event type
----------

A `CanMakePaymentEvent`. Inherits from `ExtendableEvent`.

Event

ExtendableEvent

CanMakePaymentEventExamples
--------

The `canmakepayment` event is fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls `new PaymentRequest()`. The service worker can then use the `CanMakePaymentEvent.respondWith()` method to respond appropriately:

```js
self.addEventListener("canmakepayment", (e) => {
  e.respondWith(
    new Promise((resolve, reject) => {
      someAppSpecificLogic()
        .then((result) => {
          resolve(result);
        })
        .catch((error) => {
          reject(error);
        });
    }),
  );
});
```

`respondWith()` returns a `Promise` that resolves with a boolean value to signal that the service worker is ready to handle a payment request (`true`), or not (`false`).

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

| Specification |
| --- |
| Payment Handler API # the-canmakepaymentevent |

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

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

See also
--------

* Payment Handler API
* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs

ServiceWorkerGlobalScope: pushsubscriptionchange event
======================================================

The **`pushsubscriptionchange`** event is sent to the global scope of a `ServiceWorker` to indicate a change in push subscription that was triggered outside the application's control.

This may occur if the subscription was refreshed by the browser, but it may also happen if the subscription has been revoked or lost.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("pushsubscriptionchange", (event) => {});

onpushsubscriptionchange = (event) => {};
```

Event type
----------

A generic `Event`.

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

Although examples demonstrating how to share subscription related information with the application server tend to use `fetch()`, this is not necessarily the best choice for real-world use, since it will not work if the app is offline, for example.

Consider using another method to synchronize subscription information between your service worker and the app server, or make sure your code using `fetch()` is robust enough to handle cases where attempts to exchange data fail.

**Note:** In earlier drafts of the specification, this event was defined to be sent when a `PushSubscription` has expired.

Examples
--------

This example, run in the context of a service worker, listens for a `pushsubscriptionchange` event and re-subscribes to the lapsed subscription.

```js
self.addEventListener(
  "pushsubscriptionchange",
  (event) => {
    const conv = (val) =>
      btoa(String.fromCharCode.apply(null, new Uint8Array(val)));
    const getPayload = (subscription) => ({
      endpoint: subscription.endpoint,
      publicKey: conv(subscription.getKey("p256dh")),
      authToken: conv(subscription.getKey("auth")),
    });

    const subscription = self.registration.pushManager
      .subscribe(event.oldSubscription.options)
      .then((subscription) =>
        fetch("register", {
          method: "post",
          headers: {
            "Content-type": "application/json",
          },
          body: JSON.stringify({
            old: getPayload(event.oldSubscription),
            new: getPayload(subscription),
          }),
        }),
      );
    event.waitUntil(subscription);
  },
  false,
);
```

When a `pushsubscriptionchange` event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's `subscribe()` method. When the returned promise is resolved, we receive the new subscription. This is delivered to the app server using a `fetch()` call to post a JSON formatted rendition of the subscription's `endpoint` to the app server.

You can also use the `onpushsubscriptionchange` event handler property to set up the event handler:

```js
self.onpushsubscriptionchange = (event) => {
  event.waitUntil(
    self.registration.pushManager
      .subscribe(event.oldSubscription.options)
      .then((subscription) => {
        /\* ... \*/
      }),
  );
};
```

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

| Specification |
| --- |
| Push API # the-pushsubscriptionchange-event |
| Push API # dom-serviceworkerglobalscope-onpushsubscriptionchange |

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

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

See also
--------

* Using the Push API


ServiceWorkerGlobalScope: serviceWorker property - Web APIs

ServiceWorkerGlobalScope: serviceWorker property
================================================

The **`serviceWorker`** read-only property of the `ServiceWorkerGlobalScope` interface returns a reference to the `ServiceWorker` object, which represents the service worker.

Value
-----

A `ServiceWorker` object.

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

| Specification |
| --- |
| Service Workers # dom-serviceworkerglobalscope-serviceworker |

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

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

See also
--------

* Using Service Workers


ServiceWorkerGlobalScope: notificationclose event - Web APIs

ServiceWorkerGlobalScope: notificationclose event
=================================================

The **`notificationclose`** event fires when a user closes a displayed notification spawned by `ServiceWorkerRegistration.showNotification()`.

 Notifications created on the main thread or in workers which aren't service workers
 using the `Notification()` constructor will
 instead receive a `close` event on the `Notification` object
 itself.

**Note:** Trying to create a notification inside the
 `ServiceWorkerGlobalScope` using the
 `Notification()` constructor will throw an
 error.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("notificationclose", (event) => {});

onnotificationclose = (event) => {};
```

Event type
----------

A `NotificationEvent`. Inherits from `Event`.

Event

ExtendableEvent

NotificationEventEvent properties
----------------

*Inherits properties from its ancestor, `Event`*.

`NotificationEvent.notification` Read only

Returns a `Notification` object representing the notification that was clicked to fire the event.

`NotificationEvent.action` Read only

Returns the string ID of the notification button the user clicked. This value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button.

Example
-------

```js
//Inside a service worker.
self.onnotificationclose = (event) => {
  console.log("On notification close: ", event.notification.tag);
};
```

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

| Specification |
| --- |
| Notifications API Standard # dom-serviceworkerglobalscope-onnotificationclose |

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

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


ServiceWorkerGlobalScope: cookieStore property - Web APIs

ServiceWorkerGlobalScope: cookieStore property
==============================================

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

The **`cookieStore`** read-only property of the `ServiceWorkerGlobalScope` interface returns a reference to the `CookieStore` object associated with this service worker.

Value
-----

A `CookieStore` object instance.

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

| Specification |
| --- |
| Cookie Store API # dom-serviceworkerglobalscope-cookiestore |

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

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


ServiceWorkerGlobalScope: contentdelete event - Web APIs

ServiceWorkerGlobalScope: contentdelete event
=============================================

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

The **`contentdelete`** event of the `ServiceWorkerGlobalScope` interface is fired when an item is removed from the indexed content via the user agent.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("contentdelete", (event) => {});

oncontentdelete = (event) => {};
```

Event type
----------

A `ContentIndexEvent`. Inherits from `Event`.

Event

ExtendableEvent

ContentIndexEventEvent properties
----------------

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

`id` Read only

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

Examples
--------

The following example uses a `contentdelete` event handler to remove cached content related to the deleted index item.

```js
self.addEventListener("contentdelete", (event) => {
  const deletion = caches
    .open("cache-name")
    .then((cache) =>
      Promise.all([
        cache.delete(`/icon/${event.id}`),
        cache.delete(`/content/${event.id}`),
      ]),
    );
  event.waitUntil(deletion);
});
```

You can also set up the event handler using the `oncontentdelete` property:

```js
self.oncontentdelete = (event) => {
  // ...
};
```

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

| Specification |
| --- |
| Content Index # dom-serviceworkerglobalscope-oncontentdelete |

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

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

See also
--------

* Content index API
* An introductory article on the Content Index API
* An app which uses the Content Index API to list and remove 'save for later' content


ServiceWorkerGlobalScope: periodicsync event - Web APIs

ServiceWorkerGlobalScope: periodicsync event
============================================

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

The **`periodicsync`** event of the `ServiceWorkerGlobalScope` interface is fired at timed intervals, specified when registering a `PeriodicSyncManager`.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("periodicsync", (event) => {});

onperiodicsync = (event) => {};
```

Event type
----------

A `PeriodicSyncEvent`. Inherits from `Event`.

Event

ExtendableEvent

PeriodicSyncEventEvent properties
----------------

*Inherits properties from its ancestor, `Event`*.

`PeriodicSyncEvent.tag` Read only

Returns the developer-defined identifier for this `PeriodicSyncEvent`. Multiple tags can be used by the web app to run different periodic tasks at different frequencies.

Examples
--------

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

```js
self.addEventListener("periodicsync", (event) => {
  if (event.tag === "get-latest-news") {
    event.waitUntil(fetchAndCacheLatestNews());
  }
});
```

You can also set up the event handler using the `onperiodicsync` property:

```js
self.onperiodicsync = (event) => {
  // ...
};
```

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

| Specification |
| --- |
| Web Periodic Background Synchronization # periodicsync-event |
| Web Periodic Background Synchronization # dom-serviceworkerglobalscope-onperiodicsync |

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

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

See also
--------

* Richer offline experiences with the Periodic Background Sync API
* A Periodic Background Sync demo app