File: name property - Web APIs

File: name property
===================

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

 The **`name`** read-only property of the `File` interface returns the name of the file represented by a `File` object. For security
 reasons, the path is excluded from this property.

Value
-----

A string, containing the name of the file without path, such as "My Resume.rtf".

Examples
--------

### HTML

```html
<input type="file" id="filepicker" multiple />
<div>
  <p>List of selected files:</p>
  <ul id="output"></ul>
</div>
```

### JavaScript

```js
const output = document.getElementById("output");
const filepicker = document.getElementById("filepicker");

filepicker.addEventListener("change", (event) => {
  const files = event.target.files;
  output.textContent = "";

  for (const file of files) {
    const li = document.createElement("li");
    li.textContent = file.name;
    output.appendChild(li);
  }
});
```

### Result

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

| Specification |
| --- |
| File API # dfn-name |

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

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

See also
--------

* Using files from web applications


File: File() constructor - Web APIs

File: File() constructor
========================

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

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

Syntax
------

```js
new File(fileBits, fileName)
new File(fileBits, fileName, options)
```

### Parameters

`fileBits`

 An iterable
 object such as an `Array`, having `ArrayBuffer`s,
 `TypedArray`s, `DataView`s, `Blob`s, strings,
 or a mix of any of such elements, that will be put inside the `File`.
 Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings.

`fileName`

A string representing the file name or the path to the file.

`options` Optional

 An options object containing optional attributes for the file. Available options are
 as follows:

`type` Optional

 A string representing the MIME type of the
 content that will be put into the file. Defaults to a value of `""`.

`endings` Optional

 How to interpret newline characters (`\n`) within the contents, if
 the data is text. The default value, `transparent`, copies newline
 characters into the blob without changing them. To convert newlines to the host
 system's native convention, specify the value `native`.

`lastModified` Optional

 A number representing the number of milliseconds
 between the Unix time epoch and when the file was last modified. Defaults to a
 value of `Date.now()`.

Examples
--------

```js
const file = new File(["foo"], "foo.txt", {
  type: "text/plain",
});
```

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

| Specification |
| --- |
| File API # file-constructor |

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

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

See also
--------

* `FileReader`
* `Blob`


File: webkitRelativePath property - Web APIs

File: webkitRelativePath property
=================================

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

 The **`webkitRelativePath`** read-only property of the `File` interface
 contains a string which specifies the file's path relative to the
 directory selected by the user in an `<input>` element with its
 `webkitdirectory` attribute set.

Value
-----

 A string containing the path of the file relative to the ancestor
 directory the user selected.

Example
-------

 In this example, a directory picker is presented which lets the user choose one or more
 directories. When the `change` event occurs, a list of all files contained
 within the selected directory hierarchies is generated and displayed.

### HTML

```html
<input type="file" id="filepicker" name="fileList" webkitdirectory multiple />
<output id="output"></output>
```

```
output {
  display: block;
  white-space: pre-wrap;
}
```

### JavaScript

```js
const output = document.getElementById("output");
const filepicker = document.getElementById("filepicker");

filepicker.addEventListener("change", (event) => {
  const files = event.target.files;

  for (const file of files) {
    output.textContent += `${file.webkitRelativePath}\n`;
  }
});
```

### Result

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

| Specification |
| --- |
| File and Directory Entries API # dom-file-webkitrelativepath |

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

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

See also
--------

* File and Directory Entries API
* `HTMLInputElement.webkitEntries`
* `HTMLInputElement.webkitdirectory`


File: lastModified property - Web APIs

File: lastModified property
===========================

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

 The **`lastModified`** read-only property of the `File` interface provides the
 last modified date of the file as the number of milliseconds since the Unix
 epoch (January 1, 1970 at midnight). Files without a known last modified date return the
 current date.

Value
-----

A number that represents the number of milliseconds since the Unix epoch.

Examples
--------

The example below will loop through the files you choose, and print whether each file was modified within the past year.

### HTML

```html
<input type="file" id="filepicker" name="fileList" multiple />
<output id="output"></output>
```

```
output {
  display: block;
  white-space: pre-wrap;
}
```

### JavaScript

```js
const output = document.getElementById("output");
const filepicker = document.getElementById("filepicker");

filepicker.addEventListener("change", (event) => {
  const files = event.target.files;
  const now = new Date();
  output.textContent = "";

  for (const file of files) {
    const date = new Date(file.lastModified);
    // true if the file hasn't been modified for more than 1 year
    const stale = now.getTime() - file.lastModified > 31\_536\_000\_000;
    output.textContent += `${file.name} is ${
 stale ? "stale" : "fresh"
 } (${date}).\n`;
  }
});
```

### Result

### Dynamically created files

 If a File is created dynamically, the last modified time can be supplied in the
 `new File()` constructor function. If it is missing,
 `lastModified` inherits the current time from `Date.now()` at the
 moment the `File` object gets created.

```js
const fileWithDate = new File([], "file.bin", {
  lastModified: new Date(2017, 1, 1),
});
console.log(fileWithDate.lastModified); // returns 1485903600000

const fileWithoutDate = new File([], "file.bin");
console.log(fileWithoutDate.lastModified); // returns current time
```

Reduced time precision
----------------------

 To offer protection against timing attacks and fingerprinting, the precision of
 `someFile.lastModified` might get rounded depending on browser settings.
 In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by
 default and defaults to 20us in Firefox 59; in 60 it will be 2ms.

```js
// reduced time precision (2ms) in Firefox 60
someFile.lastModified;
// 1519211809934
// 1519211810362
// 1519211811670
// …

// reduced time precision with `privacy.resistFingerprinting` enabled
someFile.lastModified;
// 1519129853500
// 1519129858900
// 1519129864400
// …
```

 In Firefox, if you enable `privacy.resistFingerprinting`, the
 precision will be 100ms or the value of
 `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever
 is larger.

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

| Specification |
| --- |
| File API # dfn-lastModified |

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

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

See also
--------

* `File`


File: lastModifiedDate property - Web APIs

File: lastModifiedDate property
===============================

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

**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 **`lastModifiedDate`** read-only property of the `File` interface returns the last modified date of the file. Files without a known last modified date return the current date.

Value
-----

A `Date` object indicating the date and time at which the file was last modified.

Examples
--------

```js
// fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput">
const fileInput = document.getElementById("myfileinput");

for (const file of fileInput.files) {
  console.log(
    `${file.name} has a last modified date of ${file.lastModifiedDate}`,
  );
}
```

Reduced time precision
----------------------

To offer protection against timing attacks and fingerprinting, the precision of `someFile.lastModifiedDate.getTime()` might get rounded depending on browser settings.

In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms.

```js
// reduced time precision (2ms) in Firefox 60
someFile.lastModifiedDate.getTime();
// 1519211809934
// 1519211810362
// 1519211811670
// …

// reduced time precision with `privacy.resistFingerprinting` enabled
someFile.lastModifiedDate.getTime();
// 1519129853500
// 1519129858900
// 1519129864400
// …
```

In Firefox, you can also enable `privacy.resistFingerprinting`, the precision will be 100ms or the value of `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever is larger.

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

*Though present in early draft of the File API spec, this property has been removed from it and is now non-standard. Use `File.lastModified` instead.*

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

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

See also
--------

* `File`


HTMLMetaElement: name property - Web APIs

HTMLMetaElement: name property
==============================

 The **`HTMLMetaElement.name`** property is used in combination with `HTMLMetaElement.content` to define the name-value pairs for the metadata of a document.
 The `name` attribute defines the metadata name and the `content` attribute defines the value.

Value
-----

A string.

Examples
--------

### Reading the metadata name of a meta element

 The following example queries the first `<meta>` element in a document.
 The `name` value is logged to the console, showing that keywords have been specified for the document:

```js
// given <meta name="keywords" content="documentation, HTML, web technologies">
let meta = document.querySelector("meta");
console.log(meta.name);
// "keywords"
```

### Creating a meta element with `author` metadata

 The following example creates a new `<meta>` element with a `name` attribute set to `author`.
 The `content` attribute sets the author of the document and the element is appended to the document `<head>`:

```js
let meta = document.createElement("meta");
meta.name = "author";
meta.content = "Franz Kafka";
document.head.appendChild(meta);
```

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

| Specification |
| --- |
| HTML Standard # dom-meta-name |

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

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

See also
--------

* `<meta>`
* Possible values for the name attribute


HTMLMetaElement: content property - Web APIs

HTMLMetaElement: content property
=================================

 The **`HTMLMetaElement.content`** property gets or sets the `content` attribute of pragma directives and named `<meta>` data in conjunction with `HTMLMetaElement.name` or `HTMLMetaElement.httpEquiv`.
 For more information, see the content attribute.

Value
-----

A string.

Examples
--------

### Reading meta element content

 The following example queries a `<meta>` element that contains a `name` attribute with the value of `keywords`.
 The `content` value is logged to the console to display the keywords of the document:

```js
// given <meta name="keywords" content="documentation, HTML, web">
let meta = document.querySelector("meta[name='keywords']");
console.log(meta.content);
// "documentation, HTML, web"
```

### Creating a meta element with content

 The following example creates a new `<meta>` element with a `name` attribute set to `description`.
 The `content` attribute sets a description of the document and is appended to the document `<head>`:

```js
let meta = document.createElement("meta");
meta.name = "description";
meta.content =
  "The <meta> element can be used to provide document metadata in terms of name-value pairs, with the name attribute giving the metadata name, and the content attribute giving the value.";
document.head.appendChild(meta);
```

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

| Specification |
| --- |
| HTML Standard # dom-meta-content |

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

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

See also
--------

* `<meta>`
* `HTMLMetaElement.name`
* `HTMLMetaElement.httpEquiv`
* Learn: Metadata in HTML


HTMLMetaElement: scheme property - Web APIs

HTMLMetaElement: scheme 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.

 The **`HTMLMetaElement.scheme`** property defines the scheme of the value in the `HTMLMetaElement.content` attribute.
 The `scheme` property was created to enable providing additional information to be used to interpret the value of the `content` property. The `scheme` property takes as its value a scheme format (i.e. `YYYY-MM-DD`) or scheme format name (i.e. `ISBN`), or a URI providing more information regarding the scheme format. The scheme defines the format of the value of the `content` attribute.
 The `scheme` content is interpreted as an extension of the element's `HTMLMetaElement.name` if a browser or user agent recognizes the scheme.

This property is deprecated and should not be used on new web pages.

Value
-----

A string.

Examples
--------

 The following example queries a `<meta>` element that contains a `name` attribute with the value of `identifier`.
 The `scheme` value is logged to the console to display the scheme of the metadata content:

```js
// given <meta name="identifier" content="1580081754" scheme="ISBN">
let meta = document.querySelector("meta[name='identifier']");
console.log(meta.scheme);
// "ISBN"
```

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

| Specification |
| --- |
| HTML Standard # dom-meta-scheme |

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

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

See also
--------

* `<meta>`


HTMLMetaElement: httpEquiv property - Web APIs

HTMLMetaElement: httpEquiv property
===================================

 The **`HTMLMetaElement.httpEquiv`** property gets or sets the pragma directive or an HTTP response header name for the `HTMLMetaElement.content` attribute.
 For more details on the possible values, see the http-equiv attribute.

Value
-----

A string.

Examples
--------

### Reading the `http-equiv` value of a meta element

 The following example queries a `<meta>` element with an `http-equiv` attribute.
 The `http-equiv` attribute is logged to the console showing a `refresh` pragma directive that instructs the browser to refresh the page after a number of seconds defined by the `content` attribute:

```js
// given <meta http-equiv="refresh" content="10" />
let meta = document.querySelector("meta[http-equiv]");
console.log(meta.httpEquiv);
// refresh
console.log(meta.content);
// 10
```

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

| Specification |
| --- |
| HTML Standard # dom-meta-httpequiv |

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

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

See also
--------

* `<meta>`


HTMLMetaElement: media property - Web APIs

HTMLMetaElement: media property
===============================

The **`HTMLMetaElement.media`** property enables specifying the media for `theme-color` metadata.

 The `theme-color` property enables setting the color of the browser's toolbar or UI in browsers and operating systems that support this property.
 The `media` property enables setting different theme colors for different `media` values.

Value
-----

A string.

Examples
--------

### Setting the theme color for dark mode

 The following example creates a new `<meta>` element with a `name` attribute set to `theme-color`.
 The `content` attribute is set to `#3c790a`, the `media` attribute is set to `prefers-color-scheme: dark`, and the element is appended to the document `<head>`.
 When a user has specified a dark mode in their operating system, the `media` property can be used to set a different `theme-color`:

```js
var meta = document.createElement("meta");
meta.name = "theme-color";
meta.content = "#3c790a";
meta.media = "(prefers-color-scheme: dark)";
document.head.appendChild(meta);
```

### Setting theme colors by device size

Most meta properties can be used only once. However, `theme-color` can be used multiple times if unique `media` values are provided.

 This example adds two meta elements with a `theme-color`; one for all devices and another for small screens.
 The order of matching the `media` query matters, so the more specific query should be added later in the document, as shown below:

```js
// Add a theme-color for all devices
meta = document.createElement("meta");
meta.name = "theme-color";
meta.content = "#ffffff";
document.head.appendChild(meta);

// Add a theme-color for small devices
var meta = document.createElement("meta");
meta.name = "theme-color";
meta.media = "(max-width: 600px)";
meta.content = "#000000";
document.head.appendChild(meta);
```

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

| Specification |
| --- |
| HTML Standard # dom-meta-media |

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

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

See also
--------

* `<meta>`
* Possible values for media queries


XRInputSourceEvent: XRInputSourceEvent() constructor - Web APIs

XRInputSourceEvent: XRInputSourceEvent() constructor
====================================================

 The **`XRInputSourceEvent()`**
 constructor creates and returns a new `XRInputSourceEvent` object
 describing an event (state change) which has occurred on a WebXR user input device
 represented by an `XRInputSource`.

Syntax
------

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

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers set it to `select`, `selectend`, `selectstart`, `squeeze`, `squeezeend`, `squeezestart`.

`options`

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

`frame`

 An `XRFrame` object representing the event frame during which the event took place.
 This event is *not* associated with the animation process, and has no viewer information contained within it.

`inputSource`

An `XRInputSource` object representing the input device from which the event is being sent.

### Return value

 A new `XRInputSourceEvent` object representing the event described by the
 given `type` and `eventInitDict`.

Examples
--------

 This example creates a new `select` event and
 sends it to the `XRSession`.

```js
let event = new XRInputSourceEvent("select", {
  frame: eventFrame,
  inputSource: source,
});
if (event) {
  xrSession.dispatchEvent(event);
}
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrinputsourceevent-xrinputsourceevent |

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

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


XRInputSourceEvent: frame property - Web APIs

XRInputSourceEvent: frame property
==================================

 The read-only `XRInputSourceEvent` property
 **`frame`** specifies an `XRFrame` object
 representing the event frame during which a WebXR user input occurred.
 This may thus be an event which occurred in the past rather than a current or impending
 event.

Value
-----

 An `XRFrame` indicating the event frame at which the user input event
 described by the object took place.

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

 The event frame does not correspond to a visual frame as is delivered to the frame
 rendering callback function (see Rendering and the WebXR frame rendering callback for details on the callback). Instead, the `XRFrame`
 specified by the `frame` property is a method to provide access to the
 `getPose()` method, which you can use to get the
 relative positions of the objects in the scene at the time the event occurred.

 However, since the event frame isn't an animation frame, there is no viewer pose
 available to represent the viewer's current point of view; the results of calling
 `getViewerPose()` will be an
 `XRViewerPose` with an empty `views`
 list.

Examples
--------

 This code shows a handler for the `selectstart` event which gets the target ray's pose from the frame, mapping the pose
 representing the ray (`event.inputSource.targetRaySpace`) to the overall
 reference space `myRefSpace`.

 Then, if the result isn't `null`, the target ray pose's transform is passed
 into a function called `myCheckAndHandleHit()` to see if the ray was pointing
 at anything when the select was triggered.

```js
xrSession.onselectstart = (event) => {
  let targetRayPose = event.frame.getPose(
    event.inputSource.targetRaySpace,
    myRefSpace,
  );
  if (targetRayPose) {
    checkAndHandleHit(targetRayPose.transform);
  }
};
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrinputsourceevent-frame |

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

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


XRInputSourceEvent: inputSource property - Web APIs

XRInputSourceEvent: inputSource property
========================================

 The `XRInputSourceEvent` interface's read-only
 **`inputSource`** property specifies the
 `XRInputSource` which generated the input event. This information
 lets you handle the event appropriately given the particulars of the user input device
 being manipulated.

Value
-----

 An `XRInputSource` object identifying the source of the user input event.
 This event indicates an action the user has taken using a WebXR input controller, such
 as a hand controller, motion sensing device, or other input apparatus.

Examples
--------

 The snippet below shows a handler for the `select` event which looks specifically for events which happen on `gaze`
 input devices. The device type is identified by looking at the
 `XRInputSource` in `inputSource` and its
 `targetRayMode` property.

```js
xrSession.onselect = (event) => {
  let source = event.inputSource;

  if (source.targetRayMode === "gaze") {
    /\* handle selection using a gaze input \*/
  }
};
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrinputsourceevent-inputsource |

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

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


ExtendableMessageEvent: origin property - Web APIs

ExtendableMessageEvent: origin property
=======================================

 The **`origin`** read-only property of the
 `ExtendableMessageEvent` interface returns the origin of the
 `Client` that sent the message.

Value
-----

A string.

Examples
--------

 When the following code is used inside a service worker to respond to a push messages
 by sending the data received via `PushMessageData` to the main context via
 a channel message, the event
 object of `onmessage` will be a `ExtendableMessageEvent`.

```js
let port;

self.addEventListener("push", (e) => {
  const obj = e.data.json();

  if (obj.action === "subscribe" || obj.action === "unsubscribe") {
    port.postMessage(obj);
  } else if (obj.action === "init" || obj.action === "chatMsg") {
    port.postMessage(obj);
  }
});

self.onmessage = (e) => {
  console.log(e.origin);
  port = e.ports[0];
};
```

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

| Specification |
| --- |
| Service Workers # extendablemessage-event-origin |

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
* Channel Messaging


ExtendableMessageEvent: source property - Web APIs

ExtendableMessageEvent: source property
=======================================

 The **`source`** read-only property of the
 `ExtendableMessageEvent` interface returns a reference to the
 `Client` object from which the message was sent.

Value
-----

 A `Client`, `ServiceWorker` or `MessagePort`
 object.

Examples
--------

 When the following code is used inside a service worker to respond to a push messages
 by sending the data received via `PushMessageData` to the main context via
 a channel message, the event
 object of `onmessage` will be a `ExtendableMessageEvent`.

```js
let port;

self.addEventListener("push", (e) => {
  const obj = e.data.json();

  if (obj.action === "subscribe" || obj.action === "unsubscribe") {
    port.postMessage(obj);
  } else if (obj.action === "init" || obj.action === "chatMsg") {
    port.postMessage(obj);
  }
});

self.onmessage = (e) => {
  console.log(e.source);
  port = e.ports[0];
};
```

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

| Specification |
| --- |
| Service Workers # extendablemessage-event-source |

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
* Channel Messaging


ExtendableMessageEvent: ExtendableMessageEvent() constructor - Web APIs

ExtendableMessageEvent: ExtendableMessageEvent() constructor
============================================================

The **`ExtendableMessageEvent()`** constructor creates a new `ExtendableMessageEvent` object.

Syntax
------

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

### Parameters

`type`

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

`options` Optional

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

`data` Optional

The event's data; this can be any data type. It defaults to `null`.

`origin` Optional

 A string that defines the origin of the corresponding service worker's environment settings object.
 It defaults to `""`.

`lastEventId` Optional

A string that defines the last event ID of the event source. It defaults to `""`.

`source` Optional

 The `Client`, `ServiceWorker` or `MessagePort` that sent the message.
 It defaults to `null`.

`ports` Optional

 An array containing the `MessagePort` objects connected to the channel sending the message.
 It defaults to an empty array.

### Return value

A new `ExtendableMessageEvent` object.

Examples
--------

```js
const options = {
  data: "hello message",
  source: MessagePortReference,
  ports: MessagePortListReference,
};

const myEME = new ExtendableMessageEvent("message", init);
```

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

| Specification |
| --- |
| Service Workers # dom-extendablemessageevent-extendablemessageevent |

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
* Channel Messaging


ExtendableMessageEvent: ports property - Web APIs

ExtendableMessageEvent: ports property
======================================

 The **`ports`** read-only property of the
 `ExtendableMessageEvent` interface returns the array containing the
 `MessagePort` objects representing the ports of the associated message
 channel (the channel the message is being sent through.)

Value
-----

An array of `MessagePort` objects.

Examples
--------

 When the following code is used inside a service worker to respond to a push messages
 by sending the data received via `PushMessageData` to the main context via
 a channel message, the event
 object of `onmessage` will be a `ExtendableMessageEvent`.

```js
let port;

self.addEventListener("push", (e) => {
  const obj = e.data.json();

  if (obj.action === "subscribe" || obj.action === "unsubscribe") {
    port.postMessage(obj);
  } else if (obj.action === "init" || obj.action === "chatMsg") {
    port.postMessage(obj);
  }
});

self.onmessage = (e) => {
  port = e.ports[0];
};
```

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

| Specification |
| --- |
| Service Workers # extendablemessage-event-ports |

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
* Channel Messaging


ExtendableMessageEvent: lastEventId property - Web APIs

ExtendableMessageEvent: lastEventId property
============================================

 The **`lastEventID`** read-only property of the
 `ExtendableMessageEvent` interface represents, in server-sent events, the last event ID of the event source. This is an empty string.

Value
-----

A string.

Examples
--------

 When the following code is used inside a service worker to respond to a push messages
 by sending the data received via `PushMessageData` to the main context via
 a channel message, the event
 object of `onmessage` will be a `ExtendableMessageEvent`.

```js
let port;

self.addEventListener("push", (e) => {
  const obj = e.data.json();

  if (obj.action === "subscribe" || obj.action === "unsubscribe") {
    port.postMessage(obj);
  } else if (obj.action === "init" || obj.action === "chatMsg") {
    port.postMessage(obj);
  }
});

self.onmessage = (e) => {
  console.log(e.lastEventId);
  port = e.ports[0];
};
```

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

| Specification |
| --- |
| Service Workers # extendablemessage-event-lasteventid |

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
* Channel Messaging


ExtendableMessageEvent: data property - Web APIs

ExtendableMessageEvent: data property
=====================================

 The **`data`** read-only property of the
 `ExtendableMessageEvent` interface returns the event's data. It can be any
 data type.

Value
-----

Any data type.

Examples
--------

 When the following code is used inside a service worker to respond to a push messages
 by sending the data received via `PushMessageData` to the main context via
 a channel message, the event
 object of `onmessage` will be a `ExtendableMessageEvent`.

```js
let port;

self.addEventListener("push", (e) => {
  const obj = e.data.json();

  if (obj.action === "subscribe" || obj.action === "unsubscribe") {
    port.postMessage(obj);
  } else if (obj.action === "init" || obj.action === "chatMsg") {
    port.postMessage(obj);
  }
});

self.onmessage = (e) => {
  console.log(e.data);
  port = e.ports[0];
};
```

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

| Specification |
| --- |
| Service Workers # extendablemessage-event-data |

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
* Channel Messaging


SharedStorageWorkletGlobalScope: register() method - Web APIs

SharedStorageWorkletGlobalScope: register() method
==================================================

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

 The **`register()`** method of the
 `SharedStorageWorkletGlobalScope` interface registers an operation defined inside the current worklet module.

Syntax
------

```js
register(name, operationCtor)
```

### Parameters

`name`

A string representing the name with which you want to register the operation. When the operation is invoked (say via `WindowSharedStorage.run()` or `WindowSharedStorage.selectURL()`), this name is used to identify the operation you want to run.

`operationCtor`

A string representing the class name of the operation to be registered. This is the class constructor that is invoked when the operation is run.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown if:

* An operation has already been registered with the specified name.
* The `operationCtor` is not a valid constructor.
* The class does not contain a valid `run()` method.
* The worklet module has not been added with `SharedStorageWorklet.addModule()`.

Examples
--------

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

    // Return the group number
    return experimentGroup;
  }
}

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

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

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

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

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

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

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

See also
--------

* Shared Storage API


SharedStorageWorkletGlobalScope: sharedStorage property - Web APIs

SharedStorageWorkletGlobalScope: sharedStorage property
=======================================================

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

 The **`context`** read-only property of the
 `SharedStorageWorkletGlobalScope` interface contains a `WorkletSharedStorage` object instance, which represents the shared storage for a particular origin as exposed to a worklet context.

Value
-----

A `WorkletSharedStorage` object instance.

Examples
--------

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

    // Return the group number
    return experimentGroup;
  }
}

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

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

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

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

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

See also
--------

* Shared Storage API


XRTransientInputHitTestSource: cancel() method - Web APIs

XRTransientInputHitTestSource: cancel() method
==============================================

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

The **`cancel()`** method of the `XRTransientInputHitTestSource` interface unsubscribes a transient input hit test.

Syntax
------

```js
cancel()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Unsubscribe from hit test

The `cancel()` method unsubscribes from a transient input hit test source. Since the `XRTransientInputHitTestSource` object will no longer be usable, you can clean up and set it to `null`.

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

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

| Specification |
| --- |
| WebXR Hit Test Module # dom-xrtransientinputhittestsource-cancel |

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

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


Keyboard: getLayoutMap() method - Web APIs

Keyboard: getLayoutMap() method
===============================

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

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

 The **`getLayoutMap()`** method of the
 `Keyboard` interface returns a `Promise` that resolves with
 an instance of `KeyboardLayoutMap` which is a map-like object with
 functions for retrieving the strings associated with specific physical keys.

Syntax
------

```js
getLayoutMap()
```

### Parameters

None.

### Return value

 A `Promise` that resolves with an instance of
 `KeyboardLayoutMap`.

### Exceptions

`SecurityError` `DOMException`

Thrown if the call is blocked by a permission policy.

Examples
--------

 The following example demonstrates how to get the location- or layout-specific string
 associated with the key that corresponds to the 'W' key on an English QWERTY keyboard.

```js
const keyboard = navigator.keyboard;
keyboard.getLayoutMap().then((keyboardLayoutMap) => {
  const upKey = keyboardLayoutMap.get("KeyW");
  window.alert(`Press ${upKey} to move up.`);
});
```

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

| Specification |
| --- |
| Keyboard Map # h-keyboard-getlayoutmap |

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

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


Keyboard: unlock() method - Web APIs

Keyboard: unlock() method
=========================

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

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

 The **`unlock()`** method of the
 `Keyboard` interface unlocks all keys captured by the
 `Keyboard.lock()` method and returns synchronously.

Syntax
------

```js
unlock()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Keyboard Lock # h-keyboard-unlock |

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

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


Keyboard: lock() method - Web APIs

Keyboard: lock() method
=======================

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

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

 The **`lock()`** method of the
 `Keyboard` interface returns a `Promise` after enabling the
 capture of keypresses for any or all of the keys on the physical keyboard. This method
 can only capture keys that are granted access by the underlying operating
 system.

 If `lock()` is called multiple times then only the key codes specified in the most recent call will be locked.
 Any keys locked by a previous call to `lock()` are unlocked.

Syntax
------

```js
lock()
lock(keyCodes)
```

### Parameters

`keyCodes` Optional

 An `Array` of one or more key codes to lock. If no keycodes are provided
 all keys will be locked. A list of valid code values is found in the UI Events KeyboardEvent code Values spec.

### Return value

A `Promise` that resolves with `undefined` when the lock was successful.

### Exceptions

`AbortError` `DOMException`

Thrown if a new call to `lock()` is made before the current one has finished.

`InvalidAccessError` `DOMException`

Thrown if any key in `keyCodes` is not a valid key code attribute value.

`InvalidStateError` `DOMException`

Thrown if `lock()` is not called in an active top-level browsing context.

Security
--------

Transient user activation is required. The user has to interact with the page or a UI element in order for this feature to work.

Examples
--------

### Capturing all keys

The following example captures all keypresses.

```js
navigator.keyboard.lock();
```

### Capturing specific keys

 The following example captures the "W", "A", "S", and "D" keys. It captures these keys
 regardless of which modifiers are used with the key press. Assuming a standard US QWERTY
 layout, registering `"KeyW"` ensures that "W", Shift+"W", Control+"W",
 Control+Shift+"W", and all other key modifier combinations with "W" are sent to the app.
 The same applies to for `"KeyA"`, `"KeyS"` and
 `"KeyD"`.

```js
navigator.keyboard.lock(["KeyW", "KeyA", "KeyS", "KeyD"]);
```

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

| Specification |
| --- |
| Keyboard Lock # h-keyboard-lock |

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

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


TextEncoder: encode() method - Web APIs

TextEncoder: encode() method
============================

The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object.

Syntax
------

```js
encode(string)
```

### Parameters

`string`

A string containing the text to encode.

### Return value

A `Uint8Array` object.

Examples
--------

```html
<p class="source">This is a sample paragraph.</p>
<p class="result">Encoded result:</p>
```

```js
const sourcePara = document.querySelector(".source");
const resultPara = document.querySelector(".result");
const string = sourcePara.textContent;

const textEncoder = new TextEncoder();

let encoded = textEncoder.encode(string);
resultPara.textContent += encoded;
```

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

| Specification |
| --- |
| Encoding Standard # ref-for-dom-textencoder-encode① |

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

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

See also
--------

* The `TextEncoder` interface it belongs to.


TextEncoder: encodeInto() method - Web APIs

TextEncoder: encodeInto() method
================================

 The **`TextEncoder.encodeInto()`** method takes a
 string to encode and a destination `Uint8Array` to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the
 progress of the encoding.
 This is potentially more performant than the older `encode()` method — especially when the target buffer is a view into a Wasm heap.

Syntax
------

```js
encodeInto(string, uint8Array)
```

### Parameters

`string`

A string containing the text to encode.

`uint8Array`

A `Uint8Array` object instance to place the resulting UTF-8 encoded text into.

### Return value

An object, which contains two members:

`read`

 The number of UTF-16 units of code from the source that has been converted over to UTF-8.
 This may be less than `string.length` if `uint8Array` did not have enough space.

`written`

 The number of bytes modified in the destination `Uint8Array`.
 The bytes written are guaranteed to form complete UTF-8 byte sequences.

Encode into a specific position
-------------------------------

*encoder*`.encodeInto()` always puts its output at the start of the array.
 However, it is sometimes useful to make the output start at a particular index.
 The solution is `TypedArray.prototype.subarray()`:

```js
const encoder = new TextEncoder();

function encodeIntoAtPosition(string, u8array, position) {
  return encoder.encodeInto(
    string,
    position ? u8array.subarray(position | 0) : u8array,
  );
}

const u8array = new Uint8Array(8);
encodeIntoAtPosition("hello", u8array, 2);
console.log(u8array.join()); // 0,0,104,101,108,108,111,0
```

Buffer sizing
-------------

 To convert a JavaScript string `s`, the output space needed for full conversion is never less than `s.length` bytes and never greater than `s.length * 3` bytes.
 If the output allocation (typically within Wasm heap) is expected to be short-lived, it makes sense to allocate `s.length * 3` bytes for the output, in which case the first conversion attempt is guaranteed to convert the whole string.
 Note that the `s.length * 3` is rare because the string would have to be packed with some of the few characters that expand into 3 bytes.
 It is unlikely that long text will exceed `s.length * 2` bytes in length.
 Thus, a more optimistic approach might be to allocate `s.length * 2 + 5` bytes, and perform reallocation in the rare circumstance that the optimistic prediction was wrong.

 If the output is expected to be long-lived, it makes sense to compute minimum allocation `roundUpToBucketSize(s.length)`, the maximum allocation size `s.length * 3`, and to have a chosen (as a tradeoff between memory usage and speed) threshold `t` such that if `roundUpToBucketSize(s.length) + t >= s.length * 3`, you allocate for `s.length * 3`.
 Otherwise, first allocate for `roundUpToBucketSize(s.length)` and convert.
 If the `read` item it the return dictionary is `s.length`, the conversion is done.
 If not, reallocate the target buffer to `written + (s.length - read) * 3` and then convert the rest by taking a substring of `s` starting from index `read` and a subbuffer of the target buffer starting from index `written`.

 Above `roundUpToBucketSize()` is a function that rounds up to the allocator bucket size.
 For example, if your Wasm allocator is known to use power-of-two buckets, `roundUpToBucketSize()` should return the argument if it is a power-of-two or the next power-of-two otherwise.
 If the behavior of the Wasm allocator is unknown, `roundUpToBucketSize()` should be an identity function.

 If the behavior of your allocator is unknown, you might want to have up to two reallocation steps and make the first reallocation step multiply the *remaining unconverted* length by two instead of three.
 However, in that case, it makes sense not to implement the usual multiplying by two of the *already written* buffer length, because in such a case if a second reallocation happened, it would always over-allocate compared to the original length times three.
 The above advice assumes that you don't need to allocate space for a zero terminator.
 That is, on the Wasm side you are working with Rust strings or a non-zero-terminating C++ class.
 If you are working with C++ `std::string`, even though the logical length is shown to you, you need to take the extra terminator byte into account when computing rounding up to allocator bucket size.
 See the next section about C strings.

No Zero-termination
-------------------

 If the input string contains the character U+0000 in the input, `encodeInto()` will write a 0x00 byte in the output.
 `encodeInto()` *does not* write a C-style 0x00 sentinel byte after the logical output.

 If your Wasm program uses C strings, it's your responsibility to write the `0x00` sentinel and you can't prevent your Wasm program from seeing a logically truncated string if the JavaScript string contained `U+0000`.
 Observe:

```js
const encoder = new TextEncoder();

function encodeIntoWithSentinel(string, u8array, position) {
  const stats = encoder.encodeInto(
    string,
    position ? u8array.subarray(position | 0) : u8array,
  );
  if (stats.written < u8array.length) u8array[stats.written] = 0; // append null if room
  return stats;
}
```

Examples
--------

```html
<p class="source">This is a sample paragraph.</p>
<p class="result"></p>
```

```js
const sourcePara = document.querySelector(".source");
const resultPara = document.querySelector(".result");
const string = sourcePara.textContent;

const textEncoder = new TextEncoder();
const utf8 = new Uint8Array(string.length);

const encodedResults = textEncoder.encodeInto(string, utf8);
resultPara.textContent +=
  `Bytes read: ${encodedResults.read}` +
  ` | Bytes written: ${encodedResults.written}` +
  ` | Encoded result: ${utf8}`;
```

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

| Specification |
| --- |
| Encoding Standard # ref-for-dom-textencoder-encodeinto① |

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

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

See also
--------

* The `TextEncoder` interface it belongs to.
* `TextEncoder.encode()`


TextEncoder: TextEncoder() constructor - Web APIs

TextEncoder: TextEncoder() constructor
======================================

The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding.

Syntax
------

```js
new TextEncoder()
```

### Parameters

None.

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

| Specification |
| --- |
| Encoding Standard # ref-for-dom-textencoder① |

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

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

See also
--------

* The `TextEncoder` interface it belongs to.


TextEncoder: encoding property - Web APIs

TextEncoder: encoding property
==============================

The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder.

It can only have the following value `utf-8`.

Value
-----

A string with the value `utf-8`.

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

| Specification |
| --- |
| Encoding Standard # dom-textencoder-encoding |

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

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

See also
--------

* The `TextEncoder` interface it belongs to.


Credential: id property - Web APIs

Credential: id property
=======================

 The **`id`** property of the
 `Credential` interface returns a string containing the
 credential's identifier. This might be any one of a GUID, username, or email
 address.

Value
-----

A string containing the credential's identifier.

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

| Specification |
| --- |
| Credential Management Level 1 # dom-credential-id |

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

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


Credential: type property - Web APIs

Credential: type property
=========================

 The **`type`** property of the
 `Credential` interface returns a string containing the
 credential's type. Valid values are `password`, `federated` and
 `public-key`.

Value
-----

A string contains a credential's given name.

Examples
--------

```js
// TBD
```

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

| Specification |
| --- |
| Credential Management Level 1 # dom-credential-type |

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

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


IdleDetector: change event - Web APIs

IdleDetector: change 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
**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

The **`change`** event of the `IdleDetector` interface fires when the value of `userState` or `screenState` has changed.

Syntax
------

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

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

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

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

A generic `Event`.

Example
-------

In the following example, the `change` callback prints the status of `userState` and `screenState` to the console.

```js
idleDetector.addEventListener("change", () => {
  const userState = idleDetector.userState;
  const screenState = idleDetector.screenState;
  console.log(`Idle change: ${userState}, ${screenState}.`);
});
```

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

| Specification |
| --- |
| Idle Detection API # api-idledetector-onchange |

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

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


IdleDetector: requestPermission() static method - Web APIs

IdleDetector: requestPermission() static method
===============================================

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

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

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

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

 The **`requestPermission()`** static method of the `IdleDetector`
 interface returns a `Promise` that resolves with a string when the user has chosen
 whether to grant the origin access to their idle state. Resolves with
 `"granted"` on acceptance and `"denied"` on refusal.

Syntax
------

```js
IdleDetector.requestPermission()
```

### Parameters

None.

### Return value

A `Promise` that resolves with `"granted"` or `"denied"`.

Security
--------

Transient user activation is required. The user has to interact with the page or a UI element in order for this feature to work.

Examples
--------

The following example uses a `click` event on a button to trigger requesting the user for permission to detect when user is idle.

```js
startButton.addEventListener("click", async () => {
  if ((await IdleDetector.requestPermission()) !== "granted") {
    console.error("Idle detection permission denied.");
    return;
  }
});
```

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

| Specification |
| --- |
| Idle Detection API # api-idledetector-requestpermission |

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

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


IdleDetector: start() method - Web APIs

IdleDetector: start() method
============================

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

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

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

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

 The **`start()`** method of the `IdleDetector` interface returns a
 `Promise` that resolves when the detector starts listening for changes in the
 user's idle state. This
 method takes an optional `options` object with the `threshold` in milliseconds
 where inactivity should be reported and `signal` for an `AbortSignal` to abort
 the idle detector.

Syntax
------

```js
start()
start(options)
```

### Parameters

`options` Optional

An object with the following properties:

`threshold`

The minimum number of idle milliseconds before reporting should begin.

`signal`

A reference to an `AbortSignal` instance allowing you to abort idle detection.

### Return value

A `Promise`.

### Exceptions

`NotAllowedError` `DOMException`

Use of this feature was blocked by a Permissions Policy.

Examples
--------

The following example shows how to start idle detection using the `options` argument. It retrieves an instance of `AbortSignal` from an instance of `AbortController`.

```js
const controller = new AbortController();
const signal = controller.signal;

await idleDetector.start({
  threshold: 60\_000,
  signal,
});
console.log("IdleDetector is active.");
```

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

| Specification |
| --- |
| Idle Detection API # api-idledetector-start |

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

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


IdleDetector: screenState property - Web APIs

IdleDetector: screenState property
==================================

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

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

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

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

 The **`screenState`** read-only property of the `IdleDetector` interface
 returns a string indicating whether the screen is locked, one of `"locked"` or
 `"unlocked"`.

Value
-----

Either `"locked"` or `"unlocked"` if `IdleDetector.start()` has been called, or `null` otherwise.

Examples
--------

In the following example, the `change` callback prints the status of `userState` and `screenState` to the console.

```js
idleDetector.addEventListener("change", () => {
  const userState = idleDetector.userState;
  const screenState = idleDetector.screenState;
  console.log(`Idle change: ${userState}, ${screenState}.`);
});
```

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

| Specification |
| --- |
| Idle Detection API # api-idledetector-screenstate |

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

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


IdleDetector: IdleDetector() constructor - Web APIs

IdleDetector: IdleDetector() constructor
========================================

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

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

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

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

 The **`IdleDetector()`** constructor creates a new `IdleDetector`
 object which provides events indicating when the user is no longer interacting
 with their device or the screen has locked.

Syntax
------

```js
new IdleDetector()
```

### Parameters

None.

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

| Specification |
| --- |
| Idle Detection API # dom-idledetector-idledetector |

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

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


IdleDetector: userState property - Web APIs

IdleDetector: userState property
================================

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

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

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

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

The **`userState`** read-only property of the `IdleDetector` interface returns a string indicating whether the user has interacted with the device since the call to `start()`.

Value
-----

Either `"active"` or `"idle"` if `IdleDetector.start()` has been called, or `null` otherwise.

Examples
--------

In the following example, the `change` callback prints the status of `userState` and `screenState` to the console.

```js
idleDetector.addEventListener("change", () => {
  const userState = idleDetector.userState;
  const screenState = idleDetector.screenState;
  console.log(`Idle change: ${userState}, ${screenState}.`);
});
```

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

| Specification |
| --- |
| Idle Detection API # api-idledetector-userstate |

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

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


GPU: wgslLanguageFeatures property - Web APIs

GPU: wgslLanguageFeatures property
==================================

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

 The **`wgslLanguageFeatures`** read-only property of the
 `GPU` interface returns a `WGSLLanguageFeatures` object that reports the WGSL language extensions supported by the WebGPU implementation.

**Note:** Not all WGSL language extensions are available to WebGPU in all browsers that support the API. We recommend you thoroughly test any extensions you choose to use.

Value
-----

A `WGSLLanguageFeatures` object instance. This is a setlike object.

Examples
--------

```js
if (!navigator.gpu) {
  throw Error("WebGPU not supported.");
}

const wgslFeatures = navigator.gpu.wgslLanguageFeatures;

// Return the size of the set
console.log(wgslFeatures.size);

// Iterate through all the set values using values()
const valueIterator = wgslFeatures.values();
for (const value of valueIterator) {
  console.log(value);
}

// ...
```

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

| Specification |
| --- |
| WebGPU # dom-gpu-wgsllanguagefeatures |

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

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

See also
--------

* WebGPU API


GPU: getPreferredCanvasFormat() method - Web APIs

GPU: getPreferredCanvasFormat() method
======================================

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

 The **`getPreferredCanvasFormat()`** method of the
 `GPU` interface returns the optimal canvas texture format for displaying 8-bit depth, standard dynamic range content on the current system.

This is commonly used to provide a `GPUCanvasContext.configure()` call with the optimal `format` value for the current system. This is recommended — if you don't use the preferred format when configuring the canvas context, you may incur additional overhead, such as additional texture copies, depending on the platform.

Syntax
------

```js
getPreferredCanvasFormat()
```

### Parameters

None.

### Return value

A string indicating a canvas texture format. The value can be `rgba8unorm` or `bgra8unorm`.

### Exceptions

None.

Examples
--------

```js
const canvas = document.querySelector("#gpuCanvas");
const context = canvas.getContext("webgpu");

context.configure({
  device: device,
  format: navigator.gpu.getPreferredCanvasFormat(),
  alphaMode: "premultiplied",
});
```

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

| Specification |
| --- |
| WebGPU # dom-gpu-getpreferredcanvasformat |

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

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

See also
--------

* The WebGPU API


GPU: requestAdapter() method - Web APIs

GPU: requestAdapter() method
============================

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

 The **`requestAdapter()`** method of the
 `GPU` interface returns a `Promise` that fulfills with a `GPUAdapter` object instance. From this you can request a `GPUDevice`, adapter info, features, and limits.

Note that the user agent chooses whether to return an adapter. If so, it chooses according to the provided options. If no options are provided, the device will provide access to the default adapter, which is usually good enough for most purposes.

Syntax
------

```js
requestAdapter()
requestAdapter(options)
```

### Parameters

`options` Optional

An object containing the following properties:

`powerPreference` Optional

An enumerated value that can be used to provide a hint to the user agent indicating what class of adapter should be chosen from the system's available adapters. Available values are:

* `undefined` (or not specified), which provides no hint.
* `"low-power"`, which provides a hint to prioritize power savings over performance. If your app runs OK with this setting, it is recommended to use it, as it can significantly improve battery life on portable devices. This is usually the default if no options are provided.
* `"high-performance"`, which provides a hint to prioritize performance over power consumption. You are encouraged to only specify this value if absolutely necessary, since it may significantly decrease battery life on portable devices. It may also result in increased `GPUDevice` loss — the system will sometimes elect to switch to a lower-power adapter to save power.

This hint's primary purpose is to influence which GPU is used in a multi-GPU system. For instance, some laptops have a low-power integrated GPU and a high-performance discrete GPU. Different factors may affect which adapter is returned including battery status, attached displays, or removable GPUs.

**Note:** On Chrome running on dual-GPU macOS devices, if `requestAdapter()` is called without a `powerPreference` option, the high-performance discrete GPU is returned when the user's device is on AC power. Otherwise, the low-power integrated GPU is returned.

### Fallback adapters

The adapter provided by the user agent may be a **fallback adapter**, if it determines it to be the most appropriate option available. A fallback adapter generally has significant performance caveats in exchange for some combination of wider compatibility, more predictable behavior, or improved privacy. For example, some browsers may offer a software-based implementation of the API via a fallback adapter. A fallback adapter will not be available on every system.

If you wish to prevent your apps from running on fallback adapters, you should check the `GPUAdapter.isFallbackAdapter` attribute prior to requesting a `GPUDevice`.

**Note:** The specification includes a `forceFallbackAdapter` option for `requestAdapter()`. This is a boolean that, if set to `true`, forces the user agent to return a fallback adapter if one is available. This is not yet supported by any browser.

### Return value

A `Promise` that fulfills with a `GPUAdapter` object instance if the request is successful.

`requestAdapter()` will resolve to `null` if an appropriate adapter is not available.

### Exceptions

None.

Examples
--------

```js
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const device = await adapter.requestDevice();

  //...
}
```

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

| Specification |
| --- |
| WebGPU # dom-gpu-requestadapter |

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

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

See also
--------

* The WebGPU API


SpeechRecognitionAlternative: transcript property - Web APIs

SpeechRecognitionAlternative: transcript property
=================================================

 The **`transcript`** read-only property of the
 `SpeechRecognitionResult` interface returns a string containing the
 transcript of the recognized word(s).

 For continuous recognition, leading or trailing whitespace will be included where
 necessary so that concatenation of consecutive `SpeechRecognitionResult`s
 produces a proper transcript of the session.

Value
-----

A string.

Examples
--------

 This code is excerpted from our
 Speech color changer example.

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

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognitionalternative-transcript |

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

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

See also
--------

* Web Speech API


SpeechRecognitionAlternative: confidence property - Web APIs

SpeechRecognitionAlternative: confidence property
=================================================

 The **`confidence`** read-only property of the
 `SpeechRecognitionResult` interface returns a numeric estimate of how
 confident the speech recognition system is that the recognition is correct.

**Note:** Mozilla's implementation of `confidence` is still
 being worked on — at the moment, it always seems to return 1.

Value
-----

A number between 0 and 1.

Examples
--------

 This code is excerpted from our
 Speech color changer example.

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

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognitionalternative-confidence |

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

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

See also
--------

* Web Speech API


RTCSessionDescription: sdp property - Web APIs

RTCSessionDescription: sdp property
===================================

 The property **`RTCSessionDescription.sdp`** is a read-only
 string containing the SDP which describes the session.

Syntax
------

```js
const value = sessionDescription.sdp
sessionDescription.sdp = value
```

### Value

The value is a string containing an SDP message like this one:
```

v=0
o=alice 2890844526 2890844526 IN IP4 host.anywhere.com
s=
c=IN IP4 host.anywhere.com
t=0 0
m=audio 49170 RTP/AVP 0
a=rtpmap:0 PCMU/8000
m=video 51372 RTP/AVP 31
a=rtpmap:31 H261/90000
m=video 53000 RTP/AVP 32
a=rtpmap:32 MPV/90000
```

Example
-------

```js
// The remote description has been set previously on pc, an RTCPeerConnection

alert(pc.remoteDescription.sdp);
```

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

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

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

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

See also
--------

* WebRTC
* The standard for using SDP in an offer/answer protocol RFC 3264.


RTCSessionDescription: RTCSessionDescription() constructor - Web APIs

RTCSessionDescription: RTCSessionDescription() constructor
==========================================================

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

 The **`RTCSessionDescription()`** constructor creates a new
 `RTCSessionDescription` with its properties initialized as described in the
 specified object.

**Note:** This constructor has been deprecated because
 `RTCPeerConnection.setLocalDescription()` and other methods which take
 SDP as input now directly accept an object conforming to the
 `RTCSessionDescriptionInit` dictionary, so you don't have to instantiate an
 `RTCSessionDescription` yourself.

Syntax
------

```js
new RTCSessionDescription(options)
```

### Values

`options` Optional

 An object providing the default values for the session description; the object
 conforms to the `RTCSessionDescriptionInit` dictionary. That dictionary has
 the following properties:

`type`

**Required.** A string which is used to set the `type` property of the new `RTCSessionDescription` object.

`sdp`

A string containing a SDP message describing the session. This value is an empty string (`""`) by default and may not be `null`.

Example
-------

 This example uses the constructor to convert an SDP offer into an
 `RTCSessionDescription` object.

**Note:** This is no longer necessary, however;
 `RTCPeerConnection.setLocalDescription()` and other methods which take
 SDP as input now directly accept an object conforming to the
 `RTCSessionDescriptionInit` dictionary, so you don't have to instantiate an
 `RTCSessionDescription` yourself.

```js
navigator.getUserMedia({ video: true }, (stream) => {
  pc.onaddstream({ stream });
  // Adding a local stream won't trigger the onaddstream callback
  pc.addStream(stream);

  pc.createOffer((offer) => {
    pc.setLocalDescription(
      new RTCSessionDescription(offer),
      () => {
        // send the offer to a server to be forwarded to the friend you're calling.
      },
      error,
    );
  }, error);
});
```

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

This feature is not part of any current specification. It is no longer on track to become a standard.

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

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

See also
--------

* WebRTC API
* `RTCSessionDescription`


RTCSessionDescription: toJSON() method - Web APIs

RTCSessionDescription: toJSON() method
======================================

 The **`RTCSessionDescription.toJSON()`** method generates a
 JSON description of the object. Both properties,
 `type` and
 `sdp`, are contained in the generated JSON.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A `JSON` object containing the following properties:

`type`

One of the following: `"offer"`, `"answer"`, `"pranswer"` or `null`.

`sdp`

Either `null` or the SDP message string corresponding to `RTCSessionDescription.sdp` property.

Example
-------

```js
// sd is a RTCSessionDescriptor

alert(JSON.stringify(sd)); // This call the toJSON() method behind the scene.
```

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

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

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

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

See also
--------

* WebRTC


RTCSessionDescription: type property - Web APIs

RTCSessionDescription: type property
====================================

 The property **`RTCSessionDescription.type`** is a read-only
 string value which describes the description's type.

Syntax
------

```js
const value = sessionDescription.type
sessionDescription.type = value
```

### Value

The possible values are:

`"answer"`

The SDP contained in the `sdp` property is the definitive choice in the exchange. In other words, this session description describes the agreed-upon configuration, and is being sent to finalize negotiation.

`"offer"`

The session description object describes the initial proposal in an offer/answer exchange. The session negotiation process begins with an offer being sent from the caller to the callee.

`"pranswer"`

The session description object describes a provisional answer; that is, a response to a previous offer that is not the final answer. It is usually employed by legacy hardware.

`"rollback"`

This special type with an empty session description is used to roll back to the previous stable state.

Example
-------

```js
// The remote description has been set previously on pc, a RTCPeerConnection

alert(pc.remoteDescription.type);
```

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

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

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

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

See also
--------

* WebRTC


HTMLSlotElement: name property - Web APIs

HTMLSlotElement: name property
==============================

 The **`name`** property of the `HTMLSlotElement`
 interface returns or sets the slot name. A slot is a placeholder inside a web component
 that users can fill with their own markup.

Value
-----

A string.

Examples
--------

The following snippet is taken from our slotchange example (See it live).

```js
let slots = this.shadowRoot.querySelectorAll("slot");
slots[1].addEventListener("slotchange", (e) => {
  let nodes = slots[1].assignedNodes();
  console.log(
    `Element in Slot "${slots[1].name}" changed to "${nodes[0].outerHTML}".`,
  );
});
```

 Here we grab references to all the slots, then add a slotchange event listener to the
 2nd slot in the template — which is the one that keeps having its contents changed in
 the example.

 Every time the element inserted in the slot changes, we log a report to the console
 saying which slot has changed, and what the new node inside the slot is.

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

| Specification |
| --- |
| HTML Standard # dom-slot-name-dev |

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

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


HTMLSlotElement: assign() method - Web APIs

HTMLSlotElement: assign() method
================================

The **`assign()`** method of the `HTMLSlotElement` interface sets the slot's *manually assigned nodes* to an ordered set of slottables. The manually assigned nodes set is initially empty until nodes are assigned using `assign()`.

**Note:** you cannot mix manually (imperative) and named (declarative, automatic) slot assignments. Therefore, for this method to work, the shadow tree needs to have been created with the `slotAssignment: "manual"` option.

Syntax
------

```js
assign(node1)
assign(node1, node2)
assign(node1, node2, /\* …, \*/ nodeN)
```

### Parameters

`node1`, …, `nodeN`

A set of `Element` or `Text` nodes.

### Return value

None (`undefined`).

### Exceptions

* `NotAllowedError` `DOMException`
 -: Thrown when calling this method on an automatically assigned slot.
Examples
--------

In the example below, the `assign()` method is used to display the correct tab in a tabbed application. The function is called and passed the panel to show, which is then assigned to the slot.

```js
function UpdateDisplayTab(elem, tabIdx) {
  const shadow = elem.shadowRoot;
  const slot = shadow.querySelector("slot");
  const panels = elem.querySelectorAll("tab-panel");
  if (panels.length && tabIdx && tabIdx <= panels.length) {
    slot.assign(panels[tabIdx - 1]);
  } else {
    slot.assign();
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-slot-assign |

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

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

See also
--------

* `Element.attachShadow()`


HTMLSlotElement: assignedElements() method - Web APIs

HTMLSlotElement: assignedElements() method
==========================================

 The **`assignedElements()`** method of the `HTMLSlotElement`
 interface returns a sequence of the elements assigned to this slot (and no
 other nodes).

If the `flatten` option is set to `true`, it returns a sequence of both the elements assigned to this slot, as well as the elements assigned to any other slots that are descendants of this slot. If no assigned elements are found, it returns the slot's fallback content.

Syntax
------

```js
assignedElements()
assignedElements(options)
```

### Parameters

`options` Optional

An object that sets options for the nodes to be returned. The available options are:

`flatten`

 A boolean value indicating whether to return the
 assigned elements of any available child `<slot>` elements
 (`true`) or not (`false`). Defaults to `false`.

### Return value

An array of elements.

Examples
--------

```js
let slots = this.shadowRoot.querySelector("slot");
let elements = slots.assignedElements({ flatten: true });
```

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

| Specification |
| --- |
| HTML Standard # dom-slot-assignedelements-dev |

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

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


HTMLSlotElement: assignedNodes() method - Web APIs

HTMLSlotElement: assignedNodes() method
=======================================

The **`assignedNodes()`** method of the `HTMLSlotElement` interface returns a sequence of the nodes assigned to this slot.

If the `flatten` option is set to `true`, it returns a sequence of both the nodes assigned to this slot, as well as the nodes assigned to any other slots that are descendants of this slot. If no assigned nodes are found, it returns the slot's fallback content.

Syntax
------

```js
assignedNodes()
assignedNodes(options)
```

### Parameters

`options` Optional

An object that sets options for the nodes to be returned. The available options are:

`flatten`

A boolean value indicating whether to return the assigned nodes of any available child `<slot>` elements (`true`) or not (`false`). Defaults to `false`.

### Return value

An array of nodes.

Examples
--------

The following snippet is taken from our slotchange example (See it live).

```js
let slots = this.shadowRoot.querySelectorAll("slot");
slots[1].addEventListener("slotchange", (e) => {
  let nodes = slots[1].assignedNodes();
  console.log(
    `Element in Slot "${slots[1].name}" changed to "${nodes[0].outerHTML}".`,
  );
});
```

 Here we grab references to all the slots, then add a slotchange event listener to the
 2nd slot in the template — which is the one that keeps having its contents changed in
 the example.

 Every time the element inserted in the slot changes, we log a report to the console
 saying which slot has changed, and what the new node inside the slot is.

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

| Specification |
| --- |
| HTML Standard # dom-slot-assignednodes-dev |

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

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


HTMLSlotElement: slotchange event - Web APIs

HTMLSlotElement: slotchange event
=================================

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

* Learn more
* See full compatibility
* Report feedback
The **`slotchange`** event is fired on an `HTMLSlotElement` instance (`<slot>` element) when the node(s) contained in that slot change.

**Note:** the `slotchange` event doesn't fire if the children of a slotted node change — only if you change (e.g. add or delete) the actual nodes themselves.

In order to trigger a **slotchange** event, one has to set or remove the `slot` attribute.

This event is not cancelable.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

```js
element.setAttribute("slot", slotName);
// element.assignedSlot = $slot
element.removeAttribute("slot");
// element.assignedSlot = null
```

The following snippet is taken from our slotchange example (see it live also).

```js
let slots = this.shadowRoot.querySelectorAll("slot");
slots[1].addEventListener("slotchange", (e) => {
  let nodes = slots[1].assignedNodes();
  console.log(
    `Element in Slot "${slots[1].name}" changed to "${nodes[0].outerHTML}".`,
  );
});
```

Here we grab references to all the `<slot>`s, then add a `slotchange` event listener to the template's second slot — which is the one which has its contents changed in the example.

Every time the element inserted in the slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.

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

| Specification |
| --- |
| DOM Standard # eventdef-htmlslotelement-slotchange |
| HTML Standard # handler-onslotchange |

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

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

See also
--------

`HTMLSlotElement`


HTMLProgressElement: labels property - Web APIs

HTMLProgressElement: labels property
====================================

 The **`HTMLProgressElement.labels`** read-only property returns
 a `NodeList` of the `<label>` elements associated with the
 `<progress>` element.

Value
-----

 A `NodeList` containing the `<label>` elements associated
 with the `<progress>` element.

Examples
--------

### HTML

```html
<label id="label1" for="test">Label 1</label>
<progress id="test" value="70" max="100">70%</progress>
<label id="label2" for="test">Label 2</label>
```

### JavaScript

```js
window.addEventListener("DOMContentLoaded", () => {
  const progress = document.getElementById("test");
  for (const label of progress.labels) {
    console.log(label.textContent); // "Label 1" and "Label 2"
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-lfe-labels-dev |

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

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


ChannelMergerNode: ChannelMergerNode() constructor - Web APIs

ChannelMergerNode: ChannelMergerNode() constructor
==================================================

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

Syntax
------

```js
new ChannelMergerNode(context)
new ChannelMergerNode(context, options)
```

### Parameters

`context`

A `BaseAudioContext` representing the audio context you want the node to be associated with.

`options` Optional

An object defining the properties you want the `ChannelMergerNode` to have:

`numberOfInputs` Optional

A number defining the number of inputs the `ChannelMergerNode` should have. If not specified, the default value used is 6.

`channelCount` Optional

 An integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node.
 (See `AudioNode.channelCount` for more information.)
 Its usage and precise definition depend on the value of `channelCountMode`.

`channelCountMode` Optional

 A string describing the way channels must be matched between
 the node's inputs and outputs. (See `AudioNode.channelCountMode` for more
 information including default values.)

`channelInterpretation` Optional

 A string describing the meaning of the channels.
 This interpretation will define how audio
 up-mixing and down-mixing will happen.
 The possible values are `"speakers"` or `"discrete"`.
 (See `AudioNode.channelCountMode` for more information including default values.)

### Return value

A new `ChannelMergerNode` object instance.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if an option such as `channelCount` or `channelCountMode` has been given an invalid value.

Examples
--------

```js
const ac = new AudioContext();

const options = {
  numberOfInputs: 2,
};

const myMerger = new ChannelMergerNode(ac, options);
```

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

| Specification |
| --- |
| Web Audio API # dom-channelmergernode-constructor-channelmergernode |

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

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


CSSValueList: length property - Web APIs

CSSValueList: length 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.

 The **`length`** read-only property of the
 `CSSValueList` interface represents the number of `CSSValue`s
 in the list. The range of valid values of the indices is `0` to
 `length-1` inclusive.

**Note:** This property was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do
 not implement it.

To achieve your purpose, you can use:

* the untyped CSS Object Model, widely supported, or
* the modern CSS Typed Object Model API, less supported and considered experimental.

Value
-----

An `unsigned long` representing the number of `CSSValue`s.

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

 This feature was originally defined in the DOM Style Level 2 specification, but has been dropped from any
 standardization effort since then.

It has been superseded by a modern, but incompatible, CSS Typed Object Model API that is now on the standard track.

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

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


CSSValueList: item() method - Web APIs

CSSValueList: item() method
===========================

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

 The **`item()`** method of the `CSSValueList`
 interface is used to retrieve a `CSSValue` by ordinal index.

 The order in this collection represents the order of the values in the CSS style
 property. If the index is greater than or equal to the number of values in the list,
 this method returns `null`.

**Note:** This method was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do
 not implement it.

To achieve your purpose, you can use:

* the untyped CSS Object Model, widely supported, or
* the modern CSS Typed Object Model API, less supported and considered experimental.

Syntax
------

```js
item(index)
```

### Parameters

`index`

 An `unsigned long` representing the index of the CSS value within the
 collection.

### Return value

 A `CSSValue` object at the `index` position in the
 `CSSValueList`, or `null` if that is not a valid index.

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

 This feature was originally defined in the DOM Style Level 2 specification, but has been dropped from any
 standardization effort since then.

It has been superseded by a modern, but incompatible, CSS Typed Object Model API that is now on the standard track.

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

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


GamepadPose: angularAcceleration property - Web APIs

GamepadPose: angularAcceleration property
=========================================

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

The **`angularAcceleration`** read-only property of the `GamepadPose` interface returns an array representing the angular acceleration vector of the `Gamepad`, in meters per second per second.

In other words, the current acceleration of the sensor's rotation around the `x`, `y`, and `z` axes.

Value
-----

A `Float32Array`, or `null` if the gamepad is not able to provide angular acceleration information.

Examples
--------

TBD

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

| Specification |
| --- |
| Gamepad Extensions # dom-gamepadpose-angularacceleration |

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

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

See also
--------

* WebVR API
* Gamepad API


GamepadPose: linearVelocity property - Web APIs

GamepadPose: linearVelocity property
====================================

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

The **`linearVelocity`** read-only property of the `GamepadPose` interface returns an array representing the linear velocity vector of the `Gamepad`, in meters per second.

In other words, the current velocity at which the sensor is moving along the `x`, `y`, and `z` axes.

Value
-----

A `Float32Array`, or `null` if the gamepad is not able to provide linear velocity data.

Examples
--------

TBD

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

| Specification |
| --- |
| Gamepad Extensions # dom-gamepadpose-linearvelocity |

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

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

See also
--------

* WebVR API
* Gamepad API


GamepadPose: linearAcceleration property - Web APIs

GamepadPose: linearAcceleration property
========================================

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

The **`linearAcceleration`** read-only property of the `GamepadPose` interface returns an array representing the linear acceleration vector of the `Gamepad`, in meters per second per second.

In other words, the current acceleration of the sensor, along the `x`, `y`, and `z` axes.

Value
-----

A `Float32Array`, or `null` if the gamepad is not able to provide linear acceleration data.

Examples
--------

TBD

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

| Specification |
| --- |
| Gamepad Extensions # dom-gamepadpose-linearacceleration |

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

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

See also
--------

* WebVR API
* Gamepad API


GamepadPose: position property - Web APIs

GamepadPose: position property
==============================

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

The **`position`** read-only property of the `GamepadPose` interface returns the position of the `Gamepad` as a 3D vector.

The coordinate system is as follows:

* Positive X is to the user's right.
* Positive Y is up.
* Positive Z is behind the user.

Positions are measured in meters from an origin point — this point is the position the sensor was first read at.

Value
-----

A `Float32Array`, or `null` if the gamepad is not able to provide position data.

**Note:** User agents may provide emulated position values through certain techniques; when doing so they should still report `GamepadPose.hasPosition` as false.

Examples
--------

TBD

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

| Specification |
| --- |
| Gamepad Extensions # dom-gamepadpose-position |

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

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

See also
--------

* WebVR API
* Gamepad API


GamepadPose: angularVelocity property - Web APIs

GamepadPose: angularVelocity property
=====================================

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

The **`angularVelocity`** read-only property of the `GamepadPose` interface returns an array representing the angular velocity vector of the `Gamepad`, in radians per second.

In other words, the current velocity at which the sensor is rotating around the `x`, `y`, and `z` axes.

Value
-----

A `Float32Array`, or `null` if the gamepad is not able to provide angular velocity information.

Examples
--------

TBD

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

| Specification |
| --- |
| Gamepad Extensions # dom-gamepadpose-angularvelocity |

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

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

See also
--------

* WebVR API
* Gamepad API


GamepadPose: hasPosition property - Web APIs

GamepadPose: hasPosition property
=================================

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

The **`hasPosition`** read-only property of the `GamepadPose` interface returns a boolean value stating whether the `Gamepad` can track and return position information.

Value
-----

A boolean value.

Examples
--------

TBD

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

| Specification |
| --- |
| Gamepad Extensions # dom-gamepadpose-hasposition |

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

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

See also
--------

* WebVR API
* Gamepad API