XRViewerPose - Web APIs

XRViewerPose
============

The WebXR Device API interface **`XRViewerPose`** represents the pose (the position and orientation) of a viewer's point of view on the scene. Each `XRViewerPose` can have multiple views to represent, for example, the slight separation between the left and right eye.

This view can represent anything from the point-of-view of a user's XR headset to the viewpoint represented by a player's movement of an avatar using mouse and keyboard, presented on the screen, to a virtual camera capturing the scene for a spectator.

XRPose

XRViewerPoseInstance properties
-------------------

*In addition to the properties inherited from `XRPose`, `XRViewerPose` includes the following:*

`views` Read only

An array of `XRView` objects, one for each viewpoint on the scene which is needed to represent the scene to the user. A typical headset provides a viewer pose with two views whose `eye` property is either `left` or `right`, indicating which eye that view represents. Taken together, these views can reproduce the 3D effect when displayed on the XR device.

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

The `XRViewerPose` object is used to describe the state of a viewer of a WebXR scene as it's tracked by the user's XR hardware. The viewer may be the virtual representation of the user, or it may represent another device or interface which may serve as the source of a position and orientation that make up a view upon the scene. For example, every player in a MMORPG might have an instance of `XRViewerPose` to provide a way to calculate what they can see; if the game provides a mechanism that tells the player if another player sees them, or that they see another player, this information becomes crucial.

An `XRViewerPose` is always obtained and referenced relative to an existing `XRReferenceSpace`. This ensures that positions and orientations are reported using the expected relative coordinate system.

To render a scene using the `XRViewerPose` representing the user's head, one would iterate over the views in the `views` array, rendering them one after another. By calling `viewport()` on the WebGL context, specifying the `XRView` as input, you can get the viewport to use when rendering in order to draw the frame for that eye into the correct part of the drawing surface.

Also, when rendering the scene for spectators or other players in a multiplayer game, the `transform` of the `XRViewerPose` can be used to determine both placement and facing direction of the other players in the game, so that they can be drawn in the correct place with the correct facing.

The viewer's pose for the animation frame represented by `XRFrame` can be obtained by calling the frame's `getViewerPose()` method, specifying the reference space in which the origin's position should be computed. The returned `XRViewerPose` tells you where the viewer is and what direction they're facing at the time at which the frame takes place.

Examples
--------

 In this example—part of the code to render an `XRFrame`,
 `getViewerPose()` is called to get an `XRViewerPose` using the
 same reference space the code is using as its base reference space. If a valid pose is
 returned, the frame is rendered by clearing the backbuffer and then rendering each of
 the views in the pose; these are most likely the views for the left and right eyes.

```js
const pose = frame.getViewerPose(xrReferenceSpace);

if (pose) {
  const glLayer = xrSession.renderState.baseLayer;

  gl.bindFrameBuffer(gl.FRAMEBUFFER, glLayer.framebuffer);
  gl.clearColor(0, 0, 0, 1);
  gl.clearDepth(1);
  gl.clear(gl.COLOR\_BUFFER\_BIT, gl.DEPTH\_BUFFER\_BIT);

  for (const view of pose.views) {
    const viewport = glLayer.getViewport(view);
    gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);

    /\* render the scene for the eye view.eye \*/
  }
}
```

 Passing each `view` to `getViewport()` returns the WebGL viewport to apply in order to cause the rendered
 output to be positioned correctly in the framebuffer for rendering to the corresponding eye on the output device.

 This code is derived from Drawing a frame in our "Movement and motion" WebXR example.
 You can see more context and see much more on that page.

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

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

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

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

See also
--------

* WebXR Device API
* Movement, orientation, and motion
* `XRPose` and `XRView`


VTTCue - Web APIs

VTTCue
======

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

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

* Learn more
* See full compatibility
* Report feedback
The `VTTCue` interface—part of the API for handling WebVTT (text tracks on media presentations)—describes and controls the text track associated with a particular `<track>` element.

EventTarget

TextTrackCue

VTTCueConstructor
-----------

`VTTCue()`

Returns a newly created `VTTCue` object that covers the given time range and has the given text.

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

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

`VTTCue.region`

A `VTTRegion` object describing the video's sub-region that the cue will be drawn onto, or `null` if none is assigned.

`VTTCue.vertical`

Returns an enum representing the cue writing direction.

`VTTCue.snapToLines`

Returns true if the `VTTCue.line` attribute is an integer number of lines or a percentage of the video size.

`VTTCue.line`

Returns the line positioning of the cue. This can be the string `auto` or a number whose interpretation depends on the value of `VTTCue.snapToLines`.

`VTTCue.lineAlign`

Returns an enum representing the alignment of the `VTTCue.line`.

`VTTCue.position`

Returns the indentation of the cue within the line. This can be the string `auto` or a number representing the percentage of the `VTTCue.region`, or the video size if `VTTCue.region` is `null`.

`VTTCue.positionAlign`

Returns an enum representing the alignment of the cue. This is used to determine what the `VTTCue.position` is anchored to. The default is `auto`.

`VTTCue.size`

Returns a `double` representing the size of the cue, as a percentage of the video size.

`VTTCue.align`

Returns an enum representing the alignment of all the lines of text within the cue box.

`VTTCue.text`

Returns a string with the contents of the cue.

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

`getCueAsHTML()`

Returns the cue text as a `DocumentFragment`.

Example
-------

### HTML

The following example adds a new `TextTrack` to the video, then adds cues using the `TextTrack.addCue()` method, with a `VTTCue` object as the value.

```html
<video
 controls
 src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/friday.mp4"></video>
```

### CSS

```css
video {
  width: 420px;
  height: 300px;
}
```

### JavaScript

```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
track.addCue(new VTTCue(0, 0.9, "Hildy!"));
track.addCue(new VTTCue(1, 1.4, "How are you?"));
track.addCue(new VTTCue(1.5, 2.9, "Tell me, is the lord of the universe in?"));
track.addCue(new VTTCue(3, 4.2, "Yes, he's in - in a bad humor"));
track.addCue(new VTTCue(4.3, 6, "Somebody must've stolen the crown jewels"));
console.log(track.cues);
```

### Result

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

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

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

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


Web Speech API - Web APIs

Web Speech API
==============

 The **Web Speech API** enables you to incorporate voice data into web apps.
 The Web Speech API has two parts: `SpeechSynthesis` (Text-to-Speech), and `SpeechRecognition` (Asynchronous Speech Recognition.)

Web Speech Concepts and Usage
-----------------------------

 The Web Speech API makes web apps able to handle voice data.
 There are two components to this API:

* Speech recognition is accessed via the `SpeechRecognition` interface, which provides the ability to recognize voice context from an audio input (normally via the device's default speech recognition service) and respond appropriately.
 Generally you'll use the interface's constructor to create a new `SpeechRecognition` object, which has a number of event handlers available for detecting when speech is input through the device's microphone. The `SpeechGrammar` interface represents a container for a particular set of grammar that your app should recognize.
 Grammar is defined using JSpeech Grammar Format (**JSGF**.)
* Speech synthesis is accessed via the `SpeechSynthesis` interface, a text-to-speech component that allows programs to read out their text content (normally via the device's default speech synthesizer.) Different voice types are represented by `SpeechSynthesisVoice` objects, and different parts of text that you want to be spoken are represented by `SpeechSynthesisUtterance` objects.
 You can get these spoken by passing them to the `SpeechSynthesis.speak()` method.

For more details on using these features, see Using the Web Speech API.

Web Speech API Interfaces
-------------------------

### Speech recognition

`SpeechRecognition`

The controller interface for the recognition service; this also handles the `SpeechRecognitionEvent` sent from the recognition service.

`SpeechRecognitionAlternative`

Represents a single word that has been recognized by the speech recognition service.

`SpeechRecognitionErrorEvent`

Represents error messages from the recognition service.

`SpeechRecognitionEvent`

The event object for the `result` and `nomatch` events, and contains all the data associated with an interim or final speech recognition result.

`SpeechGrammar`

The words or patterns of words that we want the recognition service to recognize.

`SpeechGrammarList`

Represents a list of `SpeechGrammar` objects.

`SpeechRecognitionResult`

Represents a single recognition match, which may contain multiple `SpeechRecognitionAlternative` objects.

`SpeechRecognitionResultList`

Represents a list of `SpeechRecognitionResult` objects, or a single one if results are being captured in `continuous` mode.

### Speech synthesis

`SpeechSynthesis`

The controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides.

`SpeechSynthesisErrorEvent`

Contains information about any errors that occur while processing `SpeechSynthesisUtterance` objects in the speech service.

`SpeechSynthesisEvent`

Contains information about the current state of `SpeechSynthesisUtterance` objects that have been processed in the speech service.

`SpeechSynthesisUtterance`

 Represents a speech request.
 It contains the content the speech service should read and information about how to read it (e.g. language, pitch and volume.)

`SpeechSynthesisVoice`

 Represents a voice that the system supports.
 Every `SpeechSynthesisVoice` has its own relative speech service including information about language, name and URI.

`Window.speechSynthesis`

Specified out as part of a `[NoInterfaceObject]` interface called `SpeechSynthesisGetter`, and Implemented by the `Window` object, the `speechSynthesis` property provides access to the `SpeechSynthesis` controller, and therefore the entry point to speech synthesis functionality.

Errors
------

For information on errors reported by the Speech API (for example, `"language-not-supported"` and `"language-unavailable"`), see the following documentation:

* `error` property of the `SpeechRecognitionErrorEvent` object
* `error` property of the `SpeechSynthesisErrorEvent` object
Examples
--------

The Web Speech API examples on GitHub contains demos to illustrate speech recognition and synthesis.

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

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

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

### api.SpeechRecognition

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

### api.SpeechSynthesis

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

See also
--------

* Using the Web Speech API
* SitePoint article
* HTML5Rocks article


TransitionEvent - Web APIs

TransitionEvent
===============

The **`TransitionEvent`** interface represents events providing information related to transitions.

Event

TransitionEventConstructor
-----------

`TransitionEvent()`

Creates a `TransitionEvent` event with the given parameters.

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

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

`TransitionEvent.propertyName` Read only

A string containing the name CSS property associated with the transition.

`TransitionEvent.elapsedTime` Read only

A `float` giving the amount of time the transition has been running, in seconds, when this event fired. This value is not affected by the `transition-delay` property.

`TransitionEvent.pseudoElement` Read only

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

Types of `TransitionEvent`
--------------------------

`transitioncancel`

An `Event` fired when a CSS transition has been cancelled.

`transitionend`

An `Event` fired when a CSS transition has finished playing.

`transitionrun`

An `Event` fired when a CSS transition is created (i.e., when it is added to a set of running transitions), though not necessarily started.

`transitionstart`

An `Event` fired when a CSS transition has started transitioning.

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

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

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

| Specification |
| --- |
| CSS Transitions # interface-transitionevent |

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

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

See also
--------

* Using CSS transitions
* CSS properties: `transition`, `transition-delay`, `transition-duration`, `transition-property`, `transition-timing-function`
* CSS at-rules: `@starting-style`


MediaTrackSettings - Web APIs

MediaTrackSettings
==================

The **`MediaTrackSettings`** dictionary is used to return the current values configured for each of a `MediaStreamTrack`'s settings. These values will adhere as closely as possible to any constraints previously described using a `MediaTrackConstraints` object and set using `applyConstraints()`, and will adhere to the default constraints for any properties whose constraints haven't been changed, or whose customized constraints couldn't be matched.

To learn more about how constraints and settings work, see Capabilities, constraints, and settings.

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

Some or all of the following will be included in the object, either because it's not supported by the browser or because it's not available due to context. For example, because RTP doesn't provide some of these values during negotiation of a WebRTC connection, a track associated with a `RTCPeerConnection` will not include certain values, such as `facingMode` or `groupId`.

### Instance properties of all media tracks

`deviceId`

A string indicating the current value of the `deviceId` property. The device ID is an origin-unique string identifying the source of the track; this is usually a GUID. This value is specific to the source of the track's data and is not usable for setting constraints; it can, however, be used for initially selecting media when calling `MediaDevices.getUserMedia()`.

`groupId`

A string indicating the current value of the `groupId` property. The group ID is a browsing session-unique string identifying the source group of the track. Two devices (as identified by the `deviceId`) are considered part of the same group if they are from the same physical device. For instance, the audio input and output devices for the speaker and microphone built into a phone would share the same group ID, since they're part of the same physical device. The microphone on a headset would have a different ID, though. This value is specific to the source of the track's data and is not usable for setting constraints; it can, however, be used for initially selecting media when calling `MediaDevices.getUserMedia()`.

### Instance properties of audio tracks

`autoGainControl`

A Boolean which indicates the current value of the `autoGainControl` property, which is `true` if automatic gain control is enabled and is `false` otherwise.

`channelCount`

A long integer value indicating the current value of the `channelCount` property, specifying the number of audio channels present on the track (therefore indicating how many audio samples exist in each audio frame). This is 1 for mono, 2 for stereo, and so forth.

`echoCancellation`

A Boolean indicating the current value of the `echoCancellation` property, specifying `true` if echo cancellation is enabled, otherwise `false`.

`latency`

A double-precision floating point value indicating the current value of the `latency` property, specifying the audio latency, in seconds. Latency is the amount of time which elapses between the start of processing the audio and the data being available to the next stop in the audio utilization process. This value is a target value; actual latency may vary to some extent for various reasons.

`noiseSuppression`

A Boolean which indicates the current value of the `noiseSuppression` property, which is `true` if noise suppression is enabled and is `false` otherwise.

`sampleRate`

A long integer value indicating the current value of the `sampleRate` property, specifying the sample rate in samples per second of the audio data. Standard CD-quality audio, for example, has a sample rate of 41,000 samples per second.

`sampleSize`

A long integer value indicating the current value of the `sampleSize` property, specifying the linear size, in bits, of each audio sample. CD-quality audio, for example, is 16-bit, so this value would be 16 in that case.

`volume`
Deprecated

Non-standard

A double-precision floating point value indicating the current value of the `volume` property, specifying the volume level of the track. This value will be between 0.0 (silent) to 1.0 (maximum supported volume).

### Instance properties of video tracks

`aspectRatio`

A double-precision floating point value indicating the current value of the `aspectRatio` property, specified precisely to 10 decimal places. This is the width of the image in pixels divided by its height in pixels. Common values include 1.3333333333 (for the classic television 4:3 "standard" aspect ratio, also used on tablets such as Apple's iPad), 1.7777777778 (for the 16:9 high-definition widescreen aspect ratio), and 1.6 (for the 16:10 aspect ratio common among widescreen computers and tablets).

`facingMode`

A string indicating the current value of the `facingMode` property, specifying the direction the camera is facing. The value will be one of:

`"user"`

A camera facing the user (commonly known as a "selfie cam"), used for self-portraiture and video calling.

`"environment"`

A camera facing away from the user (when the user is looking at the screen). This is typically the highest quality camera on the device, used for general photography.

`"left"`

A camera facing toward the environment to the user's left.

`"right"`

A camera facing toward the environment to the user's right.

`frameRate`

A double-precision floating point value indicating the current value of the `frameRate` property, specifying how many frames of video per second the track includes. If the value can't be determined for any reason, the value will match the vertical sync rate of the device the user agent is running on.

`height`

A long integer value indicating the current value of the `height` property, specifying the height of the track's video data in pixels.

`width`

A long integer value indicating the current value of the `width` property, specifying the width of the track's video data in pixels.

`resizeMode`

A string indicating the current value of the `resizeMode` property, specifying the mode used by the user agent to derive the resolution of the track. The value will be one of:

`"none"`

The track has the resolution offered by the camera, its driver or the OS.

`"crop-and-scale"`

The track's resolution might be the result of the user agent using cropping or downscaling from a higher camera resolution.

### Instance properties of shared screen tracks

Tracks containing video shared from a user's screen (regardless of whether the screen data comes from the entire screen or a portion of a screen, like a window or tab) are generally treated like video tracks, with the exception that they also support the following added settings:

`cursor`

A string which indicates whether or not the mouse cursor is being included in the generated stream and under what conditions. Possible values are:

`always`

The mouse is always visible in the video content of the {domxref("MediaStream"), unless the mouse has moved outside the area of the content.

`motion`

The mouse cursor is always included in the video if it's moving, and for a short time after it stops moving.

`never`

The mouse cursor is never included in the shared video.

`displaySurface`

A string which specifies the type of source the track contains; one of:

`application`

The stream contains all of the windows of the application chosen by the user rendered into the one video track.

`browser`

The stream contains the contents of a single browser tab selected by the user.

`monitor`

The stream's video track contains the entire contents of one or more of the user's screens.

`window`

The stream contains a single window selected by the user for sharing.

`logicalSurface`

A Boolean value which, if `true`, indicates that the video contained in the stream's video track contains a background rendering context, rather than a user-visible one. This is `false` if the video being captured is coming from a foreground (user-visible) source.

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

| Specification |
| --- |
| Media Capture and Streams # media-track-settings |
| Screen Capture # extensions-to-mediatracksettings |

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

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

See also
--------

* `MediaDevices.getUserMedia()`
* `MediaDevices.getDisplayMedia()`
* `MediaStreamTrack.getConstraints()`
* `MediaStreamTrack.applyConstraints()`
* `MediaStreamTrack.getSettings()`


LayoutShiftAttribution - Web APIs

LayoutShiftAttribution
======================

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

The `LayoutShiftAttribution` interface provides debugging information about elements which have shifted.

Instances of `LayoutShiftAttribution` are returned in an array by calling `LayoutShift.sources`.

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

`LayoutShiftAttribution.node` Read only
Experimental

Returns the element that has shifted (null if it has been removed).

`LayoutShiftAttribution.previousRect` Read only
Experimental

Returns a `DOMRectReadOnly` object representing the position of the element before the shift.

`LayoutShiftAttribution.currentRect` Read only
Experimental

Returns a `DOMRectReadOnly` object representing the position of the element after the shift.

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

`LayoutShiftAttribution.toJSON()`
Experimental

Returns a JSON representation of the `LayoutShiftAttribution` object.

Examples
--------

The following example finds the element with the highest layout shift score, and returns the element in that entry with the largest size prior to the shift (`previousRect`). For more detail on this see Debug Web Vitals in the field.

```js
function getCLSDebugTarget(entries) {
  const largestEntry = entries.reduce((a, b) =>
    a && a.value > b.value ? a : b,
  );
  if (largestEntry?.sources?.length) {
    const largestSource = largestEntry.sources.reduce((a, b) => {
      const area = (el) => el.previousRect.width \* el.previousRect.height;
      return a.node && area(a) > area(b) ? a : b;
    });
    if (largestSource) {
      return largestSource.node;
    }
  }
}
```

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

| Specification |
| --- |
| Layout Instability # sec-layout-shift-attribution |

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

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

See also
--------

* Debug layout shifts
* Debug Web Vitals in the field


Keyboard - Web APIs

Keyboard
========

**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 **`Keyboard`** interface of the Keyboard API provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

A list of valid code values is found in the UI Events KeyboardEvent code Values spec.

EventTarget

KeyboardInstance properties
-------------------

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

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

*Also inherits methods from its parent interface, `EventTarget`.*

`Keyboard.getLayoutMap()`
Experimental

Returns a `Promise` that resolves with an instance of `KeyboardLayoutMap` which is a map-like object with functions for retrieving the strings associated with specific physical keys.

`Keyboard.lock()`
Experimental

Returns a `Promise` after enabling the capture of keypresses for any or all of the keys on the physical keyboard.

`Keyboard.unlock()`
Experimental

Unlocks all keys captured by the `lock()` method and returns synchronously.

Example
-------

### Keyboard mapping

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

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

### Keyboard locking

The following example captures the `W`, `A`, `S`, and `D` keys, call `lock()` with a list that contains the key code attribute value for each of these keys:

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

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

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

| Specification |
| --- |
| Keyboard Map # keyboard-interface |
| Keyboard Lock # keyboard-interface |

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

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


VisualViewport - Web APIs

VisualViewport
==============

The **`VisualViewport`** interface of the Visual Viewport API represents the visual viewport for a given window. For a page containing iframes, each iframe, as well as the containing page, will have a unique window object. Each window on a page will have a unique `VisualViewport` representing the properties associated with that window.

You can get a window's visual viewport using `Window.visualViewport`.

**Note:** Only the top-level window has a visual viewport that's distinct from the layout viewport. Therefore, it's generally only the `VisualViewport` object of the top-level window that's useful. For an `<iframe>`, visual viewport metrics like `VisualViewport.width` always correspond to layout viewport metrics like `document.documentElement.clientWidth`.

EventTarget

VisualViewportInstance properties
-------------------

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

`VisualViewport.offsetLeft` Read only

Returns the offset of the left edge of the visual viewport from the left edge of the layout viewport in CSS pixels.

`VisualViewport.offsetTop` Read only

Returns the offset of the top edge of the visual viewport from the top edge of the layout viewport in CSS pixels.

`VisualViewport.pageLeft` Read only

Returns the x coordinate of the visual viewport relative to the initial containing block origin of the top edge in CSS pixels.

`VisualViewport.pageTop` Read only

Returns the y coordinate of the visual viewport relative to the initial containing block origin of the top edge in CSS pixels.

`VisualViewport.width` Read only

Returns the width of the visual viewport in CSS pixels.

`VisualViewport.height` Read only

Returns the height of the visual viewport in CSS pixels.

`VisualViewport.scale` Read only

Returns the pinch-zoom scaling factor applied to the visual viewport.

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

*Also inherits methods from its parent interface, `EventTarget`.*

Events
------

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

`resize`

 Fired when the visual viewport is resized.
 Also available via the `onresize` property.

`scroll`

 Fired when the visual viewport is scrolled.
 Also available via the `onscroll` property.

Examples
--------

### Hiding an overlaid box on zoom

This example, taken from the Visual Viewport README, shows how to write a simple bit of code that will hide an overlaid box (which might contain an advert, say) when the user zooms in. This is a nice way to improve the user experience when zooming in on pages. A live sample is also available.

```js
const bottomBar = document.getElementById("bottombar");
const viewport = window.visualViewport;

function resizeHandler() {
  bottomBar.style.display = viewport.scale > 1.3 ? "none" : "block";
}

window.visualViewport.addEventListener("resize", resizeHandler);
```

### Simulating position: device-fixed

This example, also taken from the Visual Viewport README, shows how to use this API to simulate `position: device-fixed`, which fixes elements to the visual viewport. A live sample is also available.

```js
const bottomBar = document.getElementById("bottombar");
const viewport = window.visualViewport;
function viewportHandler() {
  const layoutViewport = document.getElementById("layoutViewport");

  // Since the bar is position: fixed we need to offset it by the visual
  // viewport's offset from the layout viewport origin.
  const offsetLeft = viewport.offsetLeft;
  const offsetTop =
    viewport.height -
    layoutViewport.getBoundingClientRect().height +
    viewport.offsetTop;

  // You could also do this by setting style.left and style.top if you
  // use width: 100% instead.
  bottomBar.style.transform = `translate(${offsetLeft}px, ${offsetTop}px) scale(${
 1 / viewport.scale
 })`;
}
window.visualViewport.addEventListener("scroll", viewportHandler);
window.visualViewport.addEventListener("resize", viewportHandler);
```

**Note:** This technique should be used with care; emulating `position: device-fixed` in this way can result in the fixed element flickering during scrolling.

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

| Specification |
| --- |
| CSSOM View Module # the-visualviewport-interface |

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

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

See also
--------

* Web Viewports Explainer — useful explanation of web viewports concepts, including the difference between visual viewport and layout viewport.


CSSAnimation - Web APIs

CSSAnimation
============

The **`CSSAnimation`** interface of the Web Animations API represents an `Animation` object.

EventTarget

Animation

CSSAnimationInstance properties
-------------------

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

`CSSAnimation.animationName` Read only

Returns the animation name as a string.

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

*This interface inherits methods from its parent, `Animation`.*

Examples
--------

### Inspecting the returned CSSAnimation

The animation in the following example is defined in CSS with the name `slide-in`. Calling `Element.getAnimations()` returns an array of all `Animation` objects. In our case this returns a `CSSAnimation` object, representing the animation created in CSS.

```css
.animate {
  animation: slide-in 0.7s both;
}

@keyframes slide-in {
  0% {
    transform: translateY(-1000px);
  }
  100% {
    transform: translateY(0);
  }
}
```

```js
let animations = document.querySelector(".animate").getAnimations();
console.log(animations[0]);
```

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

| Specification |
| --- |
| CSS Animations Level 2 # the-CSSAnimation-interface |

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

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


SpeechSynthesisErrorEvent - Web APIs

SpeechSynthesisErrorEvent
=========================

The **`SpeechSynthesisErrorEvent`** interface of the Web Speech API contains information about any errors that occur while processing `SpeechSynthesisUtterance` objects in the speech service.

Event

SpeechSynthesisEvent

SpeechSynthesisErrorEventConstructor
-----------

`SpeechSynthesisErrorEvent()`

Creates a new `SpeechSynthesisErrorEvent`.

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

*`SpeechSynthesisErrorEvent` extends the `SpeechSynthesisEvent` interface, which inherits properties from its parent interface, `Event`.*

`SpeechSynthesisErrorEvent.error` Read only

Returns an error code indicating what has gone wrong with a speech synthesis attempt.

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

*`SpeechSynthesisErrorEvent` extends the `SpeechSynthesisEvent` interface, which inherits methods from its parent interface, `Event`.*

Examples
--------

```js
const synth = window.speechSynthesis;

const inputForm = document.querySelector("form");
const inputTxt = document.querySelector("input");
const voiceSelect = document.querySelector("select");

const voices = synth.getVoices();

// ...

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

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

  synth.speak(utterThis);

  utterThis.onerror = (event) => {
    console.log(
      `An error has occurred with the speech synthesis: ${event.error}`,
    );
  };

  inputTxt.blur();
};
```

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

| Specification |
| --- |
| Web Speech API # speechsynthesiserrorevent |

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

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

See also
--------

* Web Speech API


MediaStream Recording API - Web APIs

MediaStream Recording API
=========================

The **MediaStream Recording API**, sometimes referred to as the *Media Recording API* or the *MediaRecorder API*, is closely affiliated with the Media Capture and Streams API and the WebRTC API. The MediaStream Recording API makes it possible to capture the data generated by a `MediaStream` or `HTMLMediaElement` object for analysis, processing, or saving to disk. It's also surprisingly easy to work with.

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

The MediaStream Recording API is comprised of a single major interface, `MediaRecorder`, which does all the work of taking the data from a `MediaStream` and delivering it to you for processing. The data is delivered by a series of `dataavailable` events, already in the format you specify when creating the `MediaRecorder`. You can then process the data further or write it to file as desired.

### Overview of the recording process

The process of recording a stream is simple:

1. Set up a `MediaStream` or `HTMLMediaElement` (in the form of an `<audio>` or `<video>` element) to serve as the source of the media data.
2. Create a `MediaRecorder` object, specifying the source stream and any desired options (such as the container's MIME type or the desired bit rates of its tracks).
3. Set `ondataavailable` to an event handler for the `dataavailable` event; this will be called whenever data is available for you.
4. Once the source media is playing and you've reached the point where you're ready to record video, call `MediaRecorder.start()` to begin recording.
5. Your `dataavailable` event handler gets called every time there's data ready for you to do with as you will; the event has a `data` attribute whose value is a `Blob` that contains the media data. You can force a `dataavailable` event to occur, thereby delivering the latest sound to you so you can filter it, save it, or whatever.
6. Recording stops automatically when the source media stops playing.
7. You can stop recording at any time by calling `MediaRecorder.stop()`.

**Note:** Individual `Blob`s containing slices of the recorded media will not necessarily be individually playable. The media needs to be reassembled before playback.

If anything goes wrong during recording, an `error` event is sent to the `MediaRecorder`. You can listen for `error` events by setting up a `onerror` event handler.

Example here, we use an HTML Canvas as source of the `MediaStream`, and stop recording after 9 seconds.

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

// Optional frames per second argument.
const stream = canvas.captureStream(25);
const recordedChunks = [];

console.log(stream);
const options = { mimeType: "video/webm; codecs=vp9" };
const mediaRecorder = new MediaRecorder(stream, options);

mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start();

function handleDataAvailable(event) {
  console.log("data-available");
  if (event.data.size > 0) {
    recordedChunks.push(event.data);
    console.log(recordedChunks);
    download();
  } else {
    // …
  }
}
function download() {
  const blob = new Blob(recordedChunks, {
    type: "video/webm",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  a.href = url;
  a.download = "test.webm";
  a.click();
  window.URL.revokeObjectURL(url);
}

// demo: to download after 9sec
setTimeout((event) => {
  console.log("stopping");
  mediaRecorder.stop();
}, 9000);
```

### Examining and controlling the recorder status

You can also use the properties of the `MediaRecorder` object to determine the state of the recording process, and its `pause()` and `resume()` methods to pause and resume recording of the source media.

If you need or want to check to see if a specific MIME type is supported, that's possible as well. Just call `MediaRecorder.isTypeSupported()`.

### Examining potential input sources

If your goal is to record camera and/or microphone input, you may wish to examine the available input devices before beginning the process of constructing the `MediaRecorder`. To do so, you'll need to call `navigator.mediaDevices.enumerateDevices()` to get a list of the available media devices. You can then examine that list and identify the potential input sources, and even filter the list based on desired criteria.

In this code snippet, `enumerateDevices()` is used to examine the available input devices, locate those which are audio input devices, and create `<option>` elements that are then added to a `<select>` element representing an input source picker.

```js
navigator.mediaDevices.enumerateDevices().then((devices) => {
  devices.forEach((device) => {
    const menu = document.getElementById("inputdevices");
    if (device.kind === "audioinput") {
      const item = document.createElement("option");
      item.textContent = device.label;
      item.value = device.deviceId;
      menu.appendChild(item);
    }
  });
});
```

Code similar to this can be used to let the user restrict the set of devices they wish to use.

### For more information

To learn more about using the MediaStream Recording API, see Using the MediaStream Recording API, which shows how to use the API to record audio clips. A second article, Recording a media element, describes how to receive a stream from an `<audio>` or `<video>` element and use the captured stream (in this case, recording it and saving it to a local disk).

Interfaces
----------

`BlobEvent`

Each time a chunk of media data is finished being recorded, it's delivered to consumers in `Blob` form using a `BlobEvent` of type `dataavailable`.

`MediaRecorder`

The primary interface that implements the MediaStream Recording API.

`MediaRecorderErrorEvent`
Deprecated

Non-standard

The interface that represents errors thrown by the MediaStream Recording API. Its `error` property is a `DOMException` that specifies that error occurred.

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

| Specification |
| --- |
| MediaStream Recording  |

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

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

See also
--------

* Media Capture and Streams API landing page
* `MediaDevices.getUserMedia()`
* simpl.info MediaStream Recording demo, by Sam Dutton
* HTML5's Media Recorder API in Action on Chrome and Firefox
* MediaRecorder polyfill for Safari and Edge
* TutorRoom: HTML video capture/playback/download using getUserMedia and the MediaStream Recording API (source on GitHub)
* Simple video recording demo
* Advanced media stream recorder sample
* OpenLang: HTML video language lab web application using MediaDevices and the MediaStream Recording API for video recording (source on GitHub)
* MediaStream Recorder API Now Available in Safari Technology Preview 73


PeriodicSyncEvent - Web APIs

PeriodicSyncEvent
=================

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

The **`PeriodicSyncEvent`** interface of the Web Periodic Background Synchronization API provides a way to run tasks in the service worker with network connectivity.

An instance of this event is passed to the `periodicsync` handler. This happens periodically, at an interval greater than or equal to that set in the `PeriodicSyncManager.register()` method. Other implementation-specific factors such as the user's engagement with the site decide the actual interval.

Event

ExtendableEvent

PeriodicSyncEventConstructor
-----------

`PeriodicSyncEvent()`
Experimental

Creates a new `PeriodicSyncEvent` object. This constructor is not typically used. The browser creates these objects itself and provides them to `onperiodicsync` callback.

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

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

`PeriodicSyncEvent.tag` Read only
Experimental

Returns the developer-defined identifier for this `PeriodicSyncEvent`. Multiple tags can be used by the web app to run different periodic tasks at different frequencies.

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

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

Examples
--------

The following example shows how to respond to a periodic sync event in the service worker.

```js
self.addEventListener("periodicsync", (event) => {
  if (event.tag === "get-latest-news") {
    event.waitUntil(fetchAndCacheLatestNews());
  }
});
```

`fetchAndCacheLatestNews` is a developer defined function.

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

| Specification |
| --- |
| Web Periodic Background Synchronization # periodicsync-event |

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

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

See also
--------

* Richer offline experiences with the Periodic Background Sync API
* A Periodic Background Sync demo app


ImageCapture - Web APIs

ImageCapture
============

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

The **`ImageCapture`** interface of the MediaStream Image Capture API provides methods to enable the capture of images or photos from a camera or other photographic device. It provides an interface for capturing images from a photographic device referenced through a valid `MediaStreamTrack`.

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

`ImageCapture()`
Experimental

Creates a new `ImageCapture` object which can be used to capture still frames (photos) from a given `MediaStreamTrack` which represents a video stream.

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

`ImageCapture.track` Read only
Experimental

Returns a reference to the `MediaStreamTrack` passed to the constructor.

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

`ImageCapture.takePhoto()`
Experimental

Takes a single exposure using the video capture device sourcing a `MediaStreamTrack` and returns a `Promise` that resolves with a `Blob` containing the data.

`ImageCapture.getPhotoCapabilities()`
Experimental

Returns a `Promise` that resolves with an object containing the ranges of available configuration options.

`ImageCapture.getPhotoSettings()`
Experimental

Returns a `Promise` that resolves with an object containing the current photo configuration settings.

`ImageCapture.grabFrame()`
Experimental

Takes a snapshot of the live video in a `MediaStreamTrack`, returning an `ImageBitmap`, if successful.

Example
-------

The following code is taken from Chrome's Grab Frame - Take Photo Sample. Since `ImageCapture` requires some place to capture an image from, the example below starts with a device's media device (in other words a camera).

This example shows, roughly, a `MediaStreamTrack` extracted from a device's `MediaStream`. The track is then used to create an `ImageCapture` object so that `takePhoto()` and `grabFrame()` can be called. Finally, it shows how to apply the results of these calls to a canvas object.

```js
let imageCapture;

function onGetUserMediaButtonClick() {
  navigator.mediaDevices
    .getUserMedia({ video: true })
    .then((mediaStream) => {
      document.querySelector("video").srcObject = mediaStream;

      const track = mediaStream.getVideoTracks()[0];
      imageCapture = new ImageCapture(track);
    })
    .catch((error) => console.error(error));
}

function onGrabFrameButtonClick() {
  imageCapture
    .grabFrame()
    .then((imageBitmap) => {
      const canvas = document.querySelector("#grabFrameCanvas");
      drawCanvas(canvas, imageBitmap);
    })
    .catch((error) => console.error(error));
}

function onTakePhotoButtonClick() {
  imageCapture
    .takePhoto()
    .then((blob) => createImageBitmap(blob))
    .then((imageBitmap) => {
      const canvas = document.querySelector("#takePhotoCanvas");
      drawCanvas(canvas, imageBitmap);
    })
    .catch((error) => console.error(error));
}

/\* Utils \*/

function drawCanvas(canvas, img) {
  canvas.width = getComputedStyle(canvas).width.split("px")[0];
  canvas.height = getComputedStyle(canvas).height.split("px")[0];
  let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
  let x = (canvas.width - img.width \* ratio) / 2;
  let y = (canvas.height - img.height \* ratio) / 2;
  canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
  canvas
    .getContext("2d")
    .drawImage(
      img,
      0,
      0,
      img.width,
      img.height,
      x,
      y,
      img.width \* ratio,
      img.height \* ratio,
    );
}

document.querySelector("video").addEventListener("play", () => {
  document.querySelector("#grabFrameButton").disabled = false;
  document.querySelector("#takePhotoButton").disabled = false;
});
```

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

| Specification |
| --- |
| MediaStream Image Capture # imagecaptureapi |

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

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


IntersectionObserver - Web APIs

IntersectionObserver
====================

The **`IntersectionObserver`** interface of the Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport. The ancestor element or viewport is referred to as the root.

When an `IntersectionObserver` is created, it's configured to watch for given ratios of visibility within the root. The configuration cannot be changed once the `IntersectionObserver` is created, so a given observer object is only useful for watching for specific changes in degree of visibility; however, you can watch multiple target elements with the same observer.

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

`IntersectionObserver()`

Creates a new `IntersectionObserver` object which will execute a specified callback function when it detects that a target element's visibility has crossed one or more thresholds.

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

`IntersectionObserver.root` Read only

The `Element` or `Document` whose bounds are used as the bounding box when testing for intersection. If no `root` value was passed to the constructor or its value is `null`, the top-level document's viewport is used.

`IntersectionObserver.rootMargin` Read only

An offset rectangle applied to the root's bounding box when calculating intersections, effectively shrinking or growing the root for calculation purposes. The value returned by this property may not be the same as the one specified when calling the constructor as it may be changed to match internal requirements. Each offset can be expressed in pixels (`px`) or as a percentage (`%`). The default is "0px 0px 0px 0px".

`IntersectionObserver.thresholds` Read only

A list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area to bounding box area of an observed target. Notifications for a target are generated when any of the thresholds are crossed for that target. If no value was passed to the constructor, 0 is used.

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

`IntersectionObserver.disconnect()`

Stops the `IntersectionObserver` object from observing any target.

`IntersectionObserver.observe()`

Tells the `IntersectionObserver` a target element to observe.

`IntersectionObserver.takeRecords()`

Returns an array of `IntersectionObserverEntry` objects for all observed targets.

`IntersectionObserver.unobserve()`

Tells the `IntersectionObserver` to stop observing a particular target element.

Examples
--------

```js
const intersectionObserver = new IntersectionObserver((entries) => {
  // If intersectionRatio is 0, the target is out of view
  // and we do not need to do anything.
  if (entries[0].intersectionRatio <= 0) return;

  loadItems(10);
  console.log("Loaded new items");
});
// start observing
intersectionObserver.observe(document.querySelector(".scrollerFooter"));
```

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

| Specification |
| --- |
| Intersection Observer # intersection-observer-interface |

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

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

See also
--------

* `MutationObserver`
* `PerformanceObserver`
* `ResizeObserver`


CSSPrimitiveValue - Web APIs

CSSPrimitiveValue
=================

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

The **`CSSPrimitiveValue`** interface derives from the `CSSValue` interface and represents the current computed value of a CSS property.

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

To achieve your purpose, you can use:

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

This interface represents a single CSS value. It may be used to determine the value of a specific style property currently set in a block or to set a specific style property explicitly within the block. An instance of this interface might be obtained from the `getPropertyCSSValue()` method of the `CSSStyleDeclaration` interface. A `CSSPrimitiveValue` object only occurs in a context of a CSS property.

Conversions are allowed between absolute values (from millimeters to centimeters, from degrees to radians, and so on) but not between relative values. (For example, a pixel value cannot be converted to a centimeter value.) Percentage values can't be converted since they are relative to the parent value (or another property value). There is one exception for color percentage values: since a color percentage value is relative to the range 0-255, a color percentage value can be converted to a number (see also the `RGBColor` interface).

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

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

`CSSPrimitiveValue.primitiveType` Read only
Deprecated

An `unsigned short` representing the type of the value. Possible values are:

| Constant | Description |
| --- | --- |
| `CSS_ATTR` | The value is an `attr()` function. The value can be obtained by using the `getStringValue()` method. |
| `CSS_CM` | The value is a `<length>` in centimeters. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_COUNTER` | The value is a counter or counters function. The value can be obtained by using the `getCounterValue()` method. |
| `CSS_DEG` | The value is an `<angle>` in degrees. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_DIMENSION` | The value is a `<number>` with an unknown dimension. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_EMS` | The value is a `<length>` in em units. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_EXS` | The value is a `<length>` in ex units. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_GRAD` | The value is an `<angle>` in grads. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_HZ` | The value is a `<frequency>` in Hertz. The value can be obtained by using the getFloatValue method. |
| `CSS_IDENT` | The value is an identifier. The value can be obtained by using the `getStringValue()` method. |
| `CSS_IN` | The value is a `<length>` in inches. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_KHZ` | The value is a `<frequency>` in Kilohertz. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_MM` | The value is a `<length>` in millimeters. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_MS` | The value is a `<time>` in milliseconds. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_NUMBER` | The value is a simple `<number>`. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_PC` | The value is a `<length>` in picas. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_PERCENTAGE` | The value is a `<percentage>`. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_PT` | The value is a `<length>` in points. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_PX` | The value is a `<length>` in pixels. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_RAD` | The value is an `<angle>` in radians. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_RECT` | The value is a `rect()` function. The value can be obtained by using the `getRectValue()` method. |
| `CSS_RGBCOLOR` | The value is an `<color>`. The value can be obtained by using the `getRGBColorValue()` method. |
| `CSS_S` | The value is a `<time>` in seconds. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_STRING` | The value is a `<string>`. The value can be obtained by using the `getStringValue()` method. |
| `CSS_UNKNOWN` | The value is not a recognized CSS2 value. The value can only be obtained by using the `cssText` attribute. |
| `CSS_URI` | The value is a `url()`. The value can be obtained by using the `getStringValue()` method. |

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

`CSSPrimitiveValue.getCounterValue()`
Deprecated

This method is used to get the counter value. If this CSS value doesn't contain a counter value, a `DOMException` is raised. Modification to the corresponding style property can be achieved using the `Counter` interface.

`CSSPrimitiveValue.getFloatValue()`
Deprecated

This method is used to get a float value in a specified unit. If this CSS value doesn't contain a float value or can't be converted into the specified unit, a `DOMException` is raised.

`CSSPrimitiveValue.getRGBColorValue()`
Deprecated

This method is used to get the RGB color. If this CSS value doesn't contain a RGB color value, a `DOMException` is raised. Modification to the corresponding style property can be achieved using the `RGBColor` interface.

`CSSPrimitiveValue.getRectValue()`
Deprecated

This method is used to get the Rect value. If this CSS value doesn't contain a rect value, a `DOMException` is raised. Modification to the corresponding style property can be achieved using the `Rect` interface.

`CSSPrimitiveValue.getStringValue()`
Deprecated

This method is used to get the string value. If the CSS value doesn't contain a string value, a `DOMException` is raised.

`CSSPrimitiveValue.setFloatValue()`
Deprecated

A method to set the float value with a specified unit. If the property attached with this value can not accept the specified unit or the float value, the value will be unchanged and a `DOMException` will be raised.

`CSSPrimitiveValue.setStringValue()`
Deprecated

A method to set the string value with the specified unit. If the property attached to this value can't accept the specified unit or the string value, the value will be unchanged and a `DOMException` will be raised.

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

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

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

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

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

See also
--------

* `CSSValue`
* `CSSValueList`


HTMLTimeElement - Web APIs

HTMLTimeElement
===============

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

EventTarget

Node

Element

HTMLElement

HTMLTimeElementInstance properties
-------------------

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

`HTMLTimeElement.dateTime`

A string that reflects the `datetime` HTML attribute, containing a machine-readable form of the element's date and time value.

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

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

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

| Specification |
| --- |
| HTML Standard # htmltimeelement |

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

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

See also
--------

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


SVGAnimatedEnumeration - Web APIs

SVGAnimatedEnumeration
======================

The **`SVGAnimatedEnumeration`** interface describes attribute values which are constants from a particular enumeration and which can be animated.

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

`baseVal`

An integer that is the base value of the given attribute before applying any animations.

`animVal`

If the given attribute or property is being animated, it contains the current animated value of the attribute or property. If the given attribute or property is not currently being animated, it contains the same value as `baseVal`.

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

The `SVGAnimatedEnumeration` interface do not provide any specific methods.

Examples
--------

Considering this snippet with a `<clipPath>` element: Its `clipPathUnits` is associated with a `SVGAnimatedEnumeration` object.

```html
<svg viewBox="0 0 100 100" width="200" height="200">
  <clipPath id="clip1" clipPathUnits="userSpaceOnUse">
    <circle cx="50" cy="50" r="35" />
  </clipPath>

  <!-- Some reference rect to materialized to clip path -->
  <rect id="r1" x="0" y="0" width="45" height="45" />
</svg>
```

This snippet gets the element, and logs the `baseVal` and `animVal`of the `SVGClipPathElement.clipPathUnits` property. As no animation is happening, they have the same value.

```js
const clipPathElt = document.getElementById("clip1");
console.log(clipPathElt.clipPathUnits.baseVal); // Logs 1 that correspond to userSpaceOnUse
console.log(clipPathElt.clipPathUnits.animVal); // Logs 1 that correspond to userSpaceOnUse
```

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

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

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

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


WebGLProgram - Web APIs

WebGLProgram
============

The **`WebGLProgram`** is part of the WebGL API and is a combination of two compiled `WebGLShader`s consisting of a vertex shader and a fragment shader (both written in GLSL).

WebGLObject

WebGLProgram
To create a `WebGLProgram`, call the GL context's `createProgram()` function. After attaching the shader programs using `attachShader()`, you link them into a usable program. This is shown in the code below.

```js
const program = gl.createProgram();

// Attach pre-existing shaders
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);

gl.linkProgram(program);

if (!gl.getProgramParameter(program, gl.LINK\_STATUS)) {
  const info = gl.getProgramInfoLog(program);
  throw `Could not compile WebGL program. \n\n${info}`;
}
```

See `WebGLShader` for information on creating the `vertexShader` and `fragmentShader` in the above example.

Examples
--------

### Using the program

The steps to actually do some work with the program involve telling the GPU to use the program, bind the appropriate data and configuration options, and finally draw something to the screen.

```js
// Use the program
gl.useProgram(program);

// Bind existing attribute data
gl.bindBuffer(gl.ARRAY\_BUFFER, buffer);
gl.enableVertexAttribArray(attributeLocation);
gl.vertexAttribPointer(attributeLocation, 3, gl.FLOAT, false, 0, 0);

// Draw a single triangle
gl.drawArrays(gl.TRIANGLES, 0, 3);
```

### Deleting the program

If there is an error linking the program or you wish to delete an existing program, then it is as simple as running `WebGLRenderingContext.deleteProgram()`. This frees the memory of the linked program.

```js
gl.deleteProgram(program);
```

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

| Specification |
| --- |
| WebGL Specification # 5.6 |

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

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

See also
--------

* `WebGLShader`
* `WebGLRenderingContext.attachShader()`
* `WebGLRenderingContext.compileShader()`
* `WebGLRenderingContext.createProgram()`
* `WebGLRenderingContext.createShader()`
* `WebGLRenderingContext.deleteProgram()`
* `WebGLRenderingContext.deleteShader()`
* `WebGLRenderingContext.detachShader()`
* `WebGLRenderingContext.getAttachedShaders()`
* `WebGLRenderingContext.getProgramParameter()`
* `WebGLRenderingContext.getProgramInfoLog()`
* `WebGLRenderingContext.getShaderParameter()`
* `WebGLRenderingContext.getShaderPrecisionFormat()`
* `WebGLRenderingContext.getShaderInfoLog()`
* `WebGLRenderingContext.getShaderSource()`
* `WebGLRenderingContext.isProgram()`
* `WebGLRenderingContext.isShader()`
* `WebGLRenderingContext.linkProgram()`
* `WebGLRenderingContext.shaderSource()`
* `WebGLRenderingContext.useProgram()`
* `WebGLRenderingContext.validateProgram()`


AmbientLightSensor - Web APIs

AmbientLightSensor
==================

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

The **`AmbientLightSensor`** interface of the Sensor APIs returns the current light level or illuminance of the ambient light around the hosting device.

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

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

EventTarget

Sensor

AmbientLightSensorConstructor
-----------

`AmbientLightSensor()`
Experimental

Creates a new `AmbientLightSensor` object.

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

`AmbientLightSensor.illuminance`
Experimental

Returns the current light level in lux of the ambient light level around the hosting device.

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

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

Events
------

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

Example
-------

```js
if ("AmbientLightSensor" in window) {
  const sensor = new AmbientLightSensor();
  sensor.addEventListener("reading", (event) => {
    console.log("Current light level:", sensor.illuminance);
  });
  sensor.addEventListener("error", (event) => {
    console.log(event.error.name, event.error.message);
  });
  sensor.start();
}
```

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

| Specification |
| --- |
| Ambient Light Sensor # ambient-light-sensor-interface |

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

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


VirtualKeyboard API - Web APIs

VirtualKeyboard API
===================

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

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

The VirtualKeyboard API provides developers control over the layout of their applications when the on-screen virtual keyboard appears and disappears on devices such as tablets, mobile phones, or other devices where a hardware keyboard may not be available.

Web browsers usually deal with virtual keyboards on their own, by adjusting the viewport height and scrolling to input fields when focused.

The figure below illustrates the difference in viewport height and scroll position on a web page when the device has its on-screen virtual keyboard hidden, and when it is shown.

![Two devices, one without a virtual keyboard, showing that the webpage can use most of the device's vertical space, and one with a virtual keyboard, showing that the webpage can only be displayed in the remaining space](/en-US/docs/Web/API/VirtualKeyboard_API/viewport-height.png)

More complex applications or specific devices such as multi-screen mobile phones may require more control of the layout when the virtual keyboard appears.

The figure below shows what happens on a dual-screen device when the virtual keyboard appears on just one of the two screens. The viewport becomes smaller on both screens to accommodate for the virtual keyboard, leaving wasted space on the screen where the virtual keyboard is not displayed.

![A dual-screen device, with its virtual keyboard displayed on one screen, showing that the webpage can only use the vertical space that remains after the keyboard was displayed, even if that leaves empty space on the other screen](/en-US/docs/Web/API/VirtualKeyboard_API/dual-screen.png)

The VirtualKeyboard API can be used to opt out of the way the browser automatically handles the virtual keyboard, and take full control of it instead. With the VirtualKeyboard API, the keyboard still appears and disappears as necessary when form controls are focused, but the viewport does not change, and you can use JavaScript and CSS to adapt your layout.

Concept
-------

The VirtualKeyboard API consists of three parts:

* The `VirtualKeyboard` interface, accessed through `navigator.virtualKeyboard`, is used to opt out of the automatic virtual keyboard behavior, show or hide the virtual keyboard programmatically, as well as get the current position and size of the virtual keyboard.
* The `keyboard-inset-*` CSS environment variables provide information about the virtual keyboard's position and size.
* The `virtualkeyboardpolicy` attribute specifies whether the virtual keyboard should appear on `contenteditable` elements.
### Opt out of the automatic virtual keyboard behavior

To opt out of the automatic virtual keyboard behavior of the browser, use `navigator.virtualKeyboard.overlaysContent = true`. The browser will no longer automatically resize the viewport to make space for the virtual keyboard, which will overlay your content instead.

### Detect the virtual keyboard geometry using JavaScript

Once you've opted out of the default browser behavior, you can get the current geometry of the virtual keyboard using `navigator.virtualKeyboard.boundingRect`, and adapt the layout as appropriate using CSS and JavaScript. In addition, you can listen to geometry changes, such as when the keyboard is shown or hidden, by using the `geometrychange` event.

This is useful for positioning important UI elements in the area that's not covered by the virtual keyboard.

The code snippet below uses the `geometrychange` event to detect when the virtual keyboard geometry changes; it then accesses the `boundingRect` property to query the size and position of the virtual keyboard:

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

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

### Detect the virtual keyboard geometry using CSS environment variables

The VirtualKeyboard API also exposes the following `CSS environment variables`: `keyboard-inset-top`, `keyboard-inset-right`, `keyboard-inset-bottom`, `keyboard-inset-left`, `keyboard-inset-width`, and `keyboard-inset-height`.

The `keyboard-inset-*` CSS environment variables are useful to adapt your layout to the virtual keyboard appearance using CSS. They define a rectangle by its top, right, bottom, and left insets from the edge of the viewport. The `width` and `height` variables are also available if needed.

The code snippet below uses the `keyboard-inset-height` CSS variable to reserve space for the virtual keyboard to appear below the list of messages and input field in a chat-like application. When the virtual keyboard is hidden, the `env()` function returns `0px` and the `keyboard` grid area is hidden. The messages and input elements can occupy the full height of the viewport. When the virtual keyboard appears, the `keyboard` grid area gets the height of the virtual keyboard.

```html
<style>
 body {
 display: grid;
 margin: 0;
 height: 100vh;
 grid-template:
 "messages" 1fr
 "input" auto
 "keyboard" env(keyboard-inset-height, 0px);
 }
</style>
<ul id="messages"></ul>
<input type="text" />
<script>
 if ("virtualKeyboard" in navigator) {
 navigator.virtualKeyboard.overlaysContent = true;
 }
</script>
```

### Control the virtual keyboard on `contenteditable` elements

By default, elements using the `contenteditable` attribute also trigger the virtual keyboard when tapped or clicked. In certain situations, it may be desirable to prevent this behavior and instead show the virtual keyboard after a different event.

Set the `virtualkeyboardpolicy` attribute to `manual` to prevent the default handling of the virtual keyboard in the browser, and instead handle it yourself by using the `VirtualKeyboard` interface's `show()` and `hide()` methods.

The code snippet below shows how to use the `virtualkeyboardpolicy` attribute and the `navigator.virtualKeyboard.show()` method to show the virtual keyboard on double-click instead:

```html
<div contenteditable virtualkeyboardpolicy="manual" id="editor"></div>
<script>
 if ("virtualKeyboard" in navigator) {
 navigator.virtualKeyboard.overlaysContent = true;

 const editor = document.getElementById("editor");
 editor.addEventListener("dblclick", () => {
 navigator.virtualKeyboard.show();
 });
 }
</script>
```

Interfaces
----------

`VirtualKeyboard`
Experimental

Provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

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

`Navigator.virtualKeyboard` Read only
Experimental

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

`HTMLElement.virtualkeyboardpolicy`
Experimental

A string indicating whether to use the browser's default policy for showing the virtual keyboard when the element is focused, or to handle showing the virtual keyboard manually.

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

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

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

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

See also
--------

* Full control with the VirtualKeyboard API


GPUSampler - Web APIs

GPUSampler
==========

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

The **`GPUSampler`** interface of the WebGPU API represents an object that can control how shaders transform and filter texture resource data.

A `GPUSampler` object instance is created using the `GPUDevice.createSampler()` method.

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

`label`
Experimental

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

Examples
--------

The following snippet creates a `GPUSampler` that does trilinear filtering and repeats texture coordinates:

```js
// ...
const sampler = device.createSampler({
  addressModeU: "repeat",
  addressModeV: "repeat",
  magFilter: "linear",
  minFilter: "linear",
  mipmapFilter: "linear",
});
```

The WebGPU samples Shadow Mapping sample uses comparison samplers to sample from a depth texture to render shadows.

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

| Specification |
| --- |
| WebGPU # gpusampler |

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

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

See also
--------

* The WebGPU API


Federated Credential Management (FedCM) API - Web APIs

Federated Credential Management (FedCM) API
===========================================

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

The **Federated Credential Management API** (or *FedCM API*) provides a standard mechanism for identity providers (IdPs) to make identity federation services available on the web in a privacy-preserving way, without the need for third-party cookies and redirects. This includes a JavaScript API that enables the use of federated authentication for activities such as signing in or signing up on a website.

FedCM concepts
--------------

Identity federation is the delegation of user authentication from a website requiring user sign-up or sign-in, such as an e-commerce or social networking site (also known as a relying party or RP), to a trusted third-party IdP. Users register an account with the IdP, which can then be used for signing in on multiple RPs. Identity federation via a small set of dedicated IdPs has improved web authentication in terms of security, consumer confidence, and user experience, as compared to each site managing its own sign-in needs with separate usernames and passwords.

The problem is that traditional identity federation relies on `<iframe>`s, redirects, and third-party cookies, which are also used for third-party tracking. Browsers are limiting the usage of these features in an effort to preserve user privacy, but a side effect is that this makes valid, non-tracking uses more difficult to implement, and this includes identity federation.

Affected identity federation use cases that rely on third-party cookies:

* OIDC front-channel logout: This flow requires the IDP to embed several RP `<iframe>`s, which rely on RP cookies.
* Social Widgets: In order to provide social widgets, the IdP third-party cookie must be provided from the RP top-level origin.
* Personalized buttons: The display of personalized sign in information on a `<button>` in the RP origin is implemented as an IdP `<iframe>` that requires third party cookies.
* Session Refresh without top-level navigation or popups.

FedCM aims to work around this problem, providing a dedicated mechanism for federated identity flows on the web, and enabling supporting browsers to provide special UI elements on RPs, allowing users to choose an IdP account to use for sign-in.

There are two parts to using the FedCM API: IdP integration with FedCM and RP sign-in using the JavaScript API.

IdP integration with FedCM
--------------------------

To integrate with FedCM, an IdP needs to do the following:

1. Provide a well-known file to identify the IdP.
2. Provide a config file and endpoints for accounts list and assertion issuance (and optionally, client metadata).
### Provide a well-known file

There is a potential privacy issue whereby an IdP is able to discern whether a user visited an RP without explicit consent. This has tracking implications, so an IdP is required to provide a well-known file to verify its identity and mitigate this issue.

The well-known file must be served from the eTLD+1 of the IdP at `/.well-known/web-identity`.

For example, if the IdP endpoints are served under `https://accounts.idp.example/`, they must serve a well-known file at `https://idp.example/.well-known/web-identity`. The well-known file's content should have the following JSON structure:

```json
{
  "provider\_urls": ["https://accounts.idp.example/config.json"]
}
```

The `provider_urls` member should contain an array of URLs pointing to valid IdP config files that can be used by RPs to interact with the IdP. The array length is currently limited to one.

### Provide a config file

The IdP config file provides a list of the endpoints the browser needs to process the identity federation flow and manage the sign-ins. IdPs will host both this config file and the required endpoints.

The config file (hosted at `https://accounts.idp.example/config.json` in our example) should have the following JSON structure:

```json
{
  "accounts\_endpoint": "/accounts.php",
  "client\_metadata\_endpoint": "/client\_metadata.php",
  "id\_assertion\_endpoint": "/assertion.php",
  "branding": {
    "background\_color": "green",
    "color": "0xFFEEAA",
    "icons": [
      {
        "url": "https://idp.example/icon.ico",
        "size": 25
      }
    ]
  }
}
```

The properties are as follows:

`accounts_endpoint`

The URL for the accounts list endpoint, which returns a list of accounts that the user is currently signed in to on the IdP. The browser uses these to create a list of sign-in choices to show to the user in the browser-provided FedCM UI.

`client_metadata_endpoint` Optional

The URL for the client metadata endpoint, which provides URLs pointing to the RP's metadata and terms of service pages, to be used in the FedCM UI.

`id_assertion_endpoint`

The URL for the ID assertion endpoint, which when sent valid user credentials should respond with a validation token that the RP can use to validate the authentication.

`branding` Optional

Contains branding information that will be used in the browser-supplied FedCM UI to customize its appearance as desired by the IdP.

#### The accounts list endpoint

This endpoint returns a list of all the IdP accounts that the user is currently signed in with, with a JSON structure that matches the following:

```json
{
  "accounts": [
    {
      "id": "john\_doe",
      "given\_name": "John",
      "name": "John Doe",
      "email": "john\_doe@idp.example",
      "picture": "https://idp.example/profile/123",
      "approved\_clients": ["123", "456", "789"],
      "login\_hints": ["john\_doe", "john\_doe@idp.example"]
    },
    {
      "id": "johnny",
      "given\_name": "Johnny",
      "name": "Johnny",
      "email": "johnny@idp.example",
      "picture": "https://idp.example/profile/456",
      "approved\_clients": ["abc", "def", "ghi"],
      "login\_hints": ["johnny", "johnny@idp.example"]
    }
  ]
}
```

This includes the following information:

`id`

The unique ID of the user.

`name`

The family name of the user.

`email`

The email address of the user.

`given_name` Optional

The given name of the user.

`picture` Optional

The URL of the user's avatar image.

`approved_clients` Optional

An array of RP clients that the user has registered with.

`login_hints` Optional

An array of strings representing the account. These strings are used to filter the list of account options that the browser offers for the user to sign-in. This occurs when the `loginHint` property is provided within `identity.providers` in a related `get()` call. Any account with a string in its `login_hints` array that matches the provided `loginHint` is included.

**Note:**: If the user is not signed in to any IdP accounts, the endpoint should respond with HTTP 401 (Unauthorized).

#### The client metadata endpoint

Provides URLs pointing to the RP's metadata and terms of service pages, to be used in the browser-supplied FedCM UI. This should follow the JSON structure seen below:

```json
{
  "privacy\_policy\_url": "https://rp.example/privacy\_policy.html",
  "terms\_of\_service\_url": "https://rp.example/terms\_of\_service.html"
}
```

#### The ID assertion endpoint

When sent valid user credentials, this endpoint should respond with a validation token that the RP can use to validate the authentication:

```json
{
  "token": "\*\*\*\*\*\*\*\*\*\*\*"
}
```

RP sign-in using the JavaScript API
-----------------------------------

RPs can call `navigator.credentials.get()` with an `identity` option to make a request for users to sign in to the RP with the IdP, using the available IdP config and endpoints (as described above). A typical request might look like this:

```js
async function signIn() {
  const identityCredential = await navigator.credentials.get({
    identity: {
      context: "signup",
      providers: [
        {
          configURL: "https://accounts.idp.example/config.json",
          clientId: "\*\*\*\*\*\*\*\*",
          nonce: "\*\*\*\*\*\*",
          loginHint: "user1@example.com",
        },
      ],
    },
  });
}
```

The `identity.providers` property takes an array of objects containing the path to an IdP config file and the RP's client identifier issued by the IdP; the example above also includes a couple of optional features:

* `identity.context` specifies the context in which the user is authenticating with FedCM. For example, is it a first-time signup for this account, or a sign-in with an existing account? The browser uses this information to vary the text in its FedCM UI to better suit the context.
* `identity.providers.nonce` provides a random nonce value that ensures the response is issued for this specific request, preventing replay attacks.
* `identity.providers.loginHint` provides a hint about the account option(s) the browser should present for user sign-in. This hint is matched against the `login_hints` values that the IdP provides from the accounts list endpoint.

The browser requests the IdP config file and carries out the sign-in flow detailed below. For more information on the kind of interaction a user might expect from the browser-supplied UI, see Sign in to the relying party with the identity provider.

### FedCM sign-in flow

1. The RP invokes `navigator.credentials.get()` to start off the sign-in flow.
2. From the `configURL` provided in the `get()` call, the browser requests two files:
    1. The well-known file (`/.well-known/web-identity`), available from `/.well-known/web-identity` at the eTLD+1 of the `configURL`.
    2. The config file (`/config.json`), available at the `configURL`.These are both a `GET` requests, which don't have cookies and don't follow redirects. This effectively prevents the IdP from learning who made the request and which RP is attempting to connect.
 For example, the config file request would look like so:

```http
GET /config.json HTTP/1.1
Host: accounts.idp.example
Accept: application/json
Sec-Fetch-Dest: webidentity
```

**Note:** All requests sent from the browser via FedCM include a `Sec-Fetch-Dest: webidentity` header to prevent CSRF attacks. All IdP endpoints must confirm this header is included.
3. The IdP responds with the requested files. The config file URL is validated against the list of valid config URLs inside the well-known file.
4. The browser makes a request to the `accounts_endpoint` inside the config file for the list of accounts that the user is currently signed in to on the IdP. This is a `GET` request with cookies, but without a `client_id` parameter or the `Origin` header. This effectively prevents the IdP from learning which RP the user is trying to sign in to.
 For example:

```http
GET /accounts.php HTTP/1.1
Host: accounts.idp.example
Accept: application/json
Cookie: 0x23223
Sec-Fetch-Dest: webidentity
```

5. The IdP responds with the account information.
6. Optional If included in the config file, the browser makes a request to the `client_metadata_endpoint` for the location of the RP's terms of service and privacy policy pages. This is a `GET` request sent with the `clientId` passed into the `get()` call as a parameter, without cookies.
 For example:

```http
GET /client\_metadata.php?client\_id=1234 HTTP/1.1
Host: accounts.idp.example
Origin: https://rp.example/
Accept: application/json
Sec-Fetch-Dest: webidentity
```

7. Optional The IdP responds with the requested URLs.
8. The browser uses the information obtained by the previous two requests to create the UI asking the user for permission to sign in to the RP using their federated IdP account.
9. If the user grants permission to do so, the browser sends some credentials to the `id_assertion_endpoint` and requests a validation token from the IdP.
 The credentials are sent in an HTTP `POST` request with cookies and a content type of `application/x-www-form-urlencoded`. It should look something like this:

```http
POST /assertion.php HTTP/1.1
Host: accounts.idp.example
Origin: https://rp.example/
Content-Type: application/x-www-form-urlencoded
Cookie: 0x23223
Sec-Fetch-Dest: webidentity
account_id=123&client_id=client1234&nonce=Ct60bD&disclosure_text_shown=true
```

The payload should contain the following:

`client_id`

The RP's client identifier.

`account_id`

The unique ID of the user account to be signed in.

`nonce` Optional

The request nonce, provided by the RP.

`disclosure_text_shown`

A string of `"true"` or `"false"` indicating whether the disclosure text was shown or not. The disclosure text is the information shown to the user (which can include the terms of service and privacy policy links, if provided) if the user is signed in to the IdP but doesn't have an account specifically on the current RP (in which case they'd need to choose to "Continue as..." their IdP identity and then create a corresponding account on the RP).
10. The IdP checks that the account ID sent by the RP matches the ID for the account that is already signed in, and that the `Origin` matches the origin of the RP, which will have been registered in advance with the IdP. If everything looks good, it responds with the validation token.

**Note:** The origin of the RP will be registered with the IdP in a completely separate process when the RP first integrates with the IdP. This process will be specific to each IdP.

When the flow is complete, the RP validates the validation token. If validation is successful, the `get()` promise resolves with an `IdentityCredential` object, which provides further RP functionality. Additionally, at this point the RP may register the user or let them sign in and start a new session.

### Features available via IdentityCredential

The `IdentityCredential` object obtained from a successful FedCM sign-in provides access to the token used to validate the sign-in (see `IdentityCredential.token`).

Permissions Policy integration and IFrame support
-------------------------------------------------

The `identity-credentials-get` Permissions-Policy can be used to control permission to use FedCM, more specifically usage of the `navigator.credentials.get()` method.

Developers can explicitly grant permission for an `<iframe>` to use FedCM via the `allow` attribute:

```html
<iframe src="3rd-party.example" allow="identity-credentials-get"></iframe>
```

The availability of FedCM within `<iframe>`s enables a couple of use cases:

* Larger sites won't want a third-party sign-in script to gain control over the top-level frame; instead they will want to add that script and invoke FedCM from within an `<iframe>`.
* Some `<iframes>` may themselves require federated authentication.
Interfaces
----------

`IdentityCredential`

Represents a user identity credential arising from successful federated authentication. A successful `navigator.credentials.get()` call that includes an `identity` option fulfills with an `IdentityCredential` instance.

`IdentityProvider`

Represents an IdP and provides access to related information. The static `IdentityProvider.getUserInfo()` method returns information about a user who was previously signed in, when they return to an IdP. This information can be used to display a personalized welcome message and sign-in button.

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

`CredentialsContainer.get()`, the `identity` option.

`identity` is an object containing details of federated IdPs that a relying party (RP) website can use to sign users in. It causes a `get()` call to initiate a request for a user to sign in to an RP with an IdP.

Examples
--------

* FedCM sign-in example
    + RP source code
    + IdP source code
* FedCM `<iframe>` sign-in
    + RP `<iframe>` page source code
    + IdP source code
Specifications
--------------

| Specification |
| --- |
| Federated Credential Management API # browser-api-identity-credential-interface |

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

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

See also
--------

* Federated Credential Management API


IDBLocaleAwareKeyRange - Web APIs

IDBLocaleAwareKeyRange
======================

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

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

The **`IDBLocaleAwareKeyRange`** interface of the IndexedDB API is a Firefox-specific version of `IDBKeyRange` — it functions in exactly the same fashion, and has the same properties and methods, but it is intended for use with `IDBIndex` objects when the original index had a `locale` value specified upon its creation (see the `options` parameter to `IDBObjectStore.createIndex()`) — that is, it has locale aware sorting enabled.

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

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

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

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

Bear in mind however that `IDBLocaleAwareKeyRange` has its own implementation of `IDBKeyRange.bound()`. This is because when you use `bound()`, it checks if lower bound < upper bound, and throws an exception if that's not the case. With locale-aware indexes, the meaning of < depends on the locale, so for example in Lithuanian Y is sorted between I and K. The only difference between `IDBKeyRange` and `IDBLocaleAwareKeyRange` is that the latter doesn't do the aforementioned check.

Developers should always use `IDBLocaleAwareKeyRange` when dealing with locale-aware indexes.

Examples
--------

```js
function displayData() {
  const keyRangeValue = IDBLocaleAwareKeyRange.bound("A", "F");

  const transaction = db.transaction(["fThings"], "readonly");
  const objectStore = transaction.objectStore("fThings");

  const myIndex = objectStore.index("lName");
  myIndex.openCursor(keyRangeValue).onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const tableRow = document.createElement("tr");
      tableRow.innerHTML =
        `<td>${cursor.value.id}</td>` +
        `<td>${cursor.value.lName}</td>` +
        `<td>${cursor.value.fName}</td>` +
        `<td>${cursor.value.jTitle}</td>` +
        `<td>${cursor.value.company}</td>` +
        `<td>${cursor.value.eMail}</td>` +
        `<td>${cursor.value.phone}</td>` +
        `<td>${cursor.value.age}</td>`;
      tableEntry.appendChild(tableRow);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}
```

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

Not currently part of any specification.

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


RTCPeerConnectionIceEvent - Web APIs

RTCPeerConnectionIceEvent
=========================

The **`RTCPeerConnectionIceEvent`** interface represents events that occur in relation to ICE candidates with the target, usually an `RTCPeerConnection`.

Only one event is of this type: `icecandidate`.

Event

RTCPeerConnectionIceEventInstance properties
-------------------

*A `RTCPeerConnectionIceEvent` being an `Event`, this event also implements these properties*.

`RTCPeerConnectionIceEvent.candidate` Read only

Contains the `RTCIceCandidate` containing the candidate associated with the event, or `null` if this event indicates that there are no further candidates to come.

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

`RTCPeerConnectionIceEvent()`

Returns a new `RTCPeerConnectionIceEvent`. It takes two parameters, the first being a string representing the type of the event; the second a dictionary containing the `RTCIceCandidate` it refers to.

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

*A `RTCPeerConnectionIceEvent` being an `Event`, this event also implements these properties. There is no specific `RTCDataChannelEvent` method.*

Examples
--------

```js
pc.onicecandidate = (ev) => {
  console.log(
    `The ICE candidate (trsp addr: '${ev.candidate.candidate}') added to connection.`,
  );
};
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # rtcpeerconnectioniceevent |

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

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

See also
--------

* WebRTC
* Its usual target: `RTCPeerConnection`.


CSSLayerStatementRule - Web APIs

CSSLayerStatementRule
=====================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`CSSLayerStatementRule`** represents a `@layer` statement rule. Unlike `CSSLayerBlockRule`, it doesn't contain other rules and merely defines one or several layers by providing their names.

This rule allows to explicitly declare the ordering layer that is in an apparent way at the beginning of a CSS file: the layer order is defined by the order of first occurrence of each layer name. Declaring them with a statement allows the reader to understand the layer order. It also allows inline and imported layers to be interleaved, which is not possible when using the `CSSLayerBlockRule` syntax.

CSSRule

CSSLayerStatementRuleInstance properties
-------------------

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

* `CSSLayerStatementRule.nameList` Read only
    + An array of strings, that represent the name of each cascade layer by the rule
Examples
--------

### HTML

```html
<p></p>
```

### CSS

```css
@layer layerName, layerName2;
```

### JavaScript

```js
const item = document.getElementsByTagName("p")[0];
const rules = document.styleSheets[1].cssRules;
// Note that stylesheet #1 is the stylesheet associated with this embedded example,
// while stylesheet #0 is the stylesheet associated with the whole MDN page

const layer = rules[0]; // A CSSLayerStatementRule

item.textContent = `The CSS @layer statement declares the following layers: ${layer.nameList.join(
 ", ",
)}.`;
```

### Result

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

| Specification |
| --- |
| CSS Cascading and Inheritance Level 5 # csslayerstatementrule |

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

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

See also
--------

* `@layer`
* The `@layer` statement at-rule for named layers
* `CSSLayerBlockRule`