Navigator - Web APIs

Navigator
=========

The **`Navigator`** interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.

A `Navigator` object can be retrieved using the read-only `window.navigator` property.

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

*Doesn't inherit any properties.*

### Standard properties

`Navigator.bluetooth` Read only
Experimental

Returns a `Bluetooth` object for the current document, providing access to Web Bluetooth API functionality.

`Navigator.clipboard` Read only  Secure context

Returns a `Clipboard` object that provides read and write access to the system clipboard.

`Navigator.connection` Read only
Experimental

Returns a `NetworkInformation` object containing information about the network connection of a device.

`Navigator.contacts` Read only
Experimental

Returns a `ContactsManager` interface which allows users to select entries from their contact list and share limited details of the selected entries with a website or application.

`Navigator.cookieEnabled` Read only

Returns false if setting a cookie will be ignored and true otherwise.

`Navigator.credentials` Read only

Returns the `CredentialsContainer` interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out.

`Navigator.deviceMemory` Read only

Returns the amount of device memory in gigabytes. This value is an approximation given by rounding to the nearest power of 2 and dividing that number by 1024.

`Navigator.geolocation` Read only

Returns a `Geolocation` object allowing accessing the location of the device.

`Navigator.gpu` Read only
Experimental

Returns the `GPU` object for the current browsing context. The entry point for the WebGPU API.

`Navigator.hardwareConcurrency` Read only

Returns the number of logical processor cores available.

`Navigator.hid` Read only
Experimental

Returns an `HID` object providing methods for connecting to HID devices, listing attached HID devices, and event handlers for connected HID devices.

`Navigator.ink` Read only
Experimental

Returns an `Ink` object for the current document, providing access to Ink API functionality.

`Navigator.keyboard` Read only
Experimental

Returns a `Keyboard` object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

`Navigator.language` Read only

Returns a string representing the preferred language of the user, usually the language of the browser UI. The `null` value is returned when this is unknown.

`Navigator.languages` Read only

Returns an array of strings representing the languages known to the user, by order of preference.

`Navigator.locks` Read only

Returns a `LockManager` object that provides methods for requesting a new `Lock` object and querying for an existing `Lock` object.

`Navigator.maxTouchPoints` Read only

Returns the maximum number of simultaneous touch contact points are supported by the current device.

`Navigator.mediaCapabilities` Read only

Returns a `MediaCapabilities` object that can expose information about the decoding and encoding capabilities for a given format and output capabilities.

`Navigator.mediaDevices` Read only

Returns a reference to a `MediaDevices` object which can then be used to get information about available media devices (`MediaDevices.enumerateDevices()`), find out what constrainable properties are supported for media on the user's computer and user agent (`MediaDevices.getSupportedConstraints()`), and to request access to media using `MediaDevices.getUserMedia()`.

`Navigator.mediaSession` Read only

Returns `MediaSession` object which can be used to provide metadata that can be used by the browser to present information about the currently-playing media to the user, such as in a global media controls UI.

`Navigator.onLine` Read only

Returns a boolean value indicating whether the browser is working online.

`Navigator.pdfViewerEnabled` Read only

Returns `true` if the browser can display PDF files inline when navigating to them, and `false` otherwise.

`Navigator.permissions` Read only

Returns a `Permissions` object that can be used to query and update permission status of APIs covered by the Permissions API.

`Navigator.presentation` Read only

Returns a reference to the `Presentation` API.

`Navigator.scheduling` Read only
Experimental

Returns a `Scheduling` object for the current document.

`Navigator.serial` Read only
Experimental

Returns a `Serial` object, which represents the entry point into the `Web Serial API` to enable the control of serial ports.

`Navigator.serviceWorker` Read only

Returns a `ServiceWorkerContainer` object, which provides access to registration, removal, upgrade, and communication with the `ServiceWorker` objects for the associated document.

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

`Navigator.usb` Read only

Returns a `USB` object for the current document, providing access to WebUSB API functionality.

`Navigator.userActivation` Read only

Returns a `UserActivation` object containing information about the current window's user activation state.

`Navigator.userAgent` Read only

Returns the user agent string for the current browser.

`Navigator.userAgentData` Read only
Experimental

Returns a `NavigatorUAData` object, which gives access to information about the browser and operating system of the user.

`Navigator.virtualKeyboard` Read only
Experimental

Returns a reference to the `VirtualKeyboard` API, to take control of the on-screen virtual keyboard.

`Navigator.wakeLock` Read only

Returns a `WakeLock` interface you can use to request screen wake locks and prevent screen from dimming, turning off, or showing a screen saver.

`Navigator.webdriver` Read only

Indicates whether the user agent is controlled by automation.

`Navigator.windowControlsOverlay` Read only

Returns the `WindowControlsOverlay` interface which exposes information about the geometry of the title bar in desktop Progressive Web Apps, and an event to know whenever it changes.

`Navigator.xr` Read only
Experimental

Returns `XRSystem` object, which represents the entry point into the WebXR API.

### Non-standard properties

`Navigator.buildID` Read only
Non-standard

Returns the build identifier of the browser. In modern browsers this property now returns a fixed timestamp as a privacy measure, e.g. `20181001000000` in Firefox 64 onwards.

`Navigator.globalPrivacyControl` Read only
Experimental

Non-standard

Returns a boolean indicating a user's consent to their information being shared or sold.

`Navigator.standalone`
Non-standard

Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.

### Deprecated properties

`Navigator.activeVRDisplays` Read only
Deprecated

Non-standard

Returns an array containing every `VRDisplay` object that is currently presenting (`VRDisplay.ispresenting` is `true`).

`Navigator.appCodeName` Read only
Deprecated

Always returns `'Mozilla'`, in any browser.

`Navigator.appName` Read only
Deprecated

Always returns `'Netscape'`, in any browser.

`Navigator.appVersion` Read only
Deprecated

Returns the version of the browser as a string. Do not rely on this property to return the correct value.

`Navigator.doNotTrack` Read only
Deprecated

Non-standard

Reports the value of the user's do-not-track preference. When this value is "1", your website or application should not track the user.

`Navigator.mimeTypes` Read only
Deprecated

Returns an `MimeTypeArray` listing the MIME types supported by the browser.

`Navigator.oscpu` Read only
Deprecated

Returns a string that represents the current operating system.

`Navigator.platform` Read only
Deprecated

Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.

`Navigator.plugins` Read only
Deprecated

Returns a `PluginArray` listing the plugins installed in the browser.

`Navigator.product` Read only
Deprecated

Always returns `'Gecko'`, in any browser.

`Navigator.productSub` Read only
Deprecated

Returns either the string `'20030107'`, or `'"20100101'`.

`Navigator.vendor` Read only
Deprecated

Returns either the empty string, `'Apple Computer Inc.'`, or `'Google Inc.'`.

`Navigator.vendorSub` Read only
Deprecated

Always returns the empty string.

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

*Doesn't inherit any method.*

`Navigator.canShare()`

Returns `true` if a call to `Navigator.share()` would succeed.

`Navigator.clearAppBadge()`

Clears a badge on the current app's icon and returns a `Promise` that resolves with `undefined`.

`Navigator.getAutoplayPolicy()`
Experimental

Returns a value indicating whether the specified media element, audio context, or media feature "type" is allowed to autoplay.

`Navigator.getBattery()`

Returns a promise that resolves with a `BatteryManager` object that returns information about the battery charging status.

`Navigator.getGamepads()`

returns an array of `Gamepad` objects, one for each gamepad connected to the device.

`Navigator.getInstalledRelatedApps()`
Experimental

Returns a promise that resolves with an array of objects representing any related native or Progressive Web Applications that the user has installed.

`Navigator.registerProtocolHandler()`

Allows websites to register themselves as a possible handler for a given protocol.

`Navigator.requestMediaKeySystemAccess()`

Returns a `Promise` for a MediaKeySystemAccess object.

`Navigator.requestMIDIAccess()`

Returns a `Promise` representing a request for access to MIDI devices on the user's system.

`Navigator.sendBeacon()`

Used to asynchronously transfer a small amount of data using HTTP from the User Agent to a web server.

`Navigator.setAppBadge()`

Sets a badge on the icon associated with this app and returns a `Promise` that resolves with `undefined`.

`Navigator.share()`

Invokes the native sharing mechanism of the current platform.

`Navigator.vibrate()`

Causes vibration on devices with support for it. Does nothing if vibration support isn't available.

`Navigator.unregisterProtocolHandler()`

Unregister a website that is a handler for a given protocol.

### Deprecated methods

`Navigator.getUserMedia()`
Deprecated

After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.

`Navigator.getVRDisplays()`
Deprecated

Non-standard

Returns a promise that resolves to an array of `VRDisplay` objects representing any available VR devices connected to the computer.

`Navigator.javaEnabled()`
Deprecated

Always returns false.

`Navigator.taintEnabled()`
Deprecated

Returns `false`. JavaScript taint/untaint functions removed in JavaScript 1.2.

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

| Specification |
| --- |
| HTML Standard # the-navigator-object |

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

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


EditContext API - Web APIs

EditContext API
===============

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

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.

With the EditContext API, you get the flexibility to render your own editable text region using any technology you want.

Concept
-------

Multiple actors are involved when entering text in an editable region of an application:

**User**

The user provides the text by means of an input method: a keyboard, mouse, voice, or other input method.

**Input method software**

The input method software converts the user's input into text. For example, this could be an Input Method Editor (IME) that converts keystrokes from a standard keyboard into Japanese, Chinese, or Korean characters.

**OS text input service**

The text input service of the operating system acts as a link between the input method software and the application.

**Application text edit context**

The application text edit context provides a state of the text being edited. The state contains information such as the text itself, the current selection, the location of the text in the app's UI.

**Application editable region**

The application editable region is the UI element of the application that displays the text.

While the three first actors are provided by the operating system, the application is responsible for providing the editable region and the text edit context.

On the web, editable regions are often `<textarea>` elements, `<input>` elements, or elements with the `contenteditable` attribute set to `true`. For these elements, the browser automatically provides the text edit context, and web authors are not required to write any code to support text input.

### Creating custom editable regions

Web authors can also create custom editable regions using the EditContext API. For example, a web author could create a rich text editor using a `<canvas>` element to render the text. In this case, the web author needs to write code to support text input.

### Author's responsibilities

If you decide to implement your own editable region, whether it draws text into a `<canvas>` or renders it into a series of DOM elements, you are responsible for providing the things that the browser would normally provide for you if you were using a `<textarea>` instead. This includes:

* Rendering the text.
* Rendering the selection (if you build your editable region with DOM elements instead of a `<canvas>`, the browser does render the selection for you).
* Letting the OS text input service know when the selection changes.
* Letting the OS text input service know where the text is located in the UI, so the input method software can display the IME composition window in the correct location.
* Applying certain text formats when the user is composing text within the IME composition window.

In return, the EditContext API makes the DOM element you choose editable and part of the document's focus order. In addition, the EditContext API also provides information about the state of the text being edited, which allows you to render it in a custom way. The information provided to you includes:

* The current text content.
* The current selection.
* Whether IME composition is in progress, and whether text formats need to be applied.
### Accessibility

If you use the EditContext API with a `<canvas>` element, make sure to also make the text accessible to assistive technology. Screen readers can't read the text in a `<canvas>` element. For example, you could maintain a separate view of the text in an offscreen DOM element that's presented to screen readers.

### Basic usage

To use the EditContext API, you need to create an instance of the `EditContext` interface, and then attach it to the DOM element you want to make editable by using the `editContext` property. The DOM element can be any element, including a `<div>` or a `<canvas>` element.

```html
<canvas id="editor-canvas"></canvas>
```

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

An `EditContext` instance can only be attached to one DOM element at a time.

Attaching an `EditContext` instance to a DOM element makes the element focusable, as part of the document's focus order. The user can enter text into the element using the input method of their choice, and you can use event fired by the `EditContext` instance to render the text and selection.

### Model and view architecture

When using the EditContext API, it helps to build your editing experience as a model and view architecture.

The `EditContext` instance represents the model of your editable region. Its internal state gets updated when text input is received, and when the selection changes.

You can then render the text and selection in the view, using the information provided by the `EditContext` instance, however your view doesn't need to match the model exactly. You're free to render the text in any way you want.

Interfaces
----------

`EditContext`
Experimental

The **`EditContext`** interface is a JavaScript reflection of the text edit context that's normally provided transparently by the browser when using standard editable regions such as `textarea`. `EditContext` provides the state of the text being edited, with information such as the text itself, the current selection, or the location of the text in the app's UI.

`TextFormat`

The **`TextFormat`** interface is used to represent certain formats that should be applied to text ranges when the user is composing text within the IME composition window.

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

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

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

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


EyeDropper - Web APIs

EyeDropper
==========

**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 **`EyeDropper`** interface represents an instance of an eyedropper tool that can be opened and used by the user to select colors from the screen.

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

`EyeDropper()`
Experimental

Returns a new `EyeDropper` instance.

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

*The `EyeDropper` interface doesn't inherit any methods*.

`EyeDropper.open()`
Experimental

Returns a promise that resolves to an object that gives access to the selected color.

Examples
--------

### Opening the eyedropper tool and sampling a color

This example shows how to open an eyedropper tool and wait for the user to either select a pixel from the screen, or press `Escape` to cancel the eyedropper mode.

#### HTML

```html
<button id="start-button">Open the eyedropper</button> <span id="result"></span>
```

#### JavaScript

```js
document.getElementById("start-button").addEventListener("click", () => {
  const resultElement = document.getElementById("result");

  if (!window.EyeDropper) {
    resultElement.textContent =
      "Your browser does not support the EyeDropper API";
    return;
  }

  const eyeDropper = new EyeDropper();

  eyeDropper
    .open()
    .then((result) => {
      resultElement.textContent = result.sRGBHex;
      resultElement.style.backgroundColor = result.sRGBHex;
    })
    .catch((e) => {
      resultElement.textContent = e;
    });
});
```

#### Result

### Aborting the eyedropper mode

This example shows that the eyedropper mode can also be aborted before the user has selected a color or pressed `Escape`.

#### HTML

```html
<button id="start-button">Open the eyedropper</button> <span id="result"></span>
```

#### JavaScript

```js
document.getElementById("start-button").addEventListener("click", () => {
  const resultElement = document.getElementById("result");

  if (!window.EyeDropper) {
    resultElement.textContent =
      "Your browser does not support the EyeDropper API";
    return;
  }

  const eyeDropper = new EyeDropper();
  const abortController = new AbortController();

  eyeDropper
    .open({ signal: abortController.signal })
    .then((result) => {
      resultElement.textContent = result.sRGBHex;
      resultElement.style.backgroundColor = result.sRGBHex;
    })
    .catch((e) => {
      resultElement.textContent = e;
    });

  setTimeout(() => {
    abortController.abort();
  }, 2000);
});
```

#### Result

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

| Specification |
| --- |
| EyeDropper API # eyedropper-interface |

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

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


HIDConnectionEvent - Web APIs

HIDConnectionEvent
==================

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 **`HIDConnectionEvent`** interface of the `WebHID API` represents HID connection events, and is the event type passed to `connect` and `disconnect` event handlers when an input report is received.

Event

HIDConnectionEventConstructor
-----------

`HIDConnectionEvent()`
Experimental

Returns a new `HIDConnectionEvent` object. Typically this constructor is not used as events are created when an input report is received.

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

*This interface also inherits properties from `Event`.*

`HIDConnectionEvent.device` Read only
Experimental

Returns the `HIDDevice` instance representing the device associated with the connection event.

Examples
--------

The following example registers event listeners for `connect` and `disconnect` events, then prints the `HIDDevice.productName` to the console.

```js
navigator.hid.addEventListener("connect", ({ device }) => {
  console.log(`HID connected: ${device.productName}`);
});

navigator.hid.addEventListener("disconnect", ({ device }) => {
  console.log(`HID disconnected: ${device.productName}`);
});
```

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

| Specification |
| --- |
| WebHID API # dom-hidconnectionevent |

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

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


SVGCircleElement - Web APIs

SVGCircleElement
================

The **`SVGCircleElement`** interface is an interface for the `<circle>` element.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGGeometryElement

SVGCircleElementInstance properties
-------------------

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

`SVGCircleElement.cx` Read only

This property defines the x-coordinate of the center of the `<circle>` element. It is denoted by the `cx` attribute of the element.

`SVGCircleElement.cy` Read only

This property defines the y-coordinate of the center of the `<circle>` element. It is denoted by the `cy` attribute of the element.

`SVGCircleElement.r` Read only

This property defines the radius of the `<circle>` element. It is denoted by the `r` of the element.

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

*This interface has no methods but inherits methods from its parent, `SVGGeometryElement`.*

Examples
--------

### Resizing a circle

In this example we draw a circle and randomly increase or decrease its radius when you click it.

#### HTML

```html
<svg
 xmlns="http://www.w3.org/2000/svg"
 viewBox="0 0 250 250"
 width="250"
 height="250">
  <circle
 cx="100"
 cy="100"
 r="50"
 fill="gold"
 id="circle"
 onclick="clickCircle();" />
</svg>
```

#### JavaScript

```js
function clickCircle() {
  const circle = document.getElementById("circle");
  // Randomly determine if the circle radius will increase or decrease
  const change = Math.random() > 0.5 ? 10 : -10;
  // Clamp the circle radius to a minimum of 10 and a maximum of 250,
  // so it won't disappear or get bigger than the viewport
  const newValue = Math.min(Math.max(circle.r.baseVal.value + change, 10), 250);
  circle.setAttribute("r", newValue);
}
```

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

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

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

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

See also
--------

* `<circle>` SVG element


ScreenDetailed - Web APIs

ScreenDetailed
==============

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

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

The **`ScreenDetailed`** interface of the Window Management API represents detailed information about one specific screen available to the user's device.

`ScreenDetailed` objects can be accessed via the `ScreenDetails.screens` and `ScreenDetails.currentScreen` properties.

Screen

ScreenDetailedInstance properties
-------------------

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

`availLeft` Read only
Experimental

A number representing the x-coordinate (left-hand edge) of the available screen area.

`availTop` Read only
Experimental

A number representing the y-coordinate (top edge) of the available screen area.

`devicePixelRatio` Read only
Experimental

A number representing the screen's device pixel ratio.

`isInternal` Read only
Experimental

A boolean indicating whether the screen is internal to the device or external.

`isPrimary` Read only
Experimental

A boolean indicating whether the screen is set as the operating system (OS) primary screen or not.

`label` Read only
Experimental

A string providing a descriptive label for the screen, for example "Built-in Retina Display".

`left` Read only
Experimental

A number representing the x-coordinate (left-hand edge) of the total screen area.

`top` Read only
Experimental

A number representing the y-coordinate (top edge) of the total screen area.

Events
------

*Inherits events from its parent, `Screen`.*

`change`
Experimental

Fired on a specific screen when any property of the screen changes — width or height, available width or available height, color depth, or orientation, screen position and available screen position, device pixel ratio, label or screen's designation.

Examples
--------

When `Window.getScreenDetails()` is invoked, the user will be asked for permission to manage windows on all their displays (the status of this permission can be checked using `Permissions.query()` to query `window-management`). Provided they grant permission, the resulting `ScreenDetails` object contains `ScreenDetailed` objects representing all the screens available to the user's system.

The following example opens a window in the top-left corner of the OS primary screen:

```js
// Return ScreenDetails
const allScreens = await window.getScreenDetails();

// Return the primary screen ScreenDetailed object
const primaryScreenDetailed = allScreens.screens.find(
  (screenDetailed) => screenDetailed.isPrimary,
);

// Open a window in the top-left corner of the OS primary screen
window.open(
  "https://example.com",
  "\_blank",
  `left=${primaryScreenDetailed.availLeft},
 top=${primaryScreenDetailed.availTop},
 width=200,
 height=200`,
);
```

**Note:** See Multi-window learning environment for a full example (see the source code also).

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

| Specification |
| --- |
| Window Management # api-screendetailed-interface |

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

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

See also
--------

* Window Management API


DelayNode - Web APIs

DelayNode
=========

The **`DelayNode`** interface represents a delay-line; an `AudioNode` audio-processing module that causes a delay between the arrival of an input data and its propagation to the output.

A `DelayNode` always has exactly one input and one output, both with the same amount of channels.

![The DelayNode acts as a delay-line, here with a value of 1s.](/en-US/docs/Web/API/DelayNode/webaudiodelaynode.png)

When creating a graph that has a cycle, it is mandatory to have at least one `DelayNode` in the cycle, or the nodes taking part in the cycle will be muted.

EventTarget

AudioNode

DelayNode

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"max"` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `"speakers"` |

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

`DelayNode()`

Creates a new instance of an DelayNode object instance. As an alternative, you can use the `BaseAudioContext.createDelay()` factory method; see Creating an AudioNode.

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

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

`DelayNode.delayTime` Read only

An a-rate `AudioParam` representing the amount of delay to apply, specified in seconds.

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

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

Example
-------

See `BaseAudioContext.createDelay()` for example code.

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

| Specification |
| --- |
| Web Audio API # DelayNode |

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

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

See also
--------

* Using the Web Audio API


CSSMatrixComponent - Web APIs

CSSMatrixComponent
==================

The **`CSSMatrixComponent`** interface of the CSS\_Object\_Model#css\_typed\_object\_model represents the matrix() and matrix3d() values of the individual `transform` property in CSS. It inherits properties and methods from its parent `CSSTransformValue`.

CSSTransformComponent

CSSMatrixComponentConstructor
-----------

`CSSMatrixComponent()`

Creates a new `CSSMatrixComponent` object.

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

`matrix`

A matrix.

Examples
--------

To do.

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

| Specification |
| --- |
| CSS Typed OM Level 1 # cssmatrixcomponent |

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

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


MediaEncryptedEvent - Web APIs

MediaEncryptedEvent
===================

The **`MediaEncryptedEvent`** interface of the Encrypted Media Extensions API contains the information associated with an `encrypted` event sent to a `HTMLMediaElement` when some initialization data is encountered in the media.

Event

MediaEncryptedEventConstructor
-----------

`MediaEncryptedEvent()`

Creates a new instance of a `MediaEncryptedEvent` object.

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

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

`MediaEncryptedEvent.initDataType` Read only

Returns a case-sensitive string with the *type* of the format of the initialization data found.

`MediaEncryptedEvent.initData` Read only

Returns an `ArrayBuffer` containing the initialization data found. If there is no initialization data associated with the format, it returns `null`.

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

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

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

| Specification |
| --- |
| Encrypted Media Extensions # mediaencryptedevent |

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

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


EXT_sRGB extension - Web APIs

EXT\_sRGB extension
===================

The **`EXT_sRGB`** extension is part of the WebGL API and adds sRGB support to textures and framebuffer objects.

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. The constants in WebGL2 are: `gl.SRGB`, `gl.SRGB8`, `gl.SRGB8_ALPHA8` and `gl.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING`.

Constants
---------

This extension exposes the following constants, which can be used in the `texImage2D()`, `texSubImage2D()`, `renderbufferStorage()` and `getFramebufferAttachmentParameter()` methods.

`ext.SRGB_EXT`

Unsized sRGB format that leaves the precision up to the driver.

`ext.SRGB_ALPHA_EXT`

Unsized sRGB format with unsized alpha component.

`ext.SRGB8_ALPHA8_EXT`

Sized (8-bit) sRGB and alpha formats.

`ext.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT`

Returns the framebuffer color encoding (`gl.LINEAR` or `ext.SRGB_EXT`).

Examples
--------

```js
const ext = gl.getExtension("EXT\_sRGB");

const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE\_2D, texture);

gl.texImage2D(
  gl.TEXTURE\_2D,
  0,
  ext.SRGB\_EXT,
  512,
  512,
  0,
  ext.SRGB\_EXT,
  gl.UNSIGNED\_BYTE,
  image,
);
```

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

| Specification |
| --- |
| WebGL EXT\_sRGB Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.texImage2D()`
* `WebGLRenderingContext.texSubImage2D()`
* `WebGLRenderingContext.renderbufferStorage()`
* `WebGLRenderingContext.getFramebufferAttachmentParameter()`


OES_texture_half_float_linear extension - Web APIs

OES\_texture\_half\_float\_linear extension
===========================================

The **`OES_texture_half_float_linear`** extension is part of the WebGL API and allows linear filtering with half floating-point pixel types for textures.

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 extension is not needed.

Linear filtering
----------------

The `OES_texture_half_float` extension alone does not allow linear filtering with half floating-point textures. This extension enables this ability.

With the help of this extension, you can now set the magnification or minification filter in the `WebGLRenderingContext.texParameter()` method to one of `gl.LINEAR`, `gl.LINEAR_MIPMAP_NEAREST`, `gl.NEAREST_MIPMAP_LINEAR`, or `gl.LINEAR_MIPMAP_LINEAR`, and use half floating-point textures.

Examples
--------

```js
const halfFloat = gl.getExtension("OES\_texture\_half\_float");
gl.getExtension("OES\_texture\_half\_float\_linear");

const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE\_2D, texture);

gl.texParameterf(gl.TEXTURE\_2D, gl.TEXTURE\_MAG\_FILTER, gl.LINEAR);
gl.texImage2D(
  gl.TEXTURE\_2D,
  0,
  gl.RGBA,
  gl.RGBA,
  halfFloat.HALF\_FLOAT\_OES,
  image,
);
```

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

| Specification |
| --- |
| WebGL OES\_texture\_half\_float\_linear 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()`
* `WebGLRenderingContext.texImage2D()`
* `WebGLRenderingContext.texSubImage2D()`
* `OES_texture_float`
* `OES_texture_float_linear`
* `OES_texture_half_float`


CSSKeywordValue - Web APIs

CSSKeywordValue
===============

The **`CSSKeywordValue`** interface of the CSS Typed Object Model API creates an object to represent CSS keywords and other identifiers.

The interface instance name is a stringifier meaning that when used anywhere a string is expected it will return the value of `CSSKeyword.value`.

CSSStyleValue

CSSKeywordValueConstructor
-----------

`CSSKeywordValue()`

Creates a new `CSSKeywordValue` object.

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

`CSSKeywordValue.value`

Returns or sets the value of the `CSSKeywordValue`.

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

*Inherits methods from `CSSStyleValue`.*

Examples
--------

The following example resets the CSS `display` property to its defaults, setting the inline `style` attribute to `style="display: initial"` if viewed in the developer tools inspector.
```

#myElement {
  display: flex;
}
```

```
<div id="myElement">
  Check the developer tools to see the log in the console and to inspect the
  style attribute on this div.
</div>
```

```js
let myElement = document.getElementById("myElement").attributeStyleMap;
myElement.set("display", new CSSKeywordValue("initial"));

console.log(myElement.get("display").value); // 'initial'
```

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

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

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

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

See also
--------

* `CSSImageValue`
* `CSSNumericValue`
* `CSSPositionValue`
* `CSSTransformValue`
* `CSSUnparsedValue`


WEBGL_compressed_texture_astc extension - Web APIs

WEBGL\_compressed\_texture\_astc extension
==========================================

The **`WEBGL_compressed_texture_astc`** extension is part of the WebGL API and exposes Adaptive Scalable Texture Compression (ASTC) compressed texture formats to WebGL.

For more information, see the article Using ASTC Texture Compression for Game Assets by NVIDIA.

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

**Note:** ASTC compression is typically available on Mali ARM GPUs, Intel GPUs, and NVIDIA Tegra chips.

This extension is available to both, WebGL1 and WebGL2 contexts.

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

This extension exposes one new methods.

`ext.getSupportedProfiles()`

Returns an array of strings containing the names of the ASTC profiles supported by the implementation.

Constants
---------

The compressed texture formats are exposed by 28 constants and can be used in two functions: `compressedTexImage2D()` and `compressedTexSubImage2D()`.

| Constants | Blocks | Bits per pixel | `ArrayBuffer` `byteLength` | bytes if height and width are 512 |
| --- | --- | --- | --- | --- |
| `ext.COMPRESSED_RGBA_ASTC_4x4_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR` | 4x4 | 8.00 | `floor((width + 3) / 4) * floor((height + 3) / 4) * 16` | 262144 |
| `ext.COMPRESSED_RGBA_ASTC_5x4_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR` | 5x4 | 6.40 | `floor((width + 4) / 5) * floor((height + 3) / 4) * 16` | 210944 |
| `ext.COMPRESSED_RGBA_ASTC_5x5_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR` | 5x5 | 5.12 | `floor((width + 4) / 5) * floor((height + 4) / 5) * 16` | 169744 |
| `ext.COMPRESSED_RGBA_ASTC_6x5_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR` | 6x5 | 4.27 | `floor((width + 5) / 6) * floor((height + 4) / 5) * 16` | 141728 |
| `ext.COMPRESSED_RGBA_ASTC_6x6_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR` | 6x6 | 3.56 | `floor((width + 5) / 6) * floor((height + 5) / 6) * 16` | 118336 |
| `ext.COMPRESSED_RGBA_ASTC_8x5_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR` | 8x5 | 3.20 | `floor((width + 7) / 8) * floor((height + 4) / 5) * 16` | 105472 |
| `ext.COMPRESSED_RGBA_ASTC_8x6_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR` | 8x6 | 2.67 | `floor((width + 7) / 8) * floor((height + 5) / 6) * 16` | 88064 |
| `ext.COMPRESSED_RGBA_ASTC_8x8_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR` | 8x8 | 2.00 | `floor((width + 7) / 8) * floor((height + 7) / 8) * 16` | 65536 |
| `ext.COMPRESSED_RGBA_ASTC_10x5_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR` | 10x5 | 2.56 | `floor((width + 9) / 10) * floor((height + 4) / 5) * 16` | 85696 |
| `ext.COMPRESSED_RGBA_ASTC_10x6_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR` | 10x6 | 2.13 | `floor((width + 9) / 10) * floor((height + 5) / 6) * 16` | 71552 |
| `ext.COMPRESSED_RGBA_ASTC_10x8_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR` | 10x8 | 1.60 | `floor((width + 9) / 10) * floor((height + 7) / 8) * 16` | 53248 |
| `ext.COMPRESSED_RGBA_ASTC_10x10_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR` | 10x10 | 1.28 | `floor((width + 9) / 10) * floor((height + 9) / 10) * 16` | 43264 |
| `ext.COMPRESSED_RGBA_ASTC_12x10_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR` | 12x10 | 1.07 | `floor((width + 11) / 12) * floor((height + 9) / 10) * 16` | 35776 |
| `ext.COMPRESSED_RGBA_ASTC_12x12_KHRext.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR` | 12x12 | 0.89 | `floor((width + 11) / 12) * floor((height + 11) / 12) * 16` | 29584 |

Examples
--------

```js
const ext = gl.getExtension("WEBGL\_compressed\_texture\_astc");

const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE\_2D, texture);

gl.compressedTexImage2D(
  gl.TEXTURE\_2D,
  0,
  ext.COMPRESSED\_RGBA\_ASTC\_12x12\_KHR,
  512,
  512,
  0,
  textureData,
);
```

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

| Specification |
| --- |
| WebGL WEBGL\_compressed\_texture\_astc Extension Specification  |

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

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

See also
--------

* Using ASTC Texture Compression for Game Assets
* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.compressedTexImage2D()`
* `WebGLRenderingContext.compressedTexSubImage2D()`
* `WebGLRenderingContext.getParameter()`


SubtleCrypto - Web APIs

SubtleCrypto
============

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

The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the `subtle` property of the `Crypto` object you get from the `crypto` property.

**Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle.

Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts.

Errors in security system design and implementation can make the security of the system completely ineffective.

Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The Crypto 101 Course can be a great place to start learning about the design and implementation of secure systems.

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

*This interface doesn't inherit any properties, as it has no parent interface.*

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

*This interface doesn't inherit any methods, as it has no parent interface.*

`SubtleCrypto.encrypt()`

Returns a `Promise` that fulfills with the encrypted data corresponding to the clear text, algorithm, and key given as parameters.

`SubtleCrypto.decrypt()`

Returns a `Promise` that fulfills with the clear data corresponding to the encrypted text, algorithm, and key given as parameters.

`SubtleCrypto.sign()`

Returns a `Promise` that fulfills with the signature corresponding to the text, algorithm, and key given as parameters.

`SubtleCrypto.verify()`

Returns a `Promise` that fulfills with a boolean value indicating if the signature given as a parameter matches the text, algorithm, and key that are also given as parameters.

`SubtleCrypto.digest()`

Returns a `Promise` that fulfills with a digest generated from the algorithm and text given as parameters.

`SubtleCrypto.generateKey()`

Returns a `Promise` that fulfills with a newly-generated `CryptoKey`, for symmetrical algorithms, or a `CryptoKeyPair`, containing two newly generated keys, for asymmetrical algorithms. These will match the algorithm, usages, and extractability given as parameters.

`SubtleCrypto.deriveKey()`

Returns a `Promise` that fulfills with a newly generated `CryptoKey` derived from the master key and specific algorithm given as parameters.

`SubtleCrypto.deriveBits()`

Returns a `Promise` that fulfills with a newly generated buffer of pseudo-random bits derived from the master key and specific algorithm given as parameters.

`SubtleCrypto.importKey()`

Returns a `Promise` that fulfills with a `CryptoKey` corresponding to the format, the algorithm, raw key data, usages, and extractability given as parameters.

`SubtleCrypto.exportKey()`

Returns a `Promise` that fulfills with the raw key data containing the key in the requested format.

`SubtleCrypto.wrapKey()`

Returns a `Promise` that fulfills with a wrapped symmetric key for usage (transfer and storage) in insecure environments. The wrapped key matches the format specified in the given parameters, and wrapping is done by the given wrapping key, using the specified algorithm.

`SubtleCrypto.unwrapKey()`

Returns a `Promise` that fulfills with a `CryptoKey` corresponding to the wrapped key given in the parameter.

Using SubtleCrypto
------------------

We can split the functions implemented by this API into two groups: cryptography functions and key management functions.

### Cryptography functions

These are the functions you can use to implement security features such as privacy and authentication in a system. The `SubtleCrypto` API provides the following cryptography functions:

* `sign()` and `verify()`: create and verify digital signatures.
* `encrypt()` and `decrypt()`: encrypt and decrypt data.
* `digest()`: create a fixed-length, collision-resistant digest of some data.
### Key management functions

Except for `digest()`, all the cryptography functions in the API use cryptographic keys. In the `SubtleCrypto` API a cryptographic key is represented using a `CryptoKey` object. To perform operations like signing and encrypting, you pass a `CryptoKey` object into the `sign()` or `encrypt()` function.

#### Generating and deriving keys

The `generateKey()` and `deriveKey()` functions both create a new `CryptoKey` object.

The difference is that `generateKey()` will generate a new distinct key value each time you call it, while `deriveKey()` derives a key from some initial keying material. If you provide the same keying material to two separate calls to `deriveKey()`, you will get two `CryptoKey` objects that have the same underlying value. This is useful if, for example, you want to derive an encryption key from a password and later derive the same key from the same password to decrypt the data.

#### Importing and exporting keys

To make keys available outside your app, you need to export the key, and that's what `exportKey()` is for. You can choose one of a number of export formats.

The inverse of `exportKey()` is `importKey()`. You can import keys from other systems, and support for standard formats like PKCS #8 and JSON Web Key helps you do this. The `exportKey()` function exports the key in an unencrypted format.

If the key is sensitive you should use `wrapKey()`, which exports the key and then encrypts it using another key; the API calls a "key-wrapping key".

The inverse of `wrapKey()` is `unwrapKey()`, which decrypts then imports the key.

#### Storing keys

`CryptoKey` objects can be stored using the structured clone algorithm, meaning that you can store and retrieve them using standard web storage APIs. The specification expects that most developers will use the IndexedDB API to store `CryptoKey` objects.

### Supported algorithms

The cryptographic functions provided by the Web Crypto API can be performed by one or more different *cryptographic algorithms*: the `algorithm` argument to the function indicates which algorithm to use. Some algorithms need extra parameters: in these cases the `algorithm` argument is a dictionary object that includes the extra parameters.

The table below summarizes which algorithms are suitable for which cryptographic operations:

|  | sign()verify() | encrypt()decrypt() | digest() | deriveBits()deriveKey() | wrapKey()unwrapKey() |
| --- | --- | --- | --- | --- | --- |
| RSASSA-PKCS1-v1\_5 | ✓ |  |  |  |  |
| RSA-PSS | ✓ |  |  |  |  |
| ECDSA | ✓ |  |  |  |  |
| HMAC | ✓ |  |  |  |  |
| RSA-OAEP |  | ✓ |  |  | ✓ |
| AES-CTR |  | ✓ |  |  | ✓ |
| AES-CBC |  | ✓ |  |  | ✓ |
| AES-GCM |  | ✓ |  |  | ✓ |
| SHA-1 |  |  | ✓ |  |  |
| SHA-256 |  |  | ✓ |  |  |
| SHA-384 |  |  | ✓ |  |  |
| SHA-512 |  |  | ✓ |  |  |
| ECDH |  |  |  | ✓ |  |
| HKDF |  |  |  | ✓ |  |
| PBKDF2 |  |  |  | ✓ |  |
| AES-KW |  |  |  |  | ✓ |

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

| Specification |
| --- |
| Web Cryptography API # subtlecrypto-interface |

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

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

See also
--------

* Web Crypto API
* Non-cryptographic uses of SubtleCrypto
* Web security
* Privacy, permissions, and information security
* `Crypto` and `Crypto.subtle`.
* Crypto 101: an introductory course on cryptography.


SerialPort - Web APIs

SerialPort
==========

**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 `SerialPort` interface of the `Web Serial API` provides access to a serial port on the host device.

EventTarget

SerialPortConstructor
-----------

Instances of this interface may be obtained by calling methods of the `Serial` interface, therefore it has no constructor of its own.

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

`SerialPort.readable` Read only
Experimental

Returns a `ReadableStream` for receiving data from the device connected to the port.

`SerialPort.writable` Read only
Experimental

Returns a `WritableStream` for sending data to the device connected to the port.

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

`SerialPort.forget()`
Experimental

Returns a `Promise` that resolves when the port closes and is forgotten.

`SerialPort.getInfo()`
Experimental

Returns an object containing properties of the port.

`SerialPort.open()`
Experimental

Returns a `Promise` that resolves when the port is opened. By default the port is opened with 8 data bits, 1 stop bit and no parity checking.

`SerialPort.setSignals()`
Experimental

Sets control signals on the port and returns a `Promise` that resolves when they are set.

`SerialPort.getSignals()`
Experimental

Returns a `Promise` that resolves with an object containing the current state of the port's control signals.

`SerialPort.close()`
Experimental

Returns a `Promise` that resolves when the port closes.

Events
------

`connect`
Experimental

An event fired when the port has connected to the device.

`disconnect`
Experimental

An event fired when the port has disconnected from the device.

Examples
--------

### Opening a port

Before communicating on a serial port it must be opened. Opening the port allows the site to specify the necessary parameters that control how data is transmitted and received. Developers should check the documentation for the device they are connecting to for the appropriate parameters.

```js
await port.open({ baudRate: 9600 /\* pick your baud rate \*/ });
```

Once the `Promise` returned by `open()` resolves the `readable` and `writable` attributes can be accessed to get the `ReadableStream` and `WritableStream` instances for receiving data from and sending data to the connected device.

### Reading data from a port

The following example shows how to read data from a port. The outer loop handles non-fatal errors, creating a new reader until a fatal error is encountered and `readable` becomes `null`.

```js
while (port.readable) {
  const reader = port.readable.getReader();
  try {
    while (true) {
      const { value, done } = await reader.read();
      if (done) {
        // |reader| has been canceled.
        break;
      }
      // Do something with |value|…
    }
  } catch (error) {
    // Handle |error|…
  } finally {
    reader.releaseLock();
  }
}
```

### Writing data to a port

The following example shows how to write a string to a port. A `TextEncoder` converts the string to a `Uint8Array` before transmission.

```js
const encoder = new TextEncoder();
const writer = port.writable.getWriter();
await writer.write(encoder.encode("PING"));
writer.releaseLock();
```

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

| Specification |
| --- |
| Web Serial API # dom-serialport |

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

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


Badging API - Web APIs

Badging API
===========

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

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

The **Badging API** gives web developers a method of setting a badge on a document or application, to act as a notification that state has changed without displaying a more distracting notification. A common use case for this would be an application with a messaging feature displaying a badge on the app icon to show that new messages have arrived.

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

Web developers frequently update document favicons or titles in order to indicate status. The Badging API provides a more elegant way to show status, by providing a method which has meaning to the user agent and can therefore be displayed in a way that matches the rest of the UI.

### Types of badges

There are two types of badges:

* Document badges, which are typically shown in the browser tab near or on the page icon.
* App badges, which are associated with the icon of an installed web app. These may display on the app icon in the dock, shelf, or home screen depending on the device in use.
### Badge states

A badge can have one of three possible values, which are set internally:

`nothing`

Indicating that no badge is currently set. A badge can be in this state due to it being cleared by the application, or being reset by the user agent.

`flag`

Indicating that the badge is set, but has no specific data to display. A badge will be in this state if the application has set a badge, but has not passed any value to the method.

`an integer`

A value passed when setting the badge. This value will never be `0`, passing a value of `0` when setting a badge will cause the user agent to clear the badge by setting it to `nothing`.

### Setting badges

A badge is set with the methods `setAppBadge()` (for installed apps). If no parameters are passed to these methods then the badge value is flag. The user agent will display its notification badge, for example, a colored circle on the icon.

These methods can also be passed a parameter `contents`, which should be a number. This will then be displayed as part of the badge. User agents may change this value in some way. For example, if you pass a very large number such as 4000, the user agent may display this as 99+ in the badge. User agents may also ignore this data and display a marker instead.

### Clearing badges

Badges are cleared with the `clearAppBadge()` methods. These do not take any parameters and set the badge to the value `nothing`. Additionally, passing a value of `0` to `setAppBadge()` will set the badge to `nothing` and clear the badge.

Interfaces
----------

None.

### Extensions to the Navigator interface

`Navigator.setAppBadge()`

Sets a badge on the icon associated with this app.

`Navigator.clearAppBadge()`

Clears the badge on the icon associated with this app.

### Extensions to the WorkerNavigator interface

`WorkerNavigator.setAppBadge()`

Sets a badge on the icon associated with this app.

`WorkerNavigator.clearAppBadge()`

Clears the badge on the icon associated with this app.

Examples
--------

To set a notification badge on the current app with a value of 12:

```js
navigator.setAppBadge(12);
```

To clear a notification badge on the current app:

```js
navigator.clearAppBadge();
```

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

| Specification |
| --- |
| Badging API # setappbadge-method |

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

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

See also
--------

* Badging for app icons
* Badging API Explainer


MessageEvent - Web APIs

MessageEvent
============

The **`MessageEvent`** interface represents a message received by a target object.

This is used to represent messages in:

* Server-sent events (see `EventSource.message_event`).
* Web sockets (see the `onmessage` property of the WebSocket interface).
* Cross-document messaging (see `Window.postMessage()` and `Window.message_event`).
* Channel messaging (see `MessagePort.postMessage()` and `MessagePort.message_event`).
* Cross-worker/document messaging (see the above two entries, but also `Worker.postMessage()`, `Worker.message_event`, `ServiceWorkerGlobalScope.message_event`, etc.)
* Broadcast channels (see `BroadcastChannel.postMessage()`) and `BroadcastChannel.message_event`).
* WebRTC data channels (see `onmessage`).

The action triggered by this event is defined in a function set as the event handler for the relevant `message` event (e.g. using an `onmessage` handler as listed above).

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

Event

MessageEventConstructor
-----------

`MessageEvent()`

Creates a new `MessageEvent`.

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

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

`MessageEvent.data` Read only

The data sent by the message emitter.

`MessageEvent.origin` Read only

A string representing the origin of the message emitter.

`MessageEvent.lastEventId` Read only

A string representing a unique ID for the event.

`MessageEvent.source` Read only

A `MessageEventSource` (which can be a WindowProxy, `MessagePort`, or `ServiceWorker` object) representing the message emitter.

`MessageEvent.ports` Read only

An array of `MessagePort` objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).

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

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

`initMessageEvent()`
Deprecated

Initializes a message event. **Do not use this anymore** — **use the `MessageEvent()` constructor instead.**

Examples
--------

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

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:

```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 # the-messageevent-interface |

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

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

See also
--------

* `ExtendableMessageEvent` — similar to this interface but used in interfaces that needs to give more flexibility to authors.


SVGFEDropShadowElement - Web APIs

SVGFEDropShadowElement
======================

The **`SVGFEDropShadowElement`** interface corresponds to the `<feDropShadow>` element.

EventTarget

Node

Element

SVGElement

SVGFEDropShadowElementInstance properties
-------------------

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

`SVGFEDropShadowElement.dx` Read only

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

`SVGFEDropShadowElement.dy` Read only

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

`SVGFEDropShadowElement.height` Read only

An `SVGAnimatedLength` corresponding to the `height` attribute of the given element.

`SVGFEDropShadowElement.in1` Read only

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

`SVGFEDropShadowElement.result` Read only

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

`SVGFEDropShadowElement.stdDeviationX` Read only

An `SVGAnimatedNumber` corresponding to the (possibly automatically computed) X component of the `stdDeviationX` attribute of the given element.

`SVGFEDropShadowElement.stdDeviationY` Read only

An `SVGAnimatedNumber` corresponding to the (possibly automatically computed) Y component of the `stdDeviationY` attribute of the given element.

`SVGFEDropShadowElement.width` Read only

An `SVGAnimatedLength` corresponding to the `width` attribute of the given element.

`SVGFEDropShadowElement.x` Read only

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

`SVGFEDropShadowElement.y` Read only

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

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

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

`SVGFEDropShadowElement.setStdDeviation()`

Sets the values for the `stdDeviation` attribute.

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

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

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

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

See also
--------

* `<feDropShadow>`


CSSImportRule - Web APIs

CSSImportRule
=============

The **`CSSImportRule`** interface represents an `@import` at-rule.

CSSRule

CSSImportRuleInstance properties
-------------------

*Inherits properties from its ancestor `CSSRule`.*

`CSSImportRule.href` Read only

Returns the URL specified by the `@import` rule.

`CSSImportRule.layerName` Read only

Returns the name of the cascade layer declared in the `@import` rule, the empty string if the layer is anonymous, the or `null` if the rule doesn't declare any.

`CSSImportRule.media`

Returns the value of the `media` attribute of the associated stylesheet.

`CSSImportRule.styleSheet` Read only

Returns the associated stylesheet.

`CSSImportRule.supportsText` Read only

Returns the supports condition specified by the `@import` rule.

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

*Inherits methods from its ancestor `CSSRule`.*

Examples
--------

The document includes a single stylesheet which contains a single `@import` rule. Therefore the first item in the list of CSS rules will be a `CSSImportRule`.

```css
@import url("style.css") screen;
```

```js
const myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); // A CSSImportRule instance object
```

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

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

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

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


WebGLQuery - Web APIs

WebGLQuery
==========

The **`WebGLQuery`** interface is part of the WebGL 2 API and provides ways to asynchronously query for information. By default, occlusion queries and primitive queries are available.

Another kind of queries are disjoint timer queries, which allow you to measure performance and profiling of your GPU. Disjoint timer queries are available with the `EXT_disjoint_timer_query` extension only.

WebGLObject

WebGLQuery
When working with `WebGLQuery` objects, the following methods of the `WebGL2RenderingContext` are useful:

* `WebGL2RenderingContext.createQuery()`
* `WebGL2RenderingContext.deleteQuery()`
* `WebGL2RenderingContext.isQuery()`
* `WebGL2RenderingContext.beginQuery()`
* `WebGL2RenderingContext.endQuery()`
* `WebGL2RenderingContext.getQuery()`
* `WebGL2RenderingContext.getQueryParameter()`
Examples
--------

### Creating a `WebGLQuery` object

in this example, `gl` must be a `WebGL2RenderingContext`. `WebGLQuery` objects are not available in WebGL 1.

```js
const query = gl.createQuery();
```

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

| Specification |
| --- |
| WebGL 2.0 Specification # 3.2 |

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

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

See also
--------

* `EXT_disjoint_timer_query`


origin global property - Web APIs

origin global property
======================

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

 The global **`origin`** read-only property returns the origin of the global
 scope, serialized as a string.

Value
-----

A string.

Examples
--------

 Executed from inside a worker script, the following snippet will log the worker's
 global scope's origin to the console each time it receives a message

```js
onmessage = () => {
  console.log(self.origin);
};
```

 If the origin is not a scheme/host/port tuple (say you are trying to run it locally,
 i.e. via `file://` URL), `origin` will return the string
 `"null"`.

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

| Specification |
| --- |
| HTML Standard # dom-origin-dev |

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

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


AbortController - Web APIs

AbortController
===============

The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired.

You can create a new `AbortController` object using the `AbortController()` constructor. Communicating with an asynchronous operation is done using an `AbortSignal` object.

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

`AbortController()`

Creates a new `AbortController` object instance.

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

`AbortController.signal` Read only

Returns an `AbortSignal` object instance, which can be used to communicate with, or to abort, an asynchronous operation.

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

`AbortController.abort()`

Aborts an asynchronous operation before it has completed. This is able to abort fetch requests, consumption of any response bodies, and streams.

Examples
--------

**Note:** There are additional examples in the `AbortSignal` reference.

In the following snippet, we aim to download a video using the Fetch API.

We first create a controller using the `AbortController()` constructor, then grab a reference to its associated `AbortSignal` object using the `AbortController.signal` property.

When the fetch request is initiated, we pass in the `AbortSignal` as an option inside the request's options object (the `{signal}` below). This associates the signal and controller with the fetch request and allows us to abort it by calling `AbortController.abort()`, as seen below in the second event listener.

```js
let controller;
const url = "video.mp4";

const downloadBtn = document.querySelector(".download");
const abortBtn = document.querySelector(".abort");

downloadBtn.addEventListener("click", fetchVideo);

abortBtn.addEventListener("click", () => {
  if (controller) {
    controller.abort();
    console.log("Download aborted");
  }
});

function fetchVideo() {
  controller = new AbortController();
  const signal = controller.signal;
  fetch(url, { signal })
    .then((response) => {
      console.log("Download complete", response);
    })
    .catch((err) => {
      console.error(`Download error: ${err.message}`);
    });
}
```

**Note:** When `abort()` is called, the `fetch()` promise rejects with a `DOMException` named `AbortError`.

You can find a full working example on GitHub; you can also see it running live.

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

| Specification |
| --- |
| DOM Standard # interface-abortcontroller |

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

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

See also
--------

* Fetch API
* Abortable Fetch by Jake Archibald


HTML Drag and Drop API - Web APIs

HTML Drag and Drop API
======================

**HTML Drag and Drop** interfaces enable applications to use drag-and-drop features in browsers.

The user may select *draggable* elements with a mouse, drag those elements to a *droppable* element, and drop them by releasing the mouse button. A translucent representation of the *draggable* elements follows the pointer during the drag operation.

You can customize which elements can become *draggable*, the type of feedback the *draggable* elements produce, and the *droppable* elements.

This overview of HTML Drag and Drop includes a description of the interfaces, basic steps to add drag-and-drop support to an application, and an interoperability summary of the interfaces.

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

### Drag Events

HTML drag-and-drop uses the `DOM event model` and *`drag events`* inherited from `mouse events`. A typical *drag operation* begins when a user selects a *draggable* element, continues when the user drags the element to a *droppable* element, and then ends when the user releases the dragged element.

During drag operations, several event types are fired, and some events might fire many times, such as the `drag` and `dragover` events.

Each drag event type has an associated event handler:

| Event | Fires when... |
| --- | --- |
| `drag` | ...a *dragged item* (element or text selection) is dragged. |
| `dragend` | ...a drag operation ends (such as releasing a mouse button or hitting the Esc key; see Finishing a Drag.) |
| `dragenter` | ...a dragged item enters a valid drop target. (See Specifying Drop Targets.) |
| `dragleave` | ...a dragged item leaves a valid drop target. |
| `dragover` | ...a dragged item is being dragged over a valid drop target, every few hundred milliseconds. |
| `dragstart` | ...the user starts dragging an item. (See Starting a Drag Operation.) |
| `drop` | ...an item is dropped on a valid drop target. (See Performing a Drop.) |

**Note:** Neither `dragstart` nor `dragend` events are fired when dragging a file into the browser from the OS.

### The basics

This section is a summary of the basic steps to add drag-and-drop functionality to an application.

#### Identify what is draggable

Making an element *draggable* requires adding the `draggable` attribute and the `dragstart` event handler, as shown in the following code sample:

```html
<script>
 function dragstartHandler(ev) {
 // Add the target element's id to the data transfer object
 ev.dataTransfer.setData("text/plain", ev.target.id);
 }

 window.addEventListener("DOMContentLoaded", () => {
 // Get the element by id
 const element = document.getElementById("p1");
 // Add the ondragstart event listener
 element.addEventListener("dragstart", dragstartHandler);
 });
</script>

<p id="p1" draggable="true">This element is draggable.</p>
```

For more information, see:

* Draggable attribute reference
* Drag operations guide

#### Define the drag's data

The application is free to include any number of data items in a drag operation. Each data item is a string of a particular `type` — typically a MIME type such as `text/html`.

Each `drag event` has a `dataTransfer` property that *holds* the event's data. This property (which is a `DataTransfer` object) also has methods to *manage* drag data. The `setData()` method is used to add an item to the drag data, as shown in the following example.

```js
function dragstartHandler(ev) {
  // Add different types of drag data
  ev.dataTransfer.setData("text/plain", ev.target.innerText);
  ev.dataTransfer.setData("text/html", ev.target.outerHTML);
  ev.dataTransfer.setData(
    "text/uri-list",
    ev.target.ownerDocument.location.href,
  );
}
```

* For a list of common data types used in drag-and-drop (such as text, HTML, links, and files), see Recommended Drag Types.
* For more information about drag data, see Drag Data.

#### Define the drag image

By default, the browser supplies an image that appears beside the pointer during a drag operation. However, an application may define a custom image with the `setDragImage()` method, as shown in the following example.

```js
// Create an image and then use it for the drag image.
// NOTE: change "example.gif" to a real image URL or the image
// will not be created and the default drag image will be used.
let img = new Image();
img.src = "example.gif";
function dragstartHandler(ev) {
  ev.dataTransfer.setDragImage(img, 10, 10);
}
```

Learn more about drag feedback images in:

* Setting the Drag Feedback Image

#### Define the drop effect

The `dropEffect` property is used to control the feedback the user is given during a drag-and-drop operation. It typically affects which cursor the browser displays while dragging. For example, when the user hovers over a drop target, the browser's cursor may indicate the type of operation that will occur.

Three effects may be defined:

1. **`copy`** indicates that the dragged data will be copied from its present location to the drop location.
2. **`move`** indicates that the dragged data will be moved from its present location to the drop location.
3. **`link`** indicates that some form of relationship or connection will be created between the source and drop locations.

During the drag operation, drag effects may be modified to indicate that certain effects are allowed at certain locations.

The following example shows how to use this property.

```js
function dragstartHandler(ev) {
  ev.dataTransfer.dropEffect = "copy";
}
```

For more details, see:

* Drag Effects

#### Define a drop zone

By default, the browser prevents anything from happening when dropping something onto most HTML elements. To change that behavior so that an element becomes a *drop zone* or is *droppable*, the element must have both `ondragover` and `ondrop` event handler attributes.

The following example shows how to use those attributes, and includes basic event handlers for each attribute.

```html
<script>
 function dragoverHandler(ev) {
 ev.preventDefault();
 ev.dataTransfer.dropEffect = "move";
 }
 function dropHandler(ev) {
 ev.preventDefault();
 // Get the id of the target and add the moved element to the target's DOM
 const data = ev.dataTransfer.getData("text/plain");
 ev.target.appendChild(document.getElementById(data));
 }
</script>

<p id="target" ondrop="dropHandler(event)" ondragover="dragoverHandler(event)">
  Drop Zone
</p>
```

Note that each handler calls `preventDefault()` to prevent additional event processing for this event (such as touch events or pointer events).

For more information, see:

* Specifying Drop Targets

#### Handle the drop effect

The handler for the `drop` event is free to process the drag data in an application-specific way.

Typically, an application uses the `getData()` method to retrieve drag items and then process them accordingly. Additionally, application semantics may differ depending on the value of the `dropEffect` and/or the state of modifier keys.

The following example shows a drop handler getting the source element's `id` from the drag data, and then using the `id` to move the source element to the drop element:

```html
<script>
 function dragstartHandler(ev) {
 // Add the target element's id to the data transfer object
 ev.dataTransfer.setData("application/my-app", ev.target.id);
 ev.dataTransfer.effectAllowed = "move";
 }
 function dragoverHandler(ev) {
 ev.preventDefault();
 ev.dataTransfer.dropEffect = "move";
 }
 function dropHandler(ev) {
 ev.preventDefault();
 // Get the id of the target and add the moved element to the target's DOM
 const data = ev.dataTransfer.getData("application/my-app");
 ev.target.appendChild(document.getElementById(data));
 }
</script>

<p id="p1" draggable="true" ondragstart="dragstartHandler(event)">
  This element is draggable.
</p>
<div
 id="target"
 ondrop="dropHandler(event)"
 ondragover="dragoverHandler(event)">
  Drop Zone
</div>
```

For more information, see:

* Performing a Drop

#### Drag end

At the end of a drag operation, the `dragend` event fires at the *source* element — the element that was the target of the drag start.

This event fires regardless of whether the drag completed or was canceled. The `dragend` event handler can check the value of the `dropEffect` property to determine if the drag operation succeeded or not.

For more information about handling the end of a drag operation, see:

* Finishing a Drag
Interfaces
----------

The HTML Drag and Drop interfaces are `DragEvent`, `DataTransfer`, `DataTransferItem` and `DataTransferItemList`.

The `DragEvent` interface has a constructor and one `dataTransfer` property, which is a `DataTransfer` object.

`DataTransfer` objects include the drag event's state, such as the type of drag being done (like `copy` or `move`), the drag's data (one or more items), and the MIME type of each *drag item*. `DataTransfer` objects also have methods to add or remove items to the drag's data.

The `DragEvent` and `DataTransfer` interfaces should be the only ones needed to add HTML Drag and Drop capabilities to an application. (Firefox supports some Gecko-specific extensions to the `DataTransfer` object, but those extensions will only work on Firefox.)

Each `DataTransfer` object contains an `items` property, which is a `list` of `DataTransferItem` objects. A `DataTransferItem` object represents a single *drag item*, each with a `kind` property (either `string` or `file`) and a `type` property for the data item's MIME type. The `DataTransferItem` object also has methods to get the drag item's data.

The `DataTransferItemList` object is a list of `DataTransferItem` objects. The list object has methods to add a drag item to the list, remove a drag item from the list, and clear the list of all drag items.

A key difference between the `DataTransfer` and `DataTransferItem` interfaces is that the former uses the synchronous `getData()` method to access a drag item's data, but the latter instead uses the asynchronous `getAsString()` method.

**Note:** `DragEvent` and `DataTransfer` are broadly supported on desktop browsers. However, the `DataTransferItem` and `DataTransferItemList` interfaces have limited browser support. See Interoperability for more information about drag-and-drop interoperability.

Examples
--------

* Copying and moving elements with the `DataTransfer` interface
* Copying and moving elements with the `DataTransferListItem` interface
* Dragging and dropping files (Firefox only): https://jsfiddle.net/9C2EF/
* Dragging and dropping files (All browsers): https://jsbin.com/hiqasek/
* A parking project using the Drag and Drop API: https://park.glitch.me/ (You can edit here)
Specifications
--------------

| Specification |
| --- |
| HTML Standard  |

See also
--------

* Drag Operations
* Recommended Drag Types
* HTML Living Standard: Drag and Drop
* Drag and Drop interoperability data from CanIUse


ToggleEvent - Web APIs

ToggleEvent
===========

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 **`ToggleEvent`** interface represents an event notifying the user when a popover element's state toggles between showing and hidden.

It is the event object for the `HTMLElement` `beforetoggle` and `toggle` events, which fire on popovers when they transition between showing and hidden (before and after, respectively).

Event

ToggleEvent

**Note:** `ToggleEvent` is unrelated to the `HTMLDetailsElement` `toggle` event, which fires on a `<details>` element when its `open`/`closed` state is toggled. Its event object is a generic `Event`.

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

`ToggleEvent()`

Creates an `ToggleEvent` object.

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

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

`ToggleEvent.newState` Read only

A string (either `"open"` or `"closed"`), representing the state the element is transitioning to.

`ToggleEvent.oldState` Read only

A string (either `"open"` or `"closed"`), representing the state the element is transitioning from.

Examples
--------

### Basic example

```js
const popover = document.getElementById("mypopover");

// ...

popover.addEventListener("beforetoggle", (event) => {
  if (event.newState === "open") {
    console.log("Popover is being shown");
  } else {
    console.log("Popover is being hidden");
  }
});
```

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

| Specification |
| --- |
| HTML Standard # toggleevent |

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

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

See also
--------

* Popover API
* `beforetoggle` event
* `toggle` event


Screen Capture API - Web APIs

Screen Capture API
==================

The Screen Capture API introduces additions to the existing Media Capture and Streams API to let the user select a screen or portion of a screen (such as a window) to capture as a media stream. This stream can then be recorded or shared with others over the network.

Screen Capture API concepts and usage
-------------------------------------

The Screen Capture API is relatively simple to use. Its sole method is `MediaDevices.getDisplayMedia()`, whose job is to ask the user to select a screen or portion of a screen to capture in the form of a `MediaStream`.

To start capturing video from the screen, you call `getDisplayMedia()` on `navigator.mediaDevices`:

```js
captureStream =
  await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
```

The `Promise` returned by `getDisplayMedia()` resolves to a `MediaStream` which streams the captured media.

See the article Using the Screen Capture API for a more in-depth look at how to use the API to capture screen contents as a stream.

Interfaces
----------

`CaptureController`

Provides methods that can be used to further manipulate a capture session separate from its initiation via `MediaDevices.getDisplayMedia()`. A `CaptureController` object is associated with a capture session by passing it into a `getDisplayMedia()` call as the value of the options object's `controller` property.

Additions to the MediaDevices interface
---------------------------------------

`MediaDevices.getDisplayMedia()`

The `getDisplayMedia()` method is added to the `MediaDevices` interface. Similar to `getUserMedia()`, this method creates a promise that resolves with a `MediaStream` containing the display area selected by the user, in a format that matches the specified options.

Additions to existing dictionaries
----------------------------------

The Screen Capture API adds properties to the following dictionaries defined by other specifications.

### MediaTrackConstraints

`MediaTrackConstraints.displaySurface`

A `ConstrainDOMString` indicating what type of display surface is to be captured. The value is one of `browser`, `monitor`, or `window`.

`MediaTrackConstraints.logicalSurface`

Indicates whether or not the video in the stream represents a logical display surface (that is, one which may not be entirely visible onscreen, or may be completely offscreen). A value of `true` indicates a logical display surface is to be captured.

`MediaTrackConstraints.suppressLocalAudioPlayback`

Controls whether the audio playing in a tab will continue to be played out of a user's local speakers when the tab is captured, or whether it will be suppressed. A value of `true` indicates that it will be suppressed.

### MediaTrackSettings

`MediaTrackSettings.cursor`

A string which indicates whether or not the display surface currently being captured includes the mouse cursor, and if so, whether it's only visible while the mouse is in motion or if it's always visible. The value is one of `always`, `motion`, or `never`.

`MediaTrackSettings.displaySurface`

A string indicating what type of display surface is currently being captured. The value is one of `browser`, `monitor`, or `window`.

`MediaTrackSettings.logicalSurface`

A boolean value, which is `true` if the video being captured doesn't directly correspond to a single onscreen display area.

`MediaTrackSettings.suppressLocalAudioPlayback`

A boolean value, which is `true` if the audio being captured is not played out of the user's local speakers.

### MediaTrackSupportedConstraints

`MediaTrackSupportedConstraints.displaySurface`

A boolean, which is `true` if the current environment supports the `MediaTrackConstraints.displaySurface` constraint.

`MediaTrackSupportedConstraints.logicalSurface`

A boolean, which is `true` if the current environment supports the constraint `MediaTrackConstraints.logicalSurface`.

`MediaTrackSupportedConstraints.suppressLocalAudioPlayback`

A boolean, which is `true` if the current environment supports the constraint `MediaTrackConstraints.suppressLocalAudioPlayback`.

Permissions Policy validation
-----------------------------

User agents that support Permissions Policy (either using the HTTP `Permissions-Policy` header or the `<iframe>` attribute `allow`) can specify a desire to use the Screen Capture API using the directive `display-capture`:

```html
<iframe allow="display-capture" src="/some-other-document.html">…</iframe>
```

The default allowlist is `self`, which lets any content within the same origin use Screen Capture.

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

| Specification |
| --- |
| Screen Capture # dom-mediadevices-getdisplaymedia |

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

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

See also
--------

* Using the Screen Capture API
* `MediaDevices.getDisplayMedia()`


VideoColorSpace - Web APIs

VideoColorSpace
===============

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 **`VideoColorSpace`** interface of the WebCodecs API represents the color space of a video.

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

`VideoColorSpace()`

Creates a new `VideoColorSpace` object.

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

`VideoColorSpace.primaries` Read only

A string containing the color primary describing the color gamut of a video sample.

`VideoColorSpace.transfer`

A string containing the transfer characteristics of video samples.

`VideoColorSpace.matrix`

A string containing the matrix coefficients describing the relationship between sample component values and color coordinates.

`VideoColorSpace.fullRange`

A `Boolean`. If `true` indicates that full-range color values are used.

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

`VideoColorSpace.toJSON()`

Returns a JSON representation of the `VideoColorSpace` object.

Examples
--------

In the following example, `colorSpace` is a `VideoColorSpace` object returned from `VideoFrame`. The object is then printed to the console.

```js
let colorSpace = VideoFrame.colorSpace;
console.log(colorSpace);
```

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

| Specification |
| --- |
| WebCodecs # videocolorspace |

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

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


Media Session API - Web APIs

Media Session API
=================

The **Media Session API** provides a way to customize media notifications. It does this by providing metadata for display by the user agent for the media your web app is playing.

It also provides action handlers that the browser can use to access platform media keys such as hardware keys found on keyboards, headsets, remote controls, and software keys found in notification areas and on lock screens of mobile devices. So you can seamlessly control web-provided media via your device, even when not looking at the web page.

The aim is to allow users to know what's playing and to control it, without needing to open the specific page that launched it. To be able to support the Media Session API, a browser first needs a mechanism by which to access and be controlled by the OS-level media controls (such as Firefox's MediaControl).

Media Session concepts and usage
--------------------------------

The `MediaMetadata` interface lets a website provide rich metadata to the platform UI for media that is playing. This metadata includes the title, artist (creator) name, album (collection), and artwork. The platform can show this metadata in media centers, notifications, device lockscreens, etc.

The `MediaSession` interface lets users control playback of media through user-agent defined interface elements. Interaction with these elements triggers action handlers in the web page, playing the media. Since multiple pages may be simultaneously using this API, the user agent is responsible for calling the correct page's action handlers. The user agent provides default behaviors, when no page-defined behavior is available.

Accessing the Media Session API
-------------------------------

The primary interface for the Media Session API is the `MediaSession` interface. Rather than creating your own `MediaSession` instance, you access the API using the `navigator.mediaSession` property. For example, to set the current state of the media session to `playing`:

```js
navigator.mediaSession.playbackState = "playing";
```

Interfaces
----------

`MediaMetadata`

Allows a web page to provide rich media metadata for display in a platform UI.

`MediaSession`

Allows a web page to provide custom behaviors for standard media playback interactions.

Examples
--------

### Setting up action handlers for a music player

The following example shows feature detection for the Media Session API. It then instantiates a metadata object for the session, and adds action handlers for the user control actions:

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

  navigator.mediaSession.setActionHandler("play", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("pause", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("stop", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekbackward", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekforward", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekto", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("previoustrack", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("nexttrack", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("skipad", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("togglecamera", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("togglemicrophone", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("hangup", () => {
    /\* Code excerpted. \*/
  });
}
```

Some user agents disable autoplay for media elements on mobile devices and require a user gesture to start media. The following example adds a `pointerup` event to an on-page play button, which is then used to kick off the media session code:

```js
playButton.addEventListener("pointerup", (event) => {
  const audio = document.querySelector("audio");

  // User interacted with the page. Let's play audio!
  audio
    .play()
    .then(() => {
      /\* Set up media session controls, as shown above. \*/
    })
    .catch((error) => {
      console.error(error);
    });
});
```

### Using action handlers to control a slide presentation

The `"previousslide"` and `"nextslide"` action handlers can be used to handle moving forward and backward through a slide presentation, for example when the user puts their presentation into a Picture-in-Picture window, and presses the browser-supplied controls for navigating through slides.

```js
try {
  navigator.mediaSession.setActionHandler("previousslide", () => {
    log('> User clicked "Previous Slide" icon.');
    if (slideNumber > 1) slideNumber--;
    updateSlide();
  });
} catch (error) {
  log('Warning! The "previousslide" media session action is not supported.');
}

try {
  navigator.mediaSession.setActionHandler("nextslide", () => {
    log('> User clicked "Next Slide" icon.');
    slideNumber++;
    updateSlide();
  });
} catch (error) {
  log('Warning! The "nextslide" media session action is not supported.');
}
```

See Presenting Slides / Media Session Sample for a working example.

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

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

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

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


CSSFontFeatureValuesRule - Web APIs

CSSFontFeatureValuesRule
========================

The **`CSSFontFeatureValuesRule`** interface represents an `@font-feature-values` at-rule, letting developers assign for each font face a common name to specify features indices to be used in `font-variant-alternates`.

CSSRule

CSSFontFeatureValuesRuleInstance properties
-------------------

*Inherits properties from its ancestor `CSSRule`.*

`CSSFontFeatureValuesRule.fontFamily`

A string that identifies the font family this rule applies to.

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

*Inherits methods from its ancestor `CSSRule`.*

Examples
--------

### Read font family

In this example, we declare two `@font-feature-values` one for the *Font One* font family, and the other for *Font Two*. We then use the CSSOM to read these font families, displaying them into the log.

#### HTML

```html
<pre id="log"></pre>
```

#### CSS

```css
/\* At-rule for "nice-style" in Font One \*/
@font-feature-values Font One {
  @styleset {
    nice-style: 12;
  }
}

/\* At-rule for "nice-style" in Font Two \*/
@font-feature-values Font Two {
  @styleset {
    nice-style: 4;
  }
}

/\* Apply the at-rules with a single declaration \*/
.nice-look {
  font-variant-alternates: styleset(nice-style);
}
```

#### JavaScript

```js
const log = document.getElementById("log");
const rules = document.styleSheets[document.styleSheets.length - 1].cssRules;

const fontOne = rules[0]; // A CSSFontFeatureValuesRule
log.textContent = `The 1st '@font-feature-values' family: "${fontOne.fontFamily}".\n`;

const fontTwo = rules[1]; // Another CSSFontFeatureValuesRule
log.textContent += `The 2nd '@font-feature-values' family: "${fontTwo.fontFamily}".`;
```

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

| Specification |
| --- |
| CSS Fonts Module Level 4 # cssfontfeaturevaluesrule |

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

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

See also
--------

* `@font-feature-values`