PannerNode - Web APIs

PannerNode
==========

The `PannerNode` interface defines an audio-processing object that represents the location, direction, and behavior of an audio source signal in a simulated physical space. This `AudioNode` uses right-hand Cartesian coordinates to describe the source's *position* as a vector and its *orientation* as a 3D directional cone.

A `PannerNode` always has exactly one input and one output: the input can be *mono* or *stereo* but the output is always *stereo* (2 channels); you can't have panning effects without at least two audio channels!

![The PannerNode defines a spatial position and direction for a given signal.](/en-US/docs/Web/API/PannerNode/webaudiopannernode.png)

EventTarget

AudioNode

PannerNode

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"clamped-max"` |
| Channel count | `2` |
| Channel interpretation | `"speakers"` |

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

`PannerNode()`

Creates a new `PannerNode` object instance.

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

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

**Note:** The orientation and position value are set and retrieved using different syntaxes, since they're stored as `AudioParam` values. Retrieval is done by accessing, for example, `PannerNode.positionX`. While setting the same property is done with `PannerNode.positionX.value`. This is why these values are not marked read only, which is how they appear in the WebIDL.

`PannerNode.coneInnerAngle`

A double value describing the angle, in degrees, of a cone inside of which there will be no volume reduction.

`PannerNode.coneOuterAngle`

A double value describing the angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` property.

`PannerNode.coneOuterGain`

A double value describing the amount of volume reduction outside the cone defined by the `coneOuterAngle` attribute. Its default value is `0`, meaning that no sound can be heard.

`PannerNode.distanceModel`

An enumerated value determining which algorithm to use to reduce the volume of the audio source as it moves away from the listener. Possible values are `"linear"`, `"inverse"` and `"exponential"`. The default value is `"inverse"`.

`PannerNode.maxDistance`

A double value representing the maximum distance between the audio source and the listener, after which the volume is not reduced any further.

`PannerNode.orientationX`

Represents the horizontal position of the audio source's vector in a right-hand Cartesian coordinate system. While this `AudioParam` cannot be directly changed, its value can be altered using its `value` property. The default is value is 1.

`PannerNode.orientationY`

Represents the vertical position of the audio source's vector in a right-hand Cartesian coordinate system. The default is 0. While this `AudioParam` cannot be directly changed, its value can be altered using its `value` property. The default is value is 0.

`PannerNode.orientationZ`

Represents the longitudinal (back and forth) position of the audio source's vector in a right-hand Cartesian coordinate system. The default is 0. While this `AudioParam` cannot be directly changed, its value can be altered using its `value` property. The default is value is 0.

`PannerNode.panningModel`

An enumerated value determining which spatialization algorithm to use to position the audio in 3D space.

`PannerNode.positionX`

Represents the horizontal position of the audio in a right-hand Cartesian coordinate system. The default is 0. While this `AudioParam` cannot be directly changed, its value can be altered using its `value` property. The default is value is 0.

`PannerNode.positionY`

Represents the vertical position of the audio in a right-hand Cartesian coordinate system. The default is 0. While this `AudioParam` cannot be directly changed, its value can be altered using its `value` property. The default is value is 0.

`PannerNode.positionZ`

Represents the longitudinal (back and forth) position of the audio in a right-hand Cartesian coordinate system. The default is 0. While this `AudioParam` cannot be directly changed, its value can be altered using its `value` property. The default is value is 0.

`PannerNode.refDistance`

A double value representing the reference distance for reducing volume as the audio source moves further from the listener. For distances greater than this the volume will be reduced based on `rolloffFactor` and `distanceModel`.

`PannerNode.rolloffFactor`

A double value describing how quickly the volume is reduced as the source moves away from the listener. This value is used by all distance models.

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

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

`PannerNode.setPosition()`
Deprecated

Defines the position of the audio source relative to the listener (represented by an `AudioListener` object stored in the `BaseAudioContext.listener` attribute.)

`PannerNode.setOrientation()`
Deprecated

Defines the direction the audio source is playing in.

Examples
--------

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

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

| Specification |
| --- |
| Web Audio API # PannerNode |

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

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

See also
--------

* Using the Web Audio API


USBInTransferResult - Web APIs

USBInTransferResult
===================

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

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

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

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

The `USBInTransferResult` interface of the WebUSB API provides the result from a call to the `transferIn()` and `controlTransferIn()` methods of the `USBDevice` interface. It represents the result from requesting a transfer of data from the USB device to the USB host.

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

`USBInTransferResult()`
Experimental

Creates a new `USBInTransferResult` object with the provided `status` and `data` fields.

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

`USBInTransferResult.data` Read only
Experimental

Returns a `DataView` object containing the data received from the USB device, if any.

`USBInTransferResult.status` Read only
Experimental

Returns the status of the transfer request, one of:

* `"ok"` - The transfer was successful.
* `"stall"` - The device indicated an error by generating a stall condition on the endpoint. A stall on the control endpoint does not need to be cleared. A stall on a bulk or interrupt endpoint must be cleared by calling `clearHalt()` before `transferIn()` can be called again.
* `"babble"` - The device responded with more data than was expected.

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

| Specification |
| --- |
| WebUSB API # usbintransferresult |

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

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


OES_element_index_uint extension - Web APIs

OES\_element\_index\_uint extension
===================================

The **`OES_element_index_uint`** extension is part of the WebGL API and adds support for `gl.UNSIGNED_INT` types to `WebGLRenderingContext.drawElements()`.

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

**Note:** This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default.

Extended methods
----------------

This extension extends `WebGLRenderingContext.drawElements()`:

* The `type` parameter now accepts `gl.UNSIGNED_INT`.
Examples
--------

```js
const ext = gl.getExtension("OES\_element\_index\_uint");

gl.drawElements(gl.POINTS, 8, gl.UNSIGNED\_INT, 0);
```

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

| Specification |
| --- |
| WebGL OES\_element\_index\_uint Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.drawElements()`


HTMLMenuElement - Web APIs

HTMLMenuElement
===============

 The **`HTMLMenuElement`** interface provides additional properties (beyond those inherited from the `HTMLElement` interface) for manipulating a `<menu>` element.
 `<menu>` is a semantic alternative to the `<ul>` element.

EventTarget

Node

Element

HTMLElement

HTMLMenuElementInstance properties
-------------------

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

`HTMLMenuElement.compact`
Deprecated

A boolean determining if the menu displays compactly.

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

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

*`HTMLMenuElement` doesn't implement specific methods.*

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

| Specification |
| --- |
| HTML Standard # htmlmenuelement |

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

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

See also
--------

* `HTMLMenuItemElement`


SVGStringList - Web APIs

SVGStringList
=============

SVG string list interface
-------------------------

The `SVGStringList` defines a list of strings.

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

### Interface overview

|  |  |
| --- | --- |
| Also implement | *None* |
| Methods | * `void clear()`
* string
 `initialize(string *newItem*)`
* string
 `getItem(number *index*)`
* string
 `insertItemBefore(string *newItem*, number *index*)`
* string
 `replaceItem(string *newItem*,
number *index*)`
* string
 `removeItem(number *index*)`
* string
 `appendItem(string *newItem*)`
 |
| Properties | * readonly unsigned long `numberOfItems`
* readonly unsigned long
 `length`
Non-standard
 |
| Normative document | SVG 1.1 (2nd Edition) |

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

| Name | Type | Description |
| --- | --- | --- |
| `numberOfItems` | `unsigned long` | The number of items in the list. |
| `length` | `unsigned long` |
 A mirror of the value in `numberOfItems`, for consistency
 with other interfaces.
Non-standard
 |

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

| Name & Arguments | Return | Description |
| --- | --- | --- |
| `**clear**()` | *void* |
 Clears all existing current items from the list, with the result being
 an empty list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**initialize**(string *newItem*)` | string |
 Clears all existing current items from the list and re-initializes the
 list to hold the single item specified by the parameter. If the
 inserted item is already in a list, it is removed from its previous
 list before it is inserted into this list. The inserted item is the
 item itself and not a copy. The return value is the item inserted into
 the list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**getItem**(number *index*)` | string |
 Returns the specified item from the list. The returned item is the
 item itself and not a copy. Any changes made to the item are
 immediately reflected in the list. The first item is number 0.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**insertItemBefore**(string *newItem*, number *index*)` | string |
 Inserts a new item into the list at the specified position. The first
 item is number 0. If `newItem` is already in a list, it is
 removed from its previous list before it is inserted into this list.
 The inserted item is the item itself and not a copy. If the item is
 already in this list, note that the index of the item to insert before
 is before the removal of the item. If the `index` is equal
 to 0, then the new item is inserted at the front of the list. If the
 index is greater than or equal to `numberOfItems`, then the
 new item is appended to the end of the list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**replaceItem**(string *newItem*, number *index*)` | string |
 Replaces an existing item in the list with a new item. If
 `newItem` is already in a list, it is removed from its
 previous list before it is inserted into this list. The inserted item
 is the item itself and not a copy. If the item is already in this
 list, note that the index of the item to replace is before the removal
 of the item.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
* a `DOMException` with code
 `INDEX_SIZE_ERR` is raised if the index number is greater
 than or equal to `numberOfItems`.
 |
| `**removeItem**(in unsigned long *index*)` | string | Removes an existing item from the list.
**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
* a `DOMException` with code
 `INDEX_SIZE_ERR` is raised if the index number is greater
 than or equal to `numberOfItems`.
 |
| `**appendItem**(string *newItem*)` | string |
 Inserts a new item at the end of the list. If `newItem` is
 already in a list, it is removed from its previous list before it is
 inserted into this list. The inserted item is the item itself and not
 a copy.

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

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

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


PointerEvent - Web APIs

PointerEvent
============

The **`PointerEvent`** interface represents the state of a DOM event produced by a pointer such as the geometry of the contact point, the device type that generated the event, the amount of pressure that was applied on the contact surface, etc.

A *pointer* is a hardware agnostic representation of input devices (such as a mouse, pen or contact point on a touch-enable surface). The pointer can target a specific coordinate (or set of coordinates) on the contact surface such as a screen.

A pointer's *hit test* is the process a browser uses to determine the target element for a pointer event. Typically, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media.

Event

UIEvent

MouseEvent

PointerEventConstructors
------------

`PointerEvent()`

Creates a synthetic—and untrusted—`PointerEvent`.

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

*This interface inherits properties from `MouseEvent` and `Event`.*

`PointerEvent.altitudeAngle` Read only
Experimental

Represents the angle between a transducer (a pointer or stylus) axis and the X-Y plane of a device screen.

`PointerEvent.azimuthAngle` Read only
Experimental

Represents the angle between the Y-Z plane and the plane containing both the transducer (a pointer or stylus) axis and the Y axis.

`PointerEvent.pointerId` Read only

A unique identifier for the pointer causing the event.

`PointerEvent.width` Read only

The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.height` Read only

The height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.pressure` Read only

The normalized pressure of the pointer input in the range `0` to `1`, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively.

`PointerEvent.tangentialPressure` Read only

The normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range `-1` to `1`, where `0` is the neutral position of the control.

`PointerEvent.tiltX` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the Y–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the Y axis.

`PointerEvent.tiltY` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the X–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the X axis.

`PointerEvent.twist` Read only

The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range `0` to `359`.

`PointerEvent.pointerType` Read only

Indicates the device type that caused the event (mouse, pen, touch, etc.).

`PointerEvent.isPrimary` Read only

Indicates if the pointer represents the primary pointer of this pointer type.

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

`PointerEvent.getCoalescedEvents()`

Returns a sequence of all `PointerEvent` instances that were coalesced into the dispatched `pointermove` event.

`PointerEvent.getPredictedEvents()`

Returns a sequence of `PointerEvent` instances that the browser predicts will follow the dispatched `pointermove` event's coalesced events.

Pointer event types
-------------------

The `PointerEvent` interface has several event types. To determine which event fired, look at the event's `type` property.

**Note:** It's important to note that in many cases, both pointer and mouse events get sent (in order to let non-pointer-specific code still interact with the user). If you use pointer events, you should call `preventDefault()` to keep the mouse event from being sent as well.

`pointerover`

This event is fired when a pointing device is moved into an element's hit test boundaries.

`pointerenter`

This event is fired when a pointing device is moved into the hit test boundaries of an element or one of its descendants, including as a result of a `pointerdown` event from a device that does not support hover (see `pointerdown`). This event type is similar to `pointerover`, but differs in that it does not bubble.

`pointerdown`

The event is fired when a pointer becomes *active*. For mouse, it is fired when the device transitions from no buttons pressed to at least one button pressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.

**Note:** For touchscreen browsers that allow direct manipulation, a `pointerdown` event triggers implicit pointer capture, which causes the target to capture all subsequent pointer events as if they were occurring over the capturing target. Accordingly, `pointerover`, `pointerenter`, `pointerleave`, and `pointerout` **will not fire** as long as this capture is set. The capture can be released manually by calling `element.releasePointerCapture` on the target element, or it will be implicitly released after a `pointerup` or `pointercancel` event.

`pointermove`

This event is fired when a pointer changes coordinates.

`pointerrawupdate`
Experimental

This event is fired when any of a pointer's properties change.

`pointerup`

This event is fired when a pointer is no longer *active*.

`pointercancel`

A browser fires this event if it concludes the pointer will no longer be able to generate events (for example the related device is deactivated).

`pointerout`

This event is fired for several reasons including: pointing device is moved out of the hit test boundaries of an element; firing the `pointerup` event for a device that does not support hover (see `pointerup`); after firing the `pointercancel` event (see `pointercancel`); when a pen stylus leaves the hover range detectable by the digitizer.

`pointerleave`

This event is fired when a pointing device is moved out of the hit test boundaries of an element. For pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer.

`gotpointercapture`

This event is fired when an element receives pointer capture.

`lostpointercapture`

This event is fired after pointer capture is released for a pointer.

Example
-------

Examples of each property, event type, and global event handler are included in their respective reference pages.

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

| Specification |
| --- |
| Pointer Events # pointerevent-interface |

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

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

See also
--------

* `Touch Events`
* `GestureEvent`
* `touch-action`


caches global property - Web APIs

caches global property
======================

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

 The global **`caches`** read-only property returns the `CacheStorage` object associated with the current context.
 This object enables functionality such as storing assets for offline use, and generating custom responses to requests.

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

Value
-----

A `CacheStorage` object.

Examples
--------

The following example shows how you'd use a cache in a service worker context to store assets offline.

```js
this.addEventListener("install", (event) => {
  event.waitUntil(
    caches
      .open("v1")
      .then((cache) =>
        cache.addAll([
          "/",
          "/index.html",
          "/style.css",
          "/app.js",
          "/image-list.js",
          "/star-wars-logo.jpg",
          "/gallery/",
          "/gallery/bountyHunters.jpg",
          "/gallery/myLittleVader.jpg",
          "/gallery/snowTroopers.jpg",
        ]),
      ),
  );
});
```

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

| Specification |
| --- |
| Service Workers # self-caches |

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

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

See also
--------

* Service Workers
* Web Workers
* `CacheStorage`
* `Cache`


SVGFETurbulenceElement - Web APIs

SVGFETurbulenceElement
======================

The **`SVGFETurbulenceElement`** interface corresponds to the `<feTurbulence>` element.

EventTarget

Node

Element

SVGElement

SVGFETurbulenceElementConstants
---------

### Turbulence types

| Name | Value | Description |
| --- | --- | --- |
| `SVG_TURBULENCE_TYPE_UNKNOWN` | 0 |
 The type is not one of predefined types. It is invalid to attempt to
 define a new value of this type or to attempt to switch an existing
 value to this type.
  |
| `SVG_TURBULENCE_TYPE_FRACTALNOISE` | 1 | Corresponds to the `fractalNoise` value. |
| `SVG_TURBULENCE_TYPE_TURBULENCE` | 2 | Corresponds to `turbulence` value. |

### Stitch options

| Name | Value | Description |
| --- | --- | --- |
| `SVG_STITCHTYPE_UNKNOWN` | 0 |
 The type is not one of predefined types. It is invalid to attempt to
 define a new value of this type or to attempt to switch an existing
 value to this type.
  |
| `SVG_STITCHTYPE_STITCH` | 1 | Corresponds to the `stitch` value. |
| `SVG_STITCHTYPE_NOSTITCH` | 2 | Corresponds to `noStitch` value. |

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

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

`SVGFETurbulenceElement.baseFrequencyX` Read only

An `SVGAnimatedNumber` corresponding to the X component of the `baseFrequency` attribute of the given element.

`SVGFETurbulenceElement.baseFrequencyY` Read only

An `SVGAnimatedNumber` corresponding to the Y component of the `baseFrequency` attribute of the given element.

`SVGFETurbulenceElement.height` Read only

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

`SVGFETurbulenceElement.numOctaves` Read only

An `SVGAnimatedInteger` corresponding to the `numOctaves` attribute of the given element.

`SVGFETurbulenceElement.result` Read only

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

`SVGFETurbulenceElement.seed` Read only

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

`SVGFETurbulenceElement.stitchTiles` Read only

An `SVGAnimatedEnumeration` corresponding to the `stitchTiles` attribute of the given element. It takes one of the `SVG_STITCHTYPE_*` constants defined on this interface.

`SVGFETurbulenceElement.type` Read only

An `SVGAnimatedEnumeration` corresponding to the `type` attribute of the given element. It takes one of the `SVG_TURBULENCE_TYPE_*` constants defined on this interface.

`SVGFETurbulenceElement.width` Read only

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

`SVGFETurbulenceElement.x` Read only

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

`SVGFETurbulenceElement.y` Read only

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

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

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

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

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

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

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

See also
--------

* `<feTurbulence>`


SpeechSynthesisEvent - Web APIs

SpeechSynthesisEvent
====================

The **`SpeechSynthesisEvent`** interface of the Web Speech API contains information about the current state of `SpeechSynthesisUtterance` objects that have been processed in the speech service.

Event

SpeechSynthesisEventConstructor
-----------

`SpeechSynthesisEvent()`

Creates a new `SpeechSynthesisEvent`.

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

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

`SpeechSynthesisEvent.charIndex` Read only

Returns the index position of the character in the `SpeechSynthesisUtterance.text` that was being spoken when the event was triggered.

`SpeechSynthesisEvent.charLength` Read only

Returns the number of characters left to be spoken after the `charIndex` position, if the speaking engine supports it. Returns 0 if the speaking engine can't provide the information.

`SpeechSynthesisEvent.elapsedTime` Read only

Returns the elapsed time in seconds after the `SpeechSynthesisUtterance.text` started being spoken that the event was triggered at.

`SpeechSynthesisEvent.name` Read only

Returns the name associated with certain types of events occurring as the `SpeechSynthesisUtterance.text` is being spoken: the name of the SSML marker reached in the case of a `mark` event, or the type of boundary reached in the case of a `boundary` event.

`SpeechSynthesisEvent.utterance` Read only

Returns the `SpeechSynthesisUtterance` instance that the event was triggered on.

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

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

Examples
--------

```js
utterThis.onpause = (event) => {
  const char = event.utterance.text.charAt(event.charIndex);
  console.log(
    `Speech paused at character ${event.charIndex} of "${event.utterance.text}", which is "${char}".`,
  );
};

utterThis.onboundary = (event) => {
  console.log(
    `${event.name} boundary reached after ${event.elapsedTime} seconds.`,
  );
};
```

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

| Specification |
| --- |
| Web Speech API # speechsynthesisevent |

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

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

See also
--------

* Web Speech API


View Transitions API - Web APIs

View Transitions API
====================

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

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

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

The **View Transitions API** provides a mechanism for easily creating animated transitions between different DOM states while also updating the DOM contents in a single step.

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

View transitions are a popular design choice for reducing users' cognitive load, helping them stay in context, and reducing perceived loading latency as they move between states or views of an application.

However, creating view transitions on the web has historically been difficult. Transitions between states in single-page apps (SPAs) tend to involve writing significant CSS and JavaScript to:

* Handle the loading and positioning of the old and new content.
* Animate the old and new states to create the transition.
* Stop accidental user interactions with the old content from causing problems.
* Remove the old content once the transition is complete.

Accessibility issues like loss of reading position, focus confusion, and strange live region announcement behavior can also result from having the new and old content both present in the DOM at once. In addition, cross-document view transitions (i.e. across different pages in regular, non-SPA websites) are impossible.

The View Transitions API provides a much easier way of handling the required DOM changes and transition animations.

**Note:** The View Transitions API doesn't currently enable cross-document view transitions, but this is planned for a future level of the spec and is actively being worked on.

### Creating a basic view transition

As an example, an SPA may include functionality to fetch new content and update the DOM in response to an event of some kind, such as a navigation link being clicked or an update being pushed from the server. In our Basic View Transitions demo we've simplified this to a `displayNewImage()` function that shows a new full-size image based on the thumbnail that was clicked. We've encapsulated this inside an `updateView()` function that only calls the View Transition API if the browser supports it:

```js
function updateView(event) {
  // Handle the difference in whether the event is fired on the <a> or the <img>
  const targetIdentifier = event.target.firstChild || event.target;

  const displayNewImage = () => {
    const mainSrc = `${targetIdentifier.src.split("\_th.jpg")[0]}.jpg`;
    galleryImg.src = mainSrc;
    galleryCaption.textContent = targetIdentifier.alt;
  };

  // Fallback for browsers that don't support View Transitions:
  if (!document.startViewTransition) {
    displayNewImage();
    return;
  }

  // With View Transitions:
  const transition = document.startViewTransition(() => displayNewImage());
}
```

This code is enough to handle the transition between displayed images. Supporting browsers will show the change from old to new images and captions as a smooth cross-fade (the default view transition). It will still work in non-supporting browsers but without the nice animation.

It is also worth mentioning that `startViewTransition()` returns a `ViewTransition` instance, which includes several promises, allowing you to run code in response to different parts of the view transition process being reached.

### The view transition process

Let's walk through how this works:

1. When `document.startViewTransition()` is called, the API takes a screenshot of the current page.
2. Next, the callback passed to `startViewTransition()` is invoked, in this case `displayNewImage`, which causes the DOM to change.
 When the callback has run successfully, the `ViewTransition.updateCallbackDone` promise fulfills, allowing you to respond to the DOM updating.
3. The API captures the new state of the page as a live representation.
4. The API constructs a pseudo-element tree with the following structure:
```

::view-transition
└─ ::view-transition-group(root)
   └─ ::view-transition-image-pair(root)
      ├─ ::view-transition-old(root)
      └─ ::view-transition-new(root)
```

    * `::view-transition` is the root of view transitions overlay, which contains all view transitions and sits over the top of all other page content.
    * `::view-transition-old` is the screenshot of the old page view, and `::view-transition-new` is the live representation of the new page view. Both of these render as replaced content, in the same manner as an `<img>` or `<video>`, meaning that they can be styled with handy properties like `object-fit` and `object-position`.When the transition animation is about to run, the `ViewTransition.ready` promise fulfills, allowing you to respond by running a custom JavaScript animation instead of the default, for example.
5. The old page view animates from `opacity` 1 to 0, while the new view animates from `opacity` 0 to 1, which is what creates the default cross-fade.
6. When the transition animation has reached its end state, the `ViewTransition.finished` promise fulfills, allowing you to respond.
### Different transitions for different elements

At the moment, all of the different elements that change when the DOM updates are transitioned using the same animation. If you want different elements to animate differently from the default "root" animation, you can separate them out using the `view-transition-name` property. For example:

```css
figcaption {
  view-transition-name: figure-caption;
}
```

We've given the `<figcaption>` element a `view-transition-name` of `figure-caption` to separate it from the rest of the page in terms of view transitions.

With this CSS applied, the pseudo-element tree will now look like this:
```

::view-transition
├─ ::view-transition-group(root)
│ └─ ::view-transition-image-pair(root)
│     ├─ ::view-transition-old(root)
│     └─ ::view-transition-new(root)
└─ ::view-transition-group(figure-caption)
  └─ ::view-transition-image-pair(figure-caption)
      ├─ ::view-transition-old(figure-caption)
      └─ ::view-transition-new(figure-caption)
```

The existence of the second set of pseudo-elements allows separate view transition styling to be applied just to the `<figcaption>`. The different old and new page view captures are handled completely separate from one another.

The value of `view-transition-name` can be anything you want except for `none` — the `none` value specifically means that the element will not participate in a view transition.

**Note:** `view-transition-name` must be unique. If two rendered elements have the same `view-transition-name` at the same time, `ViewTransition.ready` will reject and the transition will be skipped.

### Customizing your animations

The View Transitions pseudo-elements have default CSS Animations applied (which are detailed in their reference pages).

Notably, transitions for `height`, `width`, `position`, and `transform` do not use the smooth cross-fade animation. Instead, height and width transitions apply a smooth scaling animation. Meanwhile, position and transform transitions apply smooth movement animations to the element.

You can modify the default animation in any way you want using regular CSS.

For example, to change the speed of it:

```css
::view-transition-old(root),
::view-transition-new(root) {
  animation-duration: 0.5s;
}
```

Let's look at something more interesting — a custom animation for the `<figcaption>`:

```css
@keyframes grow-x {
  from {
    transform: scaleX(0);
  }
  to {
    transform: scaleX(1);
  }
}

@keyframes shrink-x {
  from {
    transform: scaleX(1);
  }
  to {
    transform: scaleX(0);
  }
}

::view-transition-old(figure-caption),
::view-transition-new(figure-caption) {
  height: auto;
  right: 0;
  left: auto;
  transform-origin: right center;
}

::view-transition-old(figure-caption) {
  animation: 0.25s linear both shrink-x;
}

::view-transition-new(figure-caption) {
  animation: 0.25s 0.25s linear both grow-x;
}
```

Here we've created a custom CSS animation and applied it to the `::view-transition-old(figure-caption)` and `::view-transition-new(figure-caption)` pseudo-elements. We've also added a number of other styles to both to keep them in the same place and stop the default styling from interfering with our custom animations.

Note that we also discovered another transition option that is simpler and produced a nicer result than the above. Our final `<figcaption>` view transition ended up looking like this:

```css
figcaption {
  view-transition-name: figure-caption;
}

::view-transition-old(figure-caption),
::view-transition-new(figure-caption) {
  height: 100%;
}
```

This works because, by default, `::view-transition-group` transitions width and height between the old and new views. We just needed to set a fixed `height` on both states to make it work.

**Note:** Smooth and simple transitions with the View Transitions API contains several other customization examples.

### Controlling animations with JavaScript

The `document.startViewTransition()` method returns a `ViewTransition` object instance, which contains several promise members allowing you to run JavaScript in response to different states of the transition being reached. For example, `ViewTransition.ready` fulfills once the pseudo-element tree is created and the animation is about to start, whereas `ViewTransition.finished` fulfills once the animation is finished, and the new page view is visible and interactive to the user.

For example, the following JavaScript could be used to create a circular reveal view transition emanating from the position of the user's cursor on click, with animation provided by the Web Animations API.

```js
// Store the last click event
let lastClick;
addEventListener("click", (event) => (lastClick = event));

function spaNavigate(data) {
  // Fallback for browsers that don’t support this API:
  if (!document.startViewTransition) {
    updateTheDOMSomehow(data);
    return;
  }

  // Get the click position, or fallback to the middle of the screen
  const x = lastClick?.clientX ?? innerWidth / 2;
  const y = lastClick?.clientY ?? innerHeight / 2;
  // Get the distance to the furthest corner
  const endRadius = Math.hypot(
    Math.max(x, innerWidth - x),
    Math.max(y, innerHeight - y),
  );

  // Create a transition:
  const transition = document.startViewTransition(() => {
    updateTheDOMSomehow(data);
  });

  // Wait for the pseudo-elements to be created:
  transition.ready.then(() => {
    // Animate the root’s new view
    document.documentElement.animate(
      {
        clipPath: [
          `circle(0 at ${x}px ${y}px)`,
          `circle(${endRadius}px at ${x}px ${y}px)`,
        ],
      },
      {
        duration: 500,
        easing: "ease-in",
        // Specify which pseudo-element to animate
        pseudoElement: "::view-transition-new(root)",
      },
    );
  });
}
```

This animation also requires the following CSS, to turn off the default CSS animation and stop the old and new view states from blending in any way (the new state "wipes" right over the top of the old state, rather than transitioning in):

```css
::view-transition-image-pair(root) {
  isolation: auto;
}

::view-transition-old(root),
::view-transition-new(root) {
  animation: none;
  mix-blend-mode: normal;
  display: block;
}
```

Interfaces
----------

`ViewTransition`

Represents a view transition, and provides functionality to react to the transition reaching different states (e.g. ready to run the animation, or animation finished) or skip the transition altogether.

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

`Document.startViewTransition()`

Starts a new view transition and returns a `ViewTransition` object to represent it.

CSS additions
-------------

### Properties

`view-transition-name`

Provides the selected element with a separate identifying name and causes it to participate in a separate view transition from the root view transition — or no view transition if the `none` value is specified.

### Pseudo-elements

`::view-transition`

The root of the view transitions overlay, which contains all view transitions and sits over the top of all other page content.

`::view-transition-group()`

The root of a single view transition.

`::view-transition-image-pair()`

The container for a view transition's old and new views — before and after the transition.

`::view-transition-old()`

A static screenshot of the old view, before the transition.

`::view-transition-new()`

A live representation of the new view, after the transition.

Examples
--------

* Basic View Transitions demo: A basic image gallery demo with separate transitions between old and new images, and old and new captions.
* HTTP 203 playlist: A more sophisticated video player demo app that features a number of different view transitions, many of which are explained in Smooth and simple transitions with the View Transitions API.
Specifications
--------------

| Specification |
| --- |
| CSS View Transitions Module Level 1 # dom-document-startviewtransition |

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

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

See also
--------

* Smooth and simple transitions with the View Transitions API
* View Transitions API: Creating Smooth Page Transitions


RTCIceCandidatePair - Web APIs

RTCIceCandidatePair
===================

The **`RTCIceCandidatePair`** dictionary describes a pair of ICE candidates which together comprise a description of a viable connection between two WebRTC endpoints. It is used as the return value from `RTCIceTransport.getSelectedCandidatePair()` to identify the currently-selected candidate pair identified by the ICE agent.

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

`local`

An `RTCIceCandidate` describing the configuration of the local end of the connection.

`remote`

The **`RTCIceCandidate`** describing the configuration of the remote end of the connection.

Examples
--------

See `RTCIceTransport.onselectedcandidatepairchange` for example code.

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

#### No specification found

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

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

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


USBConfiguration - Web APIs

USBConfiguration
================

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

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

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

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

The `USBConfiguration` interface of the WebUSB API provides information about a particular configuration of a USB device and the interfaces that it supports.

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

`USBConfiguration()`
Experimental

Creates a new `USBConfiguration` object which contains information about the configuration on the provided `USBDevice` with the given configuration value.

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

`USBConfiguration.configurationValue` Read only
Experimental

Returns the configuration value of this configuration. This is equal to the `bConfigurationValue` field of the configuration descriptor provided by the device defining this configuration.

`USBConfiguration.configurationName` Read only
Experimental

Returns the name provided by the device to describe this configuration. This is equal to the value of the string descriptor with the index provided in the `iConfiguration` field of the configuration descriptor defining this configuration.

`USBConfiguration.interfaces` Read only
Experimental

Returns an array containing instances of the `USBInterface` describing each interface supported by this configuration.

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

| Specification |
| --- |
| WebUSB API # usbconfiguration-interface |

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

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


SVGFEOffsetElement - Web APIs

SVGFEOffsetElement
==================

The **`SVGFEOffsetElement`** interface corresponds to the `<feOffset>` element.

EventTarget

Node

Element

SVGElement

SVGFEOffsetElementInstance properties
-------------------

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

`SVGFEOffsetElement.height` Read only

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

`SVGFEOffsetElement.in1` Read only

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

`SVGFEOffsetElement.dx` Read only

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

`SVGFEOffsetElement.dy` Read only

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

`SVGFEOffsetElement.result` Read only

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

`SVGFEOffsetElement.width` Read only

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

`SVGFEOffsetElement.x` Read only

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

`SVGFEOffsetElement.y` Read only

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

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

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

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

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

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

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

See also
--------

* `<feOffset>`


DocumentTimeline - Web APIs

DocumentTimeline
================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`DocumentTimeline`** interface of the Web Animations API represents animation timelines, including the default document timeline (accessed via `Document.timeline`).

AnimationTimeline

DocumentTimelineConstructor
-----------

`DocumentTimeline()`

Creates a new `DocumentTimeline` object associated with the active document of the current browsing context.

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

*This interface inherits its property from its parent, `AnimationTimeline`.*

`AnimationTimeline.currentTime`

Returns the time value in milliseconds for this timeline or `null` if it is inactive.

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

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

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

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

See also
--------

* Web Animations API
* `AnimationTimeline`
* `AnimationTimeline.currentTime`
* `Document.timeline`
* `DocumentTimeline()`


Web Storage API - Web APIs

Web Storage API
===============

The **Web Storage API** provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

Web Storage concepts and usage
------------------------------

The two mechanisms within Web Storage are as follows:

* `sessionStorage` maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
    + Stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.
    + Data is never transferred to the server.
    + Storage limit is larger than a cookie (at most 5MB).
* `localStorage` does the same thing, but persists even when the browser is closed and reopened.
    + Stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache / Locally Stored Data.
    + Storage limit is the maximum amongst the two.

These mechanisms are available via the `Window.sessionStorage` and `Window.localStorage` properties (to be more precise, the `Window` object implements the `WindowLocalStorage` and `WindowSessionStorage` objects, which the `localStorage` and `sessionStorage` properties hang off) — invoking one of these will create an instance of the `Storage` object, through which data items can be set, retrieved and removed. A different Storage object is used for the `sessionStorage` and `localStorage` for each origin — they function and are controlled separately.

**Note:** In Firefox, when the browser crashes/restarts, to avoid memory issues caused by excessive usage of web storage, the amount of data saved per origin is limited to 10MB. See storage quotas and eviction criteria for more information.

**Note:** Access to Web Storage from third-party IFrames is denied if the user has disabled third-party cookies.

Determining storage access by a third party
-------------------------------------------

Each origin has its own storage — this is true for both web storage and shared storage). However, access of third-party (i.e., embedded) code to shared storage depends on its browsing context. The context in which a third-party code from another origin runs determines the storage access of the third-party code.

![A box diagram showing a top-level browsing context called publisher.com, with third-party content embedded in it](/en-US/docs/Web/API/Web_Storage_API/embedded-content.png)

Third-party code can be added to another site by injecting it with a `<script>` element or by setting the source of an `<iframe>` to a site that contains third-party code. The method used for integrating third-party code determines the browsing context of the code.

* If your third-party code is added to another site with a `<script>` element, your code will be executed in the browsing context of the embedder. Therefore, when you call `Storage.setItem()` or `SharedStorage.set()`, the key/value pair will be written to the embedder's storage. From the browser's perspective, there is no difference between first-party code and third-party code when a `<script>` tag is used.
* When your third-party code is added to another site within an `<iframe>`, the code inside the `<iframe>` will be executed with the origin of the `<iframe>`'s browsing context. If the code inside the `<iframe>` calls `Storage.setItem()`, data will be written into the local or session storage of the `<iframe>`'s origin. If the `<iframe>` code calls `SharedStorage.set()`, the data will be written into the shared storage of the `<iframe>`'s origin.
Web Storage interfaces
----------------------

`Storage`

Allows you to set, retrieve and remove data for a specific domain and storage type (session or local).

`Window`

The Web Storage API extends the `Window` object with two new properties — `Window.sessionStorage` and `Window.localStorage` — which provide access to the current domain's session and local `Storage` objects respectively, and a `storage` event handler that fires when a storage area changes (e.g., a new item is stored).

`StorageEvent`

The `storage` event is fired on a document's `Window` object when a storage area changes.

Examples
--------

To illustrate some typical web storage usage, we have created a simple example, imaginatively called Web Storage Demo. The landing page provides controls that can be used to customize the color, font and decorative image. When you choose different options, the page is instantly updated; in addition your choices are stored in `localStorage`, so that when you leave the page then load it again later on your choices are remembered.

In addition, we have provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as the `StorageEvent` is fired.

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

| Specification |
| --- |
| HTML Standard # dom-localstorage-dev |
| HTML Standard # dom-sessionstorage-dev |

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

### api.Window.localStorage

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

### api.Window.sessionStorage

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

Private Browsing / Incognito modes
----------------------------------

Private windows, incognito mode, and similarly named privacy browsing options, don't store data like history and cookies. In private mode, `localStorage` is treated like `sessionStorage`. The storage APIs are still available and fully functional, but all data stored in the private window is deleted when the browser or browser tab is closed.

See also
--------

* Using the Web Storage API
* Browser storage quotas and eviction criteria


CookieStore - Web APIs

CookieStore
===========

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

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

The **`CookieStore`** interface of the Cookie Store API provides methods for getting and setting cookies asynchronously from either a page or a service worker.

The `CookieStore` is accessed via attributes in the global scope in a `Window` or `ServiceWorkerGlobalScope` context. Therefore there is no constructor.

EventTarget

CookieStore

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

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

`CookieStore.delete()`
Experimental

The `delete()` method deletes a cookie with the given name or options object, it returns a `Promise` that resolves when the deletion completes.

`CookieStore.get()`
Experimental

The `get()` method gets a single cookie with the given name or options object, it returns a `Promise` that resolves with details of a single cookie.

`CookieStore.getAll()`
Experimental

The `getAll()` method gets all matching cookies, it returns a `Promise` that resolves with a list of cookies.

`CookieStore.set()`
Experimental

The `set()` method sets a cookie with the given name and value or options object, it returns a `Promise` that resolves when the cookie is set.

Events
------

`change`
Experimental

The `change` event fires when a change is made to any cookie.

Examples
--------

In this example, we set a cookie and write to the console feedback as to whether the operation succeeded or failed.

```js
const day = 24 \* 60 \* 60 \* 1000;

cookieStore
  .set({
    name: "cookie1",
    value: "cookie1-value",
    expires: Date.now() + day,
    domain: "example.com",
  })
  .then(
    () => {
      console.log("It worked!");
    },
    (reason) => {
      console.error("It failed: ", reason);
    },
  );
```

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

| Specification |
| --- |
| Cookie Store API # CookieStore |

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

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


Fullscreen API - Web APIs

Fullscreen API
==============

The **Fullscreen API** adds methods to present a specific `Element` (and its descendants) in fullscreen mode, and to exit fullscreen mode once it is no longer needed. This makes it possible to present desired content—such as an online game—using the user's entire screen, removing all browser user interface elements and other applications from the screen until fullscreen mode is shut off.

See the article Guide to the Fullscreen API for details on how to use the API.

Interfaces
----------

*The Fullscreen API has no interfaces of its own. Instead, it augments several other interfaces to add the methods, properties, and event handlers needed to provide fullscreen functionality. These are listed in the following sections.*

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

The Fullscreen API adds methods to the `Document` and `Element` interfaces to allow turning off and on fullscreen mode.

### Instance methods on the Document interface

`Document.exitFullscreen()`

Requests that the user agent switch from fullscreen mode back to windowed mode. Returns a `Promise` which is resolved once fullscreen mode has been completely shut off.

### Instance methods on the Element interface

`Element.requestFullscreen()`

Asks the user agent to place the specified element (and, by extension, its descendants) into fullscreen mode, removing all of the browser's UI elements as well as all other applications from the screen. Returns a `Promise` which is resolved once fullscreen mode has been activated.

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

`Document.fullscreenElement` / `ShadowRoot.fullscreenElement`

The `fullscreenElement` property tells you the `Element` that's currently being displayed in fullscreen mode on the DOM (or shadow DOM). If this is `null`, the document (or shadow DOM) is not in fullscreen mode.

`Document.fullscreenEnabled`

The `fullscreenEnabled` property tells you whether or not it is possible to engage fullscreen mode. This is `false` if fullscreen mode is not available for any reason (such as the `"fullscreen"` feature not being allowed, or fullscreen mode not being supported).

### Obsolete properties

`Document.fullscreen`
Deprecated

A Boolean value which is `true` if the document has an element currently being displayed in fullscreen mode; otherwise, this returns `false`.

**Note:** Use the `fullscreenElement` property on the `Document` or `ShadowRoot` instead; if it's not `null`, then it's an `Element` currently being displayed in fullscreen mode.

Events
------

`fullscreenchange`

Sent to an `Element` when it transitions into or out of fullscreen mode.

`fullscreenerror`

Sent to an `Element` if an error occurs while attempting to switch it into or out of fullscreen mode.

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

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

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

Users can choose to exit fullscreen mode by pressing the `ESC` (or `F11`) key, rather than waiting for the site or app to programmatically do so. Make sure you provide, somewhere in your user interface, appropriate user interface elements that inform the user that this option is available to them.

**Note:** Navigating to another page, changing tabs, or switching to another application using any application switcher (or `Alt`-`Tab`) will likewise exit fullscreen mode.

Examples
--------

### Simple fullscreen usage

In this example, a video is presented in a web page. Pressing the `Enter` key lets the user toggle between windowed and fullscreen presentation of the video.

View Live Example

#### Watching for the Enter key

When the page is loaded, this code is run to set up an event listener to watch for the `Enter` key.

```js
document.addEventListener(
  "keydown",
  (e) => {
    if (e.key === "Enter") {
      toggleFullScreen();
    }
  },
  false,
);
```

#### Toggling fullscreen mode

This code is called by the event handler above when the user hits the `Enter` key.

```js
function toggleFullScreen() {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen();
  } else if (document.exitFullscreen) {
    document.exitFullscreen();
  }
}
```

This starts by looking at the value of the `document`'s `fullscreenElement` attribute. In a real-world deployment, at this time, you'll want to check for prefixed versions of this (`mozFullScreenElement`, `msFullscreenElement`, or `webkitFullscreenElement`, for example). If the value is `null`, the document is currently in windowed mode, so we need to switch to fullscreen mode; otherwise, it's the element that's currently in fullscreen mode. Switching to fullscreen mode is done by calling `Element.requestFullscreen()` on the `<video>` element.

If fullscreen mode is already active (`fullscreenElement` is not `null`), we call `exitFullscreen()` on the `document` to shut off fullscreen mode.

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

| Specification |
| --- |
| Fullscreen API Standard # ref-for-dom-document-fullscreenelement① |
| Fullscreen API Standard # ref-for-dom-document-fullscreenenabled① |
| Fullscreen API Standard # ref-for-dom-document-exitfullscreen① |
| Fullscreen API Standard # ref-for-dom-element-requestfullscreen① |
| Fullscreen API Standard # dom-document-fullscreen |

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

### api.Document.fullscreenElement

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

### api.Document.fullscreenEnabled

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

### api.Document.exitFullscreen

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

### api.Element.requestFullscreen

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

### api.Document.fullscreen

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

See also
--------

* `Element.requestFullscreen()`
* `Document.exitFullscreen()`
* `Document.fullscreen`
* `Document.fullscreenElement`
* `:fullscreen`, `::backdrop`
* `allowfullscreen`


Visual Viewport API - Web APIs

Visual Viewport API
===================

The **Visual Viewport API** provides an explicit mechanism for querying and modifying the properties of the window's visual viewport. The visual viewport is the visual portion of a screen excluding on-screen keyboards, areas outside of a pinch-zoom area, or any other on-screen artifact that doesn't scale with the dimensions of a page.

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

The mobile web contains two viewports, the layout viewport and the visual viewport. The layout viewport covers all the elements on a page and the visual viewport is what is actually visible on the screen. When the user pinch-zooms into the page, the visual viewport shrinks but the layout viewport is unchanged. User-interface features like the on-screen keyboard (OSK) can shrink the visual viewport without affecting the layout viewport.

What happens when a web page element needs to be visible on screen regardless of the visible portion of a web page? For example, what if you need a set of image controls to remain on screen regardless of the pinch zoom level of the device? Current browsers vary in how they handle this. The visual viewport lets web developers solve this by positioning elements relative to what's shown on screen.

To access a window's visual viewport, you can obtain a `VisualViewport` object from the `window.visualViewport` property. The object includes a set of properties describing the viewport. It also adds two events, `onresize` and `onscroll`, that fire whenever the visual viewport changes. These events allow you to position elements relative to the visual viewport that would normally be anchored to the layout viewport.

Interfaces
----------

`VisualViewport`

Represents the visual viewport for a given window. A window's `VisualViewport` object provides information about the viewport's position and size, and receives the `resize` and `scroll` events you can monitor to know when changes occur to the window's viewport.

### Extensions to other interfaces

`Window.visualViewport` Read only

A read-only reference to the window's `VisualViewport` object. If this property doesn't exist, the API is unsupported.

Examples
--------

The code below is based on the sample in the specification, though it adds a few things that make it function better. It shows a function called `viewportHandler()`. When called it queries the `offsetLeft` and `height` properties for values it uses in a CSS `translate()` method. You invoke this function by passing it to *both* event calls.

One thing that may not be clear in this example is the use of the `pendingUpdate` flag and the call to `requestAnimationFrame()`. The `pendingUpdate` flag serves to prevent multiple invocations of the transform that can occur when `onresize` and `onscroll` fire at the same time. Using `requestAnimationFrame()` ensures that the transform occurs before the next render.

```js
let pendingUpdate = false;

function viewportHandler(event) {
  if (pendingUpdate) return;
  pendingUpdate = true;

  requestAnimationFrame(() => {
    pendingUpdate = false;
    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 viewport = event.target;
    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);
```

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

| Specification |
| --- |
| CSSOM View Module # visualViewport |

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

### api.VisualViewport

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

### api.Window.visualViewport

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


RTCOutboundRtpStreamStats - Web APIs

RTCOutboundRtpStreamStats
=========================

The **`RTCOutboundRtpStreamStats`** dictionary of the WebRTC API is used to report metrics and statistics related to an outbound RTP stream being sent by an `RTCRtpSender`.

The statistics can be obtained by iterating the `RTCStatsReport` returned by `RTCPeerConnection.getStats()` or `RTCRtpSender.getStats()` until you find a report with the `type` of `outbound-rtp`.

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

`averageRtcpInterval`

A floating-point value indicating the average RTCP interval between two consecutive compound RTCP packets.

`firCount`

An integer value which indicates the total number of Full Intra Request (FIR) packets which this `RTCRtpSender` has sent to the remote `RTCRtpReceiver`. This is an indicator of how often the stream has lagged, requiring frames to be skipped in order to catch up. *Valid only for video streams.*

`framesEncoded`

The number of frames that have been successfully encoded so far for sending on this RTP stream. *Only valid for video streams.*

`nackCount`

An integer value indicating the total number of Negative ACKnolwedgement (NACK) packets this `RTCRtpSender` has received from the remote `RTCRtpReceiver`.

`perDscpPacketsSent`

A record of key-value pairs with strings as the keys mapped to 32-bit integer values, each indicating the total number of packets this `RTCRtpSender` has transmitted for this source for each Differentiated Services Code Point (DSCP).

`pliCount`

An integer specifying the number of times the remote receiver has notified this `RTCRtpSender` that some amount of encoded video data for one or more frames has been lost, using Picture Loss Indication (PLI) packets. *Only available for video streams.*

`qpSum`

A 64-bit value containing the sum of the QP values for every frame encoded by this `RTCRtpSender`. *Valid only for video streams.*

`qualityLimitationDurations`

A record mapping each of the quality limitation reasons in the `RTCRemoteInboundRtpStreamStats` enumeration to a floating-point value indicating the number of seconds the stream has spent with its quality limited for that reason.

`qualityLimitationReason`

One of the string `none`, `cpu`, `bandwidth`, or `other`, explaining why the resolution and/or frame rate is being limited for this RTP stream. *Valid only for video streams*.

`remoteId`

A string which identifies the `RTCRemoteInboundRtpStreamStats` object that provides statistics for the remote peer for this same SSRC. This ID is stable across multiple calls to `getStats()`.

`retransmittedBytesSent`

The total number of bytes that have been retransmitted for this source as of the time the statistics were sampled. These retransmitted bytes comprise the packets included in the value returned by `retransmittedPacketsSent`.

`retransmittedPacketsSent`

The total number of packets that have needed to be retransmitted for this source as of the time the statistics were sampled. These retransmitted packets are included in the value returned by `packetsSent`.

`senderId`

The `id` of the `RTCAudioSenderStats` or `RTCVideoSenderStats` object containing statistics about this stream's `RTCRtpSender`.

`sliCount`

An integer indicating the number of times this sender received a Slice Loss Indication (SLI) frame from the remote peer, indicating that one or more consecutive video macroblocks have been lost or corrupted. Available only for video streams.

`targetBitrate`

A value indicating the bit rate the `RTCRtpSender`'s codec is configured to attempt to achieve in its output media.

`totalEncodedBytesTarget`

A cumulative sum of the *target* frame sizes (the targeted maximum size of the frame in bytes when the codec is asked to compress it) for all of the frames encoded so far. This will likely differ from the total of the *actual* frame sizes.

`totalEncodeTime`

A floating-point value indicating the total number of seconds that have been spent encoding the frames encoded so far by this `RTCRtpSender`.

`trackId`

The `id` of the `RTCSenderAudioTrackAttachmentStats` or `RTCSenderVideoTrackAttachmentStats` object containing the current track attachment to the `RTCRtpSender` responsible for this stream.

### Common instance properties

The following properties are common to all WebRTC statistics objects.

`id`

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

`timestamp`

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

`type`

A string with the value `"outbound-rtp"`, indicating the type of statistics that the object contains.

Examples
--------

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstatstype-outbound-rtp |

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

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

See also
--------

* `RTCStatsReport`


FontFaceSet - Web APIs

FontFaceSet
===========

The **`FontFaceSet`** interface of the CSS Font Loading API manages the loading of font-faces and querying of their download status.

A `FontFaceSet` instance is a `Set`-like object that can hold an ordered set of `FontFace` objects.

This property is available as `Document.fonts`, or `self.fonts` in web workers.

EventTarget

FontFaceSetInstance properties
-------------------

`FontFaceSet.status` Read only

Indicates the font-face's loading status. It will be one of `'loading'` or `'loaded'`.

`FontFaceSet.ready` Read only

`Promise` which resolves once font loading and layout operations have completed.

`FontFaceSet.size` Read only

Returns the number of values in the `FontFaceSet`.

### Events

`loading`

Fires when a font-face set has started loading.

`loadingdone`

Fires when a font face set has finished loading.

`loadingerror`

Fires when an error occurred whilst loading a font-face set.

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

`FontFaceSet.add()`

Adds a font to the font set.

`FontFaceSet.check()`

A boolean value that indicates whether a font is loaded, but doesn't initiate a load when it isn't.

`FontFaceSet.clear()`

Removes all manually-added fonts from the font set. CSS-connected fonts are unaffected.

`FontFaceSet.delete()`

Removes a manually-added font from the font set. CSS-connected fonts are unaffected.

`FontFaceSet.entries()`

Returns a new iterator with the values for each element in the `FontFaceSet` in insertion order.

`FontFaceSet.forEach()`

Executes a provided function for each value in the `FontFaceSet` object.

`FontFaceSet.has()`

Returns a `Boolean` asserting whether an element is present with the given value.

`FontFaceSet.keys()`

An alias for `FontFaceSet.values()`.

`FontFaceSet.load()`

Returns a `Promise` which resolves to a list of font-faces for a requested font.

`FontFaceSet.values()`

Returns a new iterator object that yields the values for each element in the `FontFaceSet` object in insertion order.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # FontFaceSet-interface |

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

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


WorkletGlobalScope - Web APIs

WorkletGlobalScope
==================

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

The **`WorkletGlobalScope`** interface is an abstract class that specific worklet scope classes inherit from. Each `WorkletGlobalScope` defines a new global environment.

**Note:** You don't normally need to interact with this interface. It is a base interface intended to be subclassed. You will encounter the subclasses `AudioWorkletGlobalScope` inside `AudioWorklet` objects, or `PaintWorkletGlobalScope` inside CSS paint `Worklet` objects.

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

None.

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

None.

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

| Specification |
| --- |
| HTML Standard # workletglobalscope |

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

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

See also
--------

* `AudioWorkletGlobalScope`
* `PaintWorkletGlobalScope`


SVGAnimatedInteger - Web APIs

SVGAnimatedInteger
==================

SVG animated integer interface
------------------------------

The `SVGAnimatedInteger` interface is used for attributes of basic type <integer> which can be animated.

### Interface overview

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

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

| Name | Type | Description |
| --- | --- | --- |
| `baseVal` | long | The base value of the given attribute before applying any animations. |
| `animVal` | long |
 If the given attribute or property is being animated, contains the
 current animated value of the attribute or property. If the given
 attribute or property is not currently being animated, contains the same
 value as `baseVal`.
  |

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

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

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

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


MutationObserver - Web APIs

MutationObserver
================

The `MutationObserver` interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.

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

`MutationObserver()`

Creates and returns a new `MutationObserver` which will invoke a specified callback function when DOM changes occur.

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

`disconnect()`

Stops the `MutationObserver` instance from receiving further notifications until and unless `observe()` is called again.

`observe()`

Configures the `MutationObserver` to begin receiving notifications through its callback function when DOM changes matching the given options occur.

`takeRecords()`

Removes all pending notifications from the `MutationObserver`'s notification queue and returns them in a new `Array` of `MutationRecord` objects.

Mutation Observer & customize resize event listener & demo
----------------------------------------------------------

https://codepen.io/milofultz/pen/LYjPXPw

Example
-------

The following example was adapted from this blog post.

```js
// Select the node that will be observed for mutations
const targetNode = document.getElementById("some-id");

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = (mutationList, observer) => {
  for (const mutation of mutationList) {
    if (mutation.type === "childList") {
      console.log("A child node has been added or removed.");
    } else if (mutation.type === "attributes") {
      console.log(`The ${mutation.attributeName} attribute was modified.`);
    }
  }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();
```

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

| Specification |
| --- |
| DOM Standard # interface-mutationobserver |

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

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

See also
--------

* `PerformanceObserver`
* `ResizeObserver`
* `IntersectionObserver`
* A brief overview
* A more in-depth discussion
* A screencast by Chromium developer Rafael Weinstein


GPUCanvasContext - Web APIs

GPUCanvasContext
================

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

The **`GPUCanvasContext`** interface of the WebGPU API represents the WebGPU rendering context of a `<canvas>` element, returned via an `HTMLCanvasElement.getContext()` call with a `contextType` of `"webgpu"`.

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

`canvas`
Experimental
 Read only

Returns a reference to the canvas that the context was created from.

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

`configure()`
Experimental

Configures the context to use for rendering with a given `GPUDevice` and clears the canvas to transparent black.

`getCurrentTexture()`
Experimental

Returns the next `GPUTexture` to be composited to the document by the canvas context.

`unconfigure()`
Experimental

Removes any previously-set context configuration, and destroys any textures produced while the canvas context was configured.

Examples
--------

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

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

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

| Specification |
| --- |
| WebGPU # gpucanvascontext |

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

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

See also
--------

* The WebGPU API


CSSPerspective - Web APIs

CSSPerspective
==============

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

CSSTransformComponent

CSSPerspectiveConstructor
-----------

`CSSPerspective()`

Creates a new `CSSPerspective` object.

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

`length`

Returns or sets the distance from z=0.

Examples
--------

To do

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

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

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

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


HTMLDivElement - Web APIs

HTMLDivElement
==============

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

EventTarget

Node

Element

HTMLElement

HTMLDivElementInstance properties
-------------------

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

`HTMLDivElement.align`
Deprecated

A string representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`.

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

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

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

| Specification |
| --- |
| HTML Standard # htmldivelement |

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


History API - Web APIs

History API
===========

The **History API** provides access to the browser's session history (not to be confused with WebExtensions history) through the `history` global object. It exposes useful methods and properties that let you navigate back and forth through the user's history, and manipulate the contents of the history stack.

**Note:** This API is only available on the main thread (`Window`). It cannot be accessed in `Worker` or `Worklet` contexts.

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

Moving backward and forward through the user's history is done using the `back()`, `forward()`, and `go()` methods.

### Moving forward and backward

To move backward through history:

```js
history.back();
```

This acts exactly as if the user clicked on the `**Back**` button in their browser toolbar.

Similarly, you can move forward (as if the user clicked the `**Forward**` button), like this:

```js
history.forward();
```

### Moving to a specific point in history

You can use the `go()` method to load a specific page from session history, identified by its relative position to the current page. (The current page's relative position is `0`.)

To move back one page (the equivalent of calling `back()`):

```js
history.go(-1);
```

To move forward a page, just like calling `forward()`:

```js
history.go(1);
```

Similarly, you can move forward 2 pages by passing `2`, and so forth.

Another use for the `go()` method is to refresh the current page by either passing `0`, or by invoking it without an argument:

```js
// The following statements
// both have the effect of
// refreshing the page
history.go(0);
history.go();
```

You can determine the number of pages in the history stack by looking at the value of the `length` property:

```js
const numberOfEntries = history.length;
```

Interfaces
----------

`History`

Allows manipulation of the browser *session history* (that is, the pages visited in the tab or frame that the current page is loaded in).

`PopStateEvent`

The interface of the `popstate` event.

Examples
--------

The following example assigns a listener for the `popstate` event. It then illustrates some of the methods of the history object to add, replace, and move within the browser history for the current tab.

```js
window.addEventListener("popstate", (event) => {
  alert(
    `location: ${document.location}, state: ${JSON.stringify(event.state)}`,
  );
});

history.pushState({ page: 1 }, "title 1", "?page=1");
history.pushState({ page: 2 }, "title 2", "?page=2");
history.replaceState({ page: 3 }, "title 3", "?page=3");
history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null"
history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3}"
```

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

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

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

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

See also
--------

* `history` global object
* `popstate` event


Response - Web APIs

Response
========

The **`Response`** interface of the Fetch API represents the response to a request.

You can create a new `Response` object using the `Response()` constructor, but you are more likely to encounter a `Response` object being returned as the result of another API operation—for example, a service worker `FetchEvent.respondWith`, or a simple `fetch()`.

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

`Response()`

Creates a new `Response` object.

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

`Response.body` Read only

A `ReadableStream` of the body contents.

`Response.bodyUsed` Read only

Stores a boolean value that declares whether the body has been used in a response yet.

`Response.headers` Read only

The `Headers` object associated with the response.

`Response.ok` Read only

A boolean indicating whether the response was successful (status in the range `200` – `299`) or not.

`Response.redirected` Read only

Indicates whether or not the response is the result of a redirect (that is, its URL list has more than one entry).

`Response.status` Read only

The status code of the response. (This will be `200` for a success).

`Response.statusText` Read only

The status message corresponding to the status code. (e.g., `OK` for `200`).

`Response.type` Read only

The type of the response (e.g., `basic`, `cors`).

`Response.url` Read only

The URL of the response.

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

`Response.error()`

Returns a new `Response` object associated with a network error.

`Response.redirect()`

Returns a new response with a different URL.

`Response.json()`

Returns a new `Response` object for returning the provided JSON encoded data.

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

`Response.arrayBuffer()`

Returns a promise that resolves with an `ArrayBuffer` representation of the response body.

`Response.blob()`

Returns a promise that resolves with a `Blob` representation of the response body.

`Response.clone()`

Creates a clone of a `Response` object.

`Response.formData()`

Returns a promise that resolves with a `FormData` representation of the response body.

`Response.json()`

Returns a promise that resolves with the result of parsing the response body text as `JSON`.

`Response.text()`

Returns a promise that resolves with a text representation of the response body.

Examples
--------

### Fetching an image

 In our basic fetch example (run example live) we use a simple `fetch()` call to grab an image and display it in an `<img>` element.
 The `fetch()` call returns a promise, which resolves to the `Response` object associated with the resource fetch operation.

You'll notice that since we are requesting an image, we need to run `Response.blob` to give the response its correct MIME type.

```js
const image = document.querySelector(".my-image");
fetch("flowers.jpg")
  .then((response) => response.blob())
  .then((blob) => {
    const objectURL = URL.createObjectURL(blob);
    image.src = objectURL;
  });
```

You can also use the `Response()` constructor to create your own custom `Response` object:

```js
const response = new Response();
```

### A PHP Call

Here we call a PHP program file that generates a JSON string, displaying the result as a JSON value.

```js
// Function to fetch JSON using PHP
const getJSON = async () => {
  // Generate the Response object
  const response = await fetch("getJSON.php");
  if (response.ok) {
    // Get JSON value from the response body
    return response.json();
  }
  throw new Error("\*\*\* PHP file not found");
};

// Call the function and output value or error message to console
getJSON()
  .then((result) => console.log(result))
  .catch((error) => console.error(error));
```

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

| Specification |
| --- |
| Fetch Standard # response-class |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


CSSRotate - Web APIs

CSSRotate
=========

The **`CSSRotate`** interface of the CSS\_Object\_Model#css\_typed\_object\_model represents the rotate value of the individual `transform` property in CSS. It inherits properties and methods from its parent `CSSTransformValue`.

CSSTransformComponent

CSSRotateConstructor
-----------

`CSSRotate()`

Creates a new `CSSRotate` object.

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

`x`

Returns or sets the x-axis value.

`y`

Returns or sets the y-axis value.

`z`

Returns or sets the z-axis value.

`angle`

Returns or sets the angle value.

Examples
--------

To do.

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

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

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

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


CanvasCaptureMediaStreamTrack - Web APIs

CanvasCaptureMediaStreamTrack
=============================

The **`CanvasCaptureMediaStreamTrack`** interface of the Media Capture and Streams API represents the video track contained in a `MediaStream` being generated from a `<canvas>` following a call to `HTMLCanvasElement.captureStream()`.

EventTarget

MediaStreamTrack

CanvasCaptureMediaStreamTrackInstance properties
-------------------

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

`CanvasCaptureMediaStreamTrack.canvas` Read only

Returns the `HTMLCanvasElement` object whose surface is captured in real-time.

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

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

`CanvasCaptureMediaStreamTrack.requestFrame()`

Manually forces a frame to be captured and sent to the stream. This lets applications that wish to specify the frame capture times directly do so, if they specified a `frameRate` of 0 when calling `captureStream()`.

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

| Specification |
| --- |
| Media Capture from DOM Elements # the-canvascapturemediastreamtrack |

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

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

See also
--------

* `HTMLCanvasElement.captureStream()` to begin capturing frames from a canvas


PictureInPictureEvent - Web APIs

PictureInPictureEvent
=====================

The **`PictureInPictureEvent`** interface represents picture-in-picture-related events, including `enterpictureinpicture`, `leavepictureinpicture` and `resize`

Event

PictureInPictureEventConstructor
-----------

`PictureInPictureEvent()`

Creates a `PictureInPictureEvent` event with the given parameters.

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

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

`PictureInPictureEvent.pictureInPictureWindow`

Returns the `PictureInPictureWindow` the event relates to.

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

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

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

| Specification |
| --- |
| Picture-in-Picture # event-types |

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

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

See also
--------

* The `Event` base interface


SVGPatternElement - Web APIs

SVGPatternElement
=================

The **`SVGPatternElement`** interface corresponds to the `<pattern>` element.

EventTarget

Node

Element

SVGElement

SVGPatternElementInstance properties
-------------------

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

`SVGPatternElement.href` Read only

An `SVGAnimatedString` corresponding to the `href` or `xlink:href`
Deprecated
 attribute of the given `<pattern>` element.

`SVGPatternElement.patternUnits` Read only

An `SVGAnimatedEnumeration` corresponding to the `patternUnits` attribute of the given `<pattern>` element. Takes one of the constants defined in `SVGUnitTypes`.

`SVGPatternElement.patternContentUnits` Read only

An `SVGAnimatedEnumeration` corresponding to the `patternContentUnits` attribute of the given `<pattern>` element. Takes one of the constants defined in `SVGUnitTypes`.

`SVGPatternElement.patternTransform` Read only

An `SVGAnimatedTransformList` corresponding to the `patternTransform` attribute of the given `<pattern>` element.

`SVGPatternElement.x` Read only

An `SVGAnimatedEnumeration` corresponding to the `x` attribute of the given `<pattern>` element.

`SVGPatternElement.y` Read only

An `SVGAnimatedEnumeration` corresponding to the `y` attribute of the given `<pattern>` element.

`SVGPatternElement.width` Read only

An `SVGAnimatedEnumeration` corresponding to the `width` attribute of the given `<pattern>` element.

`SVGPatternElement.height` Read only

An `SVGAnimatedEnumeration` corresponding to the `height` attribute of the given `<pattern>` element.

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

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

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

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

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

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


WindowControlsOverlayGeometryChangeEvent - Web APIs

WindowControlsOverlayGeometryChangeEvent
========================================

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

The **`WindowControlsOverlayGeometryChangeEvent`** interface of the Window Controls Overlay API is passed to `geometrychange` when the size or visibility of a desktop Progress Web App's title bar region changes.

Event

WindowControlsOverlayGeometryChangeEventConstructor
-----------

`WindowControlsOverlayGeometryChangeEvent()`
Experimental

Creates a `WindowControlsOverlayGeometryChangeEvent` event with the given parameters.

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

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

`WindowControlsOverlayGeometryChangeEvent.titlebarAreaRect` Read only
Experimental

A `DOMRect` representing the position and size of the title bar region.

`WindowControlsOverlayGeometryChangeEvent.visible` Read only
Experimental

A Boolean that indicates whether the window controls overlay is visible or not.

Examples
--------

 The following example shows how to use a `WindowControlsOverlayGeometryChangeEvent` instance by adding an
 event handler on the `Navigator.windowControlsOverlay` property, to listen to geometry changes of a PWA's title bar region.

```js
if ("windowControlsOverlay" in navigator) {
  navigator.windowControlsOverlay.addEventListener(
    "geometrychange",
    (event) => {
      if (event.visible) {
        const rect = event.titlebarAreaRect;
        // Do something with the coordinates of the title bar area.
      }
    },
  );
}
```

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

| Specification |
| --- |
| Window Controls Overlay # windowcontrolsoverlay-interface |

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

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

See also
--------

* The Window Controls Overlay API.


Web Share API - Web APIs

Web Share API
=============

The **Web Share API** provides a mechanism for sharing text, links, files, and other content to an arbitrary *share target* selected by the user.

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

**Note:** This API is *not available* in Web Workers (not exposed via `WorkerNavigator`).

**Note:** This API should not be confused with the Web Share Target API, which allows a website to specify itself as a share target.

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

 The **Web Share API** allows a site to share text, links, files, and other content to user-selected share targets, utilizing the sharing mechanisms of the underlying operating system.
 These share targets typically include the system clipboard, email, contacts or messaging applications, and Bluetooth or Wi-Fi channels.

 The API has just two methods.
 The `navigator.canShare()` method may be used to first validate whether some data is "shareable", prior to passing it to `navigator.share()` for sending.

 The `navigator.share()` method invokes the native sharing mechanism of the underlying operating system and passes the specified data.
 It requires transient activation, and hence must be triggered off a UI event like a button click.
 Further, the method must specify valid data that is supported for sharing by the native implementation.

 The Web Share API is gated by the web-share Permissions Policy.
 If the policy is supported but has not been granted, both methods will indicate that the data is not shareable.

Interfaces
----------

`navigator.canShare()`

Returns a boolean indicating whether the specified data is shareable.

`navigator.share()`

 Returns a `Promise` that resolves if the passed data was successfully sent to a share target.
 This method must be called on a button click or other user activation (requires transient activation).

Example
-------

The code below shows how you can share a link using `navigator.share()`, triggered off a button click.

```js
const shareData = {
  title: "MDN",
  text: "Learn web development on MDN!",
  url: "https://developer.mozilla.org",
};

const btn = document.querySelector("button");
const resultPara = document.querySelector(".result");

// Share must be triggered by "user activation"
btn.addEventListener("click", async () => {
  try {
    await navigator.share(shareData);
    resultPara.textContent = "MDN shared successfully";
  } catch (err) {
    resultPara.textContent = `Error: ${err}`;
  }
});
```

The above example is taken from our Web share test (see the source code). You can also see this as a live example in `navigator.share()`.

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

| Specification |
| --- |
| Web Share API # share-method |
| Web Share API # canshare-data-method |

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

### api.Navigator.share

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

### api.Navigator.canShare

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

See also
--------

* Web Share Target API