KeyframeEffect - Web APIs

KeyframeEffect
==============

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 **`KeyframeEffect`** interface of the Web Animations API lets us create sets of animatable properties and values, called **keyframes.** These can then be played using the `Animation()` constructor.

AnimationEffect

KeyframeEffectConstructor
-----------

`KeyframeEffect()`

Returns a new `KeyframeEffect` object instance, and also allows you to clone an existing keyframe effect object instance.

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

`KeyframeEffect.target`

Gets and sets the element, or originating element of the pseudo-element, being animated by this object. This may be `null` for animations that do not target a specific element or pseudo-element.

`KeyframeEffect.pseudoElement`

Gets and sets the selector of the pseudo-element being animated by this object. This may be `null` for animations that do not target a pseudo-element.

`KeyframeEffect.iterationComposite`

Gets and sets the iteration composite operation for resolving the property value changes of this keyframe effect.

`KeyframeEffect.composite`

Gets and sets the composite operation property for resolving the property value changes between this and other keyframe effects.

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

*This interface inherits some of its methods from its parent, `AnimationEffect`.*

`AnimationEffect.getComputedTiming()`

Returns the calculated, current timing values for this keyframe effect.

`KeyframeEffect.getKeyframes()`

Returns the computed keyframes that make up this effect along with their computed keyframe offsets.

`AnimationEffect.getTiming()`

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

`KeyframeEffect.setKeyframes()`

Replaces the set of keyframes that make up this effect.

`AnimationEffect.updateTiming()`

Updates the specified timing properties.

Examples
--------

In the Follow the White Rabbit example, the KeyframeEffect constructor is used to create a set of keyframes that dictate how the White Rabbit should animate down the hole:

```js
const whiteRabbit = document.getElementById("rabbit");

const rabbitDownKeyframes = new KeyframeEffect(
  whiteRabbit, // element to animate
  [
    { transform: "translateY(0%)" }, // keyframe
    { transform: "translateY(100%)" }, // keyframe
  ],
  { duration: 3000, fill: "forwards" }, // keyframe options
);

const rabbitDownAnimation = new Animation(
  rabbitDownKeyframes,
  document.timeline,
);

// Play rabbit animation
rabbitDownAnimation.play();
```

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

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

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

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

See also
--------

* Web Animations API
* `Animation`


Web Video Text Tracks Format (WebVTT) - Web APIs

Web Video Text Tracks Format (WebVTT)
=====================================

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

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

* Learn more
* See full compatibility
* Report feedback
**Web Video Text Tracks Format** (**WebVTT**) is a format for displaying timed text tracks (such as subtitles or captions) using the `<track>` element. The primary purpose of WebVTT files is to add text overlays to a `<video>`. WebVTT is a text based format, which must be encoded using UTF-8. Where you can use spaces you can also use tabs. There is also a small API available to represent and manage these tracks and the data needed to perform the playback of the text at the correct times.

WebVTT files
------------

The MIME type of WebVTT is `text/vtt`.

A WebVTT file (`.vtt`) contains cues, which can be either a single line or multiple lines, as shown below:
```

WEBVTT

00:01.000 --> 00:04.000
- Never drink liquid nitrogen.

00:05.000 --> 00:09.000
- It will perforate your stomach.
- You could die.
```

WebVTT body
-----------

The structure of a WebVTT consists of the following components, some of them optional, in this order:

* An optional byte order mark (BOM).
* The string "`WEBVTT`".
* An optional text header to the right of `WEBVTT`.
    + There must be at least one space after `WEBVTT`.
    + You could use this to add a description to the file.
    + You may use anything in the text header except newlines or the string "`-->`".
* A blank line, which is equivalent to two consecutive newlines.
* Zero or more cues or comments.
* Zero or more blank lines.
### Examples

* Simplest possible WebVTT file
```

WEBVTT
```

* Very simple WebVTT file with a text header
```

WEBVTT - This file has no cues.
```

* Common WebVTT example with a header and cues
```

WEBVTT - This file has cues.

14
00:01:14.815 --> 00:01:18.114
- What?
- Where are we now?

15
00:01:18.171 --> 00:01:20.991
- This is big bat country.

16
00:01:21.058 --> 00:01:23.868
- [ Bats Screeching ]
- They won't get in your hair. They're after the bugs.
```

### Inner structure of a WebVTT file

Let's re-examine one of our previous examples, and look at the cue structure in a bit more detail.
```

WEBVTT

00:01.000 --> 00:04.000
- Never drink liquid nitrogen.

00:05.000 --> 00:09.000
- It will perforate your stomach.
- You could die.
```

In the case of each cue:

* The first line is started with a time, which is the starting time for showing the text that appears underneath.
* On the same line, we then have a string of "`-->`".
* We finish the first line with a second time, which is the ending time for showing the associated text.
* We can then have one or more lines that start with a hyphen (-), each containing part of the text track to be shown.

We can also place comments in our `.vtt` file, to help us remember important information about the parts of our file. These should be on separate lines, starting with the string `NOTE`. You'll find more about these in the below section.

It is important to not use "extra" blank lines within a cue, for example between the timings line and the cue payload. WebVTT is line based; a blank line will close the cue.

WebVTT comments
---------------

Comments are an optional component that can be used to add information to a WebVTT file. Comments are intended for those reading the file and are not seen by users. Comments may contain newlines but cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a comment.

A comment cannot contain the string `-->`, the ampersand character (`&`), or the less-than sign (`<`). If you wish to use such characters, you need to escape them using for example `&` for ampersand and `<` for less-than. It is also recommended that you use the greater-than escape sequence (`>`) instead of the greater-than character (`>`) to avoid confusion with tags.

A comment consists of three parts:

* The string `NOTE`.
* A space or a newline.
* Zero or more characters other than those noted above.
### Examples

* Common WebVTT example
```

NOTE This is a comment
```

* Multi-line comment
```

NOTE
One comment that is spanning
more than one line.

NOTE You can also make a comment
across more than one line this way.
```

* Common comment usage
```

WEBVTT - Translation of that film I like

NOTE
This translation was done by Kyle so that
some friends can watch it with their parents.

1
00:02:15.000 --> 00:02:20.000
- Ta en kopp varmt te.
- Det är inte varmt.

2
00:02:20.000 --> 00:02:25.000
- Har en kopp te.
- Det smakar som te.

NOTE This last line may not translate well.

3
00:02:25.000 --> 00:02:30.000
- Ta en kopp
```

Styling WebVTT cues
-------------------

You can style WebVTT cues by looking for elements which match the `::cue` pseudo-element.

### Within site CSS

```css
video::cue {
  background-image: linear-gradient(to bottom, dimgray, lightgray);
  color: papayawhip;
}

video::cue(b) {
  color: peachpuff;
}
```

Here, all video elements are styled to use a gray linear gradient as their backgrounds, with a foreground color of `"papayawhip"`. In addition, text boldfaced using the `<b>` element are colored `"peachpuff"`.

The HTML snippet below actually handles displaying the media itself.

```html
<video controls autoplay src="video.webm">
  <track default src="track.vtt" />
</video>
```

### Within the WebVTT file itself

You can also define the style directly in the WebVTT file. In this case, you insert your CSS rules into the file with each rule preceded by the string `"STYLE"` all by itself on a line of text, as shown below:
```

WEBVTT

STYLE
::cue {
  background-image: linear-gradient(to bottom, dimgray, lightgray);
  color: papayawhip;
}
/* Style blocks cannot use blank lines nor "dash dash greater than" */

NOTE comment blocks can be used between style blocks.

STYLE
::cue(b) {
  color: peachpuff;
}

00:00:00.000 --> 00:00:10.000
- Hello <b>world</b>.

NOTE style blocks cannot appear after the first cue.
```

We can also use identifiers inside WebVTT file, which can be used for defining a new style for some particular cues in the file. The example where we wanted the transcription text to be red highlighted and the other part to remain normal, we can define it as follows using CSS. Where it must be noted that the CSS uses escape sequences the way they are used in HTML pages:
```

WEBVTT

1
00:00.000 --> 00:02.000
That's an, an, that's an L!

crédit de transcription
00:04.000 --> 00:05.000
Transcrit par Célestes™
```

```css
::cue(#\31) {
  color: lime;
}
::cue(#crédit\ de\ transcription) {
  color: red;
}
```

Positioning of text tracks is also supported, by including positioning information after the timings in a cue, as seen below (see Cue settings for more information):
```

WEBVTT

00:00:00.000 --> 00:00:04.000 position:10%,line-left align:left size:35%
Where did he go?

00:00:03.000 --> 00:00:06.500 position:90% align:right size:35%
I think he went down this lane.

00:00:04.000 --> 00:00:06.500 position:45%,line-right align:center size:35%
What are you waiting for?
```

WebVTT cues
-----------

A cue is a single subtitle block that has a single start time, end time, and textual payload. A cue consists of five components:

* An optional cue identifier followed by a newline.
* Cue timings.
* Optional cue settings with at least one space before the first and between each setting.
* A single newline.
* The cue payload text.

Here is an example of a cue:
```

1 - Title Crawl
00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
Some time ago in a place rather distant....
```

### Cue identifier

The identifier is a name that identifies the cue. It can be used to reference the cue from a script. It must not contain a newline and cannot contain the string "`-->`". It must end with a single new line. They do not have to be unique, although it is common to number them (e.g., 1, 2, 3).

Here are a few examples:

* A basic cue identifier
```

1 - Title Crawl
```

* Common usage of identifiers
```

WEBVTT

1
00:00:22.230 --> 00:00:24.606
This is the first subtitle.

2
00:00:30.739 --> 00:00:34.074
This is the second.

3
00:00:34.159 --> 00:00:35.743
Third
```

### Cue timings

A cue timing indicates when the cue is shown. It has a start and end time which are represented by timestamps. The end time must be greater than the start time, and the start time must be greater than or equal to all previous start times. Cues may have overlapping timings.

If the WebVTT file is being used for chapters (`<track>` `kind` is `chapters`) then the file cannot have overlapping timings.

Each cue timing contains five components:

* Timestamp for start time.
* At least one space.
* The string "`-->`".
* At least one space.
* Timestamp for end time, which must be greater than the start time.

The timestamps must be in one of two formats:

* `mm:ss.ttt`
* `hh:mm:ss.ttt`

Where the components are defined as follows:

`hh`

Represents hours and must be at least two digits. It can be greater than two digits (e.g., `9999:00:00.000`).

`mm`

Represents minutes and must be between 00 and 59, inclusive.

`ss`

Represents seconds and must be between 00 and 59, inclusive.

`ttt`

Represents milliseconds and must be between 000 and 999, inclusive.

Here are a few cue timing examples:

* Basic cue timing examples
```

00:00:22.230 --> 00:00:24.606
00:00:30.739 --> 00:00:34.074
00:00:34.159 --> 00:00:35.743
00:00:35.827 --> 00:00:40.122
```

* Overlapping cue timing examples
```

00:00:00.000 --> 00:00:10.000
00:00:05.000 --> 00:01:00.000
00:00:30.000 --> 00:00:50.000
```

* Non-overlapping cue timing examples
```

00:00:00.000 --> 00:00:10.000
00:00:10.000 --> 00:01:00.581
00:01:00.581 --> 00:02:00.100
00:02:01.000 --> 00:02:01.000
```

### Cue settings

Cue settings are optional components used to position where the cue payload text will be displayed over the video. This includes whether the text is displayed horizontally or vertically. There can be zero or more of them, and they can be used in any order so long as each setting is used no more than once.

The cue settings are added to the right of the cue timings. There must be one or more spaces between the cue timing and the first setting and between each setting. A setting's name and value are separated by a colon. The settings are case sensitive so use lower case as shown. There are five cue settings:

`vertical`

Indicates that the text will be displayed vertically rather than horizontally, such as in some Asian languages. There are two possible values:

`rl`

The writing direction is right to left

`lr`

The writing direction is left to right

`line`

If vertical is not set, specifies where the text appears vertically. If vertical is set, line specifies where text appears horizontally. Its value can be:

a line number

The number is the height of the first line of the cue as it appears on the video. Positive numbers indicate top down and negative numbers indicate bottom up.

a percentage

It must be an integer (i.e., no decimals) between 0 and 100 inclusive and must be followed by a percent sign (%).

| Line | `vertical` omitted | `vertical:rl` | `vertical:lr` |
| --- | --- | --- | --- |
| `line:0` | top | right | left |
| `line:-1` | bottom | left | right |
| `line:0%` | top | right | left |
| `line:100%` | bottom | left | right |

`position`

Specifies where the text will appear horizontally. If vertical is set, position specifies where the text will appear vertically. The value is a percentage, that is an integer (no decimals) between 0 and 100 inclusive followed by a percent sign (%).

| Position | `vertical` omitted | `vertical:rl` | `vertical:lr` |
| --- | --- | --- | --- |
| `position:0%` | left | top | top |
| `position:100%` | right | bottom | bottom |

`size`

Specifies the width of the text area. If vertical is set, size specifies the height of the text area. The value is a percentage, that is an integer (no decimals) between 0 and 100 inclusive followed by a percent sign (%).

| Size | `vertical` omitted | `vertical:rl` | `vertical:lr` |
| --- | --- | --- | --- |
| `size:100%` | full width | full height | full height |
| `size:50%` | half width | half height | half height |

`align`

Specifies the alignment of the text. Text is aligned within the space given by the size cue setting if it is set.

| Align | `vertical` omitted | `vertical:rl` | `vertical:lr` |
| --- | --- | --- | --- |
| `align:start` | left | top | top |
| `align:center` | centered horizontally | centered vertically | centered vertically |
| `align:end` | right | bottom | bottom |

Let's study an example of cue setting.

The first line demonstrates no settings. The second line might be used to overlay text on a sign or label. The third line might be used for a title. The last line might be used for an Asian language.
```

00:00:05.000 --> 00:00:10.000
00:00:05.000 --> 00:00:10.000 line:63% position:72% align:start
00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
00:00:05.000 --> 00:00:10.000 vertical:rt line:-1 align:end
```

### Cue payload

The payload is where the main information or content is located. In normal usage the payload contains the subtitles to be displayed. The payload text may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a cue.

A cue text payload cannot contain the string `-->`, the ampersand character (`&`), or the less-than sign (`<`). Instead use the escape sequence `&` for ampersand and `<` for less-than. It is also recommended that you use the greater-than escape sequence `>` instead of the greater-than character (`>`) to avoid confusion with tags. If you are using the WebVTT file for metadata these restrictions do not apply.

In addition to the three escape sequences mentioned above, there are four others. They are listed in the table below.

| Name | Character | Escape sequence |
| --- | --- | --- |
| Ampersand | `&` | `&` |
| Less-than | `<` | `<` |
| Greater-than | `>` | `>` |
| Left-to-right mark | *none* | `` |
| Right-to-left mark | *none* | `` |
| Non-breaking space |  | ` ` |

### Cue payload text tags

There are a number of tags, such as `<b>`, that can be used. However, if the WebVTT file is used in a `<track>` element where the attribute `kind` is `chapters` then you cannot use tags.

Timestamp tag

The timestamp must be greater that the cue's start timestamp, greater than any previous timestamp in the cue payload, and less than the cue's end timestamp. The *active text* is the text between the timestamp and the next timestamp or to the end of the payload if there is not another timestamp in the payload. Any text before the *active text* in the payload is *previous text*. Any text beyond the *active text* is *future text*. This enables karaoke style captions.
```

1
00:16.500 --> 00:18.500
When the moon <00:17.500>hits your eye

1
00:00:18.500 --> 00:00:20.500
Like a <00:19.000>big-a <00:19.500>pizza <00:20.000>pie

1
00:00:20.500 --> 00:00:21.500
That's <00:00:21.000>amore
```

The following tags are the HTML tags allowed in a cue and require opening and closing tags (e.g., `<b>text</b>`).

Class tag (`<c></c>`)

Style the contained text using a CSS class.

```xml
<c.classname>text</c>
```

Italics tag (`<i></i>`)

Italicize the contained text.

```xml
<i>text</i>
```

Bold tag (`<b></b>`)

Bold the contained text.

```xml
<b>text</b>
```

Underline tag (`<u></u>`)

Underline the contained text.

```xml
<u>text</u>
```

Ruby tag (`<ruby></ruby>`)

Used with ruby text tags to display ruby characters (i.e., small annotative characters above other characters).

```xml
<ruby>WWW<rt>World Wide Web</rt>oui<rt>yes</rt></ruby>
```

Ruby text tag (`<rt></rt>`)

Used with ruby tags to display ruby characters (i.e., small annotative characters above other characters).

```xml
<ruby>WWW<rt>World Wide Web</rt>oui<rt>yes</rt></ruby>
```

Voice tag (`<v></v>`)

Similar to class tag, also used to style the contained text using CSS.

```xml
<v Bob>text</v>
```

Instance methods and properties
-------------------------------

The methods used in WebVTT are those which are used to alter the cue or region as the attributes for both interfaces are different. We can categorize them for better understanding relating to each interface in WebVTT:

### VTTCue

The methods which are available in the `VTTCue` interface are:

* `getCueAsHTML()` to get the HTML of that cue.
* A constructor, `VTTCue()` for creating new instances of this interface.

Different properties allowing to read and set the characteristics of the cue, like its position, alignment or size are also available. Check `VTTCue` for a complete list.

### VTTRegion

The `VTTRegion` provides methods used for region are listed below along with description of their functionality, especially it allows to adjust the scrolling setting of all nodes present in the given region.

Tutorial on how to write a WebVTT file
--------------------------------------

There are few steps that can be followed to write a simple webVTT file. Before start, it must be noted that you can make use of a notepad and then save the file as '.vtt' file. Steps are given below:

* Open a notepad.
* The first line of WebVTT is standardized similar to the way some other languages require you to put headers as the file starts to indicate the file type. On the very first line you have to write:
```

WEBVTT
```

* Leave the second line blank, and on the third line the time for first cue is to be specified. For example, for a first cue starting at time 1 second and ending at 5 seconds, it is written as:
```

00:01.000 --> 00:05.000
```

* On the next line you can write the caption for this cue which will run from the first second to the fifth second, inclusive.
* Following the similar steps, a complete WebVTT file for specific video or audio file can be made.
CSS pseudo-classes
------------------

CSS pseudo classes allow us to classify the type of object which we want to differentiate from other types of objects. It works in similar manner in WebVTT files as it works in HTML file.

It is one of the good features supported by WebVTT is the localization and use of class elements which can be used in same way they are used in HTML and CSS to classify the style for particular type of objects, but here these are used for styling and classifying the Cues as shown below:
```

WEBVTT

04:02.500 --> 04:05.000
J'ai commencé le basket à l'âge de 13, 14 ans

04:05.001 --> 04:07.800
Sur les <i.foreignphrase><lang en>playground</lang></i>, ici à Montpellier
```

In the above example it can be observed that we can use the identifier and pseudo class name for defining the language of caption, where `<i>` tag is for italics.

The type of pseudo class is determined by the selector it is using and working is similar in nature as it works in HTML. Following CSS pseudo classes can be used:

* `lang` (Language): e.g., `p:lang(it)`.
* `link`: e.g., `a:link`.
* `nth-last-child`: e.g., `p:nth-last-child(2)`.
* `nth-child(n)`: e.g., `p:nth-child(2)`.

Where p and a are the tags which are used in HTML for paragraph and link, respectively and they can be replaced by identifiers which are used for Cues in WebVTT file.

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

| Specification |
| --- |
| WebVTT: The Web Video Text Tracks Format # the-vttcue-interface |
| HTML Standard # texttrack |
| WebVTT: The Web Video Text Tracks Format # the-vttregion-interface |

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

### api.VTTCue

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

### api.TextTrack

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

### api.VTTRegion

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

### Notes

Prior to Firefox 50, the `AlignSetting` enum (representing possible values for `VTTCue.align`) incorrectly included the value `"middle"` instead of `"center"`. This has been corrected.

WebVTT was implemented in Firefox 24 behind the preference `media.webvtt.enabled`, which is disabled by default; you can enable it by setting this preference to `true`. WebVTT is enabled by default starting in Firefox 31 and can be disabled by setting the preference to `false`.

Prior to Firefox 58, the `REGION` keyword was creating `VTTRegion` objects, but they were not being used. Firefox 58 now fully supports `VTTRegion` and its use; however, this feature is disabled by default behind the preference `media.webvtt.regions.enabled`; set it to `true` to enable region support in Firefox 58. Regions are enabled by default starting in Firefox 59 (see bugs Firefox bug 1338030 and Firefox bug 1415805).

See also
--------

* The CSS `::cue` and `::cue()` pseudo-elements


DynamicsCompressorNode - Web APIs

DynamicsCompressorNode
======================

The `DynamicsCompressorNode` interface provides a compression effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once. This is often used in musical production and game audio. `DynamicsCompressorNode` is an `AudioNode` that has exactly one input and one output.

EventTarget

AudioNode

DynamicsCompressorNode

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

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

`DynamicsCompressorNode()`

Creates a new instance of an `DynamicsCompressorNode` object.

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

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

`DynamicsCompressorNode.threshold` Read only

A k-rate `AudioParam` representing the decibel value above which the compression will start taking effect.

`DynamicsCompressorNode.knee` Read only

A k-rate `AudioParam` containing a decibel value representing the range above the threshold where the curve smoothly transitions to the compressed portion.

`DynamicsCompressorNode.ratio` Read only

A k-rate `AudioParam` representing the amount of change, in dB, needed in the input for a 1 dB change in the output.

`DynamicsCompressorNode.reduction` Read only

A `float` representing the amount of gain reduction currently applied by the compressor to the signal.

`DynamicsCompressorNode.attack` Read only

A k-rate `AudioParam` representing the amount of time, in seconds, required to reduce the gain by 10 dB.

`DynamicsCompressorNode.release` Read only

A k-rate `AudioParam` representing the amount of time, in seconds, required to increase the gain by 10 dB.

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

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

Example
-------

See `BaseAudioContext.createDynamicsCompressor()` example code.

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

| Specification |
| --- |
| Web Audio API # DynamicsCompressorNode |

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

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

See also
--------

* Using the Web Audio API


GPUComputePassEncoder - Web APIs

GPUComputePassEncoder
=====================

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

The **`GPUComputePassEncoder`** interface of the WebGPU API encodes commands related to controlling the compute shader stage, as issued by a `GPUComputePipeline`. It forms part of the overall encoding activity of a `GPUCommandEncoder`.

A compute pipeline contains a single compute stage in which a compute shader takes general data, processes it in parallel across a specified number of workgroups, then returns the result in one or more buffers.

A `GPUComputePassEncoder` object instance is created via the `GPUCommandEncoder.beginComputePass()` property.

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

`label`
Experimental

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

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

`dispatchWorkgroups()`
Experimental

Dispatches a specific grid of workgroups to perform the work being done by the current `GPUComputePipeline`.

`dispatchWorkgroupsIndirect()`
Experimental

Dispatches a grid of workgroups, defined by the parameters of a `GPUBuffer`, to perform the work being done by the current `GPUComputePipeline`.

`end()`
Experimental

Completes recording of the current compute pass command sequence.

`insertDebugMarker()`
Experimental

Marks a specific point in a series of encoded commands with a label.

`popDebugGroup()`
Experimental

Ends a debug group, which is begun with a `pushDebugGroup()` call.

`pushDebugGroup()`
Experimental

Begins a debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a `popDebugGroup()` method is invoked.

`setBindGroup()`
Experimental

Sets the `GPUBindGroup` to use for subsequent compute commands, for a given index.

`setPipeline()`
Experimental

Sets the `GPUComputePipeline` to use for this compute pass.

Examples
--------

In our basic compute demo, several commands are recorded via a `GPUCommandEncoder`. Most of these commands originate from the `GPUComputePassEncoder` created via `GPUCommandEncoder.beginComputePass()`.

```js
// ...

// Create GPUCommandEncoder to encode commands to issue to the GPU
const commandEncoder = device.createCommandEncoder();

// Create GPUComputePassEncoder to initiate compute pass
const passEncoder = commandEncoder.beginComputePass();

// Issue commands
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatchWorkgroups(Math.ceil(BUFFER\_SIZE / 64));

// End the compute pass
passEncoder.end();

// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
  output,
  0, // Source offset
  stagingBuffer,
  0, // Destination offset
  BUFFER\_SIZE,
);

// End frame by passing array of command buffers to command queue for execution
device.queue.submit([commandEncoder.finish()]);

// ...
```

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

| Specification |
| --- |
| WebGPU # gpucomputepassencoder |

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

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

See also
--------

* The WebGPU API


XRSpace - Web APIs

XRSpace
=======

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

The **`XRSpace`** interface of the WebXR Device API is an abstract interface providing a common basis for every class which represents a virtual coordinate system within the virtual world, in which its origin corresponds to a physical location. Spatial data in WebXR is always expressed relative to an object based upon one of the descendant interfaces of `XRSpace`, at the time at which a given `XRFrame` takes place.

Numeric values such as pose positions are thus coordinates in the corresponding `XRSpace`, relative to that space's origin.

**Note:** The `XRSpace` interface is never used directly; instead, all spaces are created using one of the interfaces based on `XRSpace`. At this time, those are `XRReferenceSpace`, `XRBoundedReferenceSpace`, and `XRJointSpace`.

EventTarget

XRSpaceInterfaces based on XRSpace
---------------------------

Below is a list of interfaces based on the `XRSpace` interface.

`XRBoundedReferenceSpace`

Represents a reference space which may move within a region of space whose borders are defined by an array of points laid out in clockwise order along the floor to define the passable region of the space. The origin of an `XRBoundedReferenceSpace` is always at floor level, with its X and Z coordinates typically defaulting to a location near the room's center.

`XRReferenceSpace`

Represents a reference space which is typically expected to remain static for the duration of the `XRSession`. While objects may move within the space, the space itself remains fixed in place. There are exceptions to this static nature; most commonly, an `XRReferenceSpace` may move in order to adjust based on reconfiguration of the user's headset or other motion-sensitive device.

`XRJointSpace`

Represents the space of an `XRHand` joint.

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

*The `XRSpace` interface defines no properties of its own; however, it does inherit the properties of its parent interface, `EventTarget`.*

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

*The `XRSpace` interface provides no methods of its own. However, it inherits the methods of `EventTarget`, its parent interface.*

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

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

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

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


HTMLCanvasElement - Web APIs

HTMLCanvasElement
=================

The **`HTMLCanvasElement`** interface provides properties and methods for manipulating the layout and presentation of `<canvas>` elements. The `HTMLCanvasElement` interface also inherits the properties and methods of the `HTMLElement` interface.

EventTarget

Node

Element

HTMLElement

HTMLCanvasElementInstance properties
-------------------

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

`HTMLCanvasElement.height`

The `height` HTML attribute of the `<canvas>` element is a non-negative `integer` reflecting the number of logical pixels (or RGBA values) going down one column of the canvas. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of `150` is used. If no [separate] CSS height is assigned to the `<canvas>`, then this value will also be used as the height of the canvas in the length-unit CSS Pixel.

`HTMLCanvasElement.width`

The `width` HTML attribute of the `<canvas>` element is a non-negative `integer` reflecting the number of logical pixels (or RGBA values) going across one row of the canvas. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of `300` is used. If no [separate] CSS width is assigned to the `<canvas>`, then this value will also be used as the width of the canvas in the length-unit CSS Pixel.

`HTMLCanvasElement.mozOpaque`
Non-standard

Deprecated

A boolean value reflecting the `moz-opaque` HTML attribute of the `<canvas>` element. It lets the canvas know whether or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This is only supported in Mozilla-based browsers; use the standardized `canvas.getContext('2d', { alpha: false })` instead.

`HTMLCanvasElement.mozPrintCallback`
Non-standard

A `function` that is Initially null. Web content can set this to a JavaScript function that will be called when the canvas is to be redrawn while the page is being printed. When called, the callback is passed a "printState" object that implements the MozCanvasPrintState interface. The callback can get the context to draw to from the printState object and must then call done() on it when finished. The purpose of `mozPrintCallback` is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. See this blog post.

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

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

`HTMLCanvasElement.captureStream()`

Returns a `CanvasCaptureMediaStreamTrack` that is a real-time video capture of the surface of the canvas.

`HTMLCanvasElement.getContext()`

Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. Calling getContext with `"2d"` returns a `CanvasRenderingContext2D` object, whereas calling it with `"webgl"` (or `"experimental-webgl"`) returns a `WebGLRenderingContext` object. This context is only available on browsers that implement WebGL.

`HTMLCanvasElement.toDataURL()`

Returns a data-URL containing a representation of the image in the format specified by the `type` parameter (defaults to `png`). The returned image is in a resolution of 96dpi.

`HTMLCanvasElement.toBlob()`

Creates a `Blob` object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.

`HTMLCanvasElement.transferControlToOffscreen()`

Transfers control to an `OffscreenCanvas` object, either on the main thread or on a worker.

Events
------

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

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

`contextlost`
Experimental

Fired if the user agent detects that the backing storage associated with a `CanvasRenderingContext2D` or an `OffscreenCanvasRenderingContext2D` context has been lost.

`contextrestored`
Experimental

Fired if the user agent successfully restores a `CanvasRenderingContext2D` or an `OffscreenCanvasRenderingContext2D` context.

`webglcontextcreationerror`

Fired if the user agent is unable to create a `WebGLRenderingContext` or `WebGL2RenderingContext` context.

`webglcontextlost`

Fired if the user agent detects that the drawing buffer associated with a `WebGLRenderingContext` or `WebGL2RenderingContext` object has been lost.

`webglcontextrestored`

Fired if the user agent restores the drawing buffer for a `WebGLRenderingContext` or `WebGL2RenderingContext` object.

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

| Specification |
| --- |
| HTML Standard # htmlcanvaselement |

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

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

See also
--------

* HTML element implementing this interface: `<canvas>`


ImageData - Web APIs

ImageData
=========

The **`ImageData`** interface represents the underlying pixel data of an area of a `<canvas>` element.

It is created using the `ImageData()` constructor or creator methods on the `CanvasRenderingContext2D` object associated with a canvas: `createImageData()` and `getImageData()`. It can also be used to set a part of the canvas by using `putImageData()`.

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

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

`ImageData()`

Creates an `ImageData` object from a given `Uint8ClampedArray` and the size of the image it contains. If no array is given, it creates an image of a transparent black rectangle. Note that this is the most common way to create such an object in workers as `createImageData()` is not available there.

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

`ImageData.data` Read only

A `Uint8ClampedArray` representing a one-dimensional array containing the data in the RGBA order, with integer values between `0` and `255` (inclusive). The order goes by rows from the top-left pixel to the bottom-right.

`ImageData.colorSpace` Read only

A string indicating the color space of the image data.

`ImageData.height` Read only

An `unsigned long` representing the actual height, in pixels, of the `ImageData`.

`ImageData.width` Read only

An `unsigned long` representing the actual width, in pixels, of the `ImageData`.

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

| Specification |
| --- |
| HTML Standard # imagedata |

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

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

See also
--------

* `CanvasRenderingContext2D`
* The `<canvas>` element and its associated interface, `HTMLCanvasElement`.


ImageTrack - Web APIs

ImageTrack
==========

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 **`ImageTrack`** interface of the WebCodecs API represents an individual image track.

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

`ImageTrack.animated` Read only
Experimental

Returns a `boolean` indicating whether the track is animated and therefore has multiple frames.

`ImageTrack.frameCount` Read only
Experimental

Returns an integer indicating the number of frames in the track.

`ImageTrack.repetitionCount` Read only
Experimental

Returns an integer indicating the number of times that the animation repeats.

`ImageTrack.selected` Read only
Experimental

Returns a `boolean` indicating whether the track is selected for decoding.

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

| Specification |
| --- |
| WebCodecs # imagetrack-interface |

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

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


PaymentMethodChangeEvent - Web APIs

PaymentMethodChangeEvent
========================

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

The **`PaymentMethodChangeEvent`** interface of the Payment Request API describes the `paymentmethodchange` event which is fired by some payment handlers when the user switches payment instruments (e.g., a user selects a "store" card to make a purchase while using Apple Pay).

Event

PaymentRequestUpdateEvent

PaymentMethodChangeEventConstructor
-----------

`PaymentMethodChangeEvent()`

Creates and returns a new `PaymentMethodChangeEvent` object.

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

*In addition to the properties below, this interface includes properties inherited from `PaymentRequestUpdateEvent`.*

`methodDetails` Read only

An object containing payment method-specific data useful when handling a payment method change. If no such information is available, this value is `null`.

`methodName` Read only

A string containing the payment method identifier, a string which uniquely identifies a particular payment method. This identifier is usually a URL used during the payment process, but may be a standardized non-URL string as well, such as `basic-card`. The default value is the empty string, `""`.

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

*This interface includes methods inherited from `PaymentRequestUpdateEvent`.*

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

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

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

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


SVGAnimatedBoolean - Web APIs

SVGAnimatedBoolean
==================

SVG animated boolean interface
------------------------------

The `SVGAnimatedBoolean` interface is used for attributes of type boolean which can be animated.

### Interface overview

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

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

| Name | Type | Description |
| --- | --- | --- |
| `baseVal` | boolean | The base value of the given attribute before applying any animations. |
| `animVal` | boolean |
 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 `SVGAnimatedBoolean` interface do not provide any specific methods.

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

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


Permissions - Web APIs

Permissions
===========

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

The Permissions interface of the Permissions API provides the core Permission API functionality, such as methods for querying and revoking permissions

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

`Permissions.query()`

Returns the user permission status for a given API.

`Permissions.request()`
Experimental

Requests permission to use a given API. This is not currently supported in any browser.

`Permissions.requestAll()`
Experimental

Non-standard

Requests permission to use a given set of APIs. This is not currently supported in any browser.

`Permissions.revoke()`
Deprecated

Revokes the permission currently set on a given API.

Example
-------

```js
navigator.permissions.query({ name: "geolocation" }).then((result) => {
  if (result.state === "granted") {
    showLocalNewsWithGeolocation();
  } else if (result.state === "prompt") {
    showButtonToEnableLocalNews();
  }
  // Don't do anything if the permission was denied.
});
```

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

| Specification |
| --- |
| Permissions # permissions-interface |

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

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


XRAnchor - Web APIs

XRAnchor
========

**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 **`XRAnchor`** interface creates anchors which keep track of the pose that is fixed relative to the real world. With anchors, you can specify poses in the world that need to be updated to correctly reflect the evolving understanding of the world, such that the poses remain aligned with the same place in the physical world. That helps to build an illusion that the placed objects are really present in the user's environment.

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

`XRAnchor.anchorSpace` Read only
Experimental

Returns an `XRSpace` object to locate the anchor relative to other `XRSpace` objects.

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

`XRAnchor.delete()`
Experimental

Removes the anchor.

Examples
--------

### Requesting a session with anchors enabled

```js
navigator.xr.requestSession("immersive-ar", {
  requireFeatures: ["anchors"],
});
```

### Adding anchors

You can use `XRFrame.createAnchor()` to create an anchor.

```js
frame.createAnchor(anchorPose, referenceSpace).then(
  (anchor) => {
    // Do stuff with the anchor (assign objects that will be relative to this anchor)
  },
  (error) => {
    console.error(`Could not create anchor: ${error}`);
  },
);
```

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

| Specification |
| --- |
| WebXR Anchors Module # xr-anchor |

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

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

See also
--------

* `XRAnchorSet`
* `XRFrame.createAnchor()`
* `XRFrame.trackedAnchors`
* `XRHitTestResult.createAnchor()`


HTMLParagraphElement - Web APIs

HTMLParagraphElement
====================

The **`HTMLParagraphElement`** interface provides special properties (beyond those of the regular `HTMLElement` object interface it inherits) for manipulating `<p>` elements.

EventTarget

Node

Element

HTMLElement

HTMLParagraphElementInstance properties
-------------------

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

`HTMLParagraphElement.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 methods, inherits methods from its parent, `HTMLElement`.*

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

| Specification |
| --- |
| HTML Standard # htmlparagraphelement |

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


MediaError - Web APIs

MediaError
==========

The **`MediaError`** interface represents an error which occurred while handling media in an HTML media element based on `HTMLMediaElement`, such as `<audio>` or `<video>`.

A `MediaError` object describes the error in general terms using a numeric `code` categorizing the kind of error, and a `message`, which provides specific diagnostics about what went wrong.

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

*This interface doesn't inherit any properties.*

`MediaError.code`

A number which represents the general type of error that occurred.

`MediaError.message`

A human-readable string which provides *specific diagnostic information* to help the reader understand the error condition which occurred; specifically, it isn't a summary of what the error code means, but actual diagnostic information to help in understanding what exactly went wrong. This text and its format is not defined by the specification and will vary from one user agent to another. If no diagnostics are available, or no explanation can be provided, this value is an empty string (`""`).

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

*This interface doesn't implement or inherit any methods, and has none of its own.*

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

| Specification |
| --- |
| HTML Standard # error-codes |

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

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

See also
--------

* `HTMLMediaElement.error`


MouseScrollEvent - Web APIs

MouseScrollEvent
================

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

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

The **`MouseScrollEvent`** interface represents events that occur due to the user moving a mouse wheel or similar input device.

**Warning:** Do not use this interface for wheel events.

Like `MouseWheelEvent`, this interface is non-standard and deprecated. It was used in Gecko-based browsers only. Instead use the standard *`WheelEvent`.*

Method overview
---------------

```webidl
void initMouseScrollEvent(
  in DOMString typeArg,
  in boolean canBubbleArg,
  in boolean cancelableArg,
  in nsIDOMAbstractView viewArg,
  in long detailArg,
  in long screenXArg,
  in long screenYArg,
  in long clientXArg,
  in long clientYArg,
  in boolean ctrlKeyArg,
  in boolean altKeyArg,
  in boolean shiftKeyArg,
  in boolean metaKeyArg,
  in unsigned short buttonArg,
  in nsIDOMEventTarget relatedTargetArg,
  in long axis);
```

Attributes
----------

| Attribute | Type | Description |
| --- | --- | --- |
| `axis` Read only  | `long` | Indicates scroll direction. |

Constants
---------

### Delta modes

| Constant | Value | Description |
| --- | --- | --- |
| `HORIZONTAL_AXIS` | `0x01` | The event is caused by horizontal wheel operation. |
| `VERTICAL_AXIS` | `0x02` | The event is caused by vertical wheel operation. |

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

`initMouseScrollEvent()`

See `nsIDOMMouseScrollEvent::initMouseScrollEvent()`.

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

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

See also
--------

* `DOMMouseScroll`
* `MozMousePixelScroll`
* Standardized mouse wheel event object: `WheelEvent`


HTMLBRElement - Web APIs

HTMLBRElement
=============

The **`HTMLBRElement`** interface represents an HTML line break element (`<br>`). It inherits from `HTMLElement`.

EventTarget

Node

Element

HTMLElement

HTMLBRElementInstance properties
-------------------

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

`HTMLBRElement.clear`
Deprecated

A string indicating the flow of text around floating objects.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlbrelement |

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

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

See also
--------

* HTML element implementing this interface: `<br>`


XRMediaBinding - Web APIs

XRMediaBinding
==============

**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 **`XRMediaBinding`** interface is used to create layers that display the content of an `HTMLVideoElement`.

**Note:**
 Only the video frames will be displayed in the layer. Video controls need to be implemented separately and must be drawn in another layer.

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

`XRMediaBinding()`
Experimental

Creates a new `XRMediaBinding` object for the specified `XRSession`.

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

`XRMediaBinding.createCylinderLayer()`
Experimental

Returns an `XRCylinderLayer` object bound to an `HTMLVideoElement`.

`XRMediaBinding.createEquirectLayer()`
Experimental

Returns an `XREquirectLayer` object bound to an `HTMLVideoElement`.

`XRMediaBinding.createQuadLayer()`
Experimental

Returns an `XRQuadLayer` object bound to an `HTMLVideoElement`.

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

| Specification |
| --- |
| WebXR Layers API Level 1 # XRWebGLBindingtype |

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

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

See also
--------

* `HTMLVideoElement`
* `XRCylinderLayer`, `XREquirectLayer`, `XRQuadLayer`


HID - Web APIs

HID
===

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 **`HID`** interface provides methods for connecting to *HID devices*, listing attached HID devices and event handlers for connected HID devices.

EventTarget

HIDInstance properties
-------------------

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

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

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

`getDevices()`
Experimental

Returns a `Promise` that resolves with an array of connected `HIDDevice` objects.

`requestDevice()`
Experimental

Returns a `Promise` that resolves with an array of connected `HIDDevice` objects. Calling this function will trigger the user agent's permission flow in order to gain permission to access one selected device from the returned list of devices.

### Events

`connect`
Experimental

Fired when an HID device is connected.

`disconnect`
Experimental

Fired when an HID device is disconnected.

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

| Specification |
| --- |
| WebHID API # dom-hid |

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

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

See also
--------

* `WebHID API`


Web NFC API - Web APIs

Web NFC API
===========

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

The Web NFC API allows exchanging data over NFC via light-weight NFC Data Exchange Format (NDEF) messages.

**Note:** Devices and tags have to be formatted and recorded specifically to support NDEF record format to be used with Web NFC. Low-level operations are currently not supported by the API, however there is a public discussion about API that would add such functionality.

Interfaces
----------

`NDEFMessage`

Interface that represents NDEF messages that can be received from or sent to a compatible tag via a `NDEFReader` object. A message is composed of metadata and NDEF Records.

`NDEFReader`
Experimental

Interface that enables reading and writing messages from compatible NFC tags. The messages are represented as `NDEFMessage` objects.

`NDEFRecord`

Interface that represents NDEF records that can be included in an NDEF message.

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

| Specification |
| --- |
| Web NFC API # the-ndefreader-object |

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

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


HTMLTextAreaElement - Web APIs

HTMLTextAreaElement
===================

The **`HTMLTextAreaElement`** interface provides special properties and methods for manipulating the layout and presentation of `<textarea>` elements.

EventTarget

Node

Element

HTMLElement

HTMLTextAreaElementInstance properties
-------------------

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

`autocapitalize`

A string that represents the element's capitalization behavior for user input. Valid values are: `none`, `off`, `characters`, `words`, `sentences`.

`autocomplete`

A string that represents the element's `autocomplete` attribute.

`cols`

A number that represents the element's `cols` attribute, indicating the visible width of the text area.

`defaultValue`

A string that represents the control's default value, which behaves like the `Node.textContent` property.

`dirName`

A string that represents the directionality of the element.

`disabled`

A boolean that represents the element's `disabled` attribute, indicating that the control is not available for interaction.

`form` Read only

Returns a reference to the parent form element. If this element is not contained in a form element, it can be the `id` attribute of any `<form>` element in the same document or the value `null`.

`labels` Read only

Returns a `NodeList` of the `<label>` elements associated with this element.

`maxLength`

A number that represents the element's `maxlength` attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes.

`minLength`

A number that represents the element's `minlength` attribute, indicating the minimum number of characters the user can enter. This constraint is evaluated only when the value changes.

`name`

A string that represents the element's `name` attribute, containing the name of the control.

`placeholder`

A string that represents the element's `placeholder` attribute, containing a hint to the user about what to enter in the control.

`readOnly`

A boolean that represents the element's `readonly` attribute, indicating that the user cannot modify the value of the control.

`required`

A boolean that represents the element's `required` attribute, indicating that the user must specify a value before submitting the form.

`rows`

A number that represents the element's `rows` attribute, indicating the number of visible text lines for the control.

`selectionDirection`

A string that represents the direction in which selection occurred. This is `forward` if selection was performed in the start-to-end direction of the current locale, or `backward` for the opposite direction. This can also be `none` if the direction is unknown.

`selectionEnd`

A number that represents the index of the end of selected text. If no text is selected, it contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the second argument, and `selectionStart` as the first argument.

`selectionStart`

A number that represents the index of the beginning of selected text. If no text is selected, it contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the first argument and `selectionEnd` as the second argument.

`textLength` Read only

Returns the code point length of the control's `value`. Same as reading `value.length`.

`type` Read only

Returns the string `textarea`.

`validationMessage` Read only

Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints.

`validity` Read only

Returns the validity state that this element is in.

`value`

A string that represents the raw value contained in the control.

`willValidate` Read only

Returns whether the element is a candidate for constraint validation. `false` if any conditions bar it from constraint validation, including its `readOnly` or `disabled` property is `true`.

`wrap`

A string that represents the element's `wrap` attribute, indicating how the control wraps text.

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

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

`checkValidity()`

Returns `false` if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelable `invalid` event at the control. It returns `true` if the control is not a candidate for constraint validation, or if it satisfies its constraints.

`reportValidity()`

This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable `invalid` event at the element, and returns `false`; if there are no problems, it returns `true`.

`select()`

Selects the contents of the control.

`setCustomValidity()`

Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.

`setRangeText()`

Replaces a range of text in the element with new text.

`setSelectionRange()`

Selects a range of text in the element (but does not focus it).

Events
------

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

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

`select` event

Fires when some text has been selected.

`selectionchange` event
Experimental

Fires when the text selection in a `<textarea>` element has been changed.

Examples
--------

### Autogrowing textarea example

Make a textarea autogrow while typing:

#### JavaScript

```js
function autoGrow(oField) {
  if (oField.scrollHeight > oField.clientHeight) {
    oField.style.height = `${oField.scrollHeight}px`;
  }
}
```

#### CSS

```css
textarea.noscrollbars {
  overflow: hidden;
  width: 300px;
  height: 100px;
}
```

#### HTML

```html
<form>
  <fieldset>
    <legend>Your comments</legend>
    <p><textarea class="noscrollbars" onkeyup="autoGrow(this);"></textarea></p>
    <p><input type="submit" value="Send" /></p>
  </fieldset>
</form>
```

### Insert HTML tags example

Insert some HTML tags in a textarea.

#### JavaScript

```js
function insert(startTag, endTag) {
  const textArea = document.myForm.myTxtArea;
  const selectionStart = textArea.selectionStart;
  const selectionEnd = textArea.selectionEnd;
  const oldText = textArea.value;

  const prefix = oldText.substring(0, selectionStart);
  const inserted =
    startTag + oldText.substring(selectionStart, selectionEnd) + endTag;
  const suffix = oldText.substring(selectionEnd);
  textArea.value = `${prefix}${inserted}${suffix}`;

  const newSelectionStart = selectionStart + startTag.length;
  const newSelectionEnd = selectionEnd + startTag.length;
  textArea.setSelectionRange(newSelectionStart, newSelectionEnd);

  textArea.focus();
}

function insertURL() {
  const newURL = prompt("Enter the full URL for the link");
  if (newURL) {
    insert(`<a href="${newURL}">`, "</a>");
  } else {
    document.myForm.myTxtArea.focus();
  }
}

const strong = document.querySelector("#format-strong");
const em = document.querySelector("#format-em");
const link = document.querySelector("#format-link");
const code = document.querySelector("#format-code");

strong.addEventListener("click", (e) => insert("<strong>", "</strong>"));
em.addEventListener("click", (e) => insert("<em>", "</em>"));
link.addEventListener("click", (e) => insertURL());
code.addEventListener("click", (e) => insert("\n<code>\n", "\n</code>\n"));
```

#### CSS

CSS to decorate the internal span to behave like a link:

```css
.intLink {
  cursor: pointer;
  text-decoration: underline;
  color: #0000ff;
}
```

HTML:

```html
<form name="myForm">
  <p>
    [
    <span class="intLink" id="format-strong"><strong>Bold</strong></span> |
    <span class="intLink" id="format-em"><em>Italic</em></span> |
    <span class="intLink" id="format-link">URL</span> |
    <span class="intLink" id="format-code">code</span>  ]
  </p>

  <p>
    <textarea name="myTxtArea" rows="10" cols="50">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut facilisis, arcu vitae adipiscing placerat, nisl lectus accumsan nisi, vitae iaculis sem neque vel lectus. Praesent tristique commodo lorem quis fringilla. Sed ac tellus eros. Sed consectetur eleifend felis vitae luctus. Praesent sagittis, est eget bibendum tincidunt, ligula diam tincidunt augue, a fermentum odio velit eget mi. Phasellus mattis, elit id fringilla semper, orci magna cursus ligula, non venenatis lacus augue sit amet dui. Pellentesque lacinia odio id nisi pulvinar commodo tempus at odio. Ut consectetur eros porttitor nunc mollis ultrices. Aenean porttitor, purus sollicitudin viverra auctor, neque erat blandit sapien, sit amet tincidunt massa mi ac nibh. Proin nibh sem, bibendum ut placerat nec, cursus et lacus. Phasellus vel augue turpis. Nunc eu mauris eu leo blandit mollis interdum eget lorem.
    </textarea>
  </p>
</form>
```

### Maximum length and number of lines example

Create a textarea with a maximum number of characters per line and a maximum number of lines:

First, create a function that takes the text field and a key event as input and determines if any of the limits have been reached. If the limit has not been reached, it will return the key.

```js
function checkRows(oField, oKeyEvent) {
  let nKey = (
      oKeyEvent ||
      /\* old IE \*/ window.event || /\* check is not supported! \*/ { keyCode: 38 }
    ).keyCode,
    // put here the maximum number of characters per line:
    nCols = 30,
    // put here the maximum number of lines:
    nRows = 5,
    nSelS = oField.selectionStart,
    nSelE = oField.selectionEnd,
    sVal = oField.value,
    nLen = sVal.length,
    nBackward = nSelS >= nCols ? nSelS - nCols : 0,
    nDeltaForw =
      sVal
        .substring(nBackward, nSelS)
        .search(new RegExp(`\\n(?!.{0,${String(nCols - 2)}}\\n)`)) + 1,
    nRowStart = nBackward + nDeltaForw,
    aReturns = (
      sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)
    ).match(/\n/g),
    nRowEnd = nSelE + nRowStart + nCols - nSelS,
    sRow =
      sVal.substring(nRowStart, nSelS) +
      sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd),
    bKeepCols =
      nKey === 13 ||
      nLen + 1 < nCols ||
      /\n/.test(sRow) ||
      ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) &&
        (sRow.length < nCols ||
          (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n"))));

  return (
    (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) &&
    ((nKey > 32 && nKey < 41) || bKeepCols)
  );
}
```

In the HTML we just need to hook our function to the `onkeypress` event and specify that our textarea does not accept pasting:

```html
<form>
  <p>
    Textarea with fixed number of characters per line:<br />
    <textarea
 cols="50"
 rows="10"
 onkeypress="return checkRows(this, event);"
 onpaste="return false;"></textarea>
  </p>
</form>
```

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

| Specification |
| --- |
| HTML Standard # htmltextareaelement |

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

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


Event - Web APIs

Event
=====

The **`Event`** interface represents an event which takes place in the DOM.

An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the `HTMLElement.click()` method of an element, or by defining the event, then sending it to a specified target using `EventTarget.dispatchEvent()`.

There are many types of events, some of which use other interfaces based on the main `Event` interface. `Event` itself contains the properties and methods which are common to all events.

Many DOM elements can be set up to accept (or "listen" for) these events, and execute code in response to process (or "handle") them. Event-handlers are usually connected (or "attached") to various HTML elements (such as `<button>`, `<div>`, `<span>`, etc.) using `EventTarget.addEventListener()`, and this generally replaces using the old HTML event handler attributes. Further, when properly added, such handlers can also be disconnected if needed using `removeEventListener()`.

**Note:** One element can have several such handlers, even for the exact same event—particularly if separate, independent code modules attach them, each for its own independent purposes. (For example, a webpage with an advertising-module and statistics-module both monitoring video-watching.)

When there are many nested elements, each with its own handler(s), event processing can become very complicated—especially where a parent element receives the very same event as its child elements because "spatially" they overlap so the event technically occurs in both, and the processing order of such events depends on the Event bubbling and capture settings of each handler triggered.

Interfaces based on Event
-------------------------

Below is a list of interfaces which are based on the main `Event` interface, with links to their respective documentation in the MDN API reference.

Note that all event interfaces have names which end in "Event".

* `AnimationEvent`
* `AudioProcessingEvent`
Deprecated
* `BeforeUnloadEvent`
* `BlobEvent`
* `ClipboardEvent`
* `CloseEvent`
* `CompositionEvent`
* `CustomEvent`
* `DeviceMotionEvent`
* `DeviceOrientationEvent`
* `DragEvent`
* `ErrorEvent`
* `FetchEvent`
* `FocusEvent`
* `FontFaceSetLoadEvent`
* `FormDataEvent`
* `GamepadEvent`
* `HashChangeEvent`
* `HIDInputReportEvent`
* `IDBVersionChangeEvent`
* `InputEvent`
* `KeyboardEvent`
* `MediaStreamEvent`
Deprecated
* `MessageEvent`
* `MouseEvent`
* `MutationEvent`
Deprecated
* `OfflineAudioCompletionEvent`
* `PageTransitionEvent`
* `PaymentRequestUpdateEvent`
* `PointerEvent`
* `PopStateEvent`
* `ProgressEvent`
* `RTCDataChannelEvent`
* `RTCPeerConnectionIceEvent`
* `StorageEvent`
* `SubmitEvent`
* `SVGEvent`
Deprecated
* `TimeEvent`
* `TouchEvent`
* `TrackEvent`
* `TransitionEvent`
* `UIEvent`
* `WebGLContextEvent`
* `WheelEvent`
Constructor
-----------

`Event()`

Creates an `Event` object, returning it to the caller.

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

`Event.bubbles` Read only

A boolean value indicating whether or not the event bubbles up through the DOM.

`Event.cancelable` Read only

A boolean value indicating whether the event is cancelable.

`Event.composed` Read only

A boolean indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM.

`Event.currentTarget` Read only

A reference to the currently registered target for the event. This is the object to which the event is currently slated to be sent. It's possible this has been changed along the way through *retargeting*.

`Event.defaultPrevented` Read only

Indicates whether or not the call to `event.preventDefault()` canceled the event.

`Event.eventPhase` Read only

Indicates which phase of the event flow is being processed. It is one of the following numbers: `NONE`, `CAPTURING_PHASE`, `AT_TARGET`, `BUBBLING_PHASE`.

`Event.isTrusted` Read only

Indicates whether or not the event was initiated by the browser (after a user click, for instance) or by a script (using an event creation method, for example).

`Event.target` Read only

A reference to the object to which the event was originally dispatched.

`Event.timeStamp` Read only

The time at which the event was created (in milliseconds). By specification, this value is time since epoch—but in reality, browsers' definitions vary. In addition, work is underway to change this to be a `DOMHighResTimeStamp` instead.

`Event.type` Read only

The name identifying the type of the event.

### Legacy and non-standard properties

`Event.cancelBubble`
Deprecated

A historical alias to `Event.stopPropagation()` that should be used instead. Setting its value to `true` before returning from an event handler prevents propagation of the event.

`Event.explicitOriginalTarget`
Non-standard
 Read only

The explicit original target of the event.

`Event.originalTarget`
Non-standard
 Read only

The original target of the event, before any retargetings.

`Event.returnValue`
Deprecated

A historical property still supported in order to ensure existing sites continue to work. Use `Event.preventDefault()` and `Event.defaultPrevented` instead.

`Event.scoped` Read only
Deprecated

A boolean value indicating whether the given event will bubble across through the shadow root into the standard DOM. Use `composed` instead.

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

`Event.composedPath()`

Returns the event's path (an array of objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with its `ShadowRoot.mode` closed.

`Event.preventDefault()`

Cancels the event (if it is cancelable).

`Event.stopImmediatePropagation()`

For this particular event, prevent all other listeners from being called. This includes listeners attached to the same element as well as those attached to elements that will be traversed later (during the capture phase, for instance).

`Event.stopPropagation()`

Stops the propagation of events further along in the DOM.

### Deprecated methods

`Event.initEvent()`
Deprecated

Initializes the value of an Event created. If the event has already been dispatched, this method does nothing. Use the constructor (`Event()` instead).

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

| Specification |
| --- |
| DOM Standard # interface-event |

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

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

See also
--------

* Types of events available: Event reference
* Comparison of Event Targets (`target` vs. `currentTarget` vs. `relatedTarget` vs. `originalTarget`)
* Creating and triggering custom events


MediaSourceHandle - Web APIs

MediaSourceHandle
=================

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

The **`MediaSourceHandle`** interface of the Media Source Extensions API is a proxy for a `MediaSource` that can be transferred from a dedicated worker back to the main thread and attached to a media element via its `HTMLMediaElement.srcObject` property. `MediaSource` objects are not transferable because they are event targets, hence the need for `MediaSourceHandle`s.

It can be accessed via the `MediaSource.handle` property.

Each `MediaSource` object created inside a dedicated worker has its own distinct `MediaSourceHandle`. The `MediaSource.handle` getter will always return the `MediaSourceHandle` instance specific to the associated dedicated worker `MediaSource` instance. If the handle has already been transferred to the main thread using `postMessage()`, the handle instance in the worker is technically detached and can't be transferred again.

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

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

None.

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

None.

Examples
--------

The `handle` property can be accessed inside a dedicated worker and the resulting `MediaSourceHandle` object is then transferred over to the thread that created the worker (in this case the main thread) via a `postMessage()` call:

```js
// Inside dedicated worker
let mediaSource = new MediaSource();
let handle = mediaSource.handle;
// Transfer the handle to the context that created the worker
postMessage({ arg: handle }, [handle]);

mediaSource.addEventListener("sourceopen", () => {
  // Await sourceopen on MediaSource before creating SourceBuffers
  // and populating them with fetched media — MediaSource won't
  // accept creation of SourceBuffers until it is attached to the
  // HTMLMediaElement and its readyState is "open"
});
```

Over in the main thread, we receive the handle via a `message` event handler, attach it to a `<video>` via its `HTMLMediaElement.srcObject` property, and `play` the video:

```js
worker.addEventListener("message", (msg) => {
  let mediaSourceHandle = msg.data.arg;
  video.srcObject = mediaSourceHandle;
  video.play();
});
```

**Note:** `MediaSourceHandle`s cannot be successfully transferred into or via a shared worker or service worker.

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

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

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

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

See also
--------

* MSE-in-Workers Demo by Matt Wolenetz
* Media Source Extensions API
* `MediaSource`
* `SourceBuffer`


AbortSignal - Web APIs

AbortSignal
===========

The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an `AbortController` object.

EventTarget

AbortSignalInstance properties
-------------------

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

`AbortSignal.aborted` Read only

A Boolean that indicates whether the request(s) the signal is communicating with is/are aborted (`true`) or not (`false`).

`AbortSignal.reason` Read only

A JavaScript value providing the abort reason, once the signal has aborted.

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

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

`AbortSignal.abort()`

Returns an `AbortSignal` instance that is already set as aborted.

`AbortSignal.any()`

Returns an `AbortSignal` that aborts when any of the given abort signals abort.

`AbortSignal.timeout()`

Returns an `AbortSignal` instance that will automatically abort after a specified time.

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

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

`AbortSignal.throwIfAborted()`

Throws the signal's abort `reason` if the signal has been aborted; otherwise it does nothing.

Events
------

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

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

`abort`

 Invoked when the asynchronous operations the signal is communicating with is/are aborted.
 Also available via the `onabort` property.

Examples
--------

### Aborting a fetch operation using an explicit signal

The following snippet shows how we might use a signal to abort downloading a video using the Fetch API.

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

 When the fetch request is initiated, we pass in the `AbortSignal` as an option inside the request's options object (the `{signal}` below). This associates the signal and controller with the fetch request, and allows us to abort it by calling `AbortController.abort()`.
 Below you can see that the fetch operation is aborted in the second event listener, which triggered when the abort button (`abortBtn`) is clicked.

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

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

downloadBtn.addEventListener("click", fetchVideo);

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

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

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

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

### Aborting a fetch operation with a timeout

 If you need to abort the operation on timeout then you can use the static `AbortSignal.timeout()` method.
 This returns an `AbortSignal` that will automatically timeout after a certain number of milliseconds.

 The code snippet below shows how you would either succeed in downloading a file, or handle a timeout error after 5 seconds.
 Note that when there is a timeout the `fetch()` promise rejects with a "`TimeoutError`" `DOMException`.
 This allows code to differentiate between timeouts (for which user notification is probably required), and user aborts.

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

try {
  const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
  const result = await res.blob();
  // …
} catch (err) {
  if (err.name === "TimeoutError") {
    console.error("Timeout: It took more than 5 seconds to get the result!");
  } else if (err.name === "AbortError") {
    console.error(
      "Fetch aborted by user action (browser stop button, closing tab, etc.",
    );
  } else if (err.name === "TypeError") {
    console.error("AbortSignal.timeout() method is not supported");
  } else {
    // A network error, or some other problem.
    console.error(`Error: type: ${err.name}, message: ${err.message}`);
  }
}
```

### Aborting a fetch with timeout or explicit abort

If you want to abort from multiple signals, you can use `AbortSignal.any()` to combine them into a single signal. The following example shows this using `fetch`:

```js
try {
  const controller = new AbortController();
  const timeoutSignal = AbortSignal.timeout(5000);
  const res = await fetch(url, {
    // This will abort the fetch when either signal is aborted
    signal: AbortSignal.any([controller.signal, timeoutSignal]),
  });
  const body = await res.json();
} catch (e) {
  if (e.name === "AbortError") {
    // Notify the user of abort.
  } else if (e.name === "TimeoutError") {
    // Notify the user of timeout
  } else {
    // A network error, or some other problem.
    console.log(`Type: ${e.name}, Message: ${e.message}`);
  }
}
```

**Note:** Unlike when using `AbortSignal.timeout()`, there is no way to tell whether the final abort was caused by a timeout.

### Implementing an abortable API

An API that needs to support aborting can accept an `AbortSignal` object, and use its state to trigger abort signal handling when needed.

 A `Promise`-based API should respond to the abort signal by rejecting any unsettled promise with the `AbortSignal` abort `reason`.
 For example, consider the following `myCoolPromiseAPI`, which takes a signal and returns a promise.
 The promise is rejected immediately if the signal is already aborted, or if the abort event is detected.
 Otherwise it completes normally and then resolves the promise.

```js
function myCoolPromiseAPI(/\* …, \*/ { signal }) {
  return new Promise((resolve, reject) => {
    // If the signal is already aborted, immediately throw in order to reject the promise.
    if (signal.aborted) {
      reject(signal.reason);
    }

    // Perform the main purpose of the API
    // Call resolve(result) when done.

    // Watch for 'abort' signals
    signal.addEventListener("abort", () => {
      // Stop the main operation
      // Reject the promise with the abort reason.
      reject(signal.reason);
    });
  });
}
```

 The API might then be used as shown.
 Note that `AbortController.abort()` is called to abort the operation.

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

startSpinner();

myCoolPromiseAPI({ /\* …, \*/ signal })
  .then((result) => {})
  .catch((err) => {
    if (err.name === "AbortError") return;
    showUserErrorMessage();
  })
  .then(() => stopSpinner());

controller.abort();
```

 APIs that do not return promises might react in a similar manner.
 In some cases it may make sense to absorb the signal.

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

| Specification |
| --- |
| DOM Standard # interface-AbortSignal |

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

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

See also
--------

* Fetch API
* Abortable Fetch by Jake Archibald


DataTransferItemList - Web APIs

DataTransferItemList
====================

The **`DataTransferItemList`** object is a list of `DataTransferItem` objects representing items being dragged. During a *drag operation*, each `DragEvent` has a `dataTransfer` property and that property is a `DataTransferItemList`.

The individual items can be accessed using the bracket notation `[]`.

This interface has no constructor.

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

`DataTransferItemList.length` Read only

An `unsigned long` that is the number of drag items in the list.

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

`DataTransferItemList.add()`

Adds an item (either a `File` object or a string) to the drag item list and returns a `DataTransferItem` object for the new item.

`DataTransferItemList.remove()`

Removes the drag item from the list at the given index.

`DataTransferItemList.clear()`

Removes all of the drag items from the list.

`DataTransferItemList.operator[]`

Getter that returns a `DataTransferItem` at the given index.

Example
-------

This example shows how to use drag and drop.

### JavaScript

```js
function dragstartHandler(ev) {
  console.log("dragStart");

  // Add this element's id to the drag payload so the drop handler will
  // know which element to add to its tree
  const dataList = ev.dataTransfer.items;
  dataList.add(ev.target.id, "text/plain");

  // Add some other items to the drag payload
  dataList.add("<p>Paragraph…</p>", "text/html");
  dataList.add("http://www.example.org", "text/uri-list");
}

function dropHandler(ev) {
  console.log("Drop");
  ev.preventDefault();

  // Loop through the dropped items and log their data
  for (const item of ev.dataTransfer.items) {
    if (item.kind === "string" && item.type.match(/^text\/plain/)) {
      // This item is the target node
      item.getAsString((s) => {
        ev.target.appendChild(document.getElementById(s));
      });
    } else if (item.kind === "string" && item.type.match(/^text\/html/)) {
      // Drag data item is HTML
      item.getAsString((s) => {
        console.log(`… Drop: HTML = ${s}`);
      });
    } else if (item.kind === "string" && item.type.match(/^text\/uri-list/)) {
      // Drag data item is URI
      item.getAsString((s) => {
        console.log(`… Drop: URI = ${s}`);
      });
    }
  }
}

function dragoverHandler(ev) {
  console.log("dragOver");
  ev.preventDefault();

  // Set the dropEffect to move
  ev.dataTransfer.dropEffect = "move";
}

function dragendHandler(ev) {
  console.log("dragEnd");
  const dataList = ev.dataTransfer.items;

  // Clear any remaining drag data
  dataList.clear();
}
```

### HTML

```html
<div>
  <p
 id="source"
 ondragstart="dragstartHandler(event);"
 ondragend="dragendHandler(event);"
 draggable="true">
    Select this element, drag it to the Drop Zone and then release the selection
    to move the element.
  </p>
</div>
<div
 id="target"
 ondrop="dropHandler(event);"
 ondragover="dragoverHandler(event);">
  Drop Zone
</div>
```

### CSS

```css
div {
  margin: 0em;
  padding: 2em;
}

#source {
  color: blue;
  border: 1px solid black;
}

#target {
  border: 1px solid black;
}
```

### Result

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

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

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

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


LaunchQueue - Web APIs

LaunchQueue
===========

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

The **`LaunchQueue`** interface of the Launch Handler API is available via the `Window.launchQueue` property. When a progressive web app (PWA) is launched with a `launch_handler` `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`, `LaunchQueue` provides access to functionality that allows custom launch navigation handling to be implemented in the PWA. This functionality is controlled by the properties of the `LaunchParams` object passed into the `setConsumer()` callback function.

Instance Methods
----------------

`setConsumer()`
Experimental

Contains a callback function that handles custom launch navigation for a PWA.

Examples
--------

```js
if ("launchQueue" in window) {
  window.launchQueue.setConsumer((launchParams) => {
    if (launchParams.targetURL) {
      const params = new URL(launchParams.targetURL).searchParams;

      // Assuming a music player app that gets a track passed to it to be played
      const track = params.get("track");
      if (track) {
        audio.src = track;
        title.textContent = new URL(track).pathname.substr(1);
        audio.play();
      }
    }
  });
}
```

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

| Specification |
| --- |
| Web App Launch Handler API # launchqueue-interface |

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

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

See also
--------

* Launch Handler API: Control how your app is launched
* `Window.launchQueue`
* Musicr 2.0 demo app


RsaPssParams - Web APIs

RsaPssParams
============

The **`RsaPssParams`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()`, when using the RSA-PSS algorithm.

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

`name`

A string. This should be set to `RSA-PSS`.

`saltLength`

A `long` integer representing the length of the random salt to use, in bytes.

RFC 3447 says that "Typical salt lengths" are either 0 or the length of the output of the digest algorithm that was selected when this key was generated. For example, if you use SHA-256 as the digest algorithm, this could be 32.

The maximum size of `saltLength` is given by:

```js
Math.ceil((keySizeInBits - 1) / 8) - digestSizeInBytes - 2;
```

So for a key length of 2048 bits and a digest output size of 32 bytes, the maximum size would be 222.

Examples
--------

See the examples for `SubtleCrypto.sign()` and `SubtleCrypto.verify()`.

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

| Specification |
| --- |
| Web Cryptography API # dfn-RsaPssParams |

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

Browsers that support the "RSA-PSS" algorithm for the `SubtleCrypto.sign()` and `SubtleCrypto.verify()` methods will support this type.

See also
--------

* RFC 3447: RSASSA-PSS


MediaList - Web APIs

MediaList
=========

The **`MediaList`** interface represents the media queries of a stylesheet, e.g. those set using a `<link>` element's `media` attribute.

**Note:** `MediaList` is a live list; updating the list using properties or methods listed below will immediately update the behavior of the document.

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

`MediaList.mediaText`

A stringifier that returns a string representing the `MediaList` as text, and also allows you to set a new `MediaList`.

`MediaList.length` Read only

Returns the number of media queries in the `MediaList`.

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

`MediaList.appendMedium()`

Adds a media query to the `MediaList`.

`MediaList.deleteMedium()`

Removes a media query from the `MediaList`.

`MediaList.item()`

A getter that returns a string representing a media query as text, given the media query's index value inside the `MediaList`. This method can also be called using the bracket (`[]`) syntax.

Examples
--------

The following would log to the console a textual representation of the `MediaList` of the first stylesheet applied to the current document.

```js
const stylesheets = document.styleSheets;
let stylesheet = stylesheets[0];
console.log(stylesheet.media.mediaText);
```

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

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

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

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


Document Picture-in-Picture API - Web APIs

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

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

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

The **Document Picture-in-Picture API** makes it possible to open an always-on-top window that can be populated with arbitrary HTML content — for example a video with custom controls or a set of streams showing the participants of a video conference call. It extends the earlier Picture-in-Picture API for `<video>`, which specifically enables an HTML `<video>` element to be put into an always-on-top window.

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

It is often helpful to have a different window available to a web app in addition to the main window in which the app is running. You might want to browse other windows while keeping specific app content in view, or you might want to give that content its own space while keeping the main app window freed up to display other content. You could handle this by just opening a regular new browser window, but this has two major issues:

1. You have to handle sharing of state information between the two windows.
2. The additional app window doesn't always stay on top, and can therefore get hidden by other windows.

To solve these problems, web browsers have introduced APIs allowing apps to spawn an always-on-top window that is part of the same session. The first recognized use case was keeping video content playing in a separate window so that the user can continue to consume it while looking at other content. This is handled using the Picture-in-Picture API for `<video>`, which is directly used on a `<video>` element to place it into the separate window.

However, this API has been found to be somewhat limiting — you can only put a single `<video>` element into the always-on-top window, with minimal browser-generated controls. To provide more flexibility, the **Document Picture-in-Picture API** has been introduced. This allows *any* content to be placed in the always-on-top window for a wide range of use cases, including:

* An always-on-top custom video player showing one or multiple videos with custom controls and styling.
* A video conferencing system that allows the user to always see the other participant's streams, plus controls for presenting content, muting, ending calls, etc.
* Always-visible productivity tools such as timers, notes, to-do lists, messenger tools, etc.
* A separate window in which to keep additional content while the main app window is kept free of clutter. For example, you might have a action or roleplaying game running where you want to show the game controls, instructions, or lore in an additional window, keeping the main window free for displaying the game locations and map.
### How does it work?

A new `DocumentPictureInPicture` object instance representing the always-on-top Picture-in-Picture window for the current document context is available via `Window.documentPictureInPicture`. The Picture-in-Picture window is opened by calling the `DocumentPictureInPicture.requestWindow()` method, which returns a `Promise` that fulfills with the window's own `Window` object.

The Picture-in-Picture window is similar to a blank same-origin window opened via `Window.open()`, with some differences:

* The Picture-in-Picture window floats on top of other windows.
* The Picture-in-Picture window never outlives the opening window.
* The Picture-in-Picture window cannot be navigated.
* The Picture-in-Picture window position cannot be set by the website.
* The Picture-in-Picture window is limited to one per browser tab at a time, with the user agent potentially further restricting the global number of Picture-in-Picture windows open.

Apart from that, you can manipulate the Picture-in-Picture window's `Window` instance however you want, for example appending the content you want to display there onto its DOM, and copying stylesheets to it so that the appended content will be styled the same way as when it is in the main window. You can also close the Picture-in-Picture window (by clicking the browser-provided control, or by running `Window.close()` on it), and then react to it closing using the standard `pagehide`. When it closes, you'll want to put the content it was showing back into the main app window.

See Using the Document Picture-in-Picture API for a detailed usage guide.

Interfaces
----------

`DocumentPictureInPicture`

The entry point for creating and handling document picture-in-picture windows.

`DocumentPictureInPictureEvent`

Event object for the `enter` event, which fires when the Picture-in-Picture window is opened.

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

`Window.documentPictureInPicture`

Returns a reference to the `DocumentPictureInPicture` object for the current document context.

Examples
--------

See Document Picture-in-Picture API Example for a full working demo (see the full source code also).

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

| Specification |
| --- |
| Document Picture-in-Picture Specification # dom-window-documentpictureinpicture |

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

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


WebGLTransformFeedback - Web APIs

WebGLTransformFeedback
======================

The **`WebGLTransformFeedback`** interface is part of the WebGL 2 API and enables transform feedback, which is the process of capturing primitives generated by vertex processing. It allows to preserve the post-transform rendering state of an object and resubmit this data multiple times.

WebGLObject

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

* `WebGL2RenderingContext.createTransformFeedback()`
* `WebGL2RenderingContext.deleteTransformFeedback()`
* `WebGL2RenderingContext.isTransformFeedback()`
* `WebGL2RenderingContext.bindTransformFeedback()`
* `WebGL2RenderingContext.beginTransformFeedback()`
* `WebGL2RenderingContext.endTransformFeedback()`
* `WebGL2RenderingContext.pauseTransformFeedback()`
* `WebGL2RenderingContext.resumeTransformFeedback()`
* `WebGL2RenderingContext.transformFeedbackVaryings()`
* `WebGL2RenderingContext.getTransformFeedbackVarying()`
Examples
--------

### Creating a `WebGLTransformFeedback` object

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

```js
const transformFeedback = gl.createTransformFeedback();
```

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

| Specification |
| --- |
| WebGL 2.0 Specification # 3.5 |

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

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