Picture-in-Picture API - Web APIs

Picture-in-Picture API
======================

The **Picture-in-Picture API** allow websites to create a floating, always-on-top video window. This allows users to continue consuming media while they interact with other sites or applications on their device.

**Note:** The Document Picture-in-Picture API extends the Picture-in-Picture API to allow the always-on-top window to be populated with *any* arbitrary HTML content, not just a video.

Interfaces
----------

`PictureInPictureWindow`

Represents the floating video window; contains `width` and `height` properties, and an `onresize` event handler property.

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

The Picture-in-Picture API adds methods to the `HTMLVideoElement` and `Document` interfaces to allow toggling of the floating video window.

### Instance methods on the HTMLVideoElement interface

`HTMLVideoElement.requestPictureInPicture()`

Requests that the user agent enters the video into picture-in-picture mode

### Instance methods on the Document interface

`Document.exitPictureInPicture()`

Requests that the user agent returns the element in picture-in-picture mode back into its original box.

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

The Picture-in-Picture API augments the `HTMLVideoElement`, `Document`, and `ShadowRoot` interfaces with properties that can be used to determine if the floating video window mode is supported and available, if picture-in-picture mode is currently active, and which video is floating.

### Instance properties on the HTMLVideoElement interface

`HTMLVideoElement.disablePictureInPicture`

The `disablePictureInPicture` property will provide a hint to the user agent to not suggest the picture-in-picture to users or to request it automatically.

### Instance properties on the Document interface

`Document.pictureInPictureEnabled`

The `pictureInPictureEnabled` property tells you whether or not it is possible to engage picture-in-picture mode. This is `false` if picture-in-picture mode is not available for any reason (e.g. the `"picture-in-picture"` feature has been disallowed, or picture-in-picture mode is not supported).

### Instance properties on the Document or ShadowRoot interfaces

`Document.pictureInPictureElement` / `ShadowRoot.pictureInPictureElement`

The `pictureInPictureElement` property tells you which `Element` is currently being displayed in the floating window (or in the shadow DOM). If this is `null`, the document (or shadow DOM) has no node currently in picture-in-picture mode.

Events
------

*The Picture-in-Picture API defines three events, which can be used to detect when picture-in-picture mode is toggled and when the floating video window is resized.*

`enterpictureinpicture`

Sent to a `HTMLVideoElement` when it enters picture-in-picture mode.

`leavepictureinpicture`

Sent to a `HTMLVideoElement` when it leaves picture-in-picture mode.

`resize`

Sent to a `PictureInPictureWindow` when it changes size.

Adding Controls
---------------

If media action handlers have been set via the Media Session API, then appropriate controls for those actions will be added by the browser to the picture-in-picture overlay. For example, if a `"nexttrack"` action has been set, then a skip button might be displayed in the picture-in-picture view. There is no support for adding custom HTML buttons or controls.

Controlling styling
-------------------

The `:picture-in-picture` CSS pseudo-class matches the video element currently in picture-in-picture mode, allowing you to configure your stylesheets to automatically adjust the size, style, or layout of content when a video switches back and forth between picture-in-picture and traditional presentation modes.

Controlling access
------------------

The availability of picture-in-picture mode can be controlled using Permissions Policy. The fullscreen mode feature is identified by the string `"picture-in-picture"`, with a default allowlist value of `"self"`, meaning that picture-in-picture mode is permitted in top-level document contexts, as well as to nested browsing contexts loaded from the same origin as the top-most document.

Examples
--------

In this example, a video is presented in a web page. Clicking the button below lets the user toggle the floating video window.

### Toggling picture-in-picture mode

This code is called by a click handler when the user clicks the "Toggle Picture-in-Picture" button:

```js
function togglePictureInPicture() {
  if (document.pictureInPictureElement) {
    document.exitPictureInPicture();
  } else if (document.pictureInPictureEnabled) {
    video.requestPictureInPicture();
  }
}
```

This block starts by looking at the value of the `document`'s `pictureInPictureElement` attribute.

If the value is not `null`, it's the element that's currently in picture-in-picture mode, that is in a floating window. We call `document.exitPictureInPicture()` to bring the video back into its initial box.

If the value is `null`, no video is in the floating window. So we can request a video to enter the picture-in-picture mode. We do it by calling `HTMLVideoElement.requestPictureInPicture()` on the `<video>` element.

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

| Specification |
| --- |
| Picture-in-Picture # interface-picture-in-picture-window |

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

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

See also
--------

* `HTMLVideoElement.requestPictureInPicture()`
* `HTMLVideoElement.disablePictureInPicture`
* `Document.pictureInPictureEnabled`
* `Document.exitPictureInPicture()`
* `Document.pictureInPictureElement`
* `:picture-in-picture`
* The Document Picture-in-Picture API


SVGViewElement - Web APIs

SVGViewElement
==============

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

EventTarget

Node

Element

SVGElement

SVGViewElementInstance properties
-------------------

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

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

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

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

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

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

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

See also
--------

* `<view>`


ANGLE_instanced_arrays - Web APIs

ANGLE\_instanced\_arrays
========================

The **`ANGLE_instanced_arrays`** extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type.

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

**Note:** This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default and the constants and methods are available without the "`ANGLE`" suffix.

Despite the name "ANGLE", this extension works on any device if the hardware supports it and not just on Windows when using the ANGLE library. "ANGLE" just indicates that this extension has been written by the ANGLE library authors.

Constants
---------

This extension exposes one new constant, which can be used in the `gl.getVertexAttrib()` method:

`ext.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE`

Returns a `GLint` describing the frequency divisor used for instanced rendering when used in the `gl.getVertexAttrib()` as the `pname` parameter.

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

This extension exposes three new methods.

`ext.drawArraysInstancedANGLE()`

Behaves identically to `gl.drawArrays()` except that multiple instances of the range of elements are executed, and the instance advances for each iteration.

`ext.drawElementsInstancedANGLE()`

Behaves identically to `gl.drawElements()` except that multiple instances of the set of elements are executed and the instance advances between each set.

`ext.vertexAttribDivisorANGLE()`

Modifies the rate at which generic vertex attributes advance when rendering multiple instances of primitives with `ext.drawArraysInstancedANGLE()` and `ext.drawElementsInstancedANGLE()`.

Examples
--------

The following example shows how to draw a given geometry multiple times with a single draw call.

**Warning:** The following is educational, not production level code. It should generally be avoided to construct data / buffers within the rendering loop or right before use.

```js
// enable the extension
const ext = gl.getExtension("ANGLE\_instanced\_arrays");

// binding the geometry buffer as usual
gl.bindBuffer(gl.ARRAY\_BUFFER, geometryVertexBuffer);
gl.enableVertexAttribArray(vertexPositionAttributeLocation);
gl.vertexAttribPointer(
  vertexPositionAttributeLocation,
  3,
  gl.FLOAT,
  false,
  0,
  0,
);

// build position buffer
const instancePositions = [];
for (const instance of instances) {
  instancePositions.push(
    instance.position.x,
    instance.position.y,
    instance.position.z,
  );
}
const instancePositionBuffer = createWebGLBufferFromData(instancePositions);

// binding the instance position buffer as you would with any attribute
gl.bindBuffer(gl.ARRAY\_BUFFER, instancePositionBuffer);
gl.enableVertexAttribArray(instancePositionAttributeLocation);
gl.vertexAttribPointer(
  instancePositionAttributeLocation,
  3,
  gl.FLOAT,
  false,
  0,
  0,
);

// mark the attribute as instanced and advance it every single(1) instance rather than every vertex
ext.vertexAttribDivisorANGLE(instancePositionAttributeLocation, 1);

// draw geometry for each instance
ext.drawArraysInstancedANGLE(
  gl.TRIANGLES,
  0,
  numGeometryVertices,
  instances.length,
);
```

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

| Specification |
| --- |
| WebGL ANGLE\_instanced\_arrays Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGL2RenderingContext.drawArraysInstanced()`
* `WebGL2RenderingContext.drawElementsInstanced()`
* `WebGL2RenderingContext.vertexAttribDivisor()`


SharedWorker - Web APIs

SharedWorker
============

The **`SharedWorker`** interface represents a specific kind of worker that can be *accessed* from several browsing contexts, such as several windows, iframes or even workers. They implement an interface different than dedicated workers and have a different global scope, `SharedWorkerGlobalScope`.

**Note:** If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host and port).

EventTarget

SharedWorkerConstructors
------------

`SharedWorker()`

Creates a shared web worker that executes the script at the specified URL.

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

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

`SharedWorker.port` Read only

Returns a `MessagePort` object used to communicate with and control the shared worker.

Events
------

`error`

Fires when an error occurs in the shared worker.

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

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

Example
-------

In our Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.

The following code snippet shows creation of a `SharedWorker` object using the `SharedWorker()` constructor. Both scripts contain this:

```js
const myWorker = new SharedWorker("worker.js");
```

**Note:** Once a shared worker is created, any script running in the same origin can obtain a reference to that worker and communicate with it. The shared worker will be alive as long as its global scope's owner set (a set of `Document` and `WorkerGlobalScope` objects) is not empty (for example, if there is any live page holding a reference to it, maybe through `new SharedWorker()`). To read more about shared worker lifetime, see The worker's lifetime section of the HTML specification.

Both scripts then access the worker through a `MessagePort` object created using the `SharedWorker.port` property. If the onmessage event is attached using addEventListener, the port is manually started using its `start()` method:

```js
myWorker.port.start();
```

When the port is started, both scripts post messages to the worker and handle messages sent from it using `port.postMessage()` and `port.onmessage`, respectively:

**Note:** You can use browser devtools to debug your SharedWorker, by entering a URL in your browser address bar to access the devtools workers inspector; for example, in Chrome, the URL `chrome://inspect/#workers`, and in FireFox, the URL `about:debugging#workers`.

```js
first.onchange = () => {
  myWorker.port.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};

second.onchange = () => {
  myWorker.port.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};

myWorker.port.onmessage = (e) => {
  result1.textContent = e.data;
  console.log("Message received from worker");
};
```

Inside the worker we use the `onconnect` handler to connect to the same port discussed above. The ports associated with that worker are accessible in the `connect` event's `ports` property — we then use `MessagePort` `start()` method to start the port, and the `onmessage` handler to deal with messages sent from the main threads.

```js
onconnect = (e) => {
  const port = e.ports[0];

  port.addEventListener("message", (e) => {
    const workerResult = `Result: ${e.data[0] \* e.data[1]}`;
    port.postMessage(workerResult);
  });

  port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
};
```

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

| Specification |
| --- |
| HTML Standard # shared-workers-and-the-sharedworker-interface |

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

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

See also
--------

* `Worker`


SVGTextPositioningElement - Web APIs

SVGTextPositioningElement
=========================

The **`SVGTextPositioningElement`** interface is implemented by elements that support attributes that position individual text glyphs. It is inherited by `SVGTextElement`, `SVGTSpanElement`, and `SVGTRefElement`.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGTextContentElement

SVGTextPositioningElementInstance properties
-------------------

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

`SVGTextPositioningElement.x` Read only

Returns an `SVGAnimatedLengthList` reflecting the `x` attribute of the given element.

`SVGTextPositioningElement.y` Read only

Returns an `SVGAnimatedLengthList` reflecting the `y` attribute of the given element.

`SVGTextPositioningElement.dx` Read only

Returns an `SVGAnimatedLengthList` reflecting the `dx` attribute of the given element.

`SVGTextPositioningElement.dy` Read only

Returns an `SVGAnimatedLengthList` reflecting the `dy` attribute of the given element.

`SVGTextPositioningElement.rotate` Read only

Returns an `SVGAnimatedNumberList` reflecting the `rotate` attribute of the given element.

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

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

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

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

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

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


VTTRegion - Web APIs

VTTRegion
=========

The `VTTRegion` interface—part of the API for handling WebVTT (text tracks on media presentations)—describes a portion of the video to render a `VTTCue` onto.

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

`VTTRegion()`

Returns a newly created `VTTRegion` object.

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

`VTTRegion.id`

A string that identifies the region.

`VTTRegion.width`

A `double` representing the width of the region, as a percentage of the video.

`VTTRegion.lines`

A `double` representing the height of the region, in number of lines.

`VTTRegion.regionAnchorX`

A `double` representing the region anchor X offset, as a percentage of the region.

`VTTRegion.regionAnchorY`

A `double` representing the region anchor Y offset, as a percentage of the region.

`VTTRegion.viewportAnchorX`

A `double` representing the viewport anchor X offset, as a percentage of the video.

`VTTRegion.viewportAnchorY`

A `double` representing the viewport anchor Y offset, as a percentage of the video.

`VTTRegion.scroll`

An enum representing how adding new cues will move existing cues.

Examples
--------

```js
const region = new VTTRegion();
region.width = 50; // Use 50% of the video width
region.lines = 4; // Use 4 lines of height.
region.viewportAnchorX = 25; // Have the region start at 25% from the left.
const cue = new VTTCue(2, 3, "Cool text to be displayed");
cue.region = region; // This cue will be drawn only within this region.
```

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

| Specification |
| --- |
| WebVTT: The Web Video Text Tracks Format # the-vttregion-interface |

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

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


ContentVisibilityAutoStateChangeEvent - Web APIs

ContentVisibilityAutoStateChangeEvent
=====================================

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 **`ContentVisibilityAutoStateChangeEvent`** interface is the event object for the `contentvisibilityautostatechange` event, which fires on any element with `content-visibility: auto` set on it when it starts or stops being relevant to the user and skipping its contents.

 While the element is not relevant (between the start and end events), the user agent skips an element's rendering, including layout and painting.
 This can significantly improve page rendering speed.
 The `contentvisibilityautostatechange` event provides a way for an app's code to also start or stop rendering processes (e.g. drawing on a `<canvas>`) when they are not needed, thereby conserving processing power.

Note that even when hidden from view, element contents will remain semantically relevant (e.g. to assistive technology users), so this signal should not be used to skip significant semantic DOM updates.

Event

ContentVisibilityAutoStateChangeEventConstructor
-----------

`ContentVisibilityAutoStateChangeEvent()`

Creates a new `ContentVisibilityAutoStateChangeEvent` object instance.

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

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

`skipped` Read only

Returns `true` if the user agent is skipping the element's rendering, or `false` otherwise.

Examples
--------

```js
const canvasElem = document.querySelector("canvas");

canvasElem.addEventListener("contentvisibilityautostatechange", stateChanged);
canvasElem.style.contentVisibility = "auto";

function stateChanged(event) {
  if (event.skipped) {
    stopCanvasUpdates(canvasElem);
  } else {
    startCanvasUpdates(canvasElem);
  }
}

// Call this when the canvas updates need to start.
function startCanvasUpdates(canvas) {
  // …
}

// Call this when the canvas updates need to stop.
function stopCanvasUpdates(canvas) {
  // …
}
```

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

| Specification |
| --- |
| CSS Containment Module Level 2 # content-visibility-auto-state-change |

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

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

See also
--------

* The `contentvisibilityautostatechange` event
* CSS Containment
* The `content-visibility` property
* The `contain` property


Idle Detection API - Web APIs

Idle Detection API
==================

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

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

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

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

The Idle Detection API provides a means to detect the user's idle status, active, idle, and locked, specifically, and to be notified of changes to idle status without polling from a script.

Concepts and Usage
------------------

Native applications and browser extensions use idle detection base user experiences on when a user is interacting with a device. For example, chat applications can show other users of an application whether someone is available. Other applications might choose to show notifications only when a user is interacting with the app. A web application could use this API for similar use cases. Additionally, a progressive web app could use idle detection to trigger a service worker update when the app isn't being used.

Interfaces
----------

`IdleDetector`
Experimental

Provides methods and events for detecting user activity on a device or screen.

Examples
--------

 The following example shows creating a detector and logging changes to the
 user's idle state. A button is used to get the necessary user activation before
 requesting permission.

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

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

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

    await idleDetector.start({
      threshold: 60\_000,
      signal,
    });
    console.log("IdleDetector is active.");
  } catch (err) {
    // Deal with initialization errors like permission denied,
    // running outside of top-level frame, etc.
    console.error(err.name, err.message);
  }
});

stopButton.addEventListener("click", () => {
  controller.abort();
  console.log("IdleDetector is stopped.");
});
```

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

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

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

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


Page Visibility API - Web APIs

Page Visibility API
===================

The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page.

This is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn't visible.

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

When the user minimizes the window or switches to another tab, the API sends a `visibilitychange` event to let listeners know the state of the page has changed. You can detect the event and perform some actions or behave differently. For example, if your web app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user returns to the tab. The user doesn't lose their place in the video, the video's soundtrack doesn't interfere with audio in the new foreground tab, and the user doesn't miss any of the video in the meantime.

Visibility states of an `<iframe>` are the same as the parent document. Hiding an `<iframe>` using CSS properties (such as `display: none;`) doesn't trigger visibility events or change the state of the document contained within the frame.

### Use cases

Let's consider a few use cases for the Page Visibility API.

* A site has an image carousel that shouldn't advance to the next slide unless the user is viewing the page
* An application showing a dashboard of information doesn't want to poll the server for updates when the page isn't visible
* A page wants to detect when it is being prerendered so it can keep accurate count of page views
* A site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off)

Developers have historically used imperfect proxies to detect this. For example, watching for `blur` and `focus` events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user. The Page Visibility API addresses this.

**Note:** While `onblur` and `onfocus` will tell you if the user switches windows, it doesn't necessarily mean it's hidden. Pages only become hidden when the user switches tabs or minimizes the browser window containing the tab.

### Policies in place to aid background page performance

Separately from the Page Visibility API, user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs. These may include:

* Most browsers stop sending `requestAnimationFrame()` callbacks to background tabs or hidden `<iframe>`s in order to improve performance and battery life.
* Timers such as `setTimeout()` are throttled in background/inactive tabs to help improve performance. See Reasons for delays longer than specified for more details.
* Browsers implement budget-based background timeout throttling. This operates in a similar way across modern browsers, with the details being as follows:
    + In Firefox, windows in background tabs each have their own time budget in milliseconds — a max and a min value of +50 ms and -150 ms, respectively. Chrome is very similar except that the budget is specified in seconds.
    + Windows are subjected to throttling after 30 seconds, with the same throttling delay rules as specified for window timers (again, see Reasons for delays longer than specified). In Chrome, this value is 10 seconds.
    + Timer tasks are only permitted when the budget is non-negative.
    + Once a timer's code has finished running, the duration of time it took to execute is subtracted from its window's timeout budget.
    + The budget regenerates at a rate of 10 ms per second, in both Firefox and Chrome.

Some processes are exempt from this throttling behavior. In these cases, you can use the Page Visibility API to reduce the tabs' performance impact while they're hidden.

* Tabs which are playing audio are considered foreground and aren't throttled.
* Tabs running code that's using real-time network connections (WebSockets and WebRTC) go unthrottled in order to avoid closing these connections timing out and getting unexpectedly closed.
* IndexedDB processes are also left unthrottled in order to avoid timeouts.
Extensions to other interfaces
------------------------------

### Instance properties

The Page Visibility API adds the following properties to the `Document` interface:

`Document.hidden` Read only

Returns `true` if the page is in a state considered to be hidden to the user, and `false` otherwise.

`Document.visibilityState` Read only

A string indicating the document's current visibility state. Possible values are:

`visible`

The page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window.

`hidden`

The page's content is not visible to the user, either due to the document's tab being in the background or part of a window that is minimized, or because the device's screen is off.

### Events

The Page Visibility API adds the following events to the `Document` interface:

`visibilitychange`

Fired when the content of a tab has become visible or has been hidden.

Examples
--------

### Pausing audio on page hide

This example pauses audio when the user switches to a different tab, and plays when they switch back.

#### HTML

```html
<audio
 controls
 src="https://mdn.github.io/webaudio-examples/audio-basics/outfoxing.mp3"></audio>
```

#### JavaScript

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

// Handle page visibility change:
// - If the page is hidden, pause the audio
// - If the page is shown, play the audio
document.addEventListener("visibilitychange", () => {
  if (document.hidden) {
    audio.pause();
  } else {
    audio.play();
  }
});
```

#### Result

Try playing the audio, then switching to a different tab and back again.

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

| Specification |
| --- |
| HTML Standard # dom-document-visibilitystate |

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

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


HTMLDialogElement - Web APIs

HTMLDialogElement
=================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`HTMLDialogElement`** interface provides methods to manipulate `<dialog>` elements. It inherits properties and methods from the `HTMLElement` interface.

EventTarget

Node

Element

HTMLElement

HTMLDialogElementInstance properties
-------------------

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

`HTMLDialogElement.open`

A boolean value reflecting the `open` HTML attribute, indicating whether the dialog is available for interaction.

`HTMLDialogElement.returnValue`

A string that sets or returns the return value for the dialog.

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

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

`HTMLDialogElement.close()`

Closes the dialog. An optional string may be passed as an argument, updating the `returnValue` of the dialog.

`HTMLDialogElement.show()`

Displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog.

`HTMLDialogElement.showModal()`

Displays the dialog as a modal, over the top of any other dialogs that might be present. Everything outside the dialog are inert with interactions outside the dialog being blocked.

Events
------

*Also inherits events from its parent interface, `HTMLElement`.*

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

`close`

Fired when the dialog is closed, whether with the escape key, the `HTMLDialogElement.close()` method, or via submitting a form within the dialog with `method="dialog"`.

Examples
--------

### Opening a modal dialog

The following example shows a button that, when clicked, opens a modal `<dialog>` containing a form via the `HTMLDialogElement.showModal()` function. While open, everything other than the modal dialog's contents is inert. From there you can click the *Cancel* button to close the dialog (via the `HTMLDialogElement.close()` function), or submit the form via the submit button. Selecting the cancel button closes the dialog, creating a `close` event, not a `cancel` event.

#### HTML

```html
<!-- pop-up dialog box, containing a form -->
<dialog id="favDialog">
  <form method="dialog">
    <p>
      <label for="favAnimal">Favorite animal:</label>
      <select id="favAnimal" name="favAnimal">
        <option></option>
        <option>Brine shrimp</option>
        <option>Red panda</option>
        <option>Spider monkey</option>
      </select>
    </p>
    <div>
      <button id="cancel" type="reset">Cancel</button>
      <button type="submit">Confirm</button>
    </div>
  </form>
</dialog>

<div>
  <button id="updateDetails">Update details</button>
</div>
```

#### JavaScript

```js
const updateButton = document.getElementById("updateDetails");
const cancelButton = document.getElementById("cancel");
const dialog = document.getElementById("favDialog");
dialog.returnValue = "favAnimal";

function openCheck(dialog) {
  if (dialog.open) {
    console.log("Dialog open");
  } else {
    console.log("Dialog closed");
  }
}

// Update button opens a modal dialog
updateButton.addEventListener("click", () => {
  dialog.showModal();
  openCheck(dialog);
});

// Form cancel button closes the dialog box
cancelButton.addEventListener("click", () => {
  dialog.close("animalNotChosen");
  openCheck(dialog);
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # htmldialogelement |

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


CryptoKeyPair - Web APIs

CryptoKeyPair
=============

The **`CryptoKeyPair`** dictionary of the Web Crypto API represents a key pair for an asymmetric cryptography algorithm, also known as a public-key algorithm.

A `CryptoKeyPair` object can be obtained using `SubtleCrypto.generateKey()`, when the selected algorithm is one of the asymmetric algorithms: RSASSA-PKCS1-v1\_5, RSA-PSS, RSA-OAEP, ECDSA, or ECDH.

It contains two properties, which are both `CryptoKey` objects: a `privateKey` property containing the private key and a `publicKey` property containing the public key.

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

`CryptoKeyPair.privateKey`

A `CryptoKey` object representing the private key. For encryption and decryption algorithms, this key is used to decrypt. For signing and verification algorithms it is used to sign.

`CryptoKeyPair.publicKey`

A `CryptoKey` object representing the public key. For encryption and decryption algorithms, this key is used to encrypt. For signing and verification algorithms it is used to verify signatures.

Examples
--------

The examples for `SubtleCrypto` methods often use `CryptoKeyPair` objects. For example:

* `SubtleCrypto.generateKey()`
* `SubtleCrypto.deriveKey()`
* `SubtleCrypto.importKey()`
* `SubtleCrypto.exportKey()`
* `SubtleCrypto.wrapKey()`
* `SubtleCrypto.unwrapKey()`
* `SubtleCrypto.encrypt()`
* `SubtleCrypto.decrypt()`
* `SubtleCrypto.sign()`
* `SubtleCrypto.verify()`
Specifications
--------------

| Specification |
| --- |
| Web Cryptography API # keypair |

See also
--------

* `SubtleCrypto.generateKey`.
* `SubtleCrypto.sign` and `SubtleCrypto.verify`.
* `SubtleCrypto.encrypt` and `SubtleCrypto.decrypt`.


Report - Web APIs

Report
======

The `Report` interface of the Reporting API represents a single report.

Reports can be accessed in a number of ways:

* Via the `ReportingObserver.takeRecords()` method — this returns all reports in an observer's report queue, and then empties the queue.
* Via the `reports` parameter of the callback function passed into the `ReportingObserver()` constructor upon creation of a new observer instance. This contains the list of reports currently contained in the observer's report queue.
* By sending requests to the endpoints defined via the `Report-To` HTTP header.
Instance properties
-------------------

`Report.body` Read only

The body of the report, which is a `ReportBody` object containing the detailed report information.

`Report.type` Read only

The type of report generated, e.g. `deprecation` or `intervention`.

`Report.url` Read only

The URL of the document that generated the report.

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

*This interface has no methods defined on it.*

Events
------

*This interface has no events that fire on it.*

Examples
--------

In our deprecation\_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page:

```js
const options = {
  types: ["deprecation"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  reportBtn.onclick = () => displayReports(reports);
}, options);
```

We then tell it to start observing reports using `ReportingObserver.observe()`; this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor:

```js
observer.observe();
```

Because of the event handler we set up inside the `ReportingObserver()` constructor, we can now click the button to display the report details.

![image of a jolly bearded man with various stats displayed below it about a deprecated feature](/en-US/docs/Web/API/Report/reporting_api_example.png)

The report details are displayed via the `displayReports()` function, which takes the observer callback's `reports` parameter as its parameter:

```js
function displayReports(reports) {
  const outputElem = document.querySelector(".output");
  const list = document.createElement("ul");
  outputElem.appendChild(list);

  reports.forEach((report, i) => {
    let listItem = document.createElement("li");
    let textNode = document.createTextNode(
      `Report ${i + 1}, type: ${report.type}`,
    );
    listItem.appendChild(textNode);
    let innerList = document.createElement("ul");
    listItem.appendChild(innerList);
    list.appendChild(listItem);

    for (const key in report.body) {
      const innerListItem = document.createElement("li");
      const keyValue = report.body[key];
      innerListItem.textContent = `${key}: ${keyValue}`;
      innerList.appendChild(innerListItem);
    }
  });
}
```

The `reports` parameter contains an array of all the reports in the observer's report queue. We loop over each report using a `forEach()` loop, then iterate over each entry of in the report's body using a `for...in` structure, displaying each key/value pair inside a list item.

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

| Specification |
| --- |
| Reporting API # dom-report |

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

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

See also
--------

* Reporting API


TouchList - Web APIs

TouchList
=========

The **`TouchList`** interface represents a list of contact points on a touch surface. For example, if the user has three fingers on the touch surface (such as a screen or trackpad), the corresponding `TouchList` object would have one `Touch` object for each finger, for a total of three entries.

**Note:** This interface was an attempt to create an unmodifiable list and only continues to be supported to not break code that's already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).

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

`TouchList.length` Read only

The number of `Touch` objects in the `TouchList`.

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

`TouchList.item()`

Returns the `Touch` object at the specified index in the list.

Example
-------

See the example on the main Touch events article.

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

| Specification |
| --- |
| Touch Events # touchlist-interface |

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

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

See also
--------

* Touch events
* `Document.createTouchList()`


HTMLTableCaptionElement - Web APIs

HTMLTableCaptionElement
=======================

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

EventTarget

Node

Element

HTMLElement

HTMLTableCaptionElementInstance properties
-------------------

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

`HTMLTableCaptionElement.align`
Deprecated

A string which represents an enumerated attribute indicating alignment of the caption with respect to the table.

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

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

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

| Specification |
| --- |
| HTML Standard # htmltablecaptionelement |

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


ResizeObserverEntry - Web APIs

ResizeObserverEntry
===================

The **`ResizeObserverEntry`** interface represents the object passed to the `ResizeObserver()` constructor's callback function, which allows you to access the new dimensions of the `Element` or `SVGElement` being observed.

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

`ResizeObserverEntry.borderBoxSize` Read only

An array of objects containing the new border box size of the observed element when the callback is run.

`ResizeObserverEntry.contentBoxSize` Read only

An array of objects containing the new content box size of the observed element when the callback is run.

`ResizeObserverEntry.devicePixelContentBoxSize` Read only

An array of objects containing the new content box size in device pixels of the observed element when the callback is run.

`ResizeObserverEntry.contentRect` Read only

A `DOMRectReadOnly` object containing the new size of the observed element when the callback is run. Note that this is better supported than the above two properties, but it is left over from an earlier implementation of the Resize Observer API, is still included in the spec for web compat reasons, and may be deprecated in future versions.

`ResizeObserverEntry.target` Read only

A reference to the `Element` or `SVGElement` being observed.

**Note:** The content box is the box in which content can be placed, meaning the border box minus the padding and border width. The border box encompasses the content, padding, and border. See The box model for further explanation.

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

None.

Examples
--------

The following snippet is taken from the resize-observer-text.html (see source) example.

Note that the code covers three different compatibility cases:

* Some old browsers may support `contentRect` but not `contentBoxSize`.
* Old versions of Firefox support `contentBoxSize`, but incorrectly implemented it as a single object rather than an array.
* Modern browsers support `contentBoxSize` as an array of objects, to enable them to report box sizes for fragmented elements (for example, in a multi-column scenario).

```js
const resizeObserver = new ResizeObserver((entries) => {
  for (let entry of entries) {
    if (entry.contentBoxSize) {
      // The standard makes contentBoxSize an array...
      if (entry.contentBoxSize[0]) {
        h1Elem.style.fontSize =
          Math.max(1.5, entry.contentBoxSize[0].inlineSize / 200) + "rem";
        pElem.style.fontSize =
          Math.max(1, entry.contentBoxSize[0].inlineSize / 600) + "rem";
      } else {
        // ...but old versions of Firefox treat it as a single item
        h1Elem.style.fontSize =
          Math.max(1.5, entry.contentBoxSize.inlineSize / 200) + "rem";
        pElem.style.fontSize =
          Math.max(1, entry.contentBoxSize.inlineSize / 600) + "rem";
      }
    } else {
      h1Elem.style.fontSize =
        Math.max(1.5, entry.contentRect.width / 200) + "rem";
      pElem.style.fontSize = Math.max(1, entry.contentRect.width / 600) + "rem";
    }
  }
  console.log("Size changed");
});

resizeObserver.observe(divElem);
```

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

| Specification |
| --- |
| Resize Observer # resize-observer-entry-interface |

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

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


EditContext - Web APIs

EditContext
===========

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

The **`EditContext`** interface represents the text edit context of an element that was made editable by using the EditContext API.

The EditContext API can be used to build rich text editors on the web that support advanced text input experiences, such as Input Method Editor (IME) composition, emoji picker, or any other platform-specific editing-related UI surfaces.

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

`EditContext()`
Experimental

Returns a new `EditContext` instance.

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

`EditContext.text` Read only
Experimental

The editable content of the element.

`EditContext.selectionStart` Read only
Experimental

The offset, within the editable text content, of the start of the current selection.

`EditContext.selectionEnd` Read only
Experimental

The offset, within the editable text content, of the end of the current selection.

`EditContext.characterBoundsRangeStart` Read only
Experimental

The offset, within the editable text content, where the last IME composition started.

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

*`EditContext` is based on the `EventTarget` interface, and includes its methods.*

`EditContext.attachedElements()`
Experimental

An `Array` containing one `HTMLElement` object which is the element that's associated with the `EditContext` object.

`EditContext.characterBounds()`
Experimental

The list of bounding rectangles for the characters in the `EditContext` object.

`EditContext.updateText()`
Experimental

Updates the internal text content of the `EditContext` object.

`EditContext.updateSelection()`
Experimental

Updates the internal state of the selection within the editable text context.

`EditContext.updateControlBounds()`
Experimental

Informs the operating system about the position and size of the editable text region.

`EditContext.updateSelectionBounds()`
Experimental

Informs the operating system about the position and size of the selection within the editable text region.

`EditContext.updateCharacterBounds()`
Experimental

Informs the operating system about the position and size of the characters in the `EditContext` object.

Events
------

`textupdate`
Experimental

Fired when the user has made changes to the text or selection.

`textformatupdate`
Experimental

Fired when composition using an Input Method Editor (IME) window is happening and the IME decides that certain parts of the text being composed should be formatted differently to indicate the composition state.

`characterboundsupdate`
Experimental

Fired when the operating system needs to know the size and position of certain characters within the editable text region of the `EditContext` object, in order to display an IME window.

`compositionstart`
Experimental

Fired when composition using an IME window is starting.

`compositionend`
Experimental

Fired when composition using an IME window is ending.

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

| Specification |
| --- |
| EditContext API # dom-editcontext |

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

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


Screen Orientation API - Web APIs

Screen Orientation API
======================

The **Screen Orientation API** provides information about the orientation of the screen.

Interfaces
----------

* `ScreenOrientation`
Specifications
--------------

| Specification |
| --- |
| Screen Orientation # screenorientation-interface |

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

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


SVGFESpotLightElement - Web APIs

SVGFESpotLightElement
=====================

The **`SVGFESpotLightElement`** interface corresponds to the `<feSpotLight>` element.

EventTarget

Node

Element

SVGElement

SVGFESpotLightElementInstance properties
-------------------

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

`SVGFESpotLightElement.x` Read only

An `SVGAnimatedNumber` corresponding to the `x` attribute of the given element.

`SVGFESpotLightElement.y` Read only

An `SVGAnimatedNumber` corresponding to the `y` attribute of the given element.

`SVGFESpotLightElement.z` Read only

An `SVGAnimatedNumber` corresponding to the `z` attribute of the given element.

`SVGFESpotLightElement.pointAtX` Read only

An `SVGAnimatedNumber` corresponding to the `pointAtX` attribute of the given element.

`SVGFESpotLightElement.pointAtY` Read only

An `SVGAnimatedNumber` corresponding to the `pointAtY` attribute of the given element.

`SVGFESpotLightElement.pointAtZ` Read only

An `SVGAnimatedNumber` corresponding to the `pointAtZ` attribute of the given element.

`SVGFESpotLightElement.specularExponent` Read only

An `SVGAnimatedNumber` corresponding to the `specularExponent` attribute of the given element.

`SVGFESpotLightElement.limitingConeAngle` Read only

An `SVGAnimatedNumber` corresponding to the `limitingConeAngle` 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 # InterfaceSVGFESpotLightElement |

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

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

See also
--------

* `<feSpotLight>`


FontData - Web APIs

FontData
========

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

The **`FontData`** interface of the Local Font Access API represents a single local font face.

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

`FontData.family` Read only
Experimental

Returns the family of the font face.

`FontData.fullName` Read only
Experimental

Returns the full name of the font face.

`FontData.postscriptName` Read only
Experimental

Returns the PostScript name of the font face.

`FontData.style` Read only
Experimental

Returns the style of the font face.

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

`FontData.blob()`
Experimental

Returns a `Promise` that fulfills with a `Blob` containing the raw bytes of the underlying font file.

Examples
--------

For a working live demo, see Font Select Demo.

### Font enumeration

The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.

```js
async function logFontData() {
  try {
    const availableFonts = await window.queryLocalFonts();
    for (const fontData of availableFonts) {
      console.log(fontData.postscriptName);
      console.log(fontData.fullName);
      console.log(fontData.family);
      console.log(fontData.style);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

### Accessing low-level data

The `blob()` method provides access to low-level SFNT data — this is a font file format that can contain other font formats, such as PostScript, TrueType, OpenType, or Web Open Font Format (WOFF).

```js
async function computeOutlineFormat() {
  try {
    const availableFonts = await window.queryLocalFonts({
      postscriptNames: ["ComicSansMS"],
    });
    for (const fontData of availableFonts) {
      // `blob()` returns a Blob containing valid and complete
      // SFNT-wrapped font data.
      const sfnt = await fontData.blob();
      // Slice out only the bytes we need: the first 4 bytes are the SFNT
      // version info.
      // Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
      const sfntVersion = await sfnt.slice(0, 4).text();

      let outlineFormat = "UNKNOWN";
      switch (sfntVersion) {
        case "\x00\x01\x00\x00":
        case "true":
        case "typ1":
          outlineFormat = "truetype";
          break;
        case "OTTO":
          outlineFormat = "cff";
          break;
      }
      console.log("Outline format:", outlineFormat);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

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

| Specification |
| --- |
| Local Font Access # fontdata-interface |

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

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

See also
--------

* Use advanced typography with local fonts
* `@font-face`


SVGTransform - Web APIs

SVGTransform
============

SVG transform interface
-----------------------

`SVGTransform` is the interface for one of the component transformations within an `SVGTransformList`; thus, an `SVGTransform` object corresponds to a single component (e.g., `scale(…)` or `matrix(…)`) within a `transform` attribute.

An `SVGTransform` object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown.

### Interface overview

|  |  |
| --- | --- |
| Also implement | *None* |
| Methods | * `void setMatrix(in `DOMMatrix`
matrix)`
* `void setTranslate(in float tx, in float ty)`
* `void setScale(in float sx, in float sy)`
* `void setRotate(in float angle, in float cx, in float cy)`
* `void setSkewX(in float angle)`
* `void setSkewY(in float angle)`
 |
| Properties | * readonly unsigned short `type`
* readonly float `angle`
* readonly `DOMMatrix` `matrix`
 |
| Constants | * `SVG_TRANSFORM_UNKNOWN` = 0
* `SVG_TRANSFORM_MATRIX` = 1
* `SVG_TRANSFORM_TRANSLATE` = 2
* `SVG_TRANSFORM_SCALE` = 3
* `SVG_TRANSFORM_ROTATE` = 4
* `SVG_TRANSFORM_SKEWX` = 5
* `SVG_TRANSFORM_SKEWY` = 6
 |
| Normative document | SVG 1.1 (2nd Edition) |

Constants
---------

| Name | Value | Description |
| --- | --- | --- |
| `SVG_TRANSFORM_UNKNOWN` | 0 |
 The unit type is not one of predefined unit types. It is invalid to
 attempt to define a new value of this type or to attempt to switch an
 existing value to this type.
  |
| `SVG_TRANSFORM_MATRIX` | 1 | A `matrix(…)` transformation |
| `SVG_TRANSFORM_TRANSLATE` | 2 | A `translate(…)` transformation |
| `SVG_TRANSFORM_SCALE` | 3 | A `scale(…)` transformation |
| `SVG_TRANSFORM_ROTATE` | 4 | A `rotate(…)` transformation |
| `SVG_TRANSFORM_SKEWX` | 5 | A `skewx(…)` transformation |
| `SVG_TRANSFORM_SKEWY` | 6 | A `skewy(…)` transformation |

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

| Name | Type | Description |
| --- | --- | --- |
| `type` | unsigned short |
 The type of the value as specified by one of the SVG\_TRANSFORM\_\*
 constants defined on this interface.
  |
| `angle` | float |
 A convenience attribute for `SVG_TRANSFORM_ROTATE`,
 `SVG_TRANSFORM_SKEWX` and `SVG_TRANSFORM_SKEWY`.
 It holds the angle that was specified.For
 `SVG_TRANSFORM_MATRIX`,
 `SVG_TRANSFORM_TRANSLATE` and
 `SVG_TRANSFORM_SCALE`, `angle` will be zero.
  |
| `matrix` | `DOMMatrix` |
 The matrix that represents this transformation. The matrix object is
 live, meaning that any changes made to the
 `SVGTransform` object are immediately reflected in the
 matrix object and vice versa. In case the matrix object is changed
 directly (i.e., without using the methods on the
 `SVGTransform` interface itself) then the type of the
 `SVGTransform` changes to
 `SVG_TRANSFORM_MATRIX`.
 * For `SVG_TRANSFORM_MATRIX`, the matrix contains the a, b,
 c, d, e, f values supplied by the user.
* For `SVG_TRANSFORM_TRANSLATE`, e and f represent the
 translation amounts (a=1, b=0, c=0 and d=1).
* For `SVG_TRANSFORM_SCALE`, a and d represent the scale
 amounts (b=0, c=0, e=0 and f=0).
* For `SVG_TRANSFORM_SKEWX` and
 `SVG_TRANSFORM_SKEWY`, a, b, c and d represent the matrix
 which will result in the given skew (e=0 and f=0).
* For `SVG_TRANSFORM_ROTATE`, a, b, c, d, e and f together
 represent the matrix which will result in the given rotation. When
 the rotation is around the center point (0, 0), e and f will be
 zero.
 |

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

| Name & Arguments | Return | Description |
| --- | --- | --- |
| `**setMatrix**(in `DOMMatrix`
*matrix*)` | *void* |
 Sets the transform type to `SVG_TRANSFORM_MATRIX`, with
 parameter matrix defining the new transformation. Note that the values
 from the parameter `matrix` are copied.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when attempting
 to modify a read only attribute or when the object itself is read
 only.
 |
| `**setTranslate**(in float *tx* , in float
*ty*)` | *void* |
 Sets the transform type to `SVG_TRANSFORM_TRANSLATE`, with
 parameters `tx` and `ty` defining the
 translation amounts.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when attempting
 to modify a read only attribute or when the object itself is read
 only.
 |
| `**setScale**(in float *sx* , in float
*sy*)` | *void* |
 Sets the transform type to `SVG_TRANSFORM_SCALE`, with
 parameters `sx` and `sy` defining the scale
 amounts.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when attempting
 to modify a read only attribute or when the object itself is read
 only.
 |
| `**setRotate**(in float *angle*, in float
*cx* , in float *cy*)` | *void* |
 Sets the transform type to `SVG_TRANSFORM_ROTATE`, with
 parameter `angle` defining the rotation angle and
 parameters `cx` and `cy` defining the optional
 center of rotation.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when attempting
 to modify a read only attribute or when the object itself is read
 only.
 |
| `**setSkewX**(in float *angle*)` | *void* |
 Sets the transform type to `SVG_TRANSFORM_SKEWX`, with
 parameter `angle` defining the amount of skew.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when attempting
 to modify a read only attribute or when the object itself is read
 only.
 |
| `**setSkewY**(in float *angle*)` | *void* |
 Sets the transform type to `SVG_TRANSFORM_SKEWY`, with
 parameter `angle` defining the amount of skew.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when attempting
 to modify a read only attribute or when the object itself is read
 only.
 |

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

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


File API - Web APIs

File API
========

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

Concepts and Usage
------------------

The File API enables web applications to access files and their contents.

Web applications can access files when the user makes them available, either using a file `<input>` element or via drag and drop.

Sets of files made available in this way are represented as `FileList` objects, which enable a web application to retrieve individual `File` objects. In turn `File` objects provide access to metadata such as the file's name, size, type, and last modified date.

`File` objects can be passed to `FileReader` objects to access the contents of the file. The `FileReader` interface is asynchronous, but a synchronous version, available only in web workers, is provided by the `FileReaderSync` interface.

Interfaces
----------

`Blob`

Represents a "Binary Large Object", meaning a file-like object of immutable, raw data; a `Blob` can be read as text or binary data, or converted into a `ReadableStream` so its methods can be used for processing the data.

`File`

Provides information about a file and allows JavaScript in a web page to access its content.

`FileList`

Returned by the `files` property of the HTML `<input>` element; this lets you access the list of files selected with the `<input type="file">` element. It's also used for a list of files dropped into web content when using the drag and drop API; see the `DataTransfer` object for details on this usage.

`FileReader`

Enables web applications to asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using `File` or `Blob` objects to specify the file or data to read.

`FileReaderSync`

Enables web applications to synchronously read the contents of files (or raw data buffers) stored on the user's computer, using `File` or `Blob` objects to specify the file or data to read.

### Extensions to other interfaces

`URL.createObjectURL()`

Creates a URL that can be used to fetch a `File` or `Blob` object.

`URL.revokeObjectURL()`

Releases an existing object URL which was previously created by calling `URL.createObjectURL()`.

Examples
--------

### Reading a file

In this example, we provide a file `<input>` element, and when the user selects a file, we read the contents of the first file selected as text, and display the result in a `<div>`.

#### HTML

```html
<input type="file" />
<div class="output"></div>
```

#### CSS

```css
.output {
  overflow: scroll;
  margin: 1rem 0;
  height: 200px;
}
```

#### JavaScript

```js
const fileInput = document.querySelector("input[type=file]");
const output = document.querySelector(".output");

fileInput.addEventListener("change", async () => {
  const [file] = fileInput.files;

  if (file) {
    output.innerText = await file.text();
  }
});
```

### Result

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

| Specification |
| --- |
| File API  |

See also
--------

* `<input type="file">`: the file input element
* `text() method`: .text()
* The `DataTransfer` interface


Popover API - Web APIs

Popover API
===========

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
The **Popover API** provides developers with a standard, consistent, flexible mechanism for displaying popover content on top of other page content. Popover content can be controlled either declaratively using HTML attributes, or via JavaScript.

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

A very common pattern on the web is to show content over the top of other content, drawing the user's attention to specific important information or actions that need to be taken. This content can take several different names — overlays, popups, popovers, dialogs, etc. We will refer to them as popovers through the documentation. Generally speaking, these can be:

* **modal**, meaning that while a popover is being shown, the rest of the page is rendered non-interactive until the popover is actioned in some way (for example an important choice is made).
* **non-modal**, meaning that the rest of the page can be interacted with while the popover is being shown.

Popovers created using the Popover API are always non-modal. If you want to create a modal popover, a `<dialog>` element is the right way to go. There is significant overlap between the two — you might for example want to create a popover that persists, but control it using declarative HTML. You can turn a `<dialog>` element into a popover (`<dialog popover>` is perfectly valid) if you want to combine popover control with dialog semantics.

Typical use cases for the popover API include user-interactive elements like action menus, custom "toast" notifications, form element suggestions, content pickers, or teaching UI.

You can create popovers in two different ways:

* Declaratively, via a set of new HTML attributes. A simple popover with a toggle button can be created using the following code:

```html
<button popovertarget="mypopover">Toggle the popover</button>
<div id="mypopover" popover>Popover content</div>
```

* Via a JavaScript API. For example, `HTMLElement.togglePopover()` can be used to toggle a popover between shown and hidden.

There are also new events to react to a popover being toggled, and CSS features to aid in styling popovers. All the new features are listed below.

See Using the popover API for a detailed guide to using this API.

HTML attributes
---------------

`popover`

A global attribute that turns an element into a popover element; takes a popover state (`"auto"` or `"manual"`) as its value.

`popovertarget`

Turns a `<button>` or `<input>` element into a popover control button; takes the ID of the popover element to control as its value.

`popovertargetaction`

Specifies the action to be performed (`"hide"`, `"show"`, or `"toggle"`) on the popover element being controlled by a control `<button>` or `<input>`.

CSS features
------------

`::backdrop`

The `::backdrop` pseudo-element is a full-screen element placed directly behind popover elements, allowing effects to be added to the page content behind the popover(s) if desired (for example blurring it out).

`:popover-open`

The `:popover-open` pseudo-class matches a popover element only when it is in the showing state — it can be used to style popover elements when they are showing.

Interfaces
----------

`ToggleEvent`

Represents an event notifying the user when a popover element's state toggles between showing and hidden. It is the event object for the `beforetoggle` and `toggle` events, which fire on popovers when their state changes.

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

### Instance properties

`HTMLElement.popover`

Gets and sets an element's popover state via JavaScript (`"auto"` or `"manual"`), and can be used for feature detection. Reflects the value of the `popover` global HTML attribute.

`HTMLButtonElement.popoverTargetElement` and `HTMLInputElement.popoverTargetElement`

Gets and sets the popover element being controlled by the control button. The JavaScript equivalent of the `popovertarget` HTML attribute.

`HTMLButtonElement.popoverTargetAction` and `HTMLInputElement.popoverTargetAction`

Gets and sets the action to be performed (`"hide"`, `"show"`, or `"toggle"`) on the popover element being controlled by the control button. Reflects the value of the `popovertargetaction` HTML attribute.

### Instance methods

`HTMLElement.hidePopover()`

Hides a popover element by removing it from the top layer and styling it with `display: none`.

`HTMLElement.showPopover()`

Shows a popover element by adding it to the top layer.

`HTMLElement.togglePopover()`

Toggles a popover element between the showing and hidden states.

### Events

`HTMLElement` `beforetoggle` event

Fired just before a popover element's state changes between showing and hidden, or vice versa.

`HTMLElement` `toggle` event

Fired just after a popover element's state changes between showing and hidden, or vice versa. This event already existed to signal state changes on `<details>` elements, and it seemed logical to extend it for popover elements.

Examples
--------

See our Popover API examples landing page to access the full collection of MDN popover examples.

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

| Specification |
| --- |
| HTML Standard # dom-popover |

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

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

See also
--------

* `popover` HTML global attribute
* `popovertarget` HTML attribute
* `popovertargetaction` HTML attribute
* `::backdrop` CSS pseudo-element
* `:popover-open` CSS pseudo-class


EXT_disjoint_timer_query extension - Web APIs

EXT\_disjoint\_timer\_query extension
=====================================

The **EXT\_disjoint\_timer\_query** extension is part of the WebGL API and provides a way to measure the duration of a set of GL commands, without stalling the rendering pipeline.

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

**Note:** This extension should be available in WebGL1 contexts only. `EXT_disjoint_timer_query_webgl2` is available in WebGL 2 contexts .

 In WebGL 2, the `getQueryObject` was renamed to `getQueryParameter`.
 In WebGL 2, other queries (such as occlusion queries and primitive queries) are possible using `WebGLQuery` objects.

Types
-----

This extension exposes a new type:

`GLuint64EXT`

Unsigned 64-bit integer number.

Constants
---------

This extension exposes seven new constants.

`ext.QUERY_COUNTER_BITS_EXT`

A `GLint` indicating the number of bits used to hold the query result for the given target.

`ext.CURRENT_QUERY_EXT`

A `WebGLQuery` object, which is the currently active query for the given target.

`ext.QUERY_RESULT_EXT`

A `GLuint64EXT` containing the query result.

`ext.QUERY_RESULT_AVAILABLE_EXT`

A `GLboolean` indicating whether or not a query result is available.

`ext.TIME_ELAPSED_EXT`

Elapsed time (in nanoseconds).

`ext.TIMESTAMP_EXT`

The current time.

`ext.GPU_DISJOINT_EXT`

A `GLboolean` indicating whether or not the GPU performed any disjoint operation.

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

This extension exposes eight new methods.

`ext.createQueryEXT()`

Creates a new `WebGLQuery`.

`ext.deleteQueryEXT()`

Deletes a given `WebGLQuery`.

`ext.isQueryEXT()`

Returns `true` if a given object is a valid `WebGLQuery`.

`ext.beginQueryEXT()`

The timer starts when all commands prior to `beginQueryEXT` have been fully executed.

`ext.endQueryEXT()`

The timer stops when all commands prior to `endQueryEXT` have been fully executed.

`ext.queryCounterEXT()`

Records the current time into the corresponding query object.

`ext.getQueryEXT()`

Returns information about a query target.

`ext.getQueryObjectEXT()`

Return the state of a query object.

Examples
--------

```js
const ext = gl.getExtension("EXT\_disjoint\_timer\_query");
```

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

| Specification |
| --- |
| WebGL EXT\_disjoint\_timer\_query Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`


CSSPositionValue - Web APIs

CSSPositionValue
================

**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 **`CSSPositionValue`** interface of the CSS Typed Object Model API represents values for properties that take a position, for example `object-position`.

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

`CSSPositionValue()`
Non-standard

Deprecated

Creates a new `CSSPositionValue` object.

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

`CSSPositionValue.x`
Non-standard

Deprecated

Returns the item's position along the web page's horizontal axis.

`CSSPositionValue.y`
Non-standard

Deprecated

Returns the item's position along the vertical axis.

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

None.

Examples
--------

The following example positions a container `<div>` 5 pixels from the top and 10 pixels from the left of the page.

```js
const replacedEl = document.getElementById("image");
const position = new CSSPositionValue(CSS.px(35), CSS.px(40));

replacedEl.attributeStyleMap.set("object-position", position);
console.log(position.x.value, position.y.value);
console.log(replacedEl.computedStyleMap().get("object-position"));
```

We set the `object-position` property, then check the values returned.
```

#image {
  width: 300px;
  height: 300px;
  border: 1px solid black;
  background-color: #dededf;
  object-fit: none;
}
```

```
<p>
  Check the developer tools to see the log in the console and to inspect the
  style attribute on the image.
</p>
<img id="image" src="mdn.svg" alt="MDN Logo" />
```

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

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

See also
--------

* `CSSImageValue`
* `CSSKeywordValue`
* `CSSNumericValue`
* `CSSTransformValue`
* `CSSUnparsedValue`
* Using the CSS Typed OM
* CSS Typed Object Model API


PerformanceEntry - Web APIs

PerformanceEntry
================

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

The **`PerformanceEntry`** object encapsulates a single performance metric that is part of the browser's performance timeline.

The Performance API offers built-in metrics which are specialized subclasses of `PerformanceEntry`. This includes entries for resource loading, event timing, first input delay (FID), and more.

A performance entry can also be created by calling the `Performance.mark()` or `Performance.measure()` methods at an explicit point in an application. This allows you to add your own metrics to the performance timeline.

The `PerformanceEntry` instances will always be one of the following subclasses:

* `LargestContentfulPaint`
* `LayoutShift`
* `PerformanceEventTiming`
* `PerformanceLongTaskTiming`
* `PerformanceMark`
* `PerformanceMeasure`
* `PerformanceNavigationTiming`
* `PerformancePaintTiming`
* `PerformanceResourceTiming`
* `PerformanceServerTiming`
* `TaskAttributionTiming`
* `VisibilityStateEntry`
Instance properties
-------------------

`PerformanceEntry.name` Read only

A string representing the name for a performance entry. The value depends on the subtype.

`PerformanceEntry.entryType` Read only

A string representing the type of performance metric. For example, "`mark`" when `PerformanceMark` is used.

`PerformanceEntry.startTime` Read only

A `DOMHighResTimeStamp` representing the starting time for the performance metric.

`PerformanceEntry.duration` Read only

A `DOMHighResTimeStamp` representing the duration of the performance entry.

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

`PerformanceEntry.toJSON()`

Returns a JSON representation of the `PerformanceEntry` object.

Example
-------

### Working with performance entries

 The following example creates `PerformanceEntry` objects that are of the types `PerformanceMark` and `PerformanceMeasure`.
 The `PerformanceMark` and `PerformanceMeasure` subclasses inherit the `duration`, `entryType`, `name`, and `startTime` properties from `PerformanceEntry` and set them to their appropriate values.

```js
// Place at a location in the code that starts login
performance.mark("login-started");

// Place at a location in the code that finishes login
performance.mark("login-finished");

// Measure login duration
performance.measure("login-duration", "login-started", "login-finished");

function perfObserver(list, observer) {
  list.getEntries().forEach((entry) => {
    if (entry.entryType === "mark") {
      console.log(`${entry.name}'s startTime: ${entry.startTime}`);
    }
    if (entry.entryType === "measure") {
      console.log(`${entry.name}'s duration: ${entry.duration}`);
    }
  });
}
const observer = new PerformanceObserver(perfObserver);
observer.observe({ entryTypes: ["measure", "mark"] });
```

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

| Specification |
| --- |
| Performance Timeline # dom-performanceentry |

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

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


TaskController - Web APIs

TaskController
==============

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

 The **`TaskController`** interface of the Prioritized Task Scheduling API represents a controller object that can be used to both abort and change the priority of one or more prioritized tasks.
 If there is no need to change task priorities, then `AbortController` can be used instead.

 A new `TaskController` instance is created using the `TaskController()` constructor, optionally specifying a priority for its associated signal (a `TaskSignal`).
 If not specified, the signal will have a priority of `"user-visible"` by default.

 The controller's signal can be passed as an argument to the `Scheduler.postTask()` method for one or more tasks.
 For mutable tasks (only) the task is initialized with the signal priority, and can later be changed by calling `TaskController.setPriority()`.
 For immutable tasks, any priority initialized or set by the controller is ignored.

Tasks can be aborted by calling `abort()` on the controller.

AbortController

TaskControllerConstructor
-----------

`TaskController()`

Creates a new `TaskController` object, optionally specifying the priority of its associated `signal`.

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

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

`TaskController.setPriority()`

 Sets the priority of the controller's `signal`, and hence the priority of any tasks with which it is associated.
 This notifies observers of the priority change by dispatching a `prioritychange` event.

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

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

`TaskController.signal` Read only

 Returns a `TaskSignal` object instance.
 The signal is passed to tasks so that they can be aborted or re-prioritized by the controller.
 The property is inherited from `AbortController`.

Examples
--------

**Note:** Additional "live" examples can be found in: Prioritized Task Scheduling API Examples.

First we create a task controller, setting the priority of its associated signal to `user-blocking`.

```js
// Create a TaskController, setting its signal priority to 'user-blocking'
const controller = new TaskController({ priority: "user-blocking" });
```

 We then add an event listener for `prioritychange` events (here `addEventListener()` is called, but we could instead assign a handler to `TaskSignal.onprioritychange`).
 The handler uses previousPolicy on the event to get the original priority and `TaskSignal.priority` on the event target to get the new priority.

```js
// Listen for 'prioritychange' events on the controller's signal.
controller.signal.addEventListener("prioritychange", (event) => {
  const previousPriority = event.previousPriority;
  const newPriority = event.target.priority;
  console.log(`Priority changed from ${previousPriority} to ${newPriority}.`);
});
```

 We can also listen for `abort` events as shown below.
 This same approach would be used if the controller was an `AbortController`.

```js
controller.signal.addEventListener("abort", (event) => {
  console.log("Task aborted");
});
```

 Next we post the task, passing the controller signal in the optional argument.
 In this case the task is just an arrow function that resolves the promise by returning some text.
 We use `then` and `catch` to handle when the task resolves or is rejected, logging the return text or the error in each case.
 Note that in a later code block we abort the task, so only the `catch()` block will actually be run!

```js
// Post task using the controller's signal.
// The signal priority sets the initial priority of the task
scheduler
  .postTask(() => "Task execute", { signal: controller.signal })
  .then((taskResult) => {
    console.log(`${taskResult}`);
  }) // Aborted (won't run)
  .catch((error) => {
    console.log(`Catch error: ${error}`);
  }); // Log error
```

 We can use the controller to manage the task.
 Here we can change the priority using `TaskController.setPriority()`.
 This will trigger the associated `prioritychange` event.

```js
// Change the priority to 'background' using the controller
controller.setPriority("background");
```

Finally, the task can be aborted by calling `abort()` on the controller.

```js
// Abort the task
controller.abort();
```

The console output of this example would be:
```

The priority changed from user-blocking to background.
Task aborted
Catch error: AbortError
```

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

| Specification |
| --- |
| Prioritized Task Scheduling # sec-task-controller |

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

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


Storage API - Web APIs

Storage API
===========

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

The Storage Standard defines a shared storage system designed to be used by all APIs and technologies that websites can use to store data in a user's browser.

The data stored for a website which is managed by the Storage Standard usually includes IndexedDB databases and Cache API data, but may include other kind of site-accessible data such as Web Storage API data.

The Storage API gives websites the ability to find out how much space they can use, how much they are already using, and even control whether or not they need to be alerted before the user agent disposes of data in order to make room for other things.

This article gives an overview of the way user agents store and maintain websites' data. For more information about storage limits and eviction, see Browser storage quotas and eviction criteria.

This article also gives an overview of the `StorageManager` interface used to estimate available storage for a site.

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

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

### Storage buckets

The storage system described by the Storage Standard, where site data is stored, usually consists of a single *bucket* for each origin.

In essence, every website has its own storage space into which its data gets placed. In some cases however, user agents may decide to store a single origin's data in multiple different buckets, for example when this origin is embedded in different third-party origins.

To learn more, see How browsers separate data from different websites?

### Bucket modes

Each site storage bucket has a *mode* that describes the data retention policy for that bucket. There are two modes:

`"best-effort"`

The user agent will try to retain the data contained in the bucket for as long as it can, *but will not warn users* if storage space runs low and it becomes necessary to clear the bucket in order to relieve the storage pressure.

`"persistent"`

The user agent will retain the data as long as possible, clearing all `"best-effort"` buckets before considering clearing a bucket marked `"persistent"`. If it becomes necessary to consider clearing persistent buckets, the user agent will notify the user and provide a way to clear one or more persistent buckets as needed.

You can change an origin's storage bucket mode by using the `navigator.storage.persist()` method, which requires the `"persistent-storage"` user permission.

```js
if (navigator.storage && navigator.storage.persist) {
  navigator.storage.persist().then((persistent) => {
    if (persistent) {
      console.log("Storage will not be cleared except by explicit user action");
    } else {
      console.log("Storage may be cleared by the UA under storage pressure.");
    }
  });
}
```

You can also use the `navigator.storage.persisted()` method to know whether an origin's storage is persistent or not:

```js
if (navigator.storage && navigator.storage.persist) {
  navigator.storage.persisted().then((persistent) => {
    if (persistent) {
      console.log("Storage will not be cleared except by explicit user action");
    } else {
      console.log("Storage may be cleared by the UA under storage pressure.");
    }
  });
}
```

To learn more, see Does browser-stored data persist?.

### Quotas and usage estimates

The user agent determines, using whatever mechanism it chooses, the maximum amount of storage a given site can use. This maximum is the origin's **quota**. The amount of this space which is in use by the site is called its **usage**. Both of these values are estimates; there are several reasons why they're not precise:

* User agents are encouraged to obscure the exact size of the data used by a given origin, to prevent these values from being used for fingerprinting purposes.
* De-duplication, compression, and other methods to reduce the physical size of the stored data may be used.
* Quotas are conservative estimates of the space available for the origin's use, and should be less than the available space on the device to help prevent overruns.

To determine the estimated quota and usage values for a given origin, use the `navigator.storage.estimate()` method, which returns a promise that, when resolved, receives an object that contains these figures. For example:

```js
navigator.storage.estimate().then((estimate) => {
  // estimate.quota is the estimated quota
  // estimate.usage is the estimated number of bytes used
});
```

For more information about how much data an origin can store, see How much data can be stored?.

### Data eviction

Data eviction is the process by which a user agent deletes an origin's stored data. This can happen, for example, when the device used to store the data is running low on storage space.

When clearing the data stored by an origin, the origin's bucket is treated as a single entity. The entire data stored by this origin is cleared.

If a bucket is marked as `"persistent"`, the contents won't be cleared by the user agent without either the data's origin itself or the user specifically doing so. This includes scenarios such as the user selecting a "Clear Caches" or "Clear Recent History" option. The user will be asked specifically for permission to remove persistent site storage buckets.

To learn more, see When is data evicted?.

Interfaces
----------

`StorageManager`

Provides an interface for managing persistence permissions and estimating available storage.

### Extensions to other interfaces

`Navigator.storage` Read only

Returns the singleton `StorageManager` object used for managing persistence permissions and estimating available storage on a site-by-site/app-by-app basis.

`WorkerNavigator.storage` Read only

Returns a `StorageManager` interface for managing persistence permissions and estimating available storage.

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

| Specification |
| --- |
| Storage Standard # storagemanager |

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

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

See also
--------

* Using the Permissions API
* Storage for the web on web.dev
* Persistent storage on web.dev
* Chrome Web Storage and Quota Concepts


AudioWorkletGlobalScope - Web APIs

AudioWorkletGlobalScope
=======================

The **`AudioWorkletGlobalScope`** interface of the Web Audio API represents a global execution context for user-supplied code, which defines custom `AudioWorkletProcessor`-derived classes.

Each `BaseAudioContext` has a single `AudioWorklet` available under the `audioWorklet` property, which runs its code in a single `AudioWorkletGlobalScope`.

As the global execution context is shared across the current `BaseAudioContext`, it's possible to define any other variables and perform any actions allowed in worklets — apart from defining `AudioWorkletProcessor` derived classes.

WorkletGlobalScope

AudioWorkletGlobalScopeInstance properties
-------------------

*This interface also inherits properties defined on its parent interface, `WorkletGlobalScope`.*

`currentFrame` Read only

Returns an integer that represents the ever-increasing current sample-frame of the audio block being processed. It is incremented by 128 (the size of a render quantum) after the processing of each audio block.

`currentTime` Read only

Returns a double that represents the ever-increasing context time of the audio block being processed. It is equal to the `currentTime` property of the `BaseAudioContext` the worklet belongs to.

`sampleRate` Read only

Returns a float that represents the sample rate of the associated `BaseAudioContext`.

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

*This interface also inherits methods defined on its parent interface, `WorkletGlobalScope`.*

`registerProcessor()`

Registers a class derived from the `AudioWorkletProcessor` interface. The class can then be used by creating an `AudioWorkletNode`, providing its registered name.

Examples
--------

In this example we output all global properties into the console in the constructor of a custom `AudioWorkletProcessor`.

First we need to define the processor, and register it. Note that this should be done in a separate file.

```js
// AudioWorkletProcessor defined in : test-processor.js
class TestProcessor extends AudioWorkletProcessor {
  constructor() {
    super();

    // Logs the current sample-frame and time at the moment of instantiation.
    // They are accessible from the AudioWorkletGlobalScope.
    console.log(currentFrame);
    console.log(currentTime);
  }

  // The process method is required - output silence,
  // which the outputs are already filled with.
  process(inputs, outputs, parameters) {
    return true;
  }
}

// Logs the sample rate, that is not going to change ever,
// because it's a read-only property of a BaseAudioContext
// and is set only during its instantiation.
console.log(sampleRate);

// You can declare any variables and use them in your processors
// for example it may be an ArrayBuffer with a wavetable
const usefulVariable = 42;
console.log(usefulVariable);

registerProcessor("test-processor", TestProcessor);
```

Next, in our main scripts file we'll load the processor, create an instance of `AudioWorkletNode` — passing the name of the processor to it — and connect the node to an audio graph. We should see the output of `console.log()` calls in the console:

```js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("test-processor.js");
const testNode = new AudioWorkletNode(audioContext, "test-processor");
testNode.connect(audioContext.destination);
```

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

| Specification |
| --- |
| Web Audio API # AudioWorkletGlobalScope |

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

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

See also
--------

* Web Audio API
* Using the Web Audio API
* Using AudioWorklet


Payment Request API - Web APIs

Payment Request API
===================

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

The **Payment Request API** provides a consistent user experience for merchants and users. It is not a new way of paying for things; instead, it's a way for users to select their preferred way of paying for things and make that information available to a merchant.

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

Many problems related to online shopping cart abandonment can be traced to checkout forms, which can be difficult and time-consuming to fill out and often require multiple steps to complete. The **Payment Request API** is meant to reduce the steps needed to complete payment online, potentially doing away with checkout forms. It aims to make the checkout process more accessible by having payment apps store a user's details, which are passed along to a merchant, hopefully without requiring an HTML form.

To request a payment, a web page creates a `PaymentRequest` object in response to a user action that initiates a payment, such as clicking a "Purchase" button. The `PaymentRequest` allows the web page to exchange information with the user agent while the user provides input to complete the transaction.

You can find a complete guide in Using the Payment Request API.

**Note:** The API is available inside cross-origin `<iframe>` elements only if they have had the `allowpaymentrequest` attribute set on them.

Interfaces
----------

`PaymentAddress`
Deprecated

Non-standard

An object that contains address information; used for billing and shipping addresses, for example.

`PaymentRequest`

An object that provides the API for creating and managing the user agent's payment interface.

`PaymentRequestUpdateEvent`

Enables the web page to update the details of the payment request in response to a user action.

`PaymentMethodChangeEvent`

Represents the user changing payment instrument (e.g., switching from one payment method to another).

`PaymentResponse`

An object returned after the user selects a payment method and approves a payment request.

`MerchantValidationEvent`
Deprecated

Represents the browser requiring the merchant (website) to validate themselves as allowed to use a particular payment handler (e.g., registered as allowed to use Apple Pay).

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

| Specification |
| --- |
| Payment Request API 1.1 # paymentrequest-interface |

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

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

See also
--------

* Using the Payment Request API
* Payment processing concepts
* Introducing the Payment Request API for Apple Pay
* Google Pay API PaymentRequest Tutorial
* Samsung Pay Web Payments Integration Guide
* W3C Payment Request API FAQ
* Permissions Policy directive `payment`


MediaDevices - Web APIs

MediaDevices
============

The **`MediaDevices`** interface provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data.

EventTarget

MediaDevicesInstance properties
-------------------

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

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

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

`enumerateDevices()`

Obtains an array of information about the media input and output devices available on the system.

`getSupportedConstraints()`

Returns an object conforming to `MediaTrackSupportedConstraints` indicating which constrainable properties are supported on the `MediaStreamTrack` interface. See Media Streams API to learn more about constraints and how to use them.

`getDisplayMedia()`

Prompts the user to select a display or portion of a display (such as a window) to capture as a `MediaStream` for sharing or recording purposes. Returns a promise that resolves to a `MediaStream`.

`getUserMedia()`

With the user's permission through a prompt, turns on a camera and/or a microphone on the system and provides a `MediaStream` containing a video track and/or an audio track with the input.

`selectAudioOutput()`
Experimental

Prompts the user to select a specific audio output device.

Events
------

`devicechange`

Fired when a media input or output device is attached to or removed from the user's computer.

Example
-------

```js
// Put variables in global scope to make them available to the browser console.
const video = document.querySelector("video");
const constraints = {
  audio: false,
  video: true,
};

navigator.mediaDevices
  .getUserMedia(constraints)
  .then((stream) => {
    const videoTracks = stream.getVideoTracks();
    console.log("Got stream with constraints:", constraints);
    console.log(`Using video device: ${videoTracks[0].label}`);
    stream.onremovetrack = () => {
      console.log("Stream ended");
    };
    video.srcObject = stream;
  })
  .catch((error) => {
    if (error.name === "OverconstrainedError") {
      console.error(
        `The resolution ${constraints.video.width.exact}x${constraints.video.height.exact} px is not supported by your device.`,
      );
    } else if (error.name === "NotAllowedError") {
      console.error(
        "You need to grant this page permission to access your camera and microphone.",
      );
    } else {
      console.error(`getUserMedia error: ${error.name}`, error);
    }
  });
```

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

| Specification |
| --- |
| Media Capture and Streams # mediadevices |

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

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

See also
--------

* Media Capture and Streams API: The API this interface is part of.
* Screen Capture API: The API defining the `getDisplayMedia()` method.
* WebRTC API
* `Navigator.mediaDevices`: Returns a reference to a `MediaDevices` object that can be used to access devices.
* CameraCaptureJS: HTML video capture and playback using `MediaDevices` and the MediaStream Recording API
* OpenLang: HTML video language lab web application using `MediaDevices` and the MediaStream Recording API for video recording


AnimationEffect - Web APIs

AnimationEffect
===============

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

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

* Learn more
* See full compatibility
* Report feedback
The `AnimationEffect` interface of the Web Animations API is an interface representing animation effects.

`AnimationEffect` is an abstract interface and so isn't directly instantiable. However, concrete interfaces such as `KeyframeEffect` inherit from it, and instances of these interfaces can be passed to `Animation` objects for playing, and may also be used by CSS Animations and Transitions.

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

`AnimationEffect.getTiming()`

Returns the object associated with the animation containing all the animation's timing values.

`AnimationEffect.getComputedTiming()`

Returns the calculated timing properties for this `AnimationEffect`.

`AnimationEffect.updateTiming()`

Updates the specified timing properties of this `AnimationEffect`.

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

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

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

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

See also
--------

* Web Animations API
* `Animation.effect`