PaymentRequestEvent - Web APIs

PaymentRequestEvent
===================

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

The **`PaymentRequestEvent`** interface of the Payment Handler API is the object passed to a payment handler when a `PaymentRequest` is made.

Event

ExtendableEvent

PaymentRequestEventConstructor
-----------

`PaymentRequestEvent()`
Experimental

Creates a new `PaymentRequestEvent` object instance.

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

`instrumentKey` Read only
Deprecated

Non-standard

Returns an object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument.

`methodData` Read only
Experimental

Returns an array of objects containing payment method identifiers for the payment methods that the website accepts and any associated payment method specific data.

`modifiers` Read only
Experimental

Returns an array of objects containing changes to payment details.

`paymentRequestId` Read only
Experimental

Returns the ID of the `PaymentRequest` object.

`paymentRequestOrigin` Read only
Experimental

Returns the origin where the `PaymentRequest` object was initialized.

`topOrigin` Read only
Experimental

Returns the top-level origin where the `PaymentRequest` object was initialized.

`total` Read only
Experimental

Returns the total amount being requested for payment.

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

`openWindow()`
Experimental

Opens the specified URL in a new window, if and only if the given URL is on the same origin as the calling page. It returns a `Promise` that resolves with a reference to a `WindowClient`.

`respondWith()`
Experimental

Prevents the default event handling and allows you to provide a `Promise` for a `PaymentResponse` object yourself.

Examples
--------

When the `PaymentRequest.show()` method is invoked, a `paymentrequest` event is fired on the service worker of the payment app. This event is listened for inside the payment app's service worker to begin the next stage of the payment process.

```js
let payment_request_event;
let resolver;
let client;

// `self` is the global object in service worker
self.addEventListener("paymentrequest", async (e) => {
  if (payment_request_event) {
    // If there's an ongoing payment transaction, reject it.
    resolver.reject();
  }
  // Preserve the event for future use
  payment_request_event = e;

  // ...
});
```

When a `paymentrequest` event is received, the payment app can open a payment handler window by calling `PaymentRequestEvent.openWindow()`. The payment handler window will present the customers with a payment app interface where they can authenticate, choose shipping address and options, and authorize the payment.

When the payment has been handled, `PaymentRequestEvent.respondWith()` is used to pass the payment result back to the merchant website.

See Receive a payment request event from the merchant for more details of this stage.

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

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

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

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

See also
--------

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


Push API - Web APIs

Push API
========

The **Push API** gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent. This lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content.

Push concepts and usage
-----------------------

**Warning:** When implementing PushManager subscriptions, it is vitally important that you protect against CSRF/XSRF issues in your app. See the following articles for more information:

* Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet
* Preventing CSRF and XSRF Attacks

For an app to receive push messages, it has to have an active service worker. When the service worker is active, it can subscribe to push notifications, using `PushManager.subscribe()`.

The resulting `PushSubscription` includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data.

The service worker will be started as necessary to handle incoming push messages, which are delivered to the `onpush` event handler. This allows apps to react to push messages being received, for example, by displaying a notification (using `ServiceWorkerRegistration.showNotification()`.)

Each subscription is unique to a service worker. The endpoint for the subscription is a unique capability URL: knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret, or other applications might be able to send push messages to your application.

Activating a service worker to deliver a push message can result in increased resource usage, particularly of the battery. Different browsers have different schemes for handling this, there is currently no standard mechanism. Firefox allows a limited number (quota) of push messages to be sent to an application, although Push messages that generate notifications are exempt from this limit. The limit is refreshed each time the site is visited. In Chrome there are no limits.

Interfaces
----------

`PushEvent`

Represents a push action, sent to the global scope of a `ServiceWorker`. It contains information sent from an application to a `PushSubscription`.

`PushManager`

Provides a way to receive notifications from third-party servers, as well as request URLs for push notifications.

`PushMessageData`

Provides access to push data sent by a server, and includes methods to manipulate the received data.

`PushSubscription`

Provides a subscription's URL endpoint, and allows unsubscribing from a push service.

`PushSubscriptionOptions`

Represents the options associated with the push subscription.

Service worker additions
------------------------

The following additions to the Service Worker API have been specified in the Push API spec to provide an entry point for using Push messages. They also monitor and respond to push and subscription change events.

`ServiceWorkerRegistration.pushManager` Read only

Returns a reference to the `PushManager` interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. This is the entry point into using Push messaging.

`onpush`

An event handler fired whenever a `push` event occurs; that is, whenever a server push message is received.

`onpushsubscriptionchange`

An event handler fired whenever a `pushsubscriptionchange` event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)

Examples
--------

Mozilla's ServiceWorker Cookbook contains many useful Push examples.

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

| Specification |
| --- |
| Push API # pushevent-interface |
| Push API # pushmessagedata-interface |

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

### api.PushEvent

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

### api.PushMessageData

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

See also
--------

* Sending VAPID identified WebPush Notifications via Mozilla's Push Service
* Push notifications overview
* Service Worker API


BluetoothUUID - Web APIs

BluetoothUUID
=============

 The **`BluetoothUUID`** interface of the `Web Bluetooth API` provides a way to look up Universally Unique Identifier (UUID) values by name in the
 registry maintained by the Bluetooth SIG.

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

 A UUID string is a 128-bit UUID, for example `00001818-0000-1000-8000-00805f9b34fb`.
 The Bluetooth registry contains lists of descriptors, services, and characteristics identified by these UUIDs in addition to a 16- or 32- bit alias, and a name.

The `BluetoothUUID` interface provides methods to retrieve these 128-bit UUIDs.

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

`BluetoothUUID.canonicalUUID()`
Experimental

Returns the 128-bit UUID when passed the 16- or 32-bit UUID alias.

`BluetoothUUID.getCharacteristic()`
Experimental

Returns the 128-bit UUID representing a registered characteristic when passed a name or the 16- or 32-bit UUID alias.

`BluetoothUUID.getDescriptor()`
Experimental

Returns a UUID representing a registered descriptor when passed a name or the 16- or 32-bit UUID alias.

`BluetoothUUID.getService()`
Experimental

Returns a UUID representing a registered service when passed a name or the 16- or 32-bit UUID alias.

Examples
--------

In the following example the UUID representing the service named `device_information` is returned and printed to the console.

```js
let result = BluetoothUUID.getService("device\_information");
console.log(result); // "0000180a-0000-1000-8000-00805f9b34fb"
```

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

| Specification |
| --- |
| Web Bluetooth # bluetoothuuid |

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

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


ElementInternals - Web APIs

ElementInternals
================

The **`ElementInternals`** interface of the Document Object Model gives web developers a way to allow custom elements to fully participate in HTML forms. It provides utilities for working with these elements in the same way you would work with any standard HTML form element, and also exposes the Accessibility Object Model to the element.

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

This interface has no constructor. An `ElementInternals` object is returned when calling `HTMLElement.attachInternals()`.

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

`ElementInternals.shadowRoot` Read only

Returns the `ShadowRoot` object associated with this element.

`ElementInternals.form` Read only

Returns the `HTMLFormElement` associated with this element.

`ElementInternals.states` Read only
Experimental

Returns the `CustomStateSet` associated with this element.

`ElementInternals.willValidate` Read only

 A boolean value which returns true if the element is a submittable element that is a candidate for
 constraint validation.

`ElementInternals.validity` Read only

Returns a `ValidityState` object which represents the different validity states the element can be in, with respect to constraint validation.

`ElementInternals.validationMessage` Read only

A string containing the validation message of this element.

`ElementInternals.labels` Read only

Returns a `NodeList` of all of the label elements associated with this element.

### Instance properties included from ARIA

The `ElementInternals` interface also includes the following properties.

**Note:** These are included in order that default accessibility semantics can be defined on a custom element. These may be overwritten by author-defined attributes, but ensure that default semantics are retained should the author delete those attributes, or fail to add them at all. For more information see the Accessibility Object Model explainer.

`ElementInternals.ariaAtomic`

A string reflecting the `aria-atomic` attribute, which indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the `aria-relevant` attribute.

`ElementInternals.ariaAutoComplete`

A string reflecting the `aria-autocomplete` attribute, which indicates whether inputting text could trigger display of one or more predictions of the user's intended value for a combobox, searchbox, or textbox and specifies how predictions would be presented if they were made.

`ElementInternals.ariaBusy`

A string reflecting the `aria-busy` attribute, which indicates whether an element is being modified, as assistive technologies may want to wait until the modifications are complete before exposing them to the user.

`ElementInternals.ariaChecked`

A string reflecting the `aria-checked` attribute, which indicates the current "checked" state of checkboxes, radio buttons, and other widgets that have a checked state.

`ElementInternals.ariaColCount`

A string reflecting the `aria-colcount` attribute, which defines the number of columns in a table, grid, or treegrid.

`ElementInternals.ariaColIndex`

A string reflecting the `aria-colindex` attribute, which defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid.

`ElementInternals.ariaColIndexText`
Experimental

A string reflecting the `aria-colindextext` attribute, which defines a human readable text alternative of aria-colindex.

`ElementInternals.ariaColSpan`

A string reflecting the `aria-colspan` attribute, which defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid.

`ElementInternals.ariaCurrent`

A string reflecting the `aria-current` attribute, which indicates the element that represents the current item within a container or set of related elements.

`ElementInternals.ariaDescription`

A string reflecting the `aria-description` attribute, which defines a string value that describes or annotates the current ElementInternals.

`ElementInternals.ariaDisabled`

A string reflecting the `aria-disabled` attribute, which indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

`ElementInternals.ariaExpanded`

A string reflecting the `aria-expanded` attribute, which indicates whether a grouping element owned or controlled by this element is expanded or collapsed.

`ElementInternals.ariaHasPopup`

A string reflecting the `aria-haspopup` attribute, which indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an ElementInternals.

`ElementInternals.ariaHidden`

A string reflecting the `aria-hidden` attribute, which indicates whether the element is exposed to an accessibility API.

`ElementInternals.ariaKeyShortcuts`

A string reflecting the `aria-keyshortcuts` attribute, which indicates keyboard shortcuts that an author has implemented to activate or give focus to an ElementInternals.

`ElementInternals.ariaLabel`

A string reflecting the `aria-label` attribute, which defines a string value that labels the current ElementInternals.

`ElementInternals.ariaLevel`

A string reflecting the `aria-level` attribute, which defines the hierarchical level of an element within a structure.

`ElementInternals.ariaLive`

A string reflecting the `aria-live` attribute, which indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.

`ElementInternals.ariaModal`

A string reflecting the `aria-modal` attribute, which indicates whether an element is modal when displayed.

`ElementInternals.ariaMultiline`

A string reflecting the `aria-multiline` attribute, which indicates whether a text box accepts multiple lines of input or only a single line.

`ElementInternals.ariaMultiSelectable`

A string reflecting the `aria-multiselectable` attribute, which indicates that the user may select more than one item from the current selectable descendants.

`ElementInternals.ariaOrientation`

A string reflecting the `aria-orientation` attribute, which indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous.

`ElementInternals.ariaPlaceholder`

A string reflecting the `aria-placeholder` attribute, which defines a short hint intended to aid the user with data entry when the control has no value.

`ElementInternals.ariaPosInSet`

A string reflecting the `aria-posinset` attribute, which defines an element's number or position in the current set of listitems or treeitems.

`ElementInternals.ariaPressed`

A string reflecting the `aria-pressed` attribute, which indicates the current "pressed" state of toggle buttons.

`ElementInternals.ariaReadOnly`

A string reflecting the `aria-readonly` attribute, which indicates that the element is not editable, but is otherwise operable.

`ElementInternals.ariaRelevant`
Non-standard

A string reflecting the `aria-relevant` attribute, which indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. This is used to describe what changes in an `aria-live` region are relevant and should be announced.

`ElementInternals.ariaRequired`

A string reflecting the `aria-required` attribute, which indicates that user input is required on the element before a form may be submitted.

`ElementInternals.role`

A string which contains an ARIA role. A full list of ARIA roles can be found on the ARIA techniques page.

`ElementInternals.ariaRoleDescription`

A string reflecting the `aria-roledescription` attribute, which defines a human-readable, author-localized description for the role of an Element.

`ElementInternals.ariaRowCount`

A string reflecting the `aria-rowcount` attribute, which defines the total number of rows in a table, grid, or treegrid.

`ElementInternals.ariaRowIndex`

A string reflecting the `aria-rowindex` attribute, which defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid.

`ElementInternals.ariaRowIndexText`
Experimental

A string reflecting the `aria-rowindextext` attribute, which defines a human readable text alternative of aria-rowindex.

`ElementInternals.ariaRowSpan`

A string reflecting the `aria-rowspan` attribute, which defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.

`ElementInternals.ariaSelected`

A string reflecting the `aria-selected` attribute, which indicates the current "selected" state of elements that have a selected state.

`ElementInternals.ariaSetSize`

A string reflecting the `aria-setsize` attribute, which defines the number of items in the current set of listitems or treeitems.

`ElementInternals.ariaSort`

A string reflecting the `aria-sort` attribute, which indicates if items in a table or grid are sorted in ascending or descending order.

`ElementInternals.ariaValueMax`

A string reflecting the `aria-valueMax` attribute, which defines the maximum allowed value for a range widget.

`ElementInternals.ariaValueMin`

A string reflecting the `aria-valueMin` attribute, which defines the minimum allowed value for a range widget.

`ElementInternals.ariaValueNow`

A string reflecting the `aria-valueNow` attribute, which defines the current value for a range widget.

`ElementInternals.ariaValueText`

A string reflecting the `aria-valuetext` attribute, which defines the human-readable text alternative of aria-valuenow for a range widget.

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

`ElementInternals.setFormValue()`

Sets the element's submission value and state, communicating these to the user agent.

`ElementInternals.setValidity()`

Sets the validity of the element.

`ElementInternals.checkValidity()`

Checks if an element meets any constraint validation rules applied to it.

`ElementInternals.reportValidity()`

Checks if an element meets any constraint validation rules applied to it, and also sends a validation message to the user agent.

Examples
--------

The following example demonstrates how to create a custom form-associated element with `HTMLElement.attachInternals`.

```js
class CustomCheckbox extends HTMLElement {
  static formAssociated = true;

  constructor() {
    super();
    this.internals_ = this.attachInternals();
  }

  // …
}

window.customElements.define("custom-checkbox", CustomCheckbox);

let element = document.createElement("custom-checkbox");
let form = document.createElement("form");

// Append element to form to associate it
form.appendChild(element);

console.log(element.internals_.form);
// expected output: <form><custom-checkbox></custom-checkbox></form>
```

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

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

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

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

See also
--------

* More capable form controls
* Creating custom form controls with ElementInternals
* ElementInternals polyfill


IdleDeadline - Web APIs

IdleDeadline
============

The `IdleDeadline` interface is used as the data type of the input parameter to idle callbacks established by calling `Window.requestIdleCallback()`. It offers a method, `timeRemaining()`, which lets you determine how much longer the user agent estimates it will remain idle and a property, `didTimeout`, which lets you determine if your callback is executing because its timeout duration expired.

To learn more about how request callbacks work, see Collaborative Scheduling of Background Tasks.

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

`IdleDeadline.didTimeout` Read only

A Boolean whose value is `true` if the callback is being executed because the timeout specified when the idle callback was installed has expired.

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

`IdleDeadline.timeRemaining()`

Returns a `DOMHighResTimeStamp`, which is a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period. If the idle period is over, the value is 0. Your callback can call this repeatedly to see if there's enough time left to do more work before returning.

Example
-------

See our complete example in the article Cooperative Scheduling of Background Tasks API.

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

| Specification |
| --- |
| requestIdleCallback() Cooperative Scheduling of Background Tasks # the-idledeadline-interface |

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

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

See also
--------

* Cooperative Scheduling of Background Tasks API
* `Window.requestIdleCallback()`
* `Window.cancelIdleCallback()`


reportError() global function - Web APIs

reportError() global function
=============================

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

The **`reportError()`** global method may be used to report errors to the console or global event handlers, emulating an uncaught JavaScript exception.

 This feature is primarily intended for custom event-dispatching or callback-manipulating libraries.
 Libraries can use this feature to catch errors in callback code and re-throw them to the top level handler.
 This ensures that an exception in one callback will not prevent others from being handled, while at the same time ensuring that stack trace information is still readily available for debugging at the top level.

Syntax
------

```js
reportError(throwable)
```

### Parameters

`throwable`

An error object such as a `TypeError`.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

The method is called without an error argument.

Examples
--------

Feature test for the method using:

```js
if (typeof self.reportError === "function") {
  // function is defined
}
```

 The following code shows how you might create and report an error, and how it may be caught using either the global `onerror` handler or by adding a listener for the `error` event.
 Note that the handler assigned to `onerror` must return `true` to stop the event propagating further.

```js
const newError = new Error("Some error message", "someFile.js", 11);
self.reportError(newError);

window.onerror = (message, source, lineno, colno, error) => {
  console.error(`message: ${error.message}, lineno: ${lineno}`);
  return true;
};

self.addEventListener("error", (error) => {
  console.error(error.filename);
});

// Output
// > "message:Some error message, lineno: 11"
// > "someFile.js"
```

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

| Specification |
| --- |
| HTML Standard # runtime-script-errors |

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

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

See also
--------

* `Window`
* `WorkerGlobalScope`
* error event


OES_draw_buffers_indexed - Web APIs

OES\_draw\_buffers\_indexed
===========================

The **`OES_draw_buffers_indexed`** extension is part of the WebGL API and enables the use of different blend options when writing to multiple color buffers simultaneously.

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

**Note:** This extension is only available to WebGL2 contexts.

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

`OES_draw_buffers_indexed.blendEquationiOES()`

Sets both the RGB and alpha blend equations for a particular draw buffer.

`OES_draw_buffers_indexed.blendEquationSeparateiOES()`

Sets the RGB and alpha blend equations separately for a particular draw buffer.

`OES_draw_buffers_indexed.blendFunciOES()`

Defines which function is used when blending pixels for a particular draw buffer.

`OES_draw_buffers_indexed.blendFuncSeparateiOES()`

Defines which function is used when blending pixels for RGB and alpha components separately for a particular draw buffer.

`OES_draw_buffers_indexed.colorMaskiOES()`

Sets which color components to enable or to disable when drawing or rendering for a particular draw buffer.

`OES_draw_buffers_indexed.disableiOES()`

Disables blending for a particular draw buffer.

`OES_draw_buffers_indexed.enableiOES()`

Enables blending for a particular draw buffer.

Examples
--------

### Using the `OES_draw_buffers_indexed` extension

Enable the extension with a call to `WebGLRenderingContext.getExtension()`.

```js
const ext = gl.getExtension("OES\_draw\_buffers\_indexed");
```

You can now enable blending, set blending equation, blending function, and color mask for a particular draw buffer.

```js
// For gl.DRAW\_BUFFER0
ext.enableiOES(gl.BLEND, 0);
ext.blendEquationiOES(0, gl.FUNC\_ADD);
ext.blendFunciOES(0, gl.ONE, gl.ONE);
ext.colorMaskiOES(0, 1, 0, 0, 0);

// For gl.DRAW\_BUFFER1
ext.enableiOES(gl.BLEND, 1);
ext.blendEquationSeparateiOES(1, gl.FUNC\_ADD, gl.FUNC\_SUBTRACT);
ext.blendFuncSeparateiOES(
  1,
  gl.SRC\_ALPHA,
  gl.ONE\_MINUS\_SRC\_ALPHA,
  gl.ZERO,
  gl.ZERO,
);
ext.colorMaskiOES(1, 0, 1, 0, 0);
```

To retrieve settings for a particular draw buffer, use `WebGL2RenderingContext.getIndexedParameter()`.

```js
// For gl.DRAW\_BUFFER0
gl.getIndexedParameter(gl.BLEND\_EQUATION\_RGB, 0);
gl.getIndexedParameter(gl.BLEND\_EQUATION\_ALPHA, 0);
gl.getIndexedParameter(gl.BLEND\_SRC\_RGB, 0);
gl.getIndexedParameter(gl.BLEND\_SRC\_ALPHA, 0);
gl.getIndexedParameter(gl.BLEND\_DST\_RGB, 0);
gl.getIndexedParameter(gl.BLEND\_DST\_ALPHA, 0);
gl.getIndexedParameter(gl.COLOR\_WRITEMASK, 0);

// For gl.DRAW\_BUFFER1
gl.getIndexedParameter(gl.BLEND\_EQUATION\_RGB, 1);
gl.getIndexedParameter(gl.BLEND\_EQUATION\_ALPHA, 1);
gl.getIndexedParameter(gl.BLEND\_SRC\_RGB, 1);
gl.getIndexedParameter(gl.BLEND\_SRC\_ALPHA, 1);
gl.getIndexedParameter(gl.BLEND\_DST\_RGB, 1);
gl.getIndexedParameter(gl.BLEND\_DST\_ALPHA, 1);
gl.getIndexedParameter(gl.COLOR\_WRITEMASK, 1);
```

You can use `WebGLRenderingContext.getParameter()` to see how many draw buffers are available.

```js
const maxDrawBuffers = gl.getParameter(gl.MAX\_DRAW\_BUFFERS);
```

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

| Specification |
| --- |
| WebGL OES\_draw\_buffers\_indexed Extension Specification  |

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

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


SpeechSynthesis - Web APIs

SpeechSynthesis
===============

The **`SpeechSynthesis`** interface of the Web Speech API is the controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides.

EventTarget

SpeechSynthesisInstance properties
-------------------

*`SpeechSynthesis` also inherits properties from its parent interface, `EventTarget`.*

`SpeechSynthesis.paused` Read only

A boolean value that returns `true` if the `SpeechSynthesis` object is in a paused state.

`SpeechSynthesis.pending` Read only

A boolean value that returns `true` if the utterance queue contains as-yet-unspoken utterances.

`SpeechSynthesis.speaking` Read only

A boolean value that returns `true` if an utterance is currently in the process of being spoken — even if `SpeechSynthesis` is in a paused state.

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

*`SpeechSynthesis` also inherits methods from its parent interface, `EventTarget`.*

`SpeechSynthesis.cancel()`

Removes all utterances from the utterance queue.

`SpeechSynthesis.getVoices()`

Returns a list of `SpeechSynthesisVoice` objects representing all the available voices on the current device.

`SpeechSynthesis.pause()`

Puts the `SpeechSynthesis` object into a paused state.

`SpeechSynthesis.resume()`

Puts the `SpeechSynthesis` object into a non-paused state: resumes it if it was already paused.

`SpeechSynthesis.speak()`

Adds an `utterance` to the utterance queue; it will be spoken when any other utterances queued before it have been spoken.

Events
------

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

`voiceschanged`

 Fired when the list of `SpeechSynthesisVoice` objects that would be returned by the `SpeechSynthesis.getVoices()` method has changed.
 Also available via the `onvoiceschanged` property.

Examples
--------

First, a simple example:

```js
let utterance = new SpeechSynthesisUtterance("Hello world!");
speechSynthesis.speak(utterance);
```

Now we'll look at a more fully-fledged example. In our Speech synthesizer demo, we first grab a reference to the SpeechSynthesis controller using `window.speechSynthesis`. After defining some necessary variables, we retrieve a list of the voices available using `SpeechSynthesis.getVoices()` and populate a select menu with them so the user can choose what voice they want.

Inside the `inputForm.onsubmit` handler, we stop the form submitting with preventDefault(), create a new `SpeechSynthesisUtterance` instance containing the text from the text `<input>`, set the utterance's voice to the voice selected in the `<select>` element, and start the utterance speaking via the `SpeechSynthesis.speak()` method.

```js
const synth = window.speechSynthesis;

const inputForm = document.querySelector("form");
const inputTxt = document.querySelector(".txt");
const voiceSelect = document.querySelector("select");
const pitch = document.querySelector("#pitch");
const pitchValue = document.querySelector(".pitch-value");
const rate = document.querySelector("#rate");
const rateValue = document.querySelector(".rate-value");

let voices = [];

function populateVoiceList() {
  voices = synth.getVoices();

  for (let i = 0; i < voices.length; i++) {
    const option = document.createElement("option");
    option.textContent = `${voices[i].name} (${voices[i].lang})`;

    if (voices[i].default) {
      option.textContent += " — DEFAULT";
    }

    option.setAttribute("data-lang", voices[i].lang);
    option.setAttribute("data-name", voices[i].name);
    voiceSelect.appendChild(option);
  }
}

populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
  speechSynthesis.onvoiceschanged = populateVoiceList;
}

inputForm.onsubmit = (event) => {
  event.preventDefault();

  const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  const selectedOption =
    voiceSelect.selectedOptions[0].getAttribute("data-name");
  for (let i = 0; i < voices.length; i++) {
    if (voices[i].name === selectedOption) {
      utterThis.voice = voices[i];
    }
  }
  utterThis.pitch = pitch.value;
  utterThis.rate = rate.value;
  synth.speak(utterThis);

  inputTxt.blur();
};
```

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

| Specification |
| --- |
| Web Speech API # tts-section |

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

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

See also
--------

* Web Speech API


AudioWorklet - Web APIs

AudioWorklet
============

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

The **`AudioWorklet`** interface of the Web Audio API is used to supply custom audio processing scripts that execute in a separate thread to provide very low latency audio processing.

The worklet's code is run in the `AudioWorkletGlobalScope` global execution context, using a separate Web Audio thread which is shared by the worklet and other audio nodes.

Access the audio context's instance of `AudioWorklet` through the `BaseAudioContext.audioWorklet` property.

Worklet

AudioWorkletInstance properties
-------------------

*The `AudioWorklet` interface does not define any properties of its own, but does inherit properties of `Worklet`.*

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

*This interface inherits methods from `Worklet`. The `AudioWorklet` interface does not define any methods of its own.*

Events
------

*`AudioWorklet` has no events to which it responds.*

Examples
--------

See `AudioWorkletNode` for complete examples of custom audio node creation.

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

| Specification |
| --- |
| Web Audio API # AudioWorklet |

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

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

See also
--------

* `AudioWorkletGlobalScope` — the global execution context of an `AudioWorklet`
* Web Audio API
* Using the Web Audio API
* Using AudioWorklet


VirtualKeyboard - Web APIs

VirtualKeyboard
===============

**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 **`VirtualKeyboard`** interface of the VirtualKeyboard API is useful on devices that have on-screen virtual keyboards, such as tablets, mobile phones, or other devices where a hardware keyboard may not be available.

The `VirtualKeyboard` interface makes it possible to opt out of the automatic way browsers handle on-screen virtual keyboards by reducing the height of the viewport to make room for the virtual keyboard. You can prevent the browser from changing the size of the viewport, detect the position and size of the virtual keyboard — adapting the layout of your web page as a follow-up — and programmatically show or hide the virtual keyboard.

You access the `VirtualKeyboard` interface by using `navigator.virtualKeyboard`.

EventTarget

VirtualKeyboardInstance properties
-------------------

*The `VirtualKeyboard` interface inherits properties from its parent, `EventTarget`.*

`VirtualKeyboard.boundingRect` Read only
Experimental

A `DOMRect` that describes the geometry of the virtual keyboard.

`VirtualKeyboard.overlaysContent`
Experimental

A `Boolean` that defines whether the browser should stop handling the on-screen virtual keyboard.

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

*The `VirtualKeyboard` interface inherits methods from its parent, `EventTarget`.*

`VirtualKeyboard.show()`
Experimental

Show the virtual keyboard.

`VirtualKeyboard.hide()`
Experimental

Hide the virtual keyboard.

Events
------

`geometrychange`
Experimental

Fires when the geometry of the on-screen virtual keyboard changes, which happens when the virtual keyboard appears or disappears.

Example
-------

The following example demonstrates how to opt out of the automatic virtual keyboard behavior, and detect the geometry of the virtual keyboard in the web page:

```js
if ("virtualKeyboard" in navigator) {
  navigator.virtualKeyboard.overlaysContent = true;

  navigator.virtualKeyboard.addEventListener("geometrychange", (event) => {
    const { x, y, width, height } = event.target.boundingRect;
  });
}
```

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

| Specification |
| --- |
| VirtualKeyboard API # the-virtualkeyboard-interface |

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

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

See also
--------

* The VirtualKeyboard API
* Full control with the VirtualKeyboard API


CSSStyleValue - Web APIs

CSSStyleValue
=============

The **`CSSStyleValue`** interface of the CSS Typed Object Model API is the base class of all CSS values accessible through the Typed OM API. An instance of this class may be used anywhere a string is expected.

Interfaces based on CSSStyleValue
---------------------------------

Below is a list of interfaces based on the `CSSStyleValue` interface.

* `CSSImageValue`
* `CSSKeywordValue`
* `CSSNumericValue`
* `CSSPositionValue`
* `CSSTransformValue`
* `CSSUnparsedValue`
Static methods
--------------

`CSSStyleValue.parse()`

Sets a specific CSS property to the specified values and returns the first value as a `CSSStyleValue` object.

`CSSStyleValue.parseAll()`

Sets all occurrences of a specific CSS property to the specified value and returns an array of `CSSStyleValue` objects, each containing one of the supplied values.

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

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

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

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


WakeLock - Web APIs

WakeLock
========

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

The **`WakeLock`** interface of the Screen Wake Lock API can be used to request a lock that prevents device screens from dimming or locking when an application needs to keep running.

This interface, and hence the system wake lock, is exposed through the `Navigator.wakeLock` property.

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

`request()`

Returns a `Promise` that fulfills with a `WakeLockSentinel` object if the screen wake lock is granted.

Examples
--------

The following code `awaits` the request for a `WakeLockSentinel` object, and continues if the request is granted.

The `WakeLock.request()` method is wrapped in a `try...catch` statement to catch cases when the promise might be rejected rejected, such as due to low device power.

```js
try {
  const wakeLock = await navigator.wakeLock.request("screen");
} catch (err) {
  // the wake lock request fails - usually system related, such being low on battery
  console.log(`${err.name}, ${err.message}`);
}
```

 Note that the screen wake lock may be revoked by the device after it has been granted.
 The returned `WakeLockSentinel` can be used to check the status of the lock, and/or to manually cancel a held screen wake lock.

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

| Specification |
| --- |
| Screen Wake Lock API # the-wakelock-interface |

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

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

See also
--------

* Stay awake with the Screen Wake Lock API


RemotePlayback - Web APIs

RemotePlayback
==============

The **`RemotePlayback`** interface of the Remote Playback API allows the page to detect availability of remote playback devices, then connect to and control playing on these devices.

EventTarget

RemotePlaybackInstance properties
-------------------

`RemotePlayback.state` Read only

Represents the `RemotePlayback` connection's state. One of:

`"connecting"`

The user agent is attempting to initiate remote playback with the selected device.

`"connected"`

The transition from local to remote playback has happened, all commands will now take place on the remote device.

`"disconnected"`

The remote playback has not been initiated, has failed to initiate, or has been stopped.

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

`RemotePlayback.watchAvailability()`

A `Promise` that resolves with a `callbackId` of an available remote playback device.

`RemotePlayback.cancelWatchAvailability()`

Cancels the request to monitor the availability of remote playback devices.

`RemotePlayback.prompt()`

Prompts the user to select and give permission to connect to a remote playback device.

Events
------

`connecting`

Fired when the user agent initiates remote playback.

`connect`

Fired when the user agent successfully connects to the remote device.

`disconnect`

Fired when the user agent disconnects from the remote device.

Examples
--------

The following example demonstrates a player with custom controls that support remote playback. Initially the button used to select a device is hidden:

```html
<video id="videoElement" src="https://example.org/media.ext">
  <button id="deviceBtn" style="display: none;">Pick device</button>
</video>
```

The `RemotePlayback.watchAvailability()` method is used to watch for available remote playback devices. If a device is available, use the callback to show the button.

```js
const deviceBtn = document.getElementById("deviceBtn");
const videoElem = document.getElementById("videoElement");

function availabilityCallback(available) {
  // Show or hide the device picker button depending on device availability.
  deviceBtn.style.display = available ? "inline" : "none";
}

videoElem.remote.watchAvailability(availabilityCallback).catch(() => {
  /\* If the device cannot continuously watch available,
 show the button to allow the user to try to prompt for a connection.\*/
  deviceBtn.style.display = "inline";
});
```

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

| Specification |
| --- |
| Remote Playback API # remoteplayback-interface |

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

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


Accelerometer - Web APIs

Accelerometer
=============

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

The **`Accelerometer`** interface of the Sensor APIs provides on each reading the acceleration applied to the device along all three axes.

To use this sensor, the user must grant permission to the `'accelerometer'`, device sensor through the Permissions API.

This feature may be blocked by a Permissions Policy set on your server.

EventTarget

Sensor

AccelerometerConstructor
-----------

`Accelerometer()`
Experimental

Creates a new `Accelerometer` object.

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

*In addition to the properties listed below, `Accelerometer` inherits properties from its parent interfaces, `Sensor` and `EventTarget`.*

`Accelerometer.x` Read only
Experimental

Returns a double containing the acceleration of the device along the device's x axis.

`Accelerometer.y` Read only
Experimental

Returns a double containing the acceleration of the device along the device's y axis.

`Accelerometer.z` Read only
Experimental

Returns a double containing the acceleration of the device along the device's z axis.

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

*`Accelerometer` doesn't have own methods. However, it inherits methods from its parent interfaces, `Sensor` and `EventTarget`.*

Events
------

*`Accelerometer` doesn't have own events. However, it inherits events from its parent interface, `Sensor`.*

Example
-------

Acceleration is typically read in the `reading` event callback. In the example below this occurs sixty times a second.

```js
const acl = new Accelerometer({ frequency: 60 });
acl.addEventListener("reading", () => {
  console.log(`Acceleration along the X-axis ${acl.x}`);
  console.log(`Acceleration along the Y-axis ${acl.y}`);
  console.log(`Acceleration along the Z-axis ${acl.z}`);
});

acl.start();
```

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

| Specification |
| --- |
| Accelerometer # accelerometer-interface |

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

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


XRInputSourceEvent - Web APIs

XRInputSourceEvent
==================

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

The WebXR Device API's **`XRInputSourceEvent`** interface describes an event which has occurred on a WebXR user input device such as a hand controller, gaze tracking system, or motion tracking system. More specifically, they represent a change in the state of an `XRInputSource`.

To learn more about handling inputs in a WebXR project, see the article Inputs and input sources.

Event

XRInputSourceEventConstructor
-----------

`XRInputSourceEvent()`

Creates and returns a new `XRInputSourceEvent` object whose properties match those provided in the `eventInitDict` dictionary provided.

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

`frame` Read only

An `XRFrame` object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an *event* frame, not an *animation* frame, you cannot call the `XRFrame` method `getViewerPose()` on it; instead, use `getPose()`.

`inputSource` Read only

An `XRInputSource` object indicating which input source generated the input event.

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

*The `XRInputSourceEvent` interface doesn't define any methods; however, several methods are inherited from the parent interface, `Event`.*

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

`select`

Sent to an `XRSession` when the sending input source has fully completed a primary action.

`selectend`

Sent to an `XRSession` when an ongoing primary action ends, or when an input source with an ongoing primary action has been disconnected from the system.

`selectstart`

Sent to an `XRSession` when an input source begins its primary action, indicating that the user has begun a command-like input, such as pressing a trigger or button, issuing a spoken command, tapping on a touchpad, or the like.

`squeeze`

Sent to an `XRSession` when the sending input source has fully completed a primary squeeze action.

`squeezeend`

Sent to an `XRSession` when an ongoing primary squeeze action ends or when an input source with an ongoing primary squeeze action is disconnected.

`squeezestart`

Sent to an `XRSession` when an input source begins its primary squeeze action, indicating that the user has begun to grab, squeeze, or grip the controller.

Examples
--------

The code below sets up handlers for primary action events in order to determine when the user clicks on (shoots at/pokes at/whatever) objects in the scene.

```js
xrSession.addEventListener("select", (event) => {
  let targetRayPose = event.frame.getPose(
    event.inputSource.targetRaySpace,
    myRefSpace,
  );

  if (targetRayPose) {
    let hit = myHitTest(targetRayPose.transform);
    if (hit) {
      /\* handle the hit \*/
    }
  }
});
```

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

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

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

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


PageTransitionEvent - Web APIs

PageTransitionEvent
===================

The **`PageTransitionEvent`** event object is available inside handler functions for the `pageshow` and `pagehide` events, fired when a document is being loaded or unloaded.

Event

PageTransitionEventConstructor
-----------

`PageTransitionEvent()`

Creates a new `PageTransitionEvent` object.

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

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

`PageTransitionEvent.persisted` Read only

Indicates if the document is loading from a cache.

Example
-------

### HTML

```html
<!doctype html>
<html lang="en-US">
  <body></body>
</html>
```

### JavaScript

```js
window.addEventListener("pageshow", (event) => {
  if (event.persisted) {
    alert("The page was cached by the browser");
  } else {
    alert("The page was NOT cached by the browser");
  }
});
```

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

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

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

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

See also
--------

* `pageshow` event
* `pagehide` event


CSSStyleSheet - Web APIs

CSSStyleSheet
=============

The **`CSSStyleSheet`** interface represents a single CSS stylesheet, and lets you inspect and modify the list of rules contained in the stylesheet. It inherits properties and methods from its parent, `StyleSheet`.

StyleSheet

CSSStyleSheet
A stylesheet consists of a collection of `CSSRule` objects representing each of the rules in the stylesheet. The rules are contained in a `CSSRuleList`, which can be obtained from the stylesheet's `cssRules` property.

For example, one rule might be a `CSSStyleRule` object containing a style such as:

```css
h1,
h2 {
  font-size: 16pt;
}
```

Another rule might be an *at-rule* such as `@import` or `@media`, and so forth.

See the Obtaining a StyleSheet section for the various ways a `CSSStyleSheet` object can be obtained. A `CSSStyleSheet` object can also be directly constructed. The constructor, and the `CSSStyleSheet.replace()`, and `CSSStyleSheet.replaceSync()` methods are newer additions to the specification, enabling *Constructable Stylesheets*.

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

`CSSStyleSheet()`

Creates a new `CSSStyleSheet` object.

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

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

`CSSStyleSheet.cssRules` Read only

Returns a live `CSSRuleList` which maintains an up-to-date list of the `CSSRule` objects that comprise the stylesheet.

**Note:** In some browsers, if a stylesheet is loaded from a different domain, accessing `cssRules` results in a `SecurityError`.

`CSSStyleSheet.ownerRule` Read only

If this stylesheet is imported into the document using an `@import` rule, the `ownerRule` property returns the corresponding `CSSImportRule`; otherwise, this property's value is `null`.

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

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

`CSSStyleSheet.deleteRule()`

Deletes the rule at the specified index into the stylesheet's rule list.

`CSSStyleSheet.insertRule()`

Inserts a new rule at the specified position in the stylesheet, given the textual representation of the rule.

`CSSStyleSheet.replace()`

Asynchronously replaces the content of the stylesheet and returns a `Promise` that resolves with the updated `CSSStyleSheet`.

`CSSStyleSheet.replaceSync()`

Synchronously replaces the content of the stylesheet.

Legacy properties
-----------------

*These properties are legacy properties as introduced by Microsoft; these are maintained for compatibility with existing sites.*

`rules` Read only
Deprecated

The `rules` property is functionally identical to the standard `cssRules` property; it returns a live `CSSRuleList` which maintains an up-to-date list of all of the rules in the style sheet.

Legacy methods
--------------

*These methods are legacy methods as introduced by Microsoft; these are maintained for compatibility with existing sites.*

`addRule()`
Deprecated

Adds a new rule to the stylesheet given the selector to which the style applies and the style block to apply to the matching elements.

This differs from `insertRule()`, which takes the textual representation of the entire rule as a single string.

`removeRule()`
Deprecated

Functionally identical to `deleteRule()`; removes the rule at the specified index from the stylesheet's rule list.

Obtaining a StyleSheet
----------------------

A stylesheet is associated with at most one `Document`, which it applies to (unless disabled). A list of `CSSStyleSheet` objects for a given document can be obtained using the `Document.styleSheets` property. A specific style sheet can also be accessed from its *owner* object (`Node` or `CSSImportRule`), if any.

A `CSSStyleSheet` object is created and inserted into the document's `Document.styleSheets` list automatically by the browser, when a stylesheet is loaded for a document.

A (possibly incomplete) list of ways a stylesheet can be associated with a document follows:

| Reason for the style sheet to be associated with the document | Appears in `document.styleSheets` list | Getting the owner element/rule given the style sheet object | The interface for the owner object | Getting the CSSStyleSheet object from the owner |
| --- | --- | --- | --- | --- |
| `<style>` and `<link>`
 elements in the document
  | Yes | `.ownerNode` | `HTMLLinkElement`,`HTMLStyleElement`,or
 `SVGStyleElement` | `HTMLLinkElement.sheet`,`HTMLStyleElement.sheet`,or
 `SVGStyleElement.sheet` |
|
 CSS `@import` rule in other style sheets applied to
 the document
  | Yes | `.ownerRule` | `CSSImportRule` | `.styleSheet` |
| `<?xml-stylesheet ?>` processing instruction in the
 (non-HTML) document
  | Yes | `.ownerNode` | `ProcessingInstruction` | `.sheet` |
| HTTP Link Header | Yes | *N/A* | N/A | N/A |
| User agent (default) style sheets | No | N/A | N/A | N/A |

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # the-cssstylesheet-interface |

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

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

See also
--------

* CSS Object Model
* Using dynamic styling information


XRLayer - Web APIs

XRLayer
=======

**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 **`XRLayer`** interface of the WebXR Device API is the base class for WebXR layer types. It inherits methods from `EventTarget`.

EventTarget

XRLayerInterfaces based on `XRLayer`
-----------------------------

Below is a list of interfaces based on the `XRLayer` interface.

* `XRCompositionLayer`
* `XRWebGLLayer`
Instance methods
----------------

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

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

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

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

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

See also
--------

* `XRCompositionLayer`
* `XRWebGLLayer`
* `EventTarget`


AnimationEvent - Web APIs

AnimationEvent
==============

The **`AnimationEvent`** interface represents events providing information related to animations.

Event

AnimationEventConstructor
-----------

`AnimationEvent()`

Creates an `AnimationEvent` event with the given parameters.

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

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

`AnimationEvent.animationName` Read only

A string containing the value of the `animation-name` that generated the animation.

`AnimationEvent.elapsedTime` Read only

A `float` giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused. For an `animationstart` event, `elapsedTime` is `0.0` unless there was a negative value for `animation-delay`, in which case the event will be fired with `elapsedTime` containing `(-1 * delay)`.

`AnimationEvent.pseudoElement` Read only

A string, starting with `'::'`, containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: `''`.

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

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

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

| Specification |
| --- |
| CSS Animations Level 1 # interface-animationevent |

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

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

See also
--------

* Using CSS animations
* Animation-related CSS properties and at-rules: `animation`, `animation-composition`, `animation-delay`, `animation-direction`, `animation-duration`, `animation-fill-mode`, `animation-iteration-count`, `animation-name`, `animation-play-state`, `animation-timing-function`, `@keyframes`.


GPUTextureView - Web APIs

GPUTextureView
==============

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

The **`GPUTextureView`** interface of the WebGPU API represents a view into a subset of the texture resources defined by a particular `GPUTexture`.

A `GPUTextureView` object instance is created using the `GPUTexture.createView()` method.

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

`label`
Experimental

A string providing a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

Examples
--------

In the WebGPU Samples Cubemap demo, you will see multiple examples of how `GPUTextureView`s (created by `GPUTexture.createView()` calls) are used, both as a `resource` in a `GPUDevice.createBindGroup()` call, and as a provided `view` in the `depthStencilAttachment` object of a `GPUCommandEncoder.beginRenderPass()` descriptor.

```js
const uniformBindGroup = device.createBindGroup({
  layout: pipeline.getBindGroupLayout(0),
  entries: [
    {
      binding: 0,
      resource: {
        buffer: uniformBuffer,
        offset: 0,
        size: uniformBufferSize,
      },
    },
    {
      binding: 1,
      resource: sampler,
    },
    {
      binding: 2,
      resource: cubemapTexture.createView({
        dimension: "cube",
      }),
    },
  ],
});

const renderPassDescriptor: GPURenderPassDescriptor = {
  colorAttachments: [
    {
      view: undefined, // Assigned later
      loadOp: "clear",
      storeOp: "store",
    },
  ],
  depthStencilAttachment: {
    view: depthTexture.createView(),
    depthClearValue: 1.0,
    depthLoadOp: "clear",
    depthStoreOp: "store",
  },
};

// ...

const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

// ...
```

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

| Specification |
| --- |
| WebGPU # gputextureview |

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

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

See also
--------

* The WebGPU API


WebGLRenderingContext - Web APIs

WebGLRenderingContext
=====================

The **`WebGLRenderingContext`** interface provides an interface to the OpenGL ES 2.0 graphics rendering context for the drawing surface of an HTML `<canvas>` element.

To get an access to a WebGL context for 2D and/or 3D graphics rendering, call `getContext()` on a `<canvas>` element, supplying "webgl" as the argument:

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

Once you have the WebGL rendering context for a canvas, you can render within it. The WebGL tutorial has more information, examples, and resources on how to get started with WebGL.

If you require a WebGL 2.0 context, see `WebGL2RenderingContext`; this supplies access to an implementation of OpenGL ES 3.0 graphics.

Constants
---------

See the WebGL constants page.

The WebGL context
-----------------

The following properties and methods provide general information and functionality to deal with the WebGL context:

`WebGLRenderingContext.canvas`

A read-only back-reference to the `HTMLCanvasElement`. Might be `null` if it is not associated with a `<canvas>` element.

`WebGLRenderingContext.drawingBufferWidth`

The read-only width of the current drawing buffer. Should match the width of the canvas element associated with this context.

`WebGLRenderingContext.drawingBufferHeight`

The read-only height of the current drawing buffer. Should match the height of the canvas element associated with this context.

`WebGLRenderingContext.getContextAttributes()`

Returns a `WebGLContextAttributes` object that contains the actual context parameters. Might return `null`, if the context is lost.

`WebGLRenderingContext.isContextLost()`

Returns `true` if the context is lost, otherwise returns `false`.

`WebGLRenderingContext.makeXRCompatible()`

Ensures the context is compatible with the user's XR hardware, re-creating the context if necessary with a new configuration to do so. This can be used to start an application using standard 2D presentation, then transition to using a VR or AR mode later.

Viewing and clipping
--------------------

`WebGLRenderingContext.scissor()`

Defines the scissor box.

`WebGLRenderingContext.viewport()`

Sets the viewport.

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

`WebGLRenderingContext.activeTexture()`

Selects the active texture unit.

`WebGLRenderingContext.blendColor()`

Sets the source and destination blending factors.

`WebGLRenderingContext.blendEquation()`

Sets both the RGB blend equation and alpha blend equation to a single equation.

`WebGLRenderingContext.blendEquationSeparate()`

Sets the RGB blend equation and alpha blend equation separately.

`WebGLRenderingContext.blendFunc()`

Defines which function is used for blending pixel arithmetic.

`WebGLRenderingContext.blendFuncSeparate()`

Defines which function is used for blending pixel arithmetic for RGB and alpha components separately.

`WebGLRenderingContext.clearColor()`

Specifies the color values used when clearing color buffers.

`WebGLRenderingContext.clearDepth()`

Specifies the depth value used when clearing the depth buffer.

`WebGLRenderingContext.clearStencil()`

Specifies the stencil value used when clearing the stencil buffer.

`WebGLRenderingContext.colorMask()`

Sets which color components to enable or to disable when drawing or rendering to a `WebGLFramebuffer`.

`WebGLRenderingContext.cullFace()`

Specifies whether or not front- and/or back-facing polygons can be culled.

`WebGLRenderingContext.depthFunc()`

Specifies a function that compares incoming pixel depth to the current depth buffer value.

`WebGLRenderingContext.depthMask()`

Sets whether writing into the depth buffer is enabled or disabled.

`WebGLRenderingContext.depthRange()`

Specifies the depth range mapping from normalized device coordinates to window or viewport coordinates.

`WebGLRenderingContext.disable()`

Disables specific WebGL capabilities for this context.

`WebGLRenderingContext.enable()`

Enables specific WebGL capabilities for this context.

`WebGLRenderingContext.frontFace()`

Specifies whether polygons are front- or back-facing by setting a winding orientation.

`WebGLRenderingContext.getParameter()`

Returns a value for the passed parameter name.

`WebGLRenderingContext.getError()`

Returns error information.

`WebGLRenderingContext.hint()`

Specifies hints for certain behaviors. The interpretation of these hints depend on the implementation.

`WebGLRenderingContext.isEnabled()`

Tests whether a specific WebGL capability is enabled or not for this context.

`WebGLRenderingContext.lineWidth()`

Sets the line width of rasterized lines.

`WebGLRenderingContext.pixelStorei()`

Specifies the pixel storage modes

`WebGLRenderingContext.polygonOffset()`

Specifies the scale factors and units to calculate depth values.

`WebGLRenderingContext.sampleCoverage()`

Specifies multi-sample coverage parameters for anti-aliasing effects.

`WebGLRenderingContext.stencilFunc()`

Sets the both front and back function and reference value for stencil testing.

`WebGLRenderingContext.stencilFuncSeparate()`

Sets the front and/or back function and reference value for stencil testing.

`WebGLRenderingContext.stencilMask()`

Controls enabling and disabling of both the front and back writing of individual bits in the stencil planes.

`WebGLRenderingContext.stencilMaskSeparate()`

Controls enabling and disabling of front and/or back writing of individual bits in the stencil planes.

`WebGLRenderingContext.stencilOp()`

Sets both the front and back-facing stencil test actions.

`WebGLRenderingContext.stencilOpSeparate()`

Sets the front and/or back-facing stencil test actions.

Buffers
-------

`WebGLRenderingContext.bindBuffer()`

Binds a `WebGLBuffer` object to a given target.

`WebGLRenderingContext.bufferData()`

Updates buffer data.

`WebGLRenderingContext.bufferSubData()`

Updates buffer data starting at a passed offset.

`WebGLRenderingContext.createBuffer()`

Creates a `WebGLBuffer` object.

`WebGLRenderingContext.deleteBuffer()`

Deletes a `WebGLBuffer` object.

`WebGLRenderingContext.getBufferParameter()`

Returns information about the buffer.

`WebGLRenderingContext.isBuffer()`

Returns a Boolean indicating if the passed buffer is valid.

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

`WebGLRenderingContext.bindFramebuffer()`

Binds a `WebGLFrameBuffer` object to a given target.

`WebGLRenderingContext.checkFramebufferStatus()`

Returns the status of the framebuffer.

`WebGLRenderingContext.createFramebuffer()`

Creates a `WebGLFrameBuffer` object.

`WebGLRenderingContext.deleteFramebuffer()`

Deletes a `WebGLFrameBuffer` object.

`WebGLRenderingContext.framebufferRenderbuffer()`

Attaches a `WebGLRenderingBuffer` object to a `WebGLFrameBuffer` object.

`WebGLRenderingContext.framebufferTexture2D()`

Attaches a textures image to a `WebGLFrameBuffer` object.

`WebGLRenderingContext.getFramebufferAttachmentParameter()`

Returns information about the framebuffer.

`WebGLRenderingContext.isFramebuffer()`

Returns a Boolean indicating if the passed `WebGLFrameBuffer` object is valid.

`WebGLRenderingContext.readPixels()`

Reads a block of pixels from the `WebGLFrameBuffer`.

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

`WebGLRenderingContext.bindRenderbuffer()`

Binds a `WebGLRenderBuffer` object to a given target.

`WebGLRenderingContext.createRenderbuffer()`

Creates a `WebGLRenderBuffer` object.

`WebGLRenderingContext.deleteRenderbuffer()`

Deletes a `WebGLRenderBuffer` object.

`WebGLRenderingContext.getRenderbufferParameter()`

Returns information about the renderbuffer.

`WebGLRenderingContext.isRenderbuffer()`

Returns a Boolean indicating if the passed `WebGLRenderingBuffer` is valid.

`WebGLRenderingContext.renderbufferStorage()`

Creates a renderbuffer data store.

Textures
--------

`WebGLRenderingContext.bindTexture()`

Binds a `WebGLTexture` object to a given target.

`WebGLRenderingContext.compressedTexImage2D()`

Specifies a 2D texture image in a compressed format.

`WebGLRenderingContext.compressedTexSubImage2D()`

Specifies a 2D texture sub-image in a compressed format.

`WebGLRenderingContext.copyTexImage2D()`

Copies a 2D texture image.

`WebGLRenderingContext.copyTexSubImage2D()`

Copies a 2D texture sub-image.

`WebGLRenderingContext.createTexture()`

Creates a `WebGLTexture` object.

`WebGLRenderingContext.deleteTexture()`

Deletes a `WebGLTexture` object.

`WebGLRenderingContext.generateMipmap()`

Generates a set of mipmaps for a `WebGLTexture` object.

`WebGLRenderingContext.getTexParameter()`

Returns information about the texture.

`WebGLRenderingContext.isTexture()`

Returns a Boolean indicating if the passed `WebGLTexture` is valid.

`WebGLRenderingContext.texImage2D()`

Specifies a 2D texture image.

`WebGLRenderingContext.texSubImage2D()`

Updates a sub-rectangle of the current `WebGLTexture`.

`WebGLRenderingContext.texParameterf()`

Sets texture parameters.

`WebGLRenderingContext.texParameteri()`

Sets texture parameters.

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

`WebGLRenderingContext.attachShader()`

Attaches a `WebGLShader` to a `WebGLProgram`.

`WebGLRenderingContext.bindAttribLocation()`

Binds a generic vertex index to a named attribute variable.

`WebGLRenderingContext.compileShader()`

Compiles a `WebGLShader`.

`WebGLRenderingContext.createProgram()`

Creates a `WebGLProgram`.

`WebGLRenderingContext.createShader()`

Creates a `WebGLShader`.

`WebGLRenderingContext.deleteProgram()`

Deletes a `WebGLProgram`.

`WebGLRenderingContext.deleteShader()`

Deletes a `WebGLShader`.

`WebGLRenderingContext.detachShader()`

Detaches a `WebGLShader`.

`WebGLRenderingContext.getAttachedShaders()`

Returns a list of `WebGLShader` objects attached to a `WebGLProgram`.

`WebGLRenderingContext.getProgramParameter()`

Returns information about the program.

`WebGLRenderingContext.getProgramInfoLog()`

Returns the information log for a `WebGLProgram` object.

`WebGLRenderingContext.getShaderParameter()`

Returns information about the shader.

`WebGLRenderingContext.getShaderPrecisionFormat()`

Returns a `WebGLShaderPrecisionFormat` object describing the precision for the numeric format of the shader.

`WebGLRenderingContext.getShaderInfoLog()`

Returns the information log for a `WebGLShader` object.

`WebGLRenderingContext.getShaderSource()`

Returns the source code of a `WebGLShader` as a string.

`WebGLRenderingContext.isProgram()`

Returns a Boolean indicating if the passed `WebGLProgram` is valid.

`WebGLRenderingContext.isShader()`

Returns a Boolean indicating if the passed `WebGLShader` is valid.

`WebGLRenderingContext.linkProgram()`

Links the passed `WebGLProgram` object.

`WebGLRenderingContext.shaderSource()`

Sets the source code in a `WebGLShader`.

`WebGLRenderingContext.useProgram()`

Uses the specified `WebGLProgram` as part the current rendering state.

`WebGLRenderingContext.validateProgram()`

Validates a `WebGLProgram`.

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

* `WebGLRenderingContext.disableVertexAttribArray()`
    + : Disables a vertex attribute array at a given position.
* `WebGLRenderingContext.enableVertexAttribArray()`
    + : Enables a vertex attribute array at a given position.
* `WebGLRenderingContext.getActiveAttrib()`
    + : Returns information about an active attribute variable.
* `WebGLRenderingContext.getActiveUniform()`
    + : Returns information about an active uniform variable.
* `WebGLRenderingContext.getAttribLocation()`
    + : Returns the location of an attribute variable.
* `WebGLRenderingContext.getUniform()`
    + : Returns the value of a uniform variable at a given location.
* `WebGLRenderingContext.getUniformLocation()`
    + : Returns the location of a uniform variable.
* `WebGLRenderingContext.getVertexAttrib()`
    + : Returns information about a vertex attribute at a given position.
* `WebGLRenderingContext.getVertexAttribOffset()`
    + : Returns the address of a given vertex attribute.
* `WebGLRenderingContext.uniform[1234][fi][v]()`
    + : Specifies a value for a uniform variable.
* `WebGLRenderingContext.uniformMatrix[234]fv()`
    + : Specifies a matrix value for a uniform variable.
* `WebGLRenderingContext.vertexAttrib[1234]f[v]()`
    + : Specifies a value for a generic vertex attribute.
* `WebGLRenderingContext.vertexAttribPointer()`
    + : Specifies the data formats and locations of vertex attributes in a vertex attributes array.
Drawing buffers
---------------

`WebGLRenderingContext.clear()`

Clears specified buffers to preset values.

`WebGLRenderingContext.drawArrays()`

Renders primitives from array data.

`WebGLRenderingContext.drawElements()`

Renders primitives from element array data.

`WebGLRenderingContext.finish()`

Blocks execution until all previously called commands are finished.

`WebGLRenderingContext.flush()`

Empties different buffer commands, causing all commands to be executed as quickly as possible.

Color spaces
------------

`WebGLRenderingContext.drawingBufferColorSpace`

Specifies the color space of the WebGL drawing buffer.

`WebGLRenderingContext.unpackColorSpace`
Experimental

Specifies the color space to convert to when importing textures.

Working with extensions
-----------------------

These methods manage WebGL extensions:

`WebGLRenderingContext.getSupportedExtensions()`

Returns an `Array` of strings containing all the supported WebGL extensions.

`WebGLRenderingContext.getExtension()`

Returns an extension object.

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

| Specification |
| --- |
| WebGL Specification # 5.14 |

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

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

See also
--------

* `HTMLCanvasElement`


WebTransportReceiveStream - Web APIs

WebTransportReceiveStream
=========================

**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 `WebTransportReceiveStream` interface of the WebTransport API is a `ReadableStream` that can be used to read from an incoming unidirectional or bidirectional `WebTransport` stream.

The stream is a readable byte stream of `Uint8Array`, and can be consumed using either a BYOB reader (`ReadableStreamBYOBReader`) or the default reader (`ReadableStreamDefaultReader`).

 Objects of this type are not constructed directly.
 Instead they are obtained using the `WebTransport.incomingUnidirectionalStream` property.

`WebTransportReceiveStream` is a transferable object.

ReadableStream

WebTransportReceiveStream

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

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

*Inherits properties from its parent interface, `ReadableStream`.*

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

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

`WebTransportReceiveStream.getStats()`
Experimental

Returns a `Promise` that resolves with statistics related to this stream.

Examples
--------

See `WebTransport.incomingUnidirectionalStreams` for an example of how to get a `ReadableStream` of `WebTransportReceiveStream` objects.

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

| Specification |
| --- |
| WebTransport # webtransportreceivestream |

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

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

See also
--------

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


RTCIceCandidate - Web APIs

RTCIceCandidate
===============

The **`RTCIceCandidate`** interface—part of the WebRTC API—represents a candidate Interactive Connectivity Establishment (ICE) configuration which may be used to establish an `RTCPeerConnection`.

An ICE candidate describes the protocols and routing needed for WebRTC to be able to communicate with a remote device. When starting a WebRTC peer connection, typically a number of candidates are proposed by each end of the connection, until they mutually agree upon one which describes the connection they decide will be best. WebRTC then uses that candidate's details to initiate the connection.

For details on how the ICE process works, see Lifetime of a WebRTC session. The article WebRTC connectivity provides additional useful details.

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

`RTCIceCandidate()`

Creates an `RTCIceCandidate` object to represent a single ICE candidate, optionally configured based on a configuration object.

**Note:** For backwards compatibility, the constructor also accepts as input a string containing the value of the `candidate` property instead of the configuration object.

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

`address` Read only

A string containing the IP address of the candidate.

`candidate` Read only

A string representing the transport address for the candidate that can be used for connectivity checks. The format of this address is a `candidate-attribute` as defined in RFC 5245. This string is empty (`""`) if the `RTCIceCandidate` is an "end of candidates" indicator.

`component` Read only

A string which indicates whether the candidate is an RTP or an RTCP candidate; its value is either `rtp` or `rtcp`, and is derived from the `"component-id"` field in the `candidate` a-line string.

`foundation` Read only

Returns a string containing a unique identifier that is the same for any candidates of the same type, share the same base (the address from which the ICE agent sent the candidate), and come from the same STUN server. This is used to help optimize ICE performance while prioritizing and correlating candidates that appear on multiple `RTCIceTransport` objects.

`port` Read only

An integer value indicating the candidate's port number.

`priority` Read only

A long integer value indicating the candidate's priority.

`protocol` Read only

A string indicating whether the candidate's protocol is `"tcp"` or `"udp"`.

`relatedAddress` Read only

If the candidate is derived from another candidate, `relatedAddress` is a string containing that host candidate's IP address. For host candidates, this value is `null`.

`relatedPort` Read only

For a candidate that is derived from another, such as a relay or reflexive candidate, the `relatedPort` is a number indicating the port number of the candidate from which this candidate is derived. For host candidates, the `relatedPort` property is `null`.

`sdpMid` Read only

A string specifying the candidate's media stream identification tag which uniquely identifies the media stream within the component with which the candidate is associated, or `null` if no such association exists.

`sdpMLineIndex` Read only

If not `null`, `sdpMLineIndex` indicates the zero-based index number of the media description (as defined in RFC 4566) in the SDP with which the candidate is associated.

`tcpType` Read only

If `protocol` is `"tcp"`, `tcpType` represents the type of TCP candidate. Otherwise, `tcpType` is `null`.

`type` Read only

A string indicating the type of candidate as one of the strings listed on `RTCIceCandidate.type`.

`usernameFragment` Read only

A string containing a randomly-generated username fragment ("ice-ufrag") which ICE uses for message integrity along with a randomly-generated password ("ice-pwd"). You can use this string to verify generations of ICE generation; each generation of the same ICE process will use the same `usernameFragment`, even across ICE restarts.

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

`toJSON()`

 Returns a JSON representation of the `RTCIceCandidate`'s current configuration.
 The format of the representation is the same as the `candidateInfo` object that can optionally be passed to the `RTCIceCandidate() constructor` to configure a candidate.

Examples
--------

For examples, see the article Signaling and video calling, which demonstrates the entire process.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # rtcicecandidate-interface |

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

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


BluetoothRemoteGATTServer - Web APIs

BluetoothRemoteGATTServer
=========================

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

 The **`BluetoothRemoteGATTServer`** interface of the Web Bluetooth API represents a GATT
 Server on a remote device.

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

`BluetoothRemoteGATTServer.connected` Read only
Experimental

 A boolean value that returns true while this script execution environment is
 connected to `this.device`. It can be false while the user agent is
 physically connected.

`BluetoothRemoteGATTServer.device` Read only
Experimental

A reference to the `BluetoothDevice` running the server.

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

`BluetoothRemoteGATTServer.connect()`
Experimental

Causes the script execution environment to connect to `this.device`.

`BluetoothRemoteGATTServer.disconnect()`
Experimental

Causes the script execution environment to disconnect from `this.device`.

`BluetoothRemoteGATTServer.getPrimaryService()`
Experimental

 Returns a promise to the primary `BluetoothRemoteGATTService` offered by the
 Bluetooth device for a specified `BluetoothServiceUUID`.

`BluetoothRemoteGATTServer.getPrimaryServices()`
Experimental

 Returns a promise to a list of primary `BluetoothRemoteGATTService` objects
 offered by the Bluetooth device for a specified `BluetoothServiceUUID`.

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

| Specification |
| --- |
| Web Bluetooth # bluetoothgattremoteserver-interface |

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

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


FileSystem - Web APIs

FileSystem
==========

The File and Directory Entries API interface **`FileSystem`** is used to represent a file system. These objects can be obtained from the `filesystem` property on any file system entry. Some browsers offer additional APIs to create and manage file systems, such as Chrome's `requestFileSystem()` method.

This interface will not grant you access to the users' filesystem. Instead, you will have a "virtual drive" within the browser sandbox if you want to gain access to the users' file system, you need to invoke the user, for example by installing a Chrome extension. The relevant Chrome API can be found here.

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

There are two ways to get access to a `FileSystem` object:

1. You can directly ask for one representing a sandboxed file system created just for your web app directly by calling `window.requestFileSystem()`. If that call is successful, it executes a callback handler, which receives as a parameter a `FileSystem` object describing the file system.
2. You can get it from a file system entry object, through its `filesystem` property.
Instance properties
-------------------

`FileSystem.name` Read only

A string representing the file system's name. This name is unique among the entire list of exposed file systems.

`FileSystem.root` Read only

A `FileSystemDirectoryEntry` object which represents the file system's root directory. Through this object, you can gain access to all files and directories in the file system.

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

| Specification |
| --- |
| File and Directory Entries API # api-domfilesystem |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemEntry`, `FileSystemFileEntry`, and `FileSystemDirectoryEntry`


CloseEvent - Web APIs

CloseEvent
==========

A `CloseEvent` is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the `WebSocket` object's `onclose` attribute.

Event

CloseEventConstructor
-----------

`CloseEvent()`

Creates a new `CloseEvent`.

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

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

`CloseEvent.code` Read only

Returns an `unsigned short` containing the close code sent by the server.

`CloseEvent.reason` Read only

Returns a string indicating the reason the server closed the connection. This is specific to the particular server and sub-protocol.

`CloseEvent.wasClean` Read only

Returns a boolean value that Indicates whether or not the connection was cleanly closed.

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

*This interface also inherits methods from its parent, `Event`.*

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

| Specification |
| --- |
| WebSockets Standard # the-closeevent-interface |

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

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

See also
--------

* `WebSocket`


AnimationPlaybackEvent - Web APIs

AnimationPlaybackEvent
======================

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

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

* Learn more
* See full compatibility
* Report feedback
The AnimationPlaybackEvent interface of the Web Animations API represents animation events.

As animations play, they report changes to their `playState` through animation events.

Event

AnimationPlaybackEventConstructor
-----------

`AnimationPlaybackEvent()`

Constructs a new `AnimationPlaybackEvent` object instance.

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

`AnimationPlaybackEvent.currentTime` Read only

The current time of the animation that generated the event.

`AnimationPlaybackEvent.timelineTime` Read only

The time value of the timeline of the animation that generated the event.

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

| Specification |
| --- |
| Web Animations # the-animationplaybackevent-interface |

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

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

See also
--------

* Web Animations API
* `Animation.playState`


Comment - Web APIs

Comment
=======

The **`Comment`** interface represents textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view.

Comments are represented in HTML and XML as content between '`<!--`' and '`-->`'. In XML, like inside SVG or MathML markup, the character sequence '`--`' cannot be used within a comment.

EventTarget

Node

CharacterData

CommentInstance properties
-------------------

*This interface has no specific property, but inherits those of its parent, `CharacterData`, and indirectly those of `Node`.*

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

`Comment()`

Returns a new `Comment` object with the parameter as its textual content. If not present, its default value is the empty string, `''`.

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

*This interface has no specific method, but inherits those of its parent, `CharacterData`, and indirectly those of `Node`.*

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

| Specification |
| --- |
| DOM Standard # interface-comment |

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

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

See also
--------

* The DOM API


AesCbcParams - Web APIs

AesCbcParams
============

The **`AesCbcParams`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.encrypt()`, `SubtleCrypto.decrypt()`, `SubtleCrypto.wrapKey()`, or `SubtleCrypto.unwrapKey()`, when using the AES-CBC algorithm.

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

`name`

A string. This should be set to `AES-CBC`.

`iv`

An `ArrayBuffer`, a `TypedArray`, or a `DataView`. The initialization vector. Must be 16 bytes, unpredictable, and preferably cryptographically random. However, it need not be secret (for example, it may be transmitted unencrypted along with the ciphertext).

Examples
--------

See the examples for `SubtleCrypto.encrypt()` and `SubtleCrypto.decrypt()`.

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

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

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

Browsers that support the "AES-CBC" algorithm for the `SubtleCrypto.encrypt()`, `SubtleCrypto.decrypt()`, `SubtleCrypto.wrapKey()`, or `SubtleCrypto.unwrapKey()` methods will support this type.

See also
--------

* CBC mode is defined in section 6.2 of the NIST SP800-38A standard.
* `SubtleCrypto.encrypt()`.
* `SubtleCrypto.decrypt()`.
* `SubtleCrypto.wrapKey()`.
* `SubtleCrypto.unwrapKey()`.


RTCIceParameters - Web APIs

RTCIceParameters
================

The **`RTCIceParameters`** dictionary specifies the username fragment and password assigned to an ICE session.

During ICE negotiation, each peer's username fragment and password are recorded in an `RTCIceParameters` object, which can be obtained from the `RTCIceTransport` by calling its `getLocalParameters()` or `getRemoteParameters()` method, depending on which end interests you.

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

`usernameFragment`

A string specifying the value of the ICE session's username fragment field, `ufrag`.

`password`

A string specifying the session's password string.

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

The username fragment and password uniquely identify the remote peer for the duration of the ICE session, and are used to both ensure security and to avoid crosstalk across multiple ongoing ICE sessions. See `RTCIceCandidate.usernameFragment` for further information.

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

#### No specification found

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

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

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


GPU - Web APIs

GPU
===

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

The **`GPU`** interface of the WebGPU API is the starting point for using WebGPU. It can be used to return a `GPUAdapter` from which you can request devices, configure features and limits, and more.

The `GPU` object for the current context is accessed via the `Navigator.gpu` or `WorkerNavigator.gpu` properties.

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

`wgslLanguageFeatures`
Experimental
 Read only

A `WGSLLanguageFeatures` object that reports the WGSL language extensions supported by the WebGPU implementation.

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

`requestAdapter()`
Experimental

Returns a `Promise` that fulfills with a `GPUAdapter` object instance. From this you can request a `GPUDevice`, which is the primary interface for using WebGPU functionality.

`getPreferredCanvasFormat()`
Experimental

Returns the optimal canvas texture format for displaying 8-bit depth, standard dynamic range content on the current system.

Examples
--------

### Requesting an adapter and a device

```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();

  //...
}
```

### Configuring a GPUCanvasContext with the optimal texture format

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

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

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

| Specification |
| --- |
| WebGPU # gpu-interface |

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

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

See also
--------

* The WebGPU API


ContentIndex - Web APIs

ContentIndex
============

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

The **`ContentIndex`** interface of the Content Index API allows developers to register their offline enabled content with the browser.

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

There are no properties of this interface.

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

`ContentIndex.add()`
Experimental

Registers an item with the content index.

`ContentIndex.delete()`
Experimental

Unregisters an item from the currently indexed content.

`ContentIndex.getAll()`
Experimental

Returns a `Promise` that resolves with an iterable list of content index entries.

Examples
--------

### Feature detection and interface access

Here we get a reference to the `ServiceWorkerRegistration`, then check for the `index` property, which gives us access to the content index interface.

```js
// reference registration
const registration = await navigator.serviceWorker.ready;

// feature detection
if ("index" in registration) {
  // Content Index API functionality
  const contentIndex = registration.index;
}
```

### Adding to the content index

Here we're declaring an item in the correct format and creating an asynchronous function which uses the `add()` method to register it with the content index.

```js
// our content
const item = {
  id: "post-1",
  url: "/posts/amet.html",
  title: "Amet consectetur adipisicing",
  description:
    "Repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.",
  icons: [
    {
      src: "/media/dark.png",
      sizes: "128x128",
      type: "image/png",
    },
  ],
  category: "article",
};

// our asynchronous function to add indexed content
async function registerContent(data) {
  const registration = await navigator.serviceWorker.ready;

  // feature detect Content Index
  if (!registration.index) {
    return;
  }

  // register content
  try {
    await registration.index.add(data);
  } catch (e) {
    console.log("Failed to register content: ", e.message);
  }
}
```

### Retrieving items within the current index

The below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface.

```js
async function createReadingList() {
  // access our service worker registration
  const registration = await navigator.serviceWorker.ready;

  // get our index entries
  const entries = await registration.index.getAll();

  // create a containing element
  const readingListElem = document.createElement("div");

  // test for entries
  if (!Array.length) {
    // if there are no entries, display a message
    const message = document.createElement("p");
    message.innerText =
      "You currently have no articles saved for offline reading.";

    readingListElem.append(message);
  } else {
    // if entries are present, display in a list of links to the content
    const listElem = document.createElement("ul");

    for (const entry of entries) {
      const listItem = document.createElement("li");

      const anchorElem = document.createElement("a");
      anchorElem.innerText = entry.title;
      anchorElem.setAttribute("href", entry.url);

      listElem.append(listItem);
    }

    readingListElem.append(listElem);
  }
}
```

### Unregistering indexed content

Below is an asynchronous function, that removes an item from the content index.

```js
async function unregisterContent(article) {
  // reference registration
  const registration = await navigator.serviceWorker.ready;

  // feature detect Content Index
  if (!registration.index) return;

  // unregister content from index
  await registration.index.delete(article.id);
}
```

All the above methods are available within the scope of the service worker. They are accessible from the `WorkerGlobalScope.self` property:

```js
// service worker script

self.registration.index.add(item);

self.registration.index.delete(item.id);

const contentIndexItems = self.registration.index.getAll();
```

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

| Specification |
| --- |
| Content Index # content-index |

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

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

See also
--------

* An introductory article on the Content Index API
* An app which uses the Content Index API to list and remove 'save for later' content
* Service Worker API, along with information about Cache and CacheStorage


Fetch API - Web APIs

Fetch API
=========

The Fetch API provides an interface for fetching resources (including across the network). It is a more powerful and flexible replacement for `XMLHttpRequest`.

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

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

The Fetch API uses `Request` and `Response` objects (and other things involved with network requests), as well as related concepts such as CORS and the HTTP Origin header semantics.

For making a request and fetching a resource, use the `fetch()` method. It is a global method in both `Window` and `Worker` contexts. This makes it available in pretty much any context you might want to fetch resources in.

The `fetch()` method takes one mandatory argument, the path to the resource you want to fetch. It returns a `Promise` that resolves to the `Response` to that request — as soon as the server responds with headers — **even if the server response is an HTTP error status**. You can also optionally pass in an `init` options object as the second argument (see `Request`).

Once a `Response` is retrieved, there are a number of methods available to define what the body content is and how it should be handled.

You can create a request and response directly using the `Request()` and `Response()` constructors, but it's uncommon to do this directly. Instead, these are more likely to be created as results of other API actions (for example, `FetchEvent.respondWith()` from service workers).

Find out more about using the Fetch API features in Using Fetch, and study concepts in Fetch basic concepts.

Fetch Interfaces
----------------

`fetch()`

The `fetch()` method used to fetch a resource.

`Headers`

Represents response/request headers, allowing you to query them and take different actions depending on the results.

`Request`

Represents a resource request.

`Response`

Represents the response to a request.

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

| Specification |
| --- |
| Fetch Standard # fetch-method |

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

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

See also
--------

* Using Fetch
* Service Worker API
* HTTP access control (CORS)
* HTTP
* Fetch polyfill
* Fetch basic concepts


XRAnchorSet - Web APIs

XRAnchorSet
===========

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

The **`XRAnchorSet`** interface exposes a collection of anchors. Its instances are returned by `XRFrame.trackedAnchors` and are `Set`-like objects.

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

See `Set` for details.

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

See `Set` for details.

Examples
--------

### Handling anchor tracking loss

```js
const trackedAnchors = frame.trackedAnchors;

for (const anchor of previousFrameAnchors) {
  if (!trackedAnchors.has(anchor)) {
    // Handle anchor tracking loss
  }
}
```

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

| Specification |
| --- |
| WebXR Anchors Module # xranchorset |

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

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

See also
--------

* `XRAnchor`
* `XRFrame.trackedAnchors`