GPUQuerySet - Web APIs

GPUQuerySet
===========

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

The **`GPUQuerySet`** interface of the WebGPU API is used to record the results of queries on passes, such as occlusion or timestamp queries.

* Occlusion queries are available on render passes to query whether any fragment samples pass all the per-fragment tests for a set of drawing commands (including scissor, sample mask, alpha to coverage, stencil, and depth tests). To run an occlusion query, an appropriate `GPUQuerySet` must be provided as the value of the `occlusionQuerySet` descriptor property when invoking `GPUCommandEncoder.beginRenderPass()` to run a render pass.
* Timestamp queries allow applications to write timestamps to a `GPUQuerySet`. To run a timestamp query, appropriate `GPUQuerySet`s must be provided inside the value of the `timestampWrites` descriptor property when invoking `GPUCommandEncoder.beginRenderPass()` to run a render pass, or `GPUCommandEncoder.beginComputePass()` to run a compute pass. Alternatively, you can run a single timestamp query at any time by invoking `GPUCommandEncoder.writeTimeStamp()` with an appropriate `GPUQuerySet` as a parameter.

**Note:** To use timestamp queries, the `timestamp-query` feature must be enabled in the `GPUDevice`.

A `GPUQuerySet` object instance is created using the `GPUDevice.createQuerySet()` method.

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

`count`
Experimental
 Read only

A number specifying the number of queries managed by the `GPUQuerySet`.

`label`
Experimental

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

`type`
Experimental
 Read only

An enumerated value specifying the type of queries managed by the `GPUQuerySet`.

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

`destroy()`
Experimental

Destroys the `GPUQuerySet`.

Examples
--------

The following snippet creates a `GPUQuerySet` that holds 32 occlusion query results, and then returns the `type` and `count`:

```js
const querySet = device.createQuerySet({
  type: "occlusion",
  count: 32,
});

console.log(querySet.count); // 32
console.log(querySet.type); // "occlusion"
```

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

| Specification |
| --- |
| WebGPU # gpuqueryset |

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

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

See also
--------

* The WebGPU API


HTML Sanitizer API - Web APIs

HTML Sanitizer API
==================

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

**Warning:** This documentation reflects stale browser implementations.
 The specification has changed significantly since the docs were written, and they will need to be updated once browser implementations catch up.

The **HTML Sanitizer API** allow developers to take untrusted strings of HTML and `Document` or `DocumentFragment` objects, and sanitize them for safe insertion into a document's DOM.

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

 Web applications often need to work with untrusted HTML on the client side, for example, as part of a client-side templating solution or for rendering user generated content, or when including data in a frame from another site.
 The Sanitizer API allows for rendering of this potentially untrusted HTML in a safe manner.

 To access the API you would use the `Sanitizer()` constructor to create and configure a `Sanitizer` instance.
 The configuration options parameter allows you to specify the allowed and dis-allowed elements and attributes, and to enable custom elements and comments.

 The most common use-case - preventing XSS - is handled by the default configuration.
 Creating a `Sanitizer()` with a custom configuration is necessary only to handle additional, application-specific use cases.

The API has two main methods for sanitizing data:

1. `Element.setHTML()` parses and sanitizes a string of HTML and immediately inserts it into the DOM as a child of the current element.
 This is essentially a "safe" version of `Element.innerHTML`, and should be used instead of `innerHTML` when inserting untrusted data.
2. `Sanitizer.sanitize()` sanitizes data that is in a `Document` or `DocumentFragment`. It might be used, for example, to sanitize a `Document` instance in a frame.
### Parsing and sanitizing strings

The result of parsing a string of HTML depends on the context/the element into which it is inserted.

 For example, an HTML string containing `<td>` elements is valid if inserted under a `<table>` elements, but will be dropped if inserted in a `<div>` element.
 Similarly, an `<em>` element is a valid node in a `<div>` but the tag will be escaped if used in a `<textarea>`:

```html
<!-- "<em>bla</em>" inserted into <div> -->
<div><em>bla</em></div>

<!-- "<em>bla</em>" inserted into <textarea> -->
<textarea><em>bla</textarea>
```

 The target element must therefore be known when the parser is run and the resulting subtree must be inserted into that same type of element in the DOM, or the result will be incorrect.
 This consideration does not matter for `Element.setHTML()` as it is called on a particular element and the context is therefore implicit.

 The parser may also perform normalization operations on the input string.
 As a result, even if the HTML is valid and the sanitizer method does nothing, the sanitized output may not precisely match the unsanitized input.
 This applies to both methods.

Interfaces
----------

`Sanitizer`
Experimental

Provides the functionality to define a sanitizer configuration, to sanitize untrusted strings of HTML for later insertion into the DOM, and to sanitize `Document` and `DocumentFragment` objects.

`Element.setHTML()`

Parses a string of HTML into a subtree of nodes, sanitizes it using a `Sanitizer` object, then sets it as a child of the current element.

Examples
--------

The following examples show how to use the sanitizer API using the *default* sanitizer (at time of writing configuration operations are not yet supported).

### Sanitize a string immediately

The code below demonstrates how `Element.setHTML()` is used to sanitize a string of HTML and insert it into the `Element` with an id of `target`.

The `script` element is disallowed by the default sanitizer so the alert is removed.

```js
const unsanitized_string = "abc <script>alert(1)<" + "/script> def"; // Unsanitized string of HTML

const sanitizer = new Sanitizer(); // Default sanitizer;

// Get the Element with id "target" and set it with the sanitized string.
const target = document.getElementById("target");
target.setHTML(unsanitized_string, { sanitizer });

console.log(target.innerHTML);
// "abc def"
```

### Sanitize a frame

To sanitize data from an `<iframe>` with id `userFrame`:

```js
const sanitizer = new Sanitizer(); // Default sanitizer;

// Get the frame and its Document object
const frame_element = document.getElementById("userFrame");
const unsanitized_frame_tree = frame_element.contentWindow.document;

// Sanitize the document tree and update the frame.
const sanitized_frame_tree = sanitizer.sanitize(unsanitized_frame_tree);
frame_element.replaceChildren(sanitized_frame_tree);
```

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

| Specification |
| --- |
| HTML Sanitizer API # sanitizer-api |

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

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


MediaMetadata - Web APIs

MediaMetadata
=============

The **`MediaMetadata`** interface of the Media Session API allows a web page to provide rich media metadata for display in a platform UI.

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

`MediaMetadata()`

Creates a new `MediaMetaData` object.

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

`MediaMetadata.title`

Returns or sets the title of the media to be played.

`MediaMetadata.artist`

Returns or sets the name of the artist, group, creator, etc. of the media to be played.

`MediaMetadata.album`

Returns or sets the name of the album or collection containing the media to be played.

`MediaMetadata.artwork`

Returns or sets an array of images associated with playing media.

Examples
--------

The following example checks for browser compatibility and sets the current metadata for the media session.

```js
if ("mediaSession" in navigator) {
  navigator.mediaSession.metadata = new MediaMetadata({
    title: "Unforgettable",
    artist: "Nat King Cole",
    album: "The Ultimate Collection (Remastered)",
    artwork: [
      {
        src: "https://dummyimage.com/96x96",
        sizes: "96x96",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/128x128",
        sizes: "128x128",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/192x192",
        sizes: "192x192",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/256x256",
        sizes: "256x256",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/384x384",
        sizes: "384x384",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/512x512",
        sizes: "512x512",
        type: "image/png",
      },
    ],
  });
}
```

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

| Specification |
| --- |
| Media Session # the-mediametadata-interface |

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

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


StylePropertyMapReadOnly - Web APIs

StylePropertyMapReadOnly
========================

The **`StylePropertyMapReadOnly`** interface of the CSS Typed Object Model API provides a read-only representation of a CSS declaration block that is an alternative to `CSSStyleDeclaration`. Retrieve an instance of this interface using `Element.computedStyleMap()`.

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

`StylePropertyMapReadOnly.size`

Returns an unsigned long integer containing the size of the `StylePropertyMapReadOnly` object.

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

`StylePropertyMapReadOnly.entries()`

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

`StylePropertyMapReadOnly.forEach()`

Executes a provided function once for each element of `StylePropertyMapReadOnly`.

`StylePropertyMapReadOnly.get()`

Returns the value of the specified property.

`StylePropertyMapReadOnly.getAll()`

Returns an array of `CSSStyleValue` objects containing the values for the provided property.

`StylePropertyMapReadOnly.has()`

Indicates whether the specified property is in the `StylePropertyMapReadOnly` object.

`StylePropertyMapReadOnly.keys()`

Returns a new *array iterator* containing the keys for each item in `StylePropertyMapReadOnly`.

`StylePropertyMapReadOnly.values()`

Returns a new *array iterator* containing the values for each index in the `StylePropertyMapReadOnly` object.

Examples
--------

We have to have an element to observe:

```html
<p>
  This is a paragraph with some text. We can add some CSS, or not. The style map
  will include all the default and inherited CSS property values.
</p>
<dl id="output"></dl>
```

We add a touch of CSS with a custom property to better demonstrate the output:

```css
p {
  --someVariable: 1.6em;
  --someOtherVariable: translateX(33vw);
  --anotherVariable: 42;
  line-height: var(--someVariable);
}
```

We add JavaScript to grab our paragraph and return back a definition list of all the default CSS property values using `Element.computedStyleMap()`.

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

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

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

// iterate through the map of all the properties and values, adding a <dt> and <dd> for each
for (const [prop, val] of stylePropertyMap) {
  // properties
  const cssProperty = document.createElement("dt");
  cssProperty.innerText = prop;
  stylesList.appendChild(cssProperty);

  // values
  const cssValue = document.createElement("dd");
  cssValue.innerText = val;
  stylesList.appendChild(cssValue);
}
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # the-stylepropertymap |

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

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


HTMLFormControlsCollection - Web APIs

HTMLFormControlsCollection
==========================

The **`HTMLFormControlsCollection`** interface represents a *collection* of HTML *form control elements*, returned by the `HTMLFormElement` interface's `elements` property.

This interface replaces one method from `HTMLCollection`, on which it is based.

HTMLCollection

HTMLFormControlsCollectionInstance properties
-------------------

*This interface inherits the properties of its parent, `HTMLCollection`.*

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

*This interface inherits the methods of its parent, `HTMLCollection`.*

`HTMLFormControlsCollection.namedItem()`

Returns the `RadioNodeList` or the `Element` in the collection whose `name` or `id` matches the specified name, or `null` if no nodes match. Note that this version of `namedItem()` hides the one inherited from `HTMLCollection`. Like that method, using the JavaScript array bracket syntax with a `String`, as in `collection["value"]`, is equivalent to `collection.namedItem("value")`.

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

| Specification |
| --- |
| HTML Standard # htmlformcontrolscollection |

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

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

See also
--------

* `HTMLCollection`, `RadioNodeList`, `HTMLOptionsCollection`


RTCAudioSourceStats - Web APIs

RTCAudioSourceStats
===================

The WebRTC API's **`RTCAudioSourceStats`** dictionary provides information about an audio track that is attached to one or more senders.

These statistics can be obtained by iterating the `RTCStatsReport` returned by `RTCRtpSender.getStats()` or `RTCPeerConnection.getStats()` until you find a report with the `type` of `media-source` and a `kind` of `audio`.

**Note:** For audio information about remotely sourced tracks (that are being received), see `RTCInboundRtpStreamStats`.

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

`audioLevel`
Experimental

A number that represents the audio level of the media source.

`totalAudioEnergy`
Experimental

A number that represents the total audio energy of the media source over the lifetime of the stats object.

`totalSamplesDuration`
Experimental

A number that represents the total duration of all samples produced by the media source over the lifetime of the stats object.

The following properties are present in both `RTCAudioSourceStats` and `RTCVideoSourceStats`:

`trackIdentifier`

A string that contains the `id` value of the `MediaStreamTrack` associated with the audio source.

`kind`

A string indicating whether this object represents stats for a video source or a media source. For an `RTCAudioSourceStats` this will always be `audio`.

### Common instance properties

The following properties are common to all statistics objects.

`id`

A string that uniquely identifies the object that is being monitored to produce this set of statistics.

`timestamp`

A `DOMHighResTimeStamp` object indicating the time at which the sample was taken for this statistics object.

`type`

A string with the value `"media-source"`, indicating that the object is an instance of either `RTCAudioSourceStats` or `RTCVideoSourceStats`.

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

 The interface provides statistics about an audio media source attached to one or more senders.
 The information includes the current audio level, averaged over a short (implementation dependent) duration.

 The statistics also include the accumulated total energy and total sample duration, at a particular timestamp.
 The totals can be used to determine the average audio level over the lifetime of the stats object.
 You can calculate a root mean square (RMS) value in the same units as `audioLevel` using the following formula:

totalAudioEnergy
totalSamplesDuration

You can also use the accumulated totals to calculate the average audio level over an arbitrary time period.

 The total audio energy of the stats object is accumulated by adding the energy of every sample over the lifetime of the stats object, while the total duration is accumulated by adding the duration of each sample.
 The energy of each sample is determined using the following formula, where `sample_level` is the level of the sample, `max_level` is the highest-intensity encodable value, and `duration` is the duration of the sample in seconds:

duration

(

sample\_level
max\_level

)

2

The average audio level between any two different `getStats()` calls, over any duration, can be calculated using the following equation:

totalAudioEnergy
2

-

totalAudioEnergy
1

totalSamplesDuration
2

-

totalSamplesDuration
1

Examples
--------

This example shows how you might iterate the stats object returned from `RTCRtpSender.getStats()` to get the audio source stats, and then extract the `audioLevel`.

```js
// where sender is an RTCRtpSender
const stats = await sender.getStats();
let audioSourceStats = null;

stats.forEach((report) => {
  if (report.type === "media-source" && report.kind==="audio") {
    audioSourceStats = report;
    break;
  }
});

const audioLevel = audioSourceStats?.audioLevel;
```

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstatstype-media-source |

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

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


Force Touch events - Web APIs

Force Touch events
==================

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

**Force Touch Events** are a proprietary, Apple-specific feature which makes possible (where supported by the input hardware) new interactions based on how hard the user clicks or presses down on the touchscreen or trackpad.

Events
------

`webkitmouseforcewillbegin`
Non-standard

This event is fired before the `mousedown` event. Its main use is that it can be `Event.preventDefault()`ed.

`webkitmouseforcedown`
Non-standard

This event is fired after the `mousedown` event as soon as sufficient pressure has been applied for it to qualify as a "force click".

`webkitmouseforceup`
Non-standard

This event is fired after the `webkitmouseforcedown` event as soon as the pressure has been reduced sufficiently to end the "force click".

`webkitmouseforcechanged`
Non-standard

This event is fired each time the amount of pressure changes. This event first fires after the `mousedown` event and stops firing before the `mouseup` event.

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

The following property is known to be available on the `webkitmouseforcewillbegin`, `mousedown`, `webkitmouseforcechanged`, `webkitmouseforcedown`, `webkitmouseforceup`, `mousemove`, and `mouseup` event objects:

`MouseEvent.webkitForce`
Non-standard
 Read only

The amount of pressure currently being applied to the trackpad/touchscreen.

Constants
---------

These constants are useful for determining the relative intensity of the pressure indicated by `MouseEvent.webkitForce`:

`MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN`
Non-standard
 Read only

Minimum force necessary for a normal click.

`MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN`
Non-standard
 Read only

Minimum force necessary for a force click.

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

*Not part of any specification.* Apple has a description at the Mac Developer Library.


KeyboardLayoutMap - Web APIs

KeyboardLayoutMap
=================

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

The **`KeyboardLayoutMap`** interface of the Keyboard API is a read-only object with functions for retrieving the string associated with specific physical keys.

A `KeyboardLayoutMap` instance is a read-only `Map`-like object, in which each key is a string identifying the unique physical key on the keyboard (a "key code"), and the corresponding value is the associated key attribute value (which may be affected by the keyboard layout, and so on).

A list of valid keys is found in the UI Events KeyboardEvent code Values specification.

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

`KeyboardLayoutMap.size` Read only
Experimental

Returns the number of elements in the `KeyboardLayoutMap` object.

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

`KeyboardLayoutMap.[@@iterator]()`
Experimental

Returns a new Iterator object that contains the key/value pairs.

`KeyboardLayoutMap.entries()`
Experimental

Returns a new Iterator object that contains the key/value pairs.

`KeyboardLayoutMap.forEach()`
Experimental

Executes a provided function once for each element of `KeyboardLayoutMap`.

`KeyboardLayoutMap.get()`
Experimental

Returns the element with the given key from the `KeyboardLayoutMap` object.

`KeyboardLayoutMap.has()`
Experimental

Returns a boolean indicating whether the `KeyboardLayoutMap` object has an element with the specified key.

`KeyboardLayoutMap.keys()`
Experimental

Returns a new Iterator object that contains the keys for each index in the `KeyboardLayoutMap` object.

`KeyboardLayoutMap.values()`
Experimental

Returns a new Iterator object that contains the values for each index in the `KeyboardLayoutMap` object.

Examples
--------

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

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

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

| Specification |
| --- |
| Keyboard Map # keyboardlayoutmap-interface |

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

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


TextFormat - Web APIs

TextFormat
==========

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

The **`TextFormat`** interface represents specific formatting that should be applied to a range of text in an editable text region that's attached to an `EditContext` instance. The text formatting is requested by the Input Method Editor (IME) window that the user is composing text with.

When using one of the default editable regions of the web, such as a `<textarea>` element, IME composition is handled by the browser and operating system for you. For example, when using Japanese IME in a textarea, on Windows, the following text formats can be applied:

* When text is being composed with the keyboard, the typed characters have a thin wavy underline:

 ![A textarea in Microsoft Edge on Windows with some Japanese text being composed from the IME window](/en-US/docs/Web/API/TextFormat/ime-squiggle-underline.png)
* When the user selects a suggestion from the list of candidates in the IME window, the text is replaced and is underlined with a thick solid line:

 ![A textarea in Microsoft Edge on Windows with some Japanese text being selected from the IME window](/en-US/docs/Web/API/TextFormat/ime-solid-underline.png)

When creating your own custom editable region by using the EditContext API, you need to handle IME composition yourself. You should listen for the `textformatupdate` event, which gives you the list of text formats that the IME window wants to apply to the text being composed. You should then update the formatting of the text displayed in your editable region accordingly.

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

`TextFormat()`
Experimental

Returns a new `TextFormat` instance.

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

`TextFormat.rangeStart` Read only
Experimental

The start position of the text range that needs to be formatted with the given text format.

`TextFormat.rangeEnd` Read only
Experimental

The end position of the text range that needs to be formatted with the given text format.

`TextFormat.underlineStyle` Read only
Experimental

The style of the underline that needs to be applied to the text range that is being formatted.

`TextFormat.underlineThickness` Read only
Experimental

The thickness of the underline that needs to be applied to the text range that is being formatted.

Examples
--------

### Using the `textformatupdate` event

In the following example, the `textformatupdate` event is used to log the various formats that the IME composition window wants to apply to text ranges in the editable element. Note that the event listener callback in this example is only called when using an IME window to compose text.

```html
<div id="editor" style="height:200px;background:#eee;"></div>
```

```js
const editorEl = document.getElementById("editor");
const editContext = new EditContext(editorEl);
editorEl.editContext = editContext;

editContext.addEventListener("textformatupdate", (e) => {
  // Get the TextFormat instances.
  const formats = e.getTextFormats();

  // Iterate over the TextFormat instances.
  for (const format of formats) {
    console.log(
      `Applying a ${format.underlineThickness} ${format.underlineStyle} underline between ${format.rangeStart} and ${format.rangeEnd}.`,
    );
  }
});
```

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

| Specification |
| --- |
| EditContext API # dom-textformat |

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

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


ImageTrackList - Web APIs

ImageTrackList
==============

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

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

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

The **`ImageTrackList`** interface of the WebCodecs API represents a list of image tracks.

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

`ImageTrackList.ready` Read only
Experimental

Returns a `promise` that resolves once the `ImageTrackList` has been populated with `tracks`.

`ImageTrackList.length` Read only
Experimental

Returns an integer indicating the length of the `ImageTrackList`.

`ImageTrackList.selectedIndex` Read only
Experimental

Returns an integer indicating the index of the `selectedTrack`.

`ImageTrackList.selectedTrack` Read only
Experimental

Returns the selected `ImageTrack`.

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

| Specification |
| --- |
| WebCodecs # imagetracklist-interface |

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

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


SVGFEMergeNodeElement - Web APIs

SVGFEMergeNodeElement
=====================

The **`SVGFEMergeNodeElement`** interface corresponds to the `<feMergeNode>` element.

EventTarget

Node

Element

SVGElement

SVGFEMergeNodeElementInstance properties
-------------------

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

`SVGFEMergeNodeElement.in1` Read only

An `SVGAnimatedString` corresponding to the `in` attribute of the given element.

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

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

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

| Specification |
| --- |
| Filter Effects Module Level 1 # InterfaceSVGFEMergeNodeElement |

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

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

See also
--------

* `<feMergeNode>`


ServiceWorker - Web APIs

ServiceWorker
=============

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

The **`ServiceWorker`** interface of the Service Worker API provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique `ServiceWorker` object.

A `ServiceWorker` object is available via a number of properties:

* `ServiceWorkerRegistration.active`
* `ServiceWorkerGlobalScope.serviceWorker`
* `ServiceWorkerContainer.controller` — when the service worker is in `activating` or `activated` state
* `ServiceWorkerRegistration.installing` — when the service worker is in `installing` state
* `ServiceWorkerRegistration.waiting` — when the service worker is in `installed` state

The `ServiceWorker` interface is dispatched a set of lifecycle events — `install` and `activate` — and functional events including `fetch`. A `ServiceWorker` object has an associated `ServiceWorker.state`, related to its lifecycle.

 Service workers allow static import of ECMAScript modules, if supported, using `import`.
 Dynamic import is disallowed by the specification — calling `import()` will throw.

EventTarget

ServiceWorkerInstance properties
-------------------

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

`ServiceWorker.scriptURL` Read only

Returns the `ServiceWorker` serialized script URL defined as part of `ServiceWorkerRegistration`. The URL must be on the same origin as the document that registers the `ServiceWorker`.

`ServiceWorker.state` Read only

Returns the state of the service worker. It returns one of the following values: `parsed`, `installing`, `installed`, `activating`, `activated`, or `redundant`.

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

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

`ServiceWorker.postMessage()`

Sends a message — consisting of any structured-cloneable JavaScript object — to the service worker. The message is transmitted to the service worker using a `message` event on its global scope.

Events
------

`statechange`

Fired when `ServiceWorker.state` changes.

`error`

Fired when an error happens inside the `ServiceWorker` object.

Examples
--------

This code snippet is from the service worker registration-events sample (live demo). The code listens for any change in the `ServiceWorker.state` and returns its value.

```js
if ("serviceWorker" in navigator) {
  navigator.serviceWorker
    .register("service-worker.js", {
      scope: "./",
    })
    .then((registration) => {
      let serviceWorker;
      if (registration.installing) {
        serviceWorker = registration.installing;
        document.querySelector("#kind").textContent = "installing";
      } else if (registration.waiting) {
        serviceWorker = registration.waiting;
        document.querySelector("#kind").textContent = "waiting";
      } else if (registration.active) {
        serviceWorker = registration.active;
        document.querySelector("#kind").textContent = "active";
      }
      if (serviceWorker) {
        // logState(serviceWorker.state);
        serviceWorker.addEventListener("statechange", (e) => {
          // logState(e.target.state);
        });
      }
    })
    .catch((error) => {
      // Something went wrong during registration. The service-worker.js file
      // might be unavailable or contain a syntax error.
    });
} else {
  // The current browser doesn't support service workers.
  // Perhaps it is too old or we are not in a Secure Context.
}
```

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

| Specification |
| --- |
| Service Workers # serviceworker-interface |

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

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

See also
--------

* The Offline Cookbook(service workers)
* Using Service Workers
* Service worker basic code example
* Using web workers


VRStageParameters - Web APIs

VRStageParameters
=================

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

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

The **`VRStageParameters`** interface of the WebVR API represents the values describing the stage area for devices that support room-scale experiences.

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

This interface is accessible through the `VRDisplay.stageParameters` property.

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

`VRStageParameters.sittingToStandingTransform`
Deprecated
 Read only
Non-standard

Contains a matrix that transforms the sitting-space view matrices of `VRFrameData` to standing-space.

`VRStageParameters.sizeX`
Deprecated
 Read only
Non-standard

*Returns the width* of the play-area bounds in meters.

`VRStageParameters.sizeY`
Deprecated
 Read only
Non-standard

*Returns the depth* of the play-area bounds in meters.

Examples
--------

```js
const info = document.querySelector("p");
let vrDisplay;

navigator.getVRDisplays().then((displays) => {
  vrDisplay = displays[0];
  const stageParams = vrDisplay.stageParameters;
  // stageParams is a VRStageParameters object

  if (stageParams === null) {
    info.textContent =
      "Your VR Hardware does not support room-scale experiences.";
  } else {
    info.innerHTML =
      `<strong>Display stage parameters</strong><br>` +
      `Sitting to standing transform: ${stageParams.sittingToStandingTransform}<br>` +
      `Play area width (m): ${stageParams.sizeX}<br>` +
      `Play area depth (m): ${stageParams.sizeY}`;
  }
});
```

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

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

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

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

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

See also
--------

* WebVR API


SVGAnimatedTransformList - Web APIs

SVGAnimatedTransformList
========================

SVG animated transform list interface
-------------------------------------

The `SVGAnimatedTransformList` interface is used for attributes which take a list of numbers and which can be animated.

### Interface overview

|  |  |
| --- | --- |
| Also implement | *None* |
| Methods | *None* |
| Properties | * readonly `SVGTransformList`
`baseVal`
* readonly `SVGTransformList`
`animVal`
 |
| Normative document | SVG 1.1 (2nd Edition) |

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

| Name | Type | Description |
| --- | --- | --- |
| `baseVal` | `SVGTransformList` | The base value of the given attribute before applying any animations. |
| `animVal` | `SVGTransformList` |
 A read only `SVGTransformList` representing
 the current animated value of the given attribute. If the given
 attribute is not currently being animated, then the
 `SVGTransformList` will have the same contents
 as `baseVal`. The object referenced by
 `animVal` will always be distinct from the one referenced by
 `baseVal`, even when the attribute is not animated.
  |

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

The `SVGAnimatedTransformList` interface doesn't provide any specific methods.

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

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


CSSStyleRule - Web APIs

CSSStyleRule
============

The **`CSSStyleRule`** interface represents a single CSS style rule.

CSSRule

CSSGroupingRule

CSSStyleRuleInstance properties
-------------------

*Inherits properties from its ancestor `CSSRule`.*

`CSSStyleRule.selectorText`

Returns the textual representation of the selector for this rule, e.g. `"h1, h2"`.

`CSSStyleRule.style` Read only

Returns the `CSSStyleDeclaration` object for the rule.

`CSSStyleRule.styleMap` Read only

Returns a `StylePropertyMap` object which provides access to the rule's property-value pairs.

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

*No specific methods; inherits methods from its ancestor `CSSRule`.*

Examples
--------

 The CSS includes one style rule. This will be the first `CSSRule` returned by `document.styleSheets[0].cssRules`.
 `myRules[0]` therefore returns a `CSSStyleRule` object representing the rule defined for `h1`.

```css
h1 {
  color: pink;
}
```

```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); // a CSSStyleRule representing the h1.
```

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

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

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

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


File - Web APIs

File
====

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

The **`File`** interface provides information about files and allows JavaScript in a web page to access their content.

`File` objects are generally retrieved from a `FileList` object returned as a result of a user selecting files using the `<input>` element, or from a drag and drop operation's `DataTransfer` object.

A `File` object is a specific kind of `Blob`, and can be used in any context that a Blob can. In particular, `FileReader`, `URL.createObjectURL()`, `createImageBitmap()`, the `body` option to `fetch()`, and `XMLHttpRequest.send()` accept both `Blob`s and `File`s.

See Using files from web applications for more information and examples.

Blob

FileConstructor
-----------

`File()`

Returns a newly constructed `File`.

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

*The `File` interface also inherits properties from the `Blob` interface.*

`File.lastModified` Read only

Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight).

`File.lastModifiedDate`
Deprecated
 Read only
Non-standard

Returns the last modified `Date` of the file referenced by the `File` object.

`File.name` Read only

Returns the name of the file referenced by the `File` object.

`File.webkitRelativePath` Read only

Returns the path the URL of the `File` is relative to.

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

*The `File` interface also inherits methods from the `Blob` interface.*

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

| Specification |
| --- |
| File API # file-section |

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

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

See also
--------

* Using files from web applications
* `FileReader`


HTMLParamElement - Web APIs

HTMLParamElement
================

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

The **`HTMLParamElement`** interface provides special properties (beyond those of the regular `HTMLElement` object interface it inherits) for manipulating `<param>` elements, representing a pair of a key and a value that acts as a parameter for an `<object>` element.

EventTarget

Node

Element

HTMLElement

HTMLParamElementInstance properties
-------------------

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

`HTMLParamElement.name`
Deprecated

A string representing the name of the parameter. It reflects the `name` attribute.

`HTMLParamElement.value`
Deprecated

A string representing the value associated to the parameter. It reflects the `value` attribute.

`HTMLParamElement.type`
Deprecated

A string containing the type of the parameter when `valueType` has the `"ref"` value. It reflects the `type` attribute.

`HTMLParamElement.valueType`
Deprecated

A string containing the type of the `value`. It reflects the valuetype attribute and has one of the values: `"data"`, `"ref"`, or `"object"`.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlparamelement |

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

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

See also
--------

* The HTML element implementing this interface: `<param>`.


XPathNSResolver - Web APIs

XPathNSResolver
===============

The `XPathNSResolver` interface permits prefix strings in an XPath expression to be properly bound to namespace URI strings.

The `XPathEvaluator` interface can construct an implementation of `XPathNSResolver` from a node, or the interface may be implemented by any application.

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

`XPathNSResolver.lookupNamespaceURI()`

Looks up the namespace URI associated to the given namespace prefix.

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

#### No specification found

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

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

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

See also
--------

* `XPathEvaluator`


GamepadButton - Web APIs

GamepadButton
=============

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

The **`GamepadButton`** interface defines an individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device.

A `GamepadButton` object is returned by querying any value of the array returned by the `buttons` property of the `Gamepad` interface.

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

`GamepadButton.pressed` Read only

A boolean value indicating whether the button is currently pressed (`true`) or unpressed (`false`).

`GamepadButton.touched` Read only

A boolean value indicating whether the button is currently touched (`true`) or not touched (`false`).

`GamepadButton.value` Read only

A double value used to represent the current state of analog buttons, such as the triggers on many modern gamepads. The values are normalized to the range 0.0 —1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed.

Example
-------

The button values in the following example are stored as an array of `GamepadButton` objects. This simple example checks to see if the `GamepadButton.value` of a button is greater than `0`, or if the `GamepadButton.pressed` property indicates the button has been pressed.

```js
function gameLoop() {
  const gp = navigator.getGamepads()[0];

  if (gp.buttons[0].value > 0 || gp.buttons[0].pressed) {
    b--;
  } else if (gp.buttons[1].value > 0 || gp.buttons[1].pressed) {
    a++;
  } else if (gp.buttons[2].value > 0 || gp.buttons[2].pressed) {
    b++;
  } else if (gp.buttons[3].value > 0 || gp.buttons[3].pressed) {
    a--;
  }

  ball.style.left = `${a \* 2}px`; // ball is a UI widget
  ball.style.top = `${b \* 2}px`;

  requestAnimationFrame(gameLoop);
}
```

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

| Specification |
| --- |
| Gamepad # gamepadbutton-interface |

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

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

See also
--------

Using the Gamepad API


IndexedDB API - Web APIs

IndexedDB API
=============

IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data. While Web Storage is useful for storing smaller amounts of data, it is less useful for storing larger amounts of structured data. IndexedDB provides a solution. This is the main landing page for MDN's IndexedDB coverage — here we provide links to the full API reference and usage guides, browser support details, and some explanation of key concepts.

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

Key concepts and usage
----------------------

IndexedDB is a transactional database system, like an SQL-based Relational Database Management System (RDBMS). However, unlike SQL-based RDBMSes, which use fixed-column tables, IndexedDB is a JavaScript-based object-oriented database. IndexedDB lets you store and retrieve objects that are indexed with a **key**; any objects supported by the structured clone algorithm can be stored. You need to specify the database schema, open a connection to your database, and then retrieve and update data within a series of **transactions**.

* Read more about IndexedDB key characteristics and basic terminology.
* Learn to use IndexedDB asynchronously from first principles with our Using IndexedDB guide.

**Note:** Like most web storage solutions, IndexedDB follows a same-origin policy. So while you can access stored data within a domain, you cannot access data across different domains.

### Synchronous and asynchronous

Operations performed using IndexedDB are done asynchronously, so as not to block applications.

### Storage limits and eviction criteria

There are a number of web technologies that store data of one kind or another on the client side (i.e. on your local disk). IndexedDB is most commonly talked about. The process by which the browser works out how much space to allocate to web data storage and what to delete when that limit is reached is not simple, and differs between browsers. Browser storage quotas and eviction criteria attempts to explain how this works, at least in the case of Firefox.

Interfaces
----------

To get access to a database, call `open()` on the `indexedDB` attribute of a window object. This method returns an `IDBRequest` object; asynchronous operations communicate to the calling application by firing events on `IDBRequest` objects.

### Connecting to a database

`IDBFactory`

Provides access to a database. This is the interface implemented by the global object `indexedDB` and is therefore the entry point for the API.

`IDBOpenDBRequest`

Represents a request to open a database.

`IDBDatabase`

Represents a connection to a database. It's the only way to get a transaction on the database.

### Retrieving and modifying data

`IDBTransaction`

Represents a transaction. You create a transaction on a database, specify the scope (such as which object stores you want to access), and determine the kind of access (read only or readwrite) that you want.

`IDBRequest`

Generic interface that handles database requests and provides access to results.

`IDBObjectStore`

Represents an object store that allows access to a set of data in an IndexedDB database, looked up via primary key.

`IDBIndex`

Also allows access to a subset of data in an IndexedDB database, but uses an index to retrieve the record(s) rather than the primary key. This is sometimes faster than using `IDBObjectStore`.

`IDBCursor`

Iterates over object stores and indexes.

`IDBCursorWithValue`

Iterates over object stores and indexes and returns the cursor's current value.

`IDBKeyRange`

Defines a key range that can be used to retrieve data from a database in a certain range.

`IDBLocaleAwareKeyRange`
Non-standard

Defines a key range that can be used to retrieve data from a database in a certain range, sorted according to the rules of the locale specified for a certain index (see the `options` parameter to `IDBObjectStore.createIndex()`.) This interface isn't part of the 2.0 specification.

### Custom event interfaces

This specification fires events with the following custom interface:

`IDBVersionChangeEvent`

The `IDBVersionChangeEvent` interface indicates that the version of the database has changed, as the result of an `IDBOpenDBRequest.onupgradeneeded` event handler function.

Examples
--------

* To-do Notifications (view example live): The reference application for the examples in the reference docs.
Specifications
--------------

| Specification |
| --- |
| Indexed Database API 3.0  |

See also
--------

* Web Storage API
* Window: localStorage property
* Window: sessionStorage property
* StorageEvent


XRLayerEvent - Web APIs

XRLayerEvent
============

**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 **`XRLayerEvent`** interface of the WebXR Device API is the event type for events related to a change of state of an `XRLayer` object. These events occur, for example, when the layer needs to be redrawn.

Event

XRLayerEventConstructor
-----------

`XRLayerEvent()`
Experimental

Creates and returns a new `XRLayerEvent` object.

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

*In addition to properties inherited from its parent interface, `Event`, `XRLayerEvent` provides the following:*

`layer` Read only
Experimental

The `XRLayer` which generated the event.

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

*While `XRSessionEvent` defines no methods, it inherits methods from its parent interface, `Event`.*

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

*The following events are represented using the `XRLayerEvent` interface, and are permitted values for its `type` parameter.*

### `redraw` event

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

* `XRQuadLayer`: `redraw`
* `XRCylinderLayer`: `redraw`
* `XREquirectLayer`: `redraw`
* `XRCubeLayer`: `redraw`
Specifications
--------------

| Specification |
| --- |
| WebXR Layers API Level 1 # xrlayerevent-interface |

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

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

See also
--------

* `XRCompositionLayer.needsRedraw`


DOMTokenList - Web APIs

DOMTokenList
============

The **`DOMTokenList`** interface represents a set of space-separated tokens. Such a set is returned by `Element.classList` or `HTMLLinkElement.relList`, and many others.

A `DOMTokenList` is indexed beginning with `0` as with JavaScript `Array` objects. `DOMTokenList` is always case-sensitive.

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

`DOMTokenList.length` Read only

An `integer` representing the number of objects stored in the object.

`DOMTokenList.value`

A stringifier property that returns the value of the list as a string.

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

`DOMTokenList.item()`

Returns the item in the list by its index, or `null` if the index is greater than or equal to the list's `length`.

`DOMTokenList.contains()`

Returns `true` if the list contains the given token, otherwise `false`.

`DOMTokenList.add()`

Adds the specified tokens to the list.

`DOMTokenList.remove()`

Removes the specified tokens from the list.

`DOMTokenList.replace()`

Replaces the token with another one.

`DOMTokenList.supports()`

Returns `true` if the given token is in the associated attribute's supported tokens.

`DOMTokenList.toggle()`

Removes the token from the list if it exists, or adds it to the list if it doesn't. Returns a boolean indicating whether the token is in the list after the operation.

`DOMTokenList.entries()`

Returns an iterator, allowing you to go through all key/value pairs contained in this object.

`DOMTokenList.forEach()`

Executes a provided callback function once for each `DOMTokenList` element.

`DOMTokenList.keys()`

Returns an iterator, allowing you to go through all keys of the key/value pairs contained in this object.

`DOMTokenList.values()`

Returns an iterator, allowing you to go through all values of the key/value pairs contained in this object.

Examples
--------

In the following simple example, we retrieve the list of classes set on a `<p>` element as a `DOMTokenList` using `Element.classList`, add a class using `DOMTokenList.add()`, and then update the `Node.textContent` of the `<p>` to equal the `DOMTokenList`.

First, the HTML:

```html
<p class="a b c"></p>
```

Now the JavaScript:

```js
let para = document.querySelector("p");
let classes = para.classList;
para.classList.add("d");
para.textContent = `paragraph classList is "${classes}"`;
```

The output looks like this:

Trimming of whitespace and removal of duplicates
------------------------------------------------

Methods that modify the `DOMTokenList` (such as `DOMTokenList.add()`) automatically trim any excess Whitespace and remove duplicate values from the list. For example:

```html
<span class=" d d e f"></span>
```

```js
let span = document.querySelector("span");
let classes = span.classList;
span.classList.add("x");
span.textContent = `span classList is "${classes}"`;
```

The output looks like this:

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

| Specification |
| --- |
| DOM Standard # interface-domtokenlist |

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

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


RTCDTMFToneChangeEvent - Web APIs

RTCDTMFToneChangeEvent
======================

The **`RTCDTMFToneChangeEvent`** interface represents events sent to indicate that DTMF tones have started or finished playing. This interface is used by the `tonechange` event.

Event

RTCDTMFToneChangeEventInstance properties
-------------------

*In addition to the properties of `Event`, this interface offers the following:*

`RTCDTMFToneChangeEvent.tone` Read only

A string specifying the tone which has begun playing, or an empty string (`""`) if the previous tone has finished playing.

Constructors
------------

`RTCDTMFToneChangeEvent()`

Returns a new `RTCDTMFToneChangeEvent`. It takes two parameters, the first being a string representing the type of the event (always `"tonechange"`); the second a dictionary containing the initial state of the properties of the event.

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

*Supports the methods defined in `Event`. There are no additional methods.*

Examples
--------

This snippet is derived loosely from the full, working example you'll find in the section on When a tone finishes playing. It appends each tone to a display box as it's played, and, once all tones have been sent, re-enabled a previously-disabled "Send" button, allowing the next DMTF string to be entered.

```js
dtmfSender.addEventListener(
  "change",
  (event) => {
    if (event.tone !== "") {
      dialStringBox.innerText += event.tone;
    } else {
      sendDTMFButton.disabled = false;
    }
  },
  false,
);
```

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

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

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

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

See also
--------

* WebRTC
* Its usual target: `RTCDTMFSender`.


InstallEvent - Web APIs

InstallEvent
============

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

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

The parameter passed into the `oninstall` handler, the `InstallEvent` interface represents an install action that is dispatched on the `ServiceWorkerGlobalScope` of a `ServiceWorker`. As a child of `ExtendableEvent`, it ensures that functional events such as `FetchEvent` are not dispatched during installation.

This interface inherits from the `ExtendableEvent` interface.

**Note:** Instead of using the deprecated `ServiceWorkerGlobalScope.oninstall()` handler to catch events of this type, instead handle the (non-deprecated) `install` using a listener added with `addEventListener()`.

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

`InstallEvent()`
Deprecated

Non-standard

Creates a new `InstallEvent` object.

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

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

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

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

Examples
--------

This code snippet is from the service worker prefetch sample (see prefetch running live.) The code calls `ExtendableEvent.waitUntil()` in `ServiceWorkerGlobalScope.oninstall` and delays treating the `ServiceWorkerRegistration.installing` worker as installed until the passed promise resolves successfully. The promise resolves when all resources have been fetched and cached, or when any exception occurs.

The code snippet also shows a best practice for versioning caches used by the service worker. Although this example has only one cache, you can use this approach for multiple caches. The code maps a shorthand identifier for a cache to a specific, versioned cache name.

**Note:** Logging statements are visible in Google Chrome via the "Inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals.

```js
const CACHE\_VERSION = 1;
const CURRENT\_CACHES = {
  prefetch: `prefetch-cache-v${CACHE\_VERSION}`,
};

self.addEventListener("install", (event) => {
  const urlsToPrefetch = [
    "./static/pre\_fetched.txt",
    "./static/pre\_fetched.html",
    "https://www.chromium.org/\_/rsrc/1302286216006/config/customLogo.gif",
  ];

  console.log(
    "Handling install event. Resources to pre-fetch:",
    urlsToPrefetch,
  );

  event.waitUntil(
    caches
      .open(CURRENT\_CACHES["prefetch"])
      .then((cache) => {
        return cache
          .addAll(
            urlsToPrefetch.map((urlToPrefetch) => {
              return new Request(urlToPrefetch, { mode: "no-cors" });
            }),
          )
          .then(() => {
            console.log("All resources have been fetched and cached.");
          });
      })
      .catch((error) => {
        console.error("Pre-fetching failed:", error);
      }),
  );
});
```

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

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

See also
--------

* `install` event
* `NotificationEvent`
* `Promise`
* Fetch API


HTMLMarqueeElement - Web APIs

HTMLMarqueeElement
==================

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

The **`HTMLMarqueeElement`** interface provides methods to manipulate `<marquee>` elements.

It inherits properties and methods from the `HTMLElement` interface.

EventTarget

Node

Element

HTMLElement

HTMLMarqueeElementInstance properties
-------------------

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

`HTMLMarqueeElement.behavior`
Deprecated

Sets how the text is scrolled within the marquee. Possible values are `scroll`, `slide` and `alternate`. If no value is specified, the default value is `scroll`.

`HTMLMarqueeElement.bgColor`
Deprecated

Sets the background color through color name or hexadecimal value.

`HTMLMarqueeElement.direction`
Deprecated

Sets the direction of the scrolling within the marquee. Possible values are `left`, `right`, `up` and `down`. If no value is specified, the default value is `left`.

`HTMLMarqueeElement.height`
Deprecated

Sets the height in pixels or percentage value.

`HTMLMarqueeElement.hspace`
Deprecated

Sets the horizontal margin.

`HTMLMarqueeElement.loop`
Deprecated

Sets the number of times the marquee will scroll. If no value is specified, the default value is −1, which means the marquee will scroll continuously.

`HTMLMarqueeElement.scrollAmount`
Deprecated

Sets the amount of scrolling at each interval in pixels. The default value is 6.

`HTMLMarqueeElement.scrollDelay`
Deprecated

Sets the interval between each scroll movement in milliseconds. The default value is 85. Note that any value smaller than 60 is ignored and the value 60 is used instead, unless `trueSpeed` is `true`.

`HTMLMarqueeElement.trueSpeed`
Deprecated

By default, `scrollDelay` values lower than 60 are ignored. If `trueSpeed` is `true`, then those values are not ignored.

`HTMLMarqueeElement.vspace`
Deprecated

Sets the vertical margin.

`HTMLMarqueeElement.width`
Deprecated

Sets the width in pixels or percentage value.

### Event handlers

`HTMLMarqueeElement.onbounce`
Deprecated

Fires when the marquee has reached the end of its scroll position. It can only fire when the behavior attribute is set to `alternate`.

`HTMLMarqueeElement.onfinish`
Deprecated

Fires when the marquee has finished the amount of scrolling that is set by the loop attribute. It can only fire when the loop attribute is set to some number that is greater than 0.

`HTMLMarqueeElement.onstart`
Deprecated

Fires when the marquee starts scrolling.

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

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

`HTMLMarqueeElement.start()`
Deprecated

Starts scrolling of the marquee.

`HTMLMarqueeElement.stop()`
Deprecated

Stops scrolling of the marquee.

Examples
--------

```html
<marquee>This text will scroll from right to left</marquee>

<marquee direction="up">This text will scroll from bottom to top</marquee>

<marquee
 direction="down"
 width="250"
 height="200"
 behavior="alternate"
 style="border:solid">
  <marquee behavior="alternate">This text will bounce</marquee>
</marquee>
```

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

| Specification |
| --- |
| HTML Standard # htmlmarqueeelement |

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

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

See also
--------

* `<marquee>`


CanvasRenderingContext2D - Web APIs

CanvasRenderingContext2D
========================

 The **`CanvasRenderingContext2D`** interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a `<canvas>` element.
 It is used for drawing shapes, text, images, and other objects.

 The interface's properties and methods are described in the reference section of this page.
 The Canvas tutorial has more explanation, examples, and resources, as well.

 For `OffscreenCanvas`, there is an equivalent interface that provides the rendering context.
 The offscreen rendering context inherits most of the same properties and methods as the `CanvasRenderingContext2D` and is described in more detail in the `OffscreenCanvasRenderingContext2D` reference page.

Basic example
-------------

To get a `CanvasRenderingContext2D` instance, you must first have an HTML `<canvas>` element to work with:

```html
<canvas id="my-house" width="300" height="300"></canvas>
```

To get the canvas' 2D rendering context, call `getContext()` on the `<canvas>` element, supplying `'2d'` as the argument:

```js
const canvas = document.getElementById("my-house");
const ctx = canvas.getContext("2d");
```

With the context in hand, you can draw anything you like. This code draws a house:

```js
// Set line width
ctx.lineWidth = 10;

// Wall
ctx.strokeRect(75, 140, 150, 110);

// Door
ctx.fillRect(130, 190, 40, 60);

// Roof
ctx.beginPath();
ctx.moveTo(50, 140);
ctx.lineTo(150, 60);
ctx.lineTo(250, 140);
ctx.closePath();
ctx.stroke();
```

The resulting drawing looks like this:

Reference
---------

### Context

`CanvasRenderingContext2D.isContextLost()`
Experimental

Returns `true` if the rendering context was lost.

### Drawing rectangles

There are three methods that immediately draw rectangles to the canvas.

`CanvasRenderingContext2D.clearRect()`

Sets all pixels in the rectangle defined by starting point *(x, y)* and size *(width, height)* to transparent black, erasing any previously drawn content.

`CanvasRenderingContext2D.fillRect()`

Draws a filled rectangle at *(x, y)* position whose size is determined by *width* and *height*.

`CanvasRenderingContext2D.strokeRect()`

Paints a rectangle which has a starting point at *(x, y)* and has a *w* width and an *h* height onto the canvas, using the current stroke style.

### Drawing text

The following methods draw text. See also the `TextMetrics` object for text properties.

`CanvasRenderingContext2D.fillText()`

Draws (fills) a given text at the given (x, y) position.

`CanvasRenderingContext2D.strokeText()`

Draws (strokes) a given text at the given (x, y) position.

`CanvasRenderingContext2D.measureText()`

Returns a `TextMetrics` object.

### Line styles

The following methods and properties control how lines are drawn.

`CanvasRenderingContext2D.lineWidth`

Width of lines. Default `1.0`.

`CanvasRenderingContext2D.lineCap`

Type of endings on the end of lines. Possible values: `butt` (default), `round`, `square`.

`CanvasRenderingContext2D.lineJoin`

Defines the type of corners where two lines meet. Possible values: `round`, `bevel`, `miter` (default).

`CanvasRenderingContext2D.miterLimit`

Miter limit ratio. Default `10`.

`CanvasRenderingContext2D.getLineDash()`

Returns the current line dash pattern array containing an even number of non-negative numbers.

`CanvasRenderingContext2D.setLineDash()`

Sets the current line dash pattern.

`CanvasRenderingContext2D.lineDashOffset`

Specifies where to start a dash array on a line.

### Text styles

The following properties control how text is laid out.

`CanvasRenderingContext2D.font`

Font setting. Default value `"10px sans-serif"`.

`CanvasRenderingContext2D.textAlign`

Text alignment setting. Possible values: `start` (default), `end`, `left`, `right`, `center`.

`CanvasRenderingContext2D.textBaseline`

Baseline alignment setting. Possible values: `top`, `hanging`, `middle`, `alphabetic` (default), `ideographic`, `bottom`.

`CanvasRenderingContext2D.direction`

Directionality. Possible values: `ltr`, `rtl`, `inherit` (default).

`CanvasRenderingContext2D.letterSpacing`

Letter spacing. Default: `0px`.

`CanvasRenderingContext2D.fontKerning`

Font kerning. Possible values: `auto` (default), `normal`, `none`.

`CanvasRenderingContext2D.fontStretch`

Font stretch. Possible values: `ultra-condensed`, `extra-condensed`, `condensed`, `semi-condensed`, `normal` (default), `semi-expanded`, `expanded`, `extra-expanded`, `ultra-expanded`.

`CanvasRenderingContext2D.fontVariantCaps`

Font variant caps. Possible values: `normal` (default), `small-caps`, `all-small-caps`, `petite-caps`, `all-petite-caps`, `unicase`, `titling-caps`.

`CanvasRenderingContext2D.textRendering`

Text rendering. Possible values: `auto` (default), `optimizeSpeed`, `optimizeLegibility`, `geometricPrecision`.

`CanvasRenderingContext2D.wordSpacing`

Word spacing. Default value: `0px`

### Fill and stroke styles

Fill styling is used for colors and styles inside shapes and stroke styling is used for the lines around shapes.

`CanvasRenderingContext2D.fillStyle`

Color or style to use inside shapes. Default `#000` (black).

`CanvasRenderingContext2D.strokeStyle`

Color or style to use for the lines around shapes. Default `#000` (black).

### Gradients and patterns

`CanvasRenderingContext2D.createConicGradient()`

Creates a conic gradient around a point given by coordinates represented by the parameters.

`CanvasRenderingContext2D.createLinearGradient()`

Creates a linear gradient along the line given by the coordinates represented by the parameters.

`CanvasRenderingContext2D.createRadialGradient()`

Creates a radial gradient given by the coordinates of the two circles represented by the parameters.

`CanvasRenderingContext2D.createPattern()`

Creates a pattern using the specified image. It repeats the source in the directions specified by the repetition argument. This method returns a `CanvasPattern`.

### Shadows

`CanvasRenderingContext2D.shadowBlur`

Specifies the blurring effect. Default: `0`.

`CanvasRenderingContext2D.shadowColor`

Color of the shadow. Default: fully-transparent black.

`CanvasRenderingContext2D.shadowOffsetX`

Horizontal distance the shadow will be offset. Default: `0`.

`CanvasRenderingContext2D.shadowOffsetY`

Vertical distance the shadow will be offset. Default: `0`.

### Paths

The following methods can be used to manipulate paths of objects.

`CanvasRenderingContext2D.beginPath()`

Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.

`CanvasRenderingContext2D.closePath()`

Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.

`CanvasRenderingContext2D.moveTo()`

Moves the starting point of a new sub-path to the (x, y) coordinates.

`CanvasRenderingContext2D.lineTo()`

Connects the last point in the current sub-path to the specified (x, y) coordinates with a straight line.

`CanvasRenderingContext2D.bezierCurveTo()`

Adds a cubic Bézier curve to the current path.

`CanvasRenderingContext2D.quadraticCurveTo()`

Adds a quadratic Bézier curve to the current path.

`CanvasRenderingContext2D.arc()`

Adds a circular arc to the current path.

`CanvasRenderingContext2D.arcTo()`

Adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line.

`CanvasRenderingContext2D.ellipse()`

Adds an elliptical arc to the current path.

`CanvasRenderingContext2D.rect()`

Creates a path for a rectangle at position (x, y) with a size that is determined by *width* and *height*.

`CanvasRenderingContext2D.roundRect()`

Creates a path for a rounded rectangle with a specified position, width, height, and corner radii.

### Drawing paths

`CanvasRenderingContext2D.fill()`

Fills the current sub-paths with the current fill style.

`CanvasRenderingContext2D.stroke()`

Strokes the current sub-paths with the current stroke style.

`CanvasRenderingContext2D.drawFocusIfNeeded()`

If a given element is focused, this method draws a focus ring around the current path.

`CanvasRenderingContext2D.scrollPathIntoView()`
Experimental

Scrolls the current path or a given path into the view.

`CanvasRenderingContext2D.clip()`

Creates a clipping path from the current sub-paths. Everything drawn after `clip()` is called appears inside the clipping path only. For an example, see Clipping paths in the Canvas tutorial.

`CanvasRenderingContext2D.isPointInPath()`

Reports whether or not the specified point is contained in the current path.

`CanvasRenderingContext2D.isPointInStroke()`

Reports whether or not the specified point is inside the area contained by the stroking of a path.

### Transformations

Objects in the `CanvasRenderingContext2D` rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and `Path2D` objects. The methods listed below remain for historical and compatibility reasons as `DOMMatrix` objects are used in most parts of the API nowadays and will be used in the future instead.

`CanvasRenderingContext2D.getTransform()`

Retrieves the current transformation matrix being applied to the context.

`CanvasRenderingContext2D.rotate()`

Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.

`CanvasRenderingContext2D.scale()`

Adds a scaling transformation to the canvas units by x horizontally and by y vertically.

`CanvasRenderingContext2D.translate()`

Adds a translation transformation by moving the canvas and its origin x horizontally and y vertically on the grid.

`CanvasRenderingContext2D.transform()`

Multiplies the current transformation matrix with the matrix described by its arguments.

`CanvasRenderingContext2D.setTransform()`

Resets the current transform to the identity matrix, and then invokes the `transform()` method with the same arguments.

`CanvasRenderingContext2D.resetTransform()`

Resets the current transform by the identity matrix.

### Compositing

`CanvasRenderingContext2D.globalAlpha`

Alpha value that is applied to shapes and images before they are composited onto the canvas. Default `1.0` (opaque).

`CanvasRenderingContext2D.globalCompositeOperation`

With `globalAlpha` applied this sets how shapes and images are drawn onto the existing bitmap.

### Drawing images

`CanvasRenderingContext2D.drawImage()`

Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.

### Pixel manipulation

See also the `ImageData` object.

`CanvasRenderingContext2D.createImageData()`

Creates a new, blank `ImageData` object with the specified dimensions. All of the pixels in the new object are transparent black.

`CanvasRenderingContext2D.getImageData()`

Returns an `ImageData` object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at *(sx, sy)* and has an *sw* width and *sh* height.

`CanvasRenderingContext2D.putImageData()`

Paints data from the given `ImageData` object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.

### Image smoothing

`CanvasRenderingContext2D.imageSmoothingEnabled`

Image smoothing mode; if disabled, images will not be smoothed if scaled.

`CanvasRenderingContext2D.imageSmoothingQuality`

Allows you to set the quality of image smoothing.

### The canvas state

The `CanvasRenderingContext2D` rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:

`CanvasRenderingContext2D.save()`

Saves the current drawing style state using a stack so you can revert any change you make to it using `restore()`.

`CanvasRenderingContext2D.restore()`

Restores the drawing style state to the last element on the 'state stack' saved by `save()`.

`CanvasRenderingContext2D.canvas`

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

`CanvasRenderingContext2D.getContextAttributes()`

Returns an object containing the context attributes used by the browser. Context attributes can be requested when using `HTMLCanvasElement.getContext()` to create the 2D context.

`CanvasRenderingContext2D.reset()`

Resets the rendering context, including the backing buffer, the drawing state stack, path, and styles.

`CanvasRenderingContext2D.isContextLost()`
Experimental

Returns `true` if the rendering context was lost.

### Filters

`CanvasRenderingContext2D.filter`

Applies a CSS or SVG filter to the canvas, e.g., to change its brightness or blurriness.

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

| Specification |
| --- |
| HTML Standard # 2dcontext |

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

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

See also
--------

* `HTMLCanvasElement`
* `<canvas>`
* `OffscreenCanvas`


ErrorEvent - Web APIs

ErrorEvent
==========

The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files.

Event

ErrorEventInstance properties
-------------------

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

`ErrorEvent.message` Read only

A string containing a human-readable error message describing the problem. Lacking a `crossorigin` setting reduces error logging.

`ErrorEvent.filename` Read only

A string containing the name of the script file in which the error occurred.

`ErrorEvent.lineno` Read only

An `integer` containing the line number of the script file on which the error occurred.

`ErrorEvent.colno` Read only

An `integer` containing the column number of the script file on which the error occurred.

`ErrorEvent.error` Read only

A JavaScript `Object` that is concerned by the event.

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

`ErrorEvent()`

Creates an `ErrorEvent` event with the given parameters.

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

*Inherits methods from its parent `Event`*.

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

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

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

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

See also
--------

* Using web workers, most likely objects to raise such an event


SourceBuffer - Web APIs

SourceBuffer
============

The **`SourceBuffer`** interface represents a chunk of media to be passed into an `HTMLMediaElement` and played, via a `MediaSource` object. This can be made up of one or several media segments.

EventTarget

SourceBufferInstance properties
-------------------

`SourceBuffer.appendWindowEnd`

Controls the timestamp for the end of the append window.

`SourceBuffer.appendWindowStart`

Controls the timestamp for the start of the append window. This is a timestamp range that can be used to filter what media data is appended to the `SourceBuffer`. Coded media frames with timestamps within this range will be appended, whereas those outside the range will be filtered out.

`SourceBuffer.audioTracks` Read only

A list of the audio tracks currently contained inside the `SourceBuffer`.

`SourceBuffer.buffered` Read only

Returns the time ranges that are currently buffered in the `SourceBuffer`.

`SourceBuffer.mode`

Controls how the order of media segments in the `SourceBuffer` is handled, in terms of whether they can be appended in any order, or they have to be kept in a strict sequence.

`SourceBuffer.textTracks` Read only
Experimental

A list of the text tracks currently contained inside the `SourceBuffer`.

`SourceBuffer.timestampOffset`

Controls the offset applied to timestamps inside media segments that are subsequently appended to the `SourceBuffer`.

`SourceBuffer.updating` Read only

A boolean indicating whether the `SourceBuffer` is currently being updated — i.e. whether an `SourceBuffer.appendBuffer()` or `SourceBuffer.remove()` operation is currently in progress.

`SourceBuffer.videoTracks` Read only

A list of the video tracks currently contained inside the `SourceBuffer`.

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

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

`SourceBuffer.abort()`

Aborts the current segment and resets the segment parser.

`SourceBuffer.appendBuffer()`

Appends media segment data from an `ArrayBuffer`, a `TypedArray` or a `DataView` object to the `SourceBuffer`.

`SourceBuffer.appendBufferAsync()`
Non-standard

Experimental

Starts the process of asynchronously appending the specified buffer to the `SourceBuffer`. Returns a `Promise` which is fulfilled once the buffer has been appended.

`SourceBuffer.changeType()`

Changes the MIME type that future calls to `appendBuffer()` will expect the new data to conform to.

`SourceBuffer.remove()`

Removes media segments within a specific time range from the `SourceBuffer`.

`SourceBuffer.removeAsync()`
Non-standard

Experimental

Starts the process of asynchronously removing media segments in the specified range from the `SourceBuffer`. Returns a `Promise` which is fulfilled once all matching segments have been removed.

Events
------

`abort`

Fired whenever `SourceBuffer.appendBuffer()` is ended by a call to `SourceBuffer.abort()`. `SourceBuffer.updating` changes from `true` to `false`.

`error`

Fired whenever an error occurs during `SourceBuffer.appendBuffer()`. `SourceBuffer.updating` changes from `true` to `false`.

`update`

Fired whenever `SourceBuffer.appendBuffer()` or `SourceBuffer.remove()` completes. `SourceBuffer.updating` changes from `true` to `false`. This event is fired before `updateend`.

`updateend`

Fired after `SourceBuffer.appendBuffer()` or `SourceBuffer.remove()` ends. This event is fired after `update`.

`updatestart`

Fired whenever the value of `SourceBuffer.updating` changes from `false` to `true`.

Examples
--------

### Loading a video chunk by chunk

The following example loads a video chunk by chunk as fast as possible, playing it as soon as it can.

You can see the complete code at https://github.com/mdn/dom-examples/tree/main/sourcebuffer and try the demo live at https://mdn.github.io/dom-examples/sourcebuffer/.

```js
const video = document.querySelector("video");

const assetURL = "frag\_bunny.mp4";
// Need to be specific for Blink regarding codecs
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';

function loadVideo() {
  if (MediaSource.isTypeSupported(mimeCodec)) {
    const mediaSource = new MediaSource();
    console.log(mediaSource.readyState); // closed
    video.src = URL.createObjectURL(mediaSource);
    mediaSource.addEventListener("sourceopen", sourceOpen);
  } else {
    console.error("Unsupported MIME type or codec: ", mimeCodec);
  }
}

async function sourceOpen() {
  console.log(this.readyState); // open
  const mediaSource = this;
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  const response = await fetch(assetURL);
  const buffer = await response.arrayBuffer();
  sourceBuffer.addEventListener("updateend", () => {
    mediaSource.endOfStream();
    video.play();
    console.log(mediaSource.readyState); // ended
  });
  sourceBuffer.appendBuffer(buffer);
}

const load = document.querySelector("#load");
load.addEventListener("click", loadVideo);
```

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

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

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

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

See also
--------

* `MediaSource`
* `SourceBufferList`


Navigation API - Web APIs

Navigation API
==============

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

The **Navigation API** provides the ability to initiate, intercept, and manage browser navigation actions. It can also examine an application's history entries. This is a successor to previous web platform features such as the History API and `window.location`, which solves their shortcomings and is specifically aimed at the needs of single-page applications (SPAs).

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

In SPAs, the page template tends to stay the same during usage, and the content is dynamically rewritten as the user visits different pages or features. As a result, only one distinct page is loaded in the browser, which breaks the expected user experience of navigating back and forth between different locations in the viewing history. This problem can be solved to a degree via the History API, but it is not designed for the needs of SPAs. The Navigation API aims to bridge that gap.

The API is accessed via the `Window.navigation` property, which returns a reference to a global `Navigation` object. Each `window` object has its own corresponding `navigation` instance.

### Handling navigations

The `navigation` interface has several associated events, the most notable being the `navigate` event. This is fired when any type of navigation is initiated, meaning that you can control all page navigations from one central place, ideal for routing functionality in SPA frameworks. (This is not the case with the History API, where it is sometimes hard to figure out responding to all navigations.) The `navigate` event handler is passed a `NavigateEvent` object, which contains detailed information including details around the navigation's destination, type, whether it contains `POST` form data or a download request, and more.

The `NavigationEvent` object also provides two methods:

* `intercept()` takes as an argument a callback handler function returning a promise. It allows you to control what happens when the navigation is initiated. For example, in the case of an SPA, it can be used to load relevant new content into the UI based on the path of the URL navigated to.
* `scroll()` allows you to manually initiate the browser's scroll behavior (e.g. to a fragment identifier in the URL), if it makes sense for your code, rather than waiting for the browser to handle it automatically.

Once a navigation is initiated, and your `intercept()` handler is called, a `NavigationTransition` object instance is created (accessible via `Navigation.transition`), which can be used to track the process of the ongoing navigation.

**Note:** In this context "transition" refers to the transition between one history entry and another. It isn't related to CSS transitions.

**Note:** You can also call `preventDefault()` to stop the navigation entirely for most navigation types; cancellation of traverse navigations is not yet implemented.

When the `intercept()` handler function's promise fulfills, the `Navigation` object's `navigatesuccess` event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, `navigateerror` fires instead, allowing you to gracefully handle the failure case. There is also a `finished` property on the `NavigationTransition` object, which fulfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases.

**Note:** Before the Navigation API was available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate `History.pushState()` call, then set up the page view based on the new URL. And this wouldn't handle all navigations — only user-initiated link clicks.

### Programmatically updating and traversing the navigation history

As the user navigates through your application, each new location navigated to results in the creation of a navigation history entry. Each history entry is represented by a distinct `NavigationHistoryEntry` object instance. These contain several properties such as the entry's key, URL, and state information. You can get the entry that the user is currently on right now using `Navigation.currentEntry`, and an array of all existing history entries using `Navigation.entries()`. Each `NavigationHistoryEntry` object has a `dispose` event, which fires when the entry is no longer part of the browser history. For example, if the user navigates back three times, then navigates forward to somewhere else, those three history entries will be disposed of.

**Note:** The Navigation API only exposes history entries created in the current browsing context that have the same origin as the current page (e.g. not navigations inside embedded `<iframe>`s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than with the older History API.

The `Navigation` object contains all the methods you'll need to update and traverse through the navigation history:

`navigate()`
Experimental

Navigates to a new URL, creating a new navigation history entry.

`reload()`
Experimental

Reloads the current navigation history entry.

`back()`
Experimental

Navigates to the previous navigation history entry, if that is possible.

`forward()`
Experimental

Navigates to the next navigation history entry, if that is possible.

`traverseTo()`
Experimental

Navigates to a specific navigation history entry identified by its key value, which is obtained via the relevant entry's `NavigationHistoryEntry.key` property.

Each one of the above methods returns an object containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until:

* `committed` fulfills, meaning that the visible URL has changed and a new `NavigationHistoryEntry` has been created.
* `finished` fulfills, meaning that all promises returned by your `intercept()` handler are fulfilled. This is equivalent to the `NavigationTransition.finished` promise fulfilling, when the `navigatesuccess` event fires, as mentioned earlier.
* either one of the above promises rejects, meaning that the navigation has failed for some reason.
### State

The Navigation API allows you to store state on each history entry. This is developer-defined information — it can be whatever you like. For example, you might want to store a `visitCount` property that records the number of times a view has been visited, or an object containing multiple properties related to UI state, so that state can be restored when a user returns to that view.

To get a `NavigationHistoryEntry`'s state, you call its `getState()` method. It is initially `undefined`, but when state information is set on the entry, it will return the previously-set state information.

Setting state is a bit more nuanced. You can't retrieve the state value and then update it directly — the copy stored on the entry will not change. Instead, you update it while performing a `navigate()` or `reload()` — each one of these optionally takes an options object parameter, which includes a `state` property containing the new state to set on the history entry. When these navigations commit, the state change will be automatically applied.

In some cases however, a state change will be independent from a navigation or reload — for example when a page contains an expandable/collapsible `<details>` element. In this case, you might want to store the expanded/collapsed state in your history entry, so you can restore it when the user returns to the page or restarts their browser. Cases like this are handled using `Navigation.updateCurrentEntry()`. The `currententrychange` will fire when the current entry change is complete.

### Limitations

There are a few perceived limitations with the Navigation API:

1. The current specification doesn't trigger a `navigate` event on a page's first load. This might be fine for sites that use Server Side Rendering (SSR)—your server could return the correct initial state, which is the fastest way to get content to your users. But sites that leverage client-side code to create their pages may need an additional function to initialize the page.
2. The Navigation API operates only within a single frame—the top-level page, or a single specific `<iframe>`. This has some interesting implications that are further documented in the spec, but in practice, will reduce developer confusion. The previous History API has several confusing edge cases, like support for frames, which the Navigation API handles up-front.
3. You can't currently use the Navigation API to programmatically modify or rearrange the history list. It might be useful to have a temporary state, for example navigating the user to a temporary modal that asks them for some information, then going back to the previous URL. In this case, you'd want to delete the temporary modal navigation entry so the user cannot mess up the application flow by hitting the forward button and opening it again.
Interfaces
----------

`NavigateEvent`
Experimental

Event object for the `navigate` event, which fires when any type of navigation is initiated. It provides access to information about that navigation, and most notably the `intercept()`, which allows you to control what happens when the navigation is initiated.

`Navigation`
Experimental

Allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, examining navigation history entries, and managing navigations as they happen.

`NavigationCurrentEntryChangeEvent`
Experimental

Event object for the `currententrychange` event, which fires when the `Navigation.currentEntry` has changed. It provides access to the navigation type, and the previous history entry that was navigated from.

`NavigationDestination`
Experimental

Represents the destination being navigated to in the current navigation.

`NavigationHistoryEntry`
Experimental

Represents a single navigation history entry.

`NavigationTransition`
Experimental

Represents an ongoing navigation.

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

`Window.navigation` Read only
Experimental

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

Examples
--------

**Note:** Check out Domenic Denicola's Navigation API live demo.

### Handling a navigation using `intercept()`

```js
navigation.addEventListener("navigate", (event) => {
  // Exit early if this navigation shouldn't be intercepted,
  // e.g. if the navigation is cross-origin, or a download request
  if (shouldNotIntercept(event)) {
    return;
  }

  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        // The URL has already changed, so show a placeholder while
        // fetching the new content, such as a spinner or loading page
        renderArticlePagePlaceholder();

        // Fetch the new content and display when ready
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);
      },
    });
  }
});
```

### Handling scrolling using `scroll()`

In this example of intercepting a navigation, the `handler()` function starts by fetching and rendering some article content, but then fetches and renders some secondary content afterwards. It makes sense to scroll the page to the main article content as soon as it is available so the user can interact with it, rather than waiting until the secondary content is also rendered. To achieve this, we have added a `scroll()` call between the two.

```js
navigation.addEventListener("navigate", (event) => {
  if (shouldNotIntercept(event)) {
    return;
  }
  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);

        event.scroll();

        const secondaryContent = await getSecondaryContent(url.pathname);
        addSecondaryContent(secondaryContent);
      },
    });
  }
});
```

### Traversing to a specific history entry

```js
// On JS startup, get the key of the first loaded page
// so the user can always go back there.
const { key } = navigation.currentEntry;
backToHomeButton.onclick = () => navigation.traverseTo(key);

// Navigate away, but the button will always work.
await navigation.navigate("/another\_url").finished;
```

### Updating state

```js
navigation.navigate(url, { state: newState });
```

Or

```js
navigation.reload({ state: newState });
```

Or if the state is independent from a navigation or reload:

```js
navigation.updateCurrentEntry({ state: newState });
```

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

| Specification |
| --- |
| HTML Standard # navigation-api |

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

### api.Navigation

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

### api.NavigationDestination

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

### api.NavigationHistoryEntry

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

### api.NavigationTransition

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer