The HTML DOM API - Web APIs

The HTML DOM API
================

The **HTML DOM API** is made up of the interfaces that define the functionality of each of the elements in HTML, as well as any supporting types and interfaces they rely upon.

The functional areas included in the HTML DOM API include:

* Access to and control of HTML elements via the DOM.
* Access to and manipulation of form data.
* Interacting with the contents of 2D images and the context of an HTML `<canvas>`, for example to draw on top of them.
* Management of media connected to the HTML media elements (`<audio>` and `<video>`).
* Dragging and dropping of content on webpages.
* Access to the browser navigation history
* Supporting and connective interfaces for other APIs such as Web Components, Web Storage, Web Workers, WebSocket, and Server-sent events.
HTML DOM concepts and usage
---------------------------

In this article, we'll focus on the parts of the HTML DOM that involve engaging with HTML elements. Discussion of other areas, such as Drag and Drop, WebSockets, Web Storage, etc. can be found in the documentation for those APIs.

### Structure of an HTML document

The Document Object Model (DOM) is an architecture that describes the structure of a `document`; each document is represented by an instance of the interface `Document`. A document, in turn, consists of a hierarchical tree of **nodes**, in which a node is a fundamental record representing a single object within the document (such as an element or text node).

Nodes may be strictly organizational, providing a means for grouping other nodes together or for providing a point at which a hierarchy can be constructed; other nodes may represent visible components of a document. Each node is based on the `Node` interface, which provides properties for getting information about the node as well as methods for creating, deleting, and organizing nodes within the DOM.

Nodes don't have any concept of including the content that is actually displayed in the document. They're empty vessels. The fundamental notion of a node that can represent visual content is introduced by the `Element` interface. An `Element` object instance represents a single element in a document created using either HTML or an XML vocabulary such as SVG.

For example, consider a document with two elements, one of which has two more elements nested inside it:

![Structure of a document with elements inside a document in a window](/en-US/docs/Web/API/HTML_DOM_API/dom-structure.svg)

While the `Document` interface is defined as part of the DOM specification, the HTML specification significantly enhances it to add information specific to using the DOM in the context of a web browser, as well as to using it to represent HTML documents specifically.

Among the things added to `Document` by the HTML standard are:

* Support for accessing various information provided by the HTTP headers when loading the page, such as the location from which the document was loaded, cookies, modification date, referring site, and so forth.
* Access to lists of elements in the document's `<head>` block and body, as well as lists of the images, links, scripts, etc. contained in the document.
* Support for interacting with the user by examining focus and by executing commands on editable content.
* Event handlers for document events defined by the HTML standard to allow access to mouse and keyboard events, drag and drop, media control, and more.
* Event handlers for events that can be delivered to both elements and documents; these presently include only copy, cut, and paste actions.
### HTML element interfaces

The `Element` interface has been further adapted to represent HTML elements specifically by introducing the `HTMLElement` interface, which all more specific HTML element classes inherit from. This expands the `Element` class to add HTML-specific general features to the element nodes. Properties added by `HTMLElement` include for example `hidden` and `innerText`.

An HTML document is a DOM tree in which each of the nodes is an HTML element, represented by the `HTMLElement` interface. The `HTMLElement` class, in turn, implements `Node`, so every element is also a node (but not the other way around). This way, the structural features implemented by the `Node` interface are also available to HTML elements, allowing them to be nested within each other, created and deleted, moved around, and so forth.

The `HTMLElement` interface is generic, however, providing only the functionality common to all HTML elements such as the element's ID, its coordinates, the HTML making up the element, information about scroll position, and so forth.

In order to expand upon the functionality of the core `HTMLElement` interface to provide the features needed by a specific element, the `HTMLElement` class is subclassed to add the needed properties and methods. For example, the `<canvas>` element is represented by an object of type `HTMLCanvasElement`. `HTMLCanvasElement` augments the `HTMLElement` type by adding properties such as `height` and methods like `getContext()` to provide canvas-specific features.

The overall inheritance for HTML element classes looks like this:

![Hierarchy of interfaces for HTML elements](/en-US/docs/Web/API/HTML_DOM_API/html-dom-hierarchy.svg)

As such, an element inherits the properties and methods of all of its ancestors. For example, consider a `<a>` element, which is represented in the DOM by an object of type `HTMLAnchorElement`. The element, then, includes the anchor-specific properties and methods described in that class's documentation, but also those defined by `HTMLElement` and `Element`, as well as from `Node` and, finally, `EventTarget`.

Each level defines a key aspect of the utility of the element. From `Node`, the element inherits concepts surrounding the ability for the element to be contained by another element, and to contain other elements itself. Of special importance is what is gained by inheriting from `EventTarget`: the ability to receive and handle events such as mouse clicks, play and pause events, and so forth.

There are elements that share commonalities and thus have an additional intermediary type. For example, the `<audio>` and `<video>` elements both present audiovisual media. The corresponding types, `HTMLAudioElement` and `HTMLVideoElement`, are both based upon the common type `HTMLMediaElement`, which in turn is based upon `HTMLElement` and so forth. `HTMLMediaElement` defines the methods and properties held in common between audio and video elements.

These element-specific interfaces make up the majority of the HTML DOM API, and are the focus of this article. To learn more about the actual structure of the DOM, see Introduction to the DOM.

HTML DOM target audience
------------------------

 The features exposed by the HTML DOM are among the most commonly-used APIs in a web developer's toolkit.
 All but the most simple web applications will use some features of the HTML DOM.

HTML DOM API interfaces
-----------------------

The majority of the interfaces that comprise the HTML DOM API map almost one-to-one to individual HTML elements, or to a small group of elements with similar functionality. In addition, the HTML DOM API includes a few interfaces and types to support the HTML element interfaces.

### HTML element interfaces

These interfaces represent specific HTML elements (or sets of related elements which have the same properties and methods associated with them).

* `HTMLAnchorElement`
* `HTMLAreaElement`
* `HTMLAudioElement`
* `HTMLBaseElement`
* `HTMLBodyElement`
* `HTMLBRElement`
* `HTMLButtonElement`
* `HTMLCanvasElement`
* `HTMLDataElement`
* `HTMLDataListElement`
* `HTMLDetailsElement`
* `HTMLDialogElement`
* `HTMLDirectoryElement`
* `HTMLDivElement`
* `HTMLDListElement`
* `HTMLElement`
* `HTMLEmbedElement`
* `HTMLFieldSetElement`
* `HTMLFormElement`
* `HTMLHRElement`
* `HTMLHeadElement`
* `HTMLHeadingElement`
* `HTMLHtmlElement`
* `HTMLIFrameElement`
* `HTMLImageElement`
* `HTMLInputElement`
* `HTMLLabelElement`
* `HTMLLegendElement`
* `HTMLLIElement`
* `HTMLLinkElement`
* `HTMLMapElement`
* `HTMLMediaElement`
* `HTMLMenuElement`
* `HTMLMetaElement`
* `HTMLMeterElement`
* `HTMLModElement`
* `HTMLObjectElement`
* `HTMLOListElement`
* `HTMLOptGroupElement`
* `HTMLOptionElement`
* `HTMLOutputElement`
* `HTMLParagraphElement`
* `HTMLPictureElement`
* `HTMLPreElement`
* `HTMLProgressElement`
* `HTMLQuoteElement`
* `HTMLScriptElement`
* `HTMLSelectElement`
* `HTMLSlotElement`
* `HTMLSourceElement`
* `HTMLSpanElement`
* `HTMLStyleElement`
* `HTMLTableCaptionElement`
* `HTMLTableCellElement`
* `HTMLTableColElement`
* `HTMLTableElement`
* `HTMLTableRowElement`
* `HTMLTableSectionElement`
* `HTMLTemplateElement`
* `HTMLTextAreaElement`
* `HTMLTimeElement`
* `HTMLTitleElement`
* `HTMLTrackElement`
* `HTMLUListElement`
* `HTMLUnknownElement`
* `HTMLVideoElement`

#### Deprecated HTML Element Interfaces

* `HTMLMarqueeElement`
Deprecated

#### Obsolete HTML Element Interfaces

* `HTMLFontElement`
Deprecated
* `HTMLFrameElement`
Deprecated
* `HTMLFrameSetElement`
Deprecated
* `HTMLIsIndexElement`
Deprecated
* `HTMLMenuItemElement`
Deprecated
### Web app and browser integration interfaces

These interfaces offer access to the browser window and document that contain the HTML, as well as to the browser's state, available plugins (if any), and various configuration options.

* `BarProp`
* `Navigator`
* `Window`

#### Deprecated web app and browser integration interfaces

* `External`
Deprecated

#### Obsolete web app and browser integration interfaces

* `ApplicationCache`
Deprecated
* `Plugin`
Deprecated
* `PluginArray`
Deprecated
### Form support interfaces

These interfaces provide structure and functionality required by the elements used to create and manage forms, including the `<form>` and `<input>` elements.

* `FormDataEvent`
* `HTMLFormControlsCollection`
* `HTMLOptionsCollection`
* `RadioNodeList`
* `ValidityState`
### Canvas and image interfaces

These interfaces represent objects used by the Canvas API as well as the `<img>` element and `<picture>` elements.

* `CanvasGradient`
* `CanvasPattern`
* `CanvasRenderingContext2D`
* `ImageBitmap`
* `ImageBitmapRenderingContext`
* `ImageData`
* `OffscreenCanvas`
* `OffscreenCanvasRenderingContext2D`
* `Path2D`
* `TextMetrics`
### Media interfaces

The media interfaces provide HTML access to the contents of the media elements: `<audio>` and `<video>`.

* `AudioTrack`
* `AudioTrackList`
* `MediaError`
* `TextTrack`
* `TextTrackCue`
* `TextTrackCueList`
* `TextTrackList`
* `TimeRanges`
* `TrackEvent`
* `VideoTrack`
* `VideoTrackList`
### Drag and drop interfaces

These interfaces are used by the HTML Drag and Drop API to represent individual draggable (or dragged) items, groups of dragged or draggable items, and to handle the drag and drop process.

* `DataTransfer`
* `DataTransferItem`
* `DataTransferItemList`
* `DragEvent`
### Page history interfaces

The History API interfaces let you access information about the browser's history, as well as to shift the browser's current tab forward and backward through that history.

* `BeforeUnloadEvent`
* `HashChangeEvent`
* `History`
* `Location`
* `PageTransitionEvent`
* `PopStateEvent`
### Web Components interfaces

These interfaces are used by the Web Components API to create and manage the available custom elements.

* `CustomElementRegistry`
### Miscellaneous and supporting interfaces

These supporting object types are used in a variety of ways in the HTML DOM API. In addition, `PromiseRejectionEvent` represents the event delivered when a JavaScript `Promise` is rejected.

* `DOMStringList`
* `DOMStringMap`
* `ErrorEvent`
* `HTMLAllCollection`
* `MimeType`
* `MimeTypeArray`
* `PromiseRejectionEvent`
### Interfaces belonging to other APIs

Several interfaces are technically defined in the HTML specification while actually being part of other APIs.

#### Web storage interfaces

The Web Storage API provides the ability for websites to store data either temporarily or permanently on the user's device for later re-use.

* `Storage`
* `StorageEvent`

#### Web Workers interfaces

These interfaces are used by the Web Workers API both to establish the ability for workers to interact with an app and its content, but also to support messaging between windows or apps.

* `BroadcastChannel`
* `DedicatedWorkerGlobalScope`
* `MessageChannel`
* `MessageEvent`
* `MessagePort`
* `SharedWorker`
* `SharedWorkerGlobalScope`
* `Worker`
* `WorkerGlobalScope`
* `WorkerLocation`
* `WorkerNavigator`

#### WebSocket interfaces

These interfaces, defined by the HTML specification, are used by the WebSockets API.

* `CloseEvent`
* `WebSocket`

#### Server-sent events interfaces

The `EventSource` interface represents the source which sent or is sending server-sent events.

* `EventSource`
Examples
--------

In this example, an `<input>` element's `input` event is monitored in order to update the state of a form's "submit" button based on whether or not a given field currently has a value.

### JavaScript

```js
const nameField = document.getElementById("userName");
const sendButton = document.getElementById("sendButton");

sendButton.disabled = true;
// [note: this is disabled since it causes this article to always load with this example focused and scrolled into view]
//nameField.focus();

nameField.addEventListener("input", (event) => {
  const elem = event.target;
  const valid = elem.value.length !== 0;

  if (valid && sendButton.disabled) {
    sendButton.disabled = false;
  } else if (!valid && !sendButton.disabled) {
    sendButton.disabled = true;
  }
});
```

This code uses the `Document` interface's `getElementById()` method to get the DOM object representing the `<input>` elements whose IDs are `userName` and `sendButton`. With these, we can access the properties and methods that provide information about and grant control over these elements.

The `HTMLInputElement` object for the "Send" button's `disabled` property is set to `true`, which disables the "Send" button so it can't be clicked. In addition, the user name input field is made the active focus by calling the `focus()` method it inherits from `HTMLElement`.

Then `addEventListener()` is called to add a handler for the `input` event to the user name input. This code looks at the length of the current value of the input; if it's zero, then the "Send" button is disabled if it's not already disabled. Otherwise, the code ensures that the button is enabled.

With this in place, the "Send" button is always enabled whenever the user name input field has a value, and disabled when it's empty.

### HTML

The HTML for the form looks like this:

```html
<p>Please provide the information below. Items marked with "*" are required.</p>
<form action="" method="get">
  <p>
    <label for="userName" required>Your name:</label>
    <input type="text" id="userName" /> (*)
  </p>
  <p>
    <label for="email">Email:</label>
    <input type="email" id="userEmail" />
  </p>
  <input type="submit" value="Send" id="sendButton" />
</form>
```

### Result

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

| Specification |
| --- |
| HTML Standard # htmlelement |

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

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

See also
--------

### References

* HTML elements reference
* HTML attribute reference
* Document Object Model (DOM) reference
### Guides

* Manipulating documents: A beginner's guide to manipulating the DOM.


SVGAnimateElement - Web APIs

SVGAnimateElement
=================

The **`SVGAnimateElement`** interface corresponds to the `<animate>` element.

EventTarget

Node

Element

SVGElement

SVGAnimationElement

SVGAnimateElementInstance properties
-------------------

*This interface has no properties but inherits properties from its parent, `SVGAnimationElement`.*

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

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

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

| Specification |
| --- |
| SVG Animations Level 2 # InterfaceSVGAnimateElement |

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

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


RTCRemoteOutboundRtpStreamStats - Web APIs

RTCRemoteOutboundRtpStreamStats
===============================

The **`RTCRemoteOutboundRtpStreamStats`** dictionary of the WebRTC API is used to report statistics from remote endpoint of its outbound RTP stream, which corresponds to an inbound stream that is currently received by an `RTCPeerConnection` object.

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

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

### Remote outbound specific properties

`localId` Optional

A string which is used to find the local `RTCInboundRtpStreamStats` object which shares the same Synchronization Source (SSRC).

`remoteTimestamp` Optional

A `DOMHighResTimeStamp` specifying the timestamp (on the remote device) at which the statistics in the `RTCRemoteOutboundRtpStreamStats` object were sent by the remote endpoint. This is different from the `timestamp`; it represents the time at which the object's statistics were received or generated by the local endpoint.

`reportsSent` Optional
Experimental

A positive integer indicating the total number of RTCP Sender Report (SR) blocks sent for this synchronization source (SSRC).

`roundTripTimeMeasurements` Optional
Experimental

A positive integer indicating the total number of RTCP Sender Report (SR) blocks received for this synchronization source (SSRC) that contain a DLRR (Delay Since last Receiver Report) block that can be used to derive a valid round trip time. This counter will not increment if the round trip time cannot be calculated.

`totalRoundTripTime` Optional
Experimental

 A real number indicating the cumulative sum of all round trip time measurements since the beginning of the session, in seconds.
 The average round trip time can be computed by dividing `totalRoundTripTime` by `roundTripTimeMeasurements`.

### RTP sent-stream stat properties

`bytesSent` Optional

A positive integer indicating the total number of bytes sent for this SSRC, including retransmissions.

`packetsSent` Optional

A positive integer indicating the total number of RTP packets sent for this SSRC, including retransmissions.

### RTP stream-stat properties

`codecId` Optional

A string that uniquely identifies the object that was inspected to produce the `RTCCodecStats` report associated with this RTP stream.

`kind`

 A string whose value is `"audio"` if the associated `MediaStreamTrack` is audio-only or `"video"` if the track contains video.
 This value will match that of the media type indicated by `RTCCodecStats.codec`, as well as the track's `kind` property. Previously called `mediaType`.

`ssrc`

 A positive integer that identifies the synchronization source (SSRC) of the RTP stream that is being sent to the remote endpoint.
 This value is generated per the RFC 3550 specification.

`transportId` Optional

A string that uniquely identifies the object that was inspected to produce the `RTCTransportStats` report associated with this RTP stream.

### Common instance properties

The following properties are common to all WebRTC statistics objects.

`id`

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

`timestamp`

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

`type`

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

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

 The `RTCRemoteOutboundRtpStreamStats` object's `remoteTimestamp` property provides statistics based on the received data's NTP timestamp taken from an RTCP Sender Report (SR) block.
 Be aware that the remote clock may not be synchronized with the local clock (either in current time or speed at which time elapses).

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

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

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

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


VisibilityStateEntry - Web APIs

VisibilityStateEntry
====================

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

The **`VisibilityStateEntry`** interface provides timings of page visibility state changes, i.e., when a tab changes from the foreground to the background or vice versa.

This can be used to pinpoint visibility changes on the performance timeline, and cross-reference them against other performance entries such as "first-contentful-paint" (see `PerformancePaintTiming`).

There are two key visibility state change times that this API reports on:

* `visible`: The time when the page becomes visible (i.e. when its tab moves into the foreground).
* `hidden`: The time when the pages become hidden (i.e. when its tab moves into the background).

The performance timeline will always have a "`visibility-state`" entry with a `startTime` of `0` and a `name` representing the initial page visibility state.

**Note:** Like other Performance APIs, this API extends `PerformanceEntry`.

PerformanceEntry

VisibilityStateEntryInstance properties
-------------------

This interface has no properties but it extends the properties of `PerformanceEntry` by qualifying and constraining them as follows:

`PerformanceEntry.entryType`
Experimental

Returns "`visibility-state`".

`PerformanceEntry.name`
Experimental

Returns either `"visible"` or `"hidden"`.

`PerformanceEntry.startTime`
Experimental

Returns the `timestamp` when the visibility state change occurred.

`PerformanceEntry.duration`
Experimental

Returns 0.

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

This interface has no methods.

Examples
--------

### Basic usage

The following function could be used to log a table of all "`visibility-state`" performance entries to the console:

```js
function getVisibilityStateEntries() {
  const visibilityStateEntries =
    performance.getEntriesByType("visibility-state");
  console.table(visibilityStateEntries);
}
```

### Correlating visibility state changes with paint timing

The below function gets a reference to all "`visibility-state`" entries and the "`first-contentful-paint`" entry, then uses `Array.some()` to test whether any of the "`hidden`" visibility entries occurred before the first contentful paint:

```js
function wasHiddenBeforeFirstContentfulPaint() {
  const fcpEntry = performance.getEntriesByName("first-contentful-paint")[0];
  const visibilityStateEntries =
    performance.getEntriesByType("visibility-state");
  return visibilityStateEntries.some(
    (e) => e.startTime < fcpEntry.startTime && e.name === "hidden",
  );
}
```

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

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

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

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

See also
--------

Page Visibility API


FileSystemDirectoryHandle - Web APIs

FileSystemDirectoryHandle
=========================

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

The **`FileSystemDirectoryHandle`** interface of the File System API provides a handle to a file system directory.

The interface can be accessed via the `window.showDirectoryPicker()`, `StorageManager.getDirectory()`, `DataTransferItem.getAsFileSystemHandle()`, and `FileSystemDirectoryHandle.getDirectoryHandle()` methods.

FileSystemHandle

FileSystemDirectoryHandleInstance properties
-------------------

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

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

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

Regular methods:

`FileSystemDirectoryHandle.getDirectoryHandle()`

Returns a `Promise` fulfilled with a `FileSystemDirectoryHandle` for a subdirectory with the specified name within the directory handle on which the method is called.

`FileSystemDirectoryHandle.getFileHandle()`

Returns a `Promise` fulfilled with a `FileSystemFileHandle` for a file with the specified name, within the directory the method is called.

`FileSystemDirectoryHandle.removeEntry()`

Attempts to asynchronously remove an entry if the directory handle contains a file or directory called the name specified.

`FileSystemDirectoryHandle.resolve()`

Returns a `Promise` fulfilled with an `Array` of directory names from the parent handle to the specified child entry, with the name of the child entry as the last array item.

Asynchronous iterator methods:

`FileSystemDirectoryHandle.entries()`

Returns a new *async iterator* of a given object's own enumerable property `[key, value]` pairs.

`FileSystemDirectoryHandle.keys()`

Returns a new *async iterator* containing the keys for each item in `FileSystemDirectoryHandle`.

`FileSystemDirectoryHandle.values()`

Returns a new *async iterator* containing the values for each index in the `FileSystemDirectoryHandle` object.

`FileSystemDirectoryHandle[@@asyncIterator]()`

Returns the `entries` function by default.

Examples
--------

### Return directory handle

The following example returns a directory handle with the specified name; if the directory does not already exist it is created.

```js
const dirName = "directoryToGetName";

// assuming we have a directory handle: 'currentDirHandle'
const subDir = currentDirHandle.getDirectoryHandle(dirName, { create: true });
```

### Return file path

The following asynchronous function uses `resolve()` to find the path to a chosen file, relative to a specified directory handle.

```js
async function returnPathDirectories(directoryHandle) {
  // Get a file handle by showing a file picker:
  const handle = await self.showOpenFilePicker();
  if (!handle) {
    // User cancelled, or otherwise failed to open a file.
    return;
  }

  // Check if handle exists inside our directory handle
  const relativePaths = await directoryHandle.resolve(handle);

  if (relativePath === null) {
    // Not inside directory handle
  } else {
    // relativePath is an array of names, giving the relative path

    for (const name of relativePaths) {
      // log each entry
      console.log(name);
    }
  }
}
```

### Return handles for all files in a directory

The following example scans recursively through a directory to return `FileSystemFileHandle` objects for each file in that directory:

```js
async function\* getFilesRecursively(entry) {
  if (entry.kind === "file") {
    const file = await entry.getFile();
    if (file !== null) {
      file.relativePath = getRelativePath(entry);
      yield file;
    }
  } else if (entry.kind === "directory") {
    for await (const handle of entry.values()) {
      yield\* getFilesRecursively(handle);
    }
  }
}
for await (const fileHandle of getFilesRecursively(directoryHandle)) {
  console.log(fileHandle);
}
```

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

| Specification |
| --- |
| File System Standard # api-filesystemdirectoryhandle |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files


AudioNode - Web APIs

AudioNode
=========

The **`AudioNode`** interface is a generic interface for representing an audio processing module.

Examples include:

* an audio source (e.g. an HTML `<audio>` or `<video>` element, an `OscillatorNode`, etc.),
* the audio destination,
* intermediate processing module (e.g. a filter like `BiquadFilterNode` or `ConvolverNode`), or
* volume control (like `GainNode`)

EventTarget

AudioNode

**Note:** An `AudioNode` can be target of events, therefore it implements the `EventTarget` interface.

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

`AudioNode.context` Read only

Returns the associated `BaseAudioContext`, that is the object representing the processing graph the node is participating in.

`AudioNode.numberOfInputs` Read only

Returns the number of inputs feeding the node. Source nodes are defined as nodes having a `numberOfInputs` property with a value of `0`.

`AudioNode.numberOfOutputs` Read only

Returns the number of outputs coming out of the node. Destination nodes — like `AudioDestinationNode` — have a value of `0` for this attribute.

`AudioNode.channelCount`

Represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. Its usage and precise definition depend on the value of `AudioNode.channelCountMode`.

`AudioNode.channelCountMode`

Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.

`AudioNode.channelInterpretation`

 Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio up-mixing and down-mixing will happen.
 The possible values are `"speakers"` or `"discrete"`.

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

*Also implements methods from the interface* `EventTarget`.

`AudioNode.connect()`

Allows us to connect the output of this node to be input into another node, either as audio data or as the value of an `AudioParam`.

`AudioNode.disconnect()`

Allows us to disconnect the current node from another one it is already connected to.

Description
-----------

### The audio routing graph

![AudioNodes participating in an AudioContext create an audio routing graph.](/en-US/docs/Web/API/AudioNode/webaudiobasics.png)

Each `AudioNode` has inputs and outputs, and multiple audio nodes are connected to build a *processing graph*. This graph is contained in an `AudioContext`, and each audio node can only belong to one audio context.

A *source node* has zero inputs but one or multiple outputs, and can be used to generate sound. On the other hand, a *destination node* has no outputs; instead, all its inputs are directly played back on the speakers (or whatever audio output device the audio context uses). In addition, there are *processing nodes* which have inputs and outputs. The exact processing done varies from one `AudioNode` to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or lets the audio pass through (for example in the `AnalyserNode`, where the result of the processing is accessed separately).

The more nodes in a graph, the higher the latency will be. For example, if your graph has a latency of 500ms, when the source node plays a sound, it will take half a second until that sound can be heard on your speakers (or even longer because of latency in the underlying audio device). Therefore, if you need to have interactive audio, keep the graph as small as possible, and put user-controlled audio nodes at the end of a graph. For example, a volume control (`GainNode`) should be the last node so that volume changes take immediate effect.

Each input and output has a given amount of *channels*. For example, mono audio has one channel, while stereo audio has two channels. The Web Audio API will up-mix or down-mix the number of channels as required; check the Web Audio spec for details.

For a list of all audio nodes, see the Web Audio API homepage.

### Creating an `AudioNode`

There are two ways to create an `AudioNode`: via the *constructor* and via the *factory method*.

```js
// constructor
const analyserNode = new AnalyserNode(audioCtx, {
  fftSize: 2048,
  maxDecibels: -25,
  minDecibels: -60,
  smoothingTimeConstant: 0.5,
});
```

```js
// factory method
const analyserNode = audioCtx.createAnalyser();
analyserNode.fftSize = 2048;
analyserNode.maxDecibels = -25;
analyserNode.minDecibels = -60;
analyserNode.smoothingTimeConstant = 0.5;
```

You are free to use either constructors or factory methods, or mix both, however there are advantages to using the constructors:

* All parameters can be set during construction time and don't need to be set individually.
* You can sub-class an audio node. While the actual processing is done internally by the browser and cannot be altered, you could write a wrapper around an audio node to provide custom properties and methods.
* Slightly better performance: In both Chrome and Firefox, the factory methods call the constructors internally.

*Brief history:* The first version of the Web Audio spec only defined the factory methods. After a design review in October 2013, it was decided to add constructors because they have numerous benefits over factory methods. The constructors were added to the spec from August to October 2016. Factory methods continue to be included in the spec and are not deprecated.

Example
-------

This simple snippet of code shows the creation of some audio nodes, and how the `AudioNode` properties and methods can be used. You can find examples of such usage on any of the examples linked to on the Web Audio API landing page (for example Violent Theremin).

```js
const audioCtx = new AudioContext();

const oscillator = new OscillatorNode(audioCtx);
const gainNode = new GainNode(audioCtx);

oscillator.connect(gainNode).connect(audioCtx.destination);

oscillator.context;
oscillator.numberOfInputs;
oscillator.numberOfOutputs;
oscillator.channelCount;
```

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

| Specification |
| --- |
| Web Audio API # AudioNode |

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

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

See also
--------

* Using the Web Audio API


WebGL: 2D and 3D graphics for the web - Web APIs

WebGL: 2D and 3D graphics for the web
=====================================

**WebGL** (Web Graphics Library) is a JavaScript API for rendering high-performance interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. WebGL does so by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML `<canvas>` elements. This conformance makes it possible for the API to take advantage of hardware graphics acceleration provided by the user's device.

Support for WebGL is present in all modern browsers (see the compatibility tables below); however, the user's device must also have hardware that supports these features.

The WebGL 2 API introduces support for much of the OpenGL ES 3.0 feature set; it's provided through the `WebGL2RenderingContext` interface.

The `<canvas>` element is also used by the Canvas API to do 2D graphics on web pages.

Reference
---------

### Standard interfaces

* `WebGLRenderingContext`
* `WebGL2RenderingContext`
* `WebGLActiveInfo`
* `WebGLBuffer`
* `WebGLContextEvent`
* `WebGLFramebuffer`
* `WebGLProgram`
* `WebGLQuery`
* `WebGLRenderbuffer`
* `WebGLSampler`
* `WebGLShader`
* `WebGLShaderPrecisionFormat`
* `WebGLSync`
* `WebGLTexture`
* `WebGLTransformFeedback`
* `WebGLUniformLocation`
* `WebGLVertexArrayObject`
### Extensions

* `ANGLE_instanced_arrays`
* `EXT_blend_minmax`
* `EXT_color_buffer_float`
* `EXT_color_buffer_half_float`
* `EXT_disjoint_timer_query`
* `EXT_float_blend`
Experimental
* `EXT_frag_depth`
* `EXT_shader_texture_lod`
* `EXT_sRGB`
* `EXT_texture_compression_bptc`
* `EXT_texture_compression_rgtc`
* `EXT_texture_filter_anisotropic`
* `EXT_texture_norm16`
* `KHR_parallel_shader_compile`
* `OES_draw_buffers_indexed`
* `OES_element_index_uint`
* `OES_fbo_render_mipmap`
* `OES_standard_derivatives`
* `OES_texture_float`
* `OES_texture_float_linear`
* `OES_texture_half_float`
* `OES_texture_half_float_linear`
* `OES_vertex_array_object`
* `OVR_multiview2`
* `WEBGL_color_buffer_float`
* `WEBGL_compressed_texture_astc`
* `WEBGL_compressed_texture_etc`
* `WEBGL_compressed_texture_etc1`
* `WEBGL_compressed_texture_pvrtc`
* `WEBGL_compressed_texture_s3tc`
* `WEBGL_compressed_texture_s3tc_srgb`
* `WEBGL_debug_renderer_info`
* `WEBGL_debug_shaders`
* `WEBGL_depth_texture`
* `WEBGL_draw_buffers`
* `WEBGL_lose_context`
* `WEBGL_multi_draw`
### Events

* `webglcontextlost`
* `webglcontextrestored`
* `webglcontextcreationerror`
### Constants and types

* WebGL constants
* WebGL types
### WebGL 2

WebGL 2 is a major update to WebGL which is provided through the `WebGL2RenderingContext` interface. It is based on OpenGL ES 3.0 and new features include:

* 3D textures,
* Sampler objects,
* Uniform Buffer objects,
* Sync objects,
* Query objects,
* Transform Feedback objects,
* Promoted extensions that are now core to WebGL 2: Vertex Array objects, instancing, multiple render targets, fragment depth.

See also the blog post "WebGL 2 lands in Firefox" and webglsamples.org/WebGL2Samples for a few demos.

Guides and tutorials
--------------------

Below, you'll find an assortment of guides to help you learn WebGL concepts and tutorials that offer step-by-step lessons and examples.

### Guides

Data in WebGL

A guide to variables, buffers, and other types of data used when writing WebGL code.

WebGL best practices

Tips and suggestions to help you improve the quality, performance, and reliability of your WebGL content.

Using extensions

A guide to using WebGL extensions.

### Tutorials

WebGL tutorial

A beginner's guide to WebGL core concepts. A good place to start if you don't have previous WebGL experience.

### Examples

A basic 2D WebGL animation example

This example demonstrates the simple animation of a one-color shape. Topics examined are adapting to aspect ratio differences, a function to build shader programs from sets of multiple shaders, and the basics of drawing in WebGL.

WebGL by example

A series of live samples with short explanations that showcase WebGL concepts and capabilities. The examples are sorted according to topic and level of difficulty, covering the WebGL rendering context, shader programming, textures, geometry, user interaction, and more.

### Advanced tutorials

WebGL model view projection

A detailed explanation of the three core matrices that are typically used to represent a 3D object view: the model, view and projection matrices.

Matrix math for the web

A useful guide to how 3D transform matrices work, and can be used on the web — both for WebGL calculations and in CSS transforms.

Resources
---------

* Khronos WebGL site The main website for WebGL at the Khronos Group.
* WebGL Fundamentals A basic tutorial with fundamentals of WebGL.
* Raw WebGL: An introduction to WebGL A talk by Nick Desaulniers that introduces the basics of WebGL.
* WebGL playground An online tool for creating and sharing WebGL projects. Good for quick prototyping and experimenting.
* WebGL Academy An HTML/JavaScript editor with tutorials to learn basics of webgl programming.
* WebGL Stats A site with statistics about WebGL capabilities in browsers on different platforms.
### Libraries

* three.js is an open-source, fully featured 3D WebGL library.
* Babylon.js is a powerful, simple, and open game and 3D rendering engine packed into a friendly JavaScript framework.
* Pixi.js is a fast, open-source 2D WebGL renderer.
* Phaser is a fast, free and fun open source framework for Canvas and WebGL powered browser games.
* PlayCanvas is an open-source game engine.
* glMatrix is a JavaScript matrix and vector library for high-performance WebGL apps.
* twgl is a library for making webgl less verbose.
* RedGL is an open-source 3D WebGL library.
* vtk.js is a JavaScript library for scientific visualization in your browser.
* webgl-lint will help find errors in your WebGL code and provide useful info
Specifications
--------------

| Specification |
| --- |
| WebGL Specification # 5.14 |
| WebGL 2.0 Specification # 3.7 |

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

### api.WebGLRenderingContext

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

### api.WebGL2RenderingContext

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

### Compatibility notes

In addition to the browser, the GPU itself also needs to support the feature. So, for example, S3 Texture Compression (S3TC) is only available on Tegra-based tablets. Most browsers make the WebGL context available through the `webgl` context name, but older ones need `experimental-webgl` as well. In addition, the upcoming WebGL 2 is fully backwards-compatible and will have the context name `webgl2`.

### Gecko notes

#### WebGL debugging and testing

Firefox provides two preferences available which let you control the capabilities of WebGL for testing purposes:

`webgl.min_capability_mode`

A Boolean property that, when `true`, enables a minimum capability mode. When in this mode, WebGL is configured to only support the bare minimum feature set and capabilities required by the WebGL specification. This lets you ensure that your WebGL code will work on any device or browser, regardless of their capabilities. This is `false` by default.

`webgl.disable_extensions`

A Boolean property that, when `true`, disables all WebGL extensions. This is `false` by default.

See also
--------

* Canvas API
* Compatibility info about WebGL extensions


SVGFESpecularLightingElement - Web APIs

SVGFESpecularLightingElement
============================

The **`SVGFESpecularLightingElement`** interface corresponds to the `<feSpecularLighting>` element.

EventTarget

Node

Element

SVGElement

SVGFESpecularLightingElementInstance properties
-------------------

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

`SVGFESpecularLightingElement.height` Read only

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

`SVGFESpecularLightingElement.in1` Read only

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

`SVGFESpecularLightingElement.kernelUnitLengthX` Read only

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

`SVGFESpecularLightingElement.kernelUnitLengthY` Read only

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

`SVGFESpecularLightingElement.result` Read only

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

`SVGFESpecularLightingElement.specularConstant` Read only

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

`SVGFESpecularLightingElement.specularExponent` Read only

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

`SVGFESpecularLightingElement.surfaceScale` Read only

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

`SVGFESpecularLightingElement.width` Read only

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

`SVGFESpecularLightingElement.x` Read only

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

`SVGFESpecularLightingElement.y` Read only

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

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

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

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

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

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

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

See also
--------

* `<feSpecularLighting>`


HTMLOptionElement - Web APIs

HTMLOptionElement
=================

The **`HTMLOptionElement`** interface represents `<option>` elements and inherits all properties and methods of the `HTMLElement` interface.

EventTarget

Node

Element

HTMLElement

HTMLOptionElementConstructor
-----------

`Option()`

Returns a newly created `HTMLOptionElement` object. It has four parameters: the text to display, `text`, the value associated, `value`, the value of `defaultSelected`, and the value of `selected`. The last three parameters are optional.

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

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

`HTMLOptionElement.defaultSelected`

Has a value of either `true` or `false` that shows the initial value of the `selected` HTML attribute, indicating whether the option is selected by default or not.

`HTMLOptionElement.disabled`

Has a value of either `true` or `false` representing the value of the `disabled` HTML attribute, which indicates that the option is unavailable to be selected. An option can also be disabled if it is a child of an `<optgroup>` element that is disabled.

`HTMLOptionElement.form` Read only

A `HTMLFormElement` representing the same value as the `form` of the corresponding `<select>` element, if the option is a descendant of a `<select>` element, or null if none is found.

`HTMLOptionElement.index` Read only

A `long` representing the position of the option within the list of options it belongs to, in tree-order. If the option is not part of a list of options, like when it is part of the `<datalist>` element, the value is `0`.

`HTMLOptionElement.label` Read only

A string that reflects the value of the `label` HTML attribute, which provides a label for the option. If this attribute isn't specifically set, reading it returns the element's text content.

`HTMLOptionElement.selected`

Has a value of either `true` or `false` that indicates whether the option is currently selected.

`HTMLOptionElement.text`

A string that contains the text content of the element.

`HTMLOptionElement.value`

A string that reflects the value of the `value` HTML attribute, if it exists; otherwise reflects value of the `Node.textContent` property.

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

*Doesn't implement any specific method, but inherits methods from its parent, `HTMLElement`.*

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

| Specification |
| --- |
| HTML Standard # htmloptionelement |

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: `<option>`.
* The `HTMLOptionsCollection` interface.


Gamepad API - Web APIs

Gamepad API
===========

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

The **Gamepad API** is a way for developers to access and respond to signals from gamepads and other game controllers in a simple, consistent way. It contains three interfaces, two events and one specialist function, to respond to gamepads being connected and disconnected, and to access other information about the gamepads themselves, and what buttons and other controls are currently being pressed.

Interfaces
----------

`Gamepad`

Represents a gamepad/controller connected to the computer.

`GamepadButton`

Represents a button on one of the connected controllers.

`GamepadEvent`

The event object representing events fired that are related to gamepads.

### Experimental Gamepad extensions

`GamepadHapticActuator`

Represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware.

`GamepadPose`

Represents the pose of a controller (e.g. position and orientation in 3D space) in the case of a WebVR controller. This is *not* used by the newer WebXR standard.

See also the extensions to the Gamepad interface, for features that allow you to access the above information.

### Extensions to other interfaces

#### Navigator

`Navigator.getGamepads()`

An extension to the `Navigator` object that returns an array of `Gamepad` objects, one for each connected gamepad.

#### Window events

`gamepadconnected`

An event that will fire when a gamepad is connected.

`gamepaddisconnected`

An event that will fire when a gamepad is disconnected.

Tutorials and guides
--------------------

* Using the Gamepad API
* Implementing controls using the Gamepad API
Specifications
--------------

| Specification |
| --- |
| Gamepad # gamepad-interface |
| Gamepad Extensions # partial-gamepad-interface |

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

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

See also
--------

* The Gamepad API by Ted Mielczarek and Robert Nyman
* Simple API demo page (source)


MutationRecord - Web APIs

MutationRecord
==============

The `MutationRecord` is a read-only interface that represents an individual DOM mutation observed by a `MutationObserver`. It is the object inside the array passed to the callback of a `MutationObserver`.

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

`MutationRecord.addedNodes` Read only

The nodes added by a mutation. Will be an empty `NodeList` if no nodes were added.

`MutationRecord.attributeName` Read only

The name of the changed attribute as a string, or `null`.

`MutationRecord.attributeNamespace` Read only

The namespace of the changed attribute as a string, or `null`.

`MutationRecord.nextSibling` Read only

The next sibling of the added or removed nodes, or `null`.

`MutationRecord.oldValue` Read only

The value depends on the `MutationRecord.type`:

* For `attributes`, it is the value of the changed attribute before the change.
* For `characterData`, it is the data of the changed node before the change.
* For `childList`, it is `null`.

`MutationRecord.previousSibling` Read only

The previous sibling of the added or removed nodes, or `null`.

`MutationRecord.removedNodes` Read only

The nodes removed by a mutation. Will be an empty `NodeList` if no nodes were removed.

`MutationRecord.target` Read only

The node the mutation affected, depending on the `MutationRecord.type`.

* For `attributes`, it is the element whose attribute changed.
* For `characterData`, it is the `CharacterData` node.
* For `childList`, it is the node whose children changed.

`MutationRecord.type` Read only

A string representing the type of mutation: `attributes` if the mutation was an attribute mutation, `characterData` if it was a mutation to a `CharacterData` node, and `childList` if it was a mutation to the tree of nodes.

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

| Specification |
| --- |
| DOM Standard # interface-mutationrecord |

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

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


Encoding API - Web APIs

Encoding API
============

The **Encoding API** provides a mechanism for handling text in various character encodings, including legacy non-UTF-8 encodings.

The API provides four interfaces: `TextDecoder`, `TextEncoder`, `TextDecoderStream` and `TextEncoderStream`.

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

Interfaces
----------

* `TextDecoder`
* `TextEncoder`
* `TextDecoderStream`
* `TextEncoderStream`
Specifications
--------------

| Specification |
| --- |
| Encoding Standard # interface-textdecoder |
| Encoding Standard # interface-textencoder |
| Encoding Standard # interface-textencoderstream |
| Encoding Standard # interface-textdecoderstream |

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

### api.TextDecoder

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

### api.TextEncoder

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

### api.TextEncoderStream

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

### api.TextDecoderStream

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

See also
--------

* Encoding API Encodings - Encodings that must be supported for decoding text.
* A polyfill allowing to use this interface in browsers that don't support it


Device Memory API - Web APIs

Device Memory API
=================

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

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

The capabilities of a client device largely depend on the amount of available RAM. Traditionally, developers had to use heuristics and either benchmark a device or infer device capabilities based on other factors like the device manufacturer or User Agent strings.

Determining device memory
-------------------------

There are two ways to determine the approximate amount of RAM a device has: use the Device Memory JavaScript API or accept Client Hints.

### JavaScript API

You may query the approximate amount of RAM a device has by retrieving `Navigator.deviceMemory` or `WorkerNavigator.deviceMemory`.

```js
const RAM = navigator.deviceMemory;
```

### Client Hints

You may also use the Client Hints HTTP Header with the `Device-Memory` directive to retrieve the same approximate RAM capacity.

Interfaces
----------

### Extensions to other interfaces

`Navigator.deviceMemory` Read only

Returns the approximate amount of device memory in gigabytes.

`WorkerNavigator.deviceMemory` Read only

Returns the approximate amount of device memory in gigabytes.

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

| Specification |
| --- |
| Device Memory  |

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

### api.Navigator.deviceMemory

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

### api.WorkerNavigator.deviceMemory

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

### http.headers.Device-Memory

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

See also
--------

* `Device-Memory` header


GPUCompilationInfo - Web APIs

GPUCompilationInfo
==================

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

The **`GPUCompilationInfo`** interface of the WebGPU API represents an array of `GPUCompilationMessage` objects generated by the GPU shader module compiler to help diagnose problems with shader code.

`GPUCompilationInfo` is accessed via `GPUShaderModule.getCompilationInfo()`.

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

`messages`
Experimental
 Read only

An array of `GPUCompilationMessage` objects, each one containing the details of an individual shader compilation message. Messages can be informational, warnings, or errors.

Examples
--------

In the example below, we have deliberately left a parenthesis out of a function declaration in our shader code:

```js
const shaders = `
struct VertexOut {
 @builtin(position) position : vec4f,
 @location(0) color : vec4f
}

@vertex
fn vertex\_main(@location(0) position: vec4f,
 @location(1) color: vec4f -> VertexOut
{
 var output : VertexOut;
 output.position = position;
 output.color = color;
 return output;
}

@fragment
fn fragment\_main(fragData: VertexOut) -> @location(0) vec4f
{
 return fragData.color;
}
`;
```

When we compile the shader module, we use `getCompilationInfo()` to grab some information about the resulting error:

```js
async function init() {
  // ...

  const shaderModule = device.createShaderModule({
    code: shaders,
  });

  const shaderInfo = await shaderModule.getCompilationInfo();
  const firstMessage = shaderInfo.messages[0];

  console.log(firstMessage.lineNum); // 9
  console.log(firstMessage.message); // "expected ')' for function declaration"
  console.log(firstMessage.type); // "error"
  // ...
}
```

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

| Specification |
| --- |
| WebGPU # gpucompilationinfo |

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

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

See also
--------

* The WebGPU API


WebHID API - Web APIs

WebHID API
==========

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

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

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

A Human Interface Device (HID) is a type of device that takes input from or provides output to humans. It also refers to the HID protocol, a standard for bi-directional communication between a host and a device that is designed to simplify the installation procedure. The HID protocol was originally developed for USB devices but has since been implemented over many other protocols, including Bluetooth.

Interfaces
----------

`HID`

Provides methods for connecting to HID devices, listing attached HID devices and event handlers for connected HID devices.

`HIDDevice`

Represents an HID device. It's possible for a single physical device to be represented by multiple `HIDDevice` objects.

`HIDInputReportEvent`

Passed to `HIDDevice.inputreport_event` when an input report is received from any associated HID device.

`HIDConnectionEvent`

Passed to `HID` `connect` and `disconnect` events when a device is connected or disconnected.

Examples
--------

You can connect to a device with the `requestDevice()` method. In this case, we select from all the available devices.

```js
const device = await navigator.hid.requestDevice({ filters: [] });
// A popup titled `... wants to connect to a HID Device` with `Cancel` and `Connect` buttons will show up with a device list to select from.
// Select one and click on `Connect` button. Then the device will be an array with the selected device in it.
```

We can retrieve all the devices the website has been granted access to previously and log the device names to the console.

```js
let devices = await navigator.hid.getDevices();
devices.forEach((device) => {
  console.log(`HID: ${device.productName}`);
});
```

We can register event listeners for disconnection of any HID devices.

```js
navigator.hid.addEventListener("disconnect", (event) => {
  console.log(`HID disconnected: ${event.device.productName}`);
  console.dir(event);
});
// For example, when my connected keyboard gets disconnected, the log in the console will show:
// HID disconnected: USB Keyboard
// {
// bubbles: false
// cancelBubble: false
// cancelable: false
// composed: false
// currentTarget: HID {onconnect: null, ondisconnect: null}
// defaultPrevented: false
// device: HIDDevice {oninputreport: null, opened: false, vendorId: 6700, productId: 11555, productName: "USB Keyboard", …}
// eventPhase: 0
// isTrusted: true
// path: []
// returnValue: true
// srcElement: HID {onconnect: null, ondisconnect: null}
// target: HID {onconnect: null, ondisconnect: null}
// timeStamp: 18176.600000023842
// type: "disconnect"
// }

// The event above is an instance of the HIDConnectionEvent interface.
```

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

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

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

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


UserActivation - Web APIs

UserActivation
==============

The **`UserActivation`** interface provides information about whether a user is currently interacting with the page, or has completed an interaction since page load.

This API is only available in the window context and not exposed to workers.

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

`UserActivation.hasBeenActive` Read only

Indicates whether the current window has sticky user activation.

`UserActivation.isActive` Read only

Indicates whether the current window has transient user activation.

Description
-----------

An object of this type is accessed via the `navigator.userActivation` property, and can be used to query information about a window's user activation state.

 A user activation either implies that the user is currently interacting with the page, or has completed an interaction since page load.
 User activation can be triggered by a button click, pointer touch, or some other user interaction with the page.

There are two kinds of window user activation states:

* Transient activation (user is currently interacting with the page) and
* Sticky activation (user has interacted at least once since page load).

See Features gated by user activation for more information and a list of APIs that require either sticky or transient user activation.

Examples
--------

### Checking if a user gesture was recently performed

Use `navigator.userActivation` to access the `UserActivation` object, and then `UserActivation.isActive` to check whether the user is currently interacting with the page (Transient activation).

```js
if (navigator.userActivation.isActive) {
  // proceed to request playing media, for example
}
```

### Checking if a user gesture was ever performed

Use `UserActivation.hasBeenActive` to check whether the user has ever interacted with the page (Sticky activation).

```js
if (navigator.userActivation.hasBeenActive) {
  // proceed with auto-playing an animation, for example
}
```

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

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

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

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

See also
--------

* `navigator.userActivation`
* Features gated by user activation


SVGTextContentElement - Web APIs

SVGTextContentElement
=====================

The **`SVGTextContentElement`** interface is implemented by elements that support rendering child text content. It is inherited by various text-related interfaces, such as `SVGTextElement`, `SVGTSpanElement`, `SVGTRefElement`, and `SVGTextPathElement`.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGTextContentElementConstants
---------

|  |  |  |
| --- | --- | --- |
| Constant | Value | Description |
| LENGTHADJUST\_UNKNOWN | 0 | Some other value. |
| LENGTHADJUST\_SPACING | 1 | The `spacing` keyword. |
| LENGTHADJUST\_SPACINGANDGLYPHS | 2 | The `spacingAndGlyphs` keyword. |

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

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

`SVGTextContentElement.textLength` Read only

An `SVGAnimatedLength` reflecting the `textLength` attribute of the given element.

`SVGTextContentElement.lengthAdjust` Read only

An `SVGAnimatedEnumeration` reflecting the `lengthAdjust` attribute of the given element. The numeric type values represent one of the constant values above.

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

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

`SVGTextContentElement.getNumberOfChars()`

Returns a long representing the total number of addressable characters available for rendering within the current element, regardless of whether they will be rendered.

`SVGTextContentElement.getComputedTextLength()`

Returns a float representing the computed length for the text within the element.

`SVGTextContentElement.getSubStringLength()`

Returns a float representing the computed length of the formatted text advance distance for a substring of text within the element. Note that this method only accounts for the widths of the glyphs in the substring and any extra spacing inserted by the CSS 'letter-spacing' and 'word-spacing' properties. Visual spacing adjustments made by the 'x' attribute is ignored.

`SVGTextContentElement.getStartPositionOfChar()`

Returns a `DOMPoint` representing the position of a typographic character after text layout has been performed.

**Note:** In SVG 1.1 this method returned an `SVGPoint`.

`SVGTextContentElement.getEndPositionOfChar()`

Returns a `DOMPoint` representing the trailing position of a typographic character after text layout has been performed.

**Note:** In SVG 1.1 this method returned an `SVGPoint`.

`SVGTextContentElement.getExtentOfChar()`

Returns a `DOMRect` representing the computed tight bounding box of the glyph cell that corresponds to a given typographic character.

`SVGTextContentElement.getRotationOfChar()`

Returns a float representing the rotation of typographic character.

`SVGTextContentElement.getCharNumAtPosition()`

Returns a long representing the character which caused a text glyph to be rendered at a given position in the coordinate system. Because the relationship between characters and glyphs is not one-to-one, only the first character of the relevant typographic character is returned

`SVGTextContentElement.selectSubString()`
Deprecated

Selects text within the element.

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

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

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

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


BackgroundFetchManager - Web APIs

BackgroundFetchManager
======================

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 **`BackgroundFetchManager`** interface of the Background Fetch API is a map where the keys are background fetch IDs and the values are `BackgroundFetchRegistration` objects.

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

None.

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

`fetch()`
Experimental

Returns a `Promise` that resolves with a `BackgroundFetchRegistration` object for a supplied array of URLs and `Request` objects.

`get()`
Experimental

Returns a `Promise` that resolves with the `BackgroundFetchRegistration` associated with the provided `id` or `undefined` if the `id` is not found.

`getIds()`
Experimental

Returns the IDs of all registered background fetches.

Examples
--------

The example below shows how to get an instance of `BackgroundFetchManager` from a `ServiceWorkerRegistration` object and calls `fetch()` to download an audio file in the background.

```js
navigator.serviceWorker.ready.then(async (swReg) => {
  const bgFetch = await swReg.backgroundFetch.fetch(
    "my-fetch",
    ["/ep-5.mp3", "ep-5-artwork.jpg"],
    {
      title: "Episode 5: Interesting things.",
      icons: [
        {
          sizes: "300x300",
          src: "/ep-5-icon.png",
          type: "image/png",
        },
      ],
      downloadTotal: 60 \* 1024 \* 1024,
    },
  );
});
```

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

| Specification |
| --- |
| Background Fetch # background-fetch-manager |

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

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


CSSMathInvert - Web APIs

CSSMathInvert
=============

The **`CSSMathInvert`** interface of the CSS\_Object\_Model#css\_typed\_object\_model represents a CSS `calc()` used as `calc(1 / <value>).` It inherits properties and methods from its parent `CSSNumericValue`.

CSSStyleValue

CSSNumericValue

CSSMathValue

CSSMathInvertConstructor
-----------

`CSSMathInvert()`

Creates a new `CSSMathInvert` object.

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

`CSSMathInvert.value` Read only

Returns a `CSSNumericValue` object.

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

*The interface may also inherit methods from its parent interface, `CSSMathValue`.*

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

*The interface may also inherit methods from its parent interface, `CSSMathValue`.*

Examples
--------

To do

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

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

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

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


AudioBuffer - Web APIs

AudioBuffer
===========

The **`AudioBuffer`** interface represents a short audio asset residing in memory, created from an audio file using the `AudioContext.decodeAudioData()` method, or from raw data using `AudioContext.createBuffer()`. Once put into an AudioBuffer, the audio can then be played by being passed into an `AudioBufferSourceNode`.

Objects of these types are designed to hold small audio snippets, typically less than 45 s. For longer sounds, objects implementing the `MediaElementAudioSourceNode` are more suitable. The buffer contains the audio signal waveform encoded as a series of amplitudes in the following format: non-interleaved IEEE754 32-bit linear PCM with a nominal range between `-1` and `+1`, that is, a 32-bit floating point buffer, with each sample between -1.0 and 1.0. If the `AudioBuffer` has multiple channels, they are stored in separate buffers.

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

`AudioBuffer()`

Creates and returns a new `AudioBuffer` object instance.

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

`AudioBuffer.sampleRate` Read only

Returns a float representing the sample rate, in samples per second, of the PCM data stored in the buffer.

`AudioBuffer.length` Read only

Returns an integer representing the length, in sample-frames, of the PCM data stored in the buffer.

`AudioBuffer.duration` Read only

Returns a double representing the duration, in seconds, of the PCM data stored in the buffer.

`AudioBuffer.numberOfChannels` Read only

Returns an integer representing the number of discrete audio channels described by the PCM data stored in the buffer.

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

`AudioBuffer.getChannelData()`

Returns a `Float32Array` containing the PCM data associated with the channel, defined by the `channel` parameter (with `0` representing the first channel).

`AudioBuffer.copyFromChannel()`

Copies the samples from the specified channel of the `AudioBuffer` to the `destination` array.

`AudioBuffer.copyToChannel()`

Copies the samples to the specified channel of the `AudioBuffer`, from the `source` array.

Example
-------

The following simple example shows how to create an `AudioBuffer` and fill it with random white noise. You can find the full source code at our webaudio-examples repository; a running live version is also available.

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// Create an empty three-second stereo buffer at the sample rate of the AudioContext
const myArrayBuffer = audioCtx.createBuffer(
  2,
  audioCtx.sampleRate \* 3,
  audioCtx.sampleRate,
);

// Fill the buffer with white noise;
// just random values between -1.0 and 1.0
for (let channel = 0; channel < myArrayBuffer.numberOfChannels; channel++) {
  // This gives us the actual array that contains the data
  const nowBuffering = myArrayBuffer.getChannelData(channel);
  for (let i = 0; i < myArrayBuffer.length; i++) {
    // Math.random() is in [0; 1.0]
    // audio needs to be in [-1.0; 1.0]
    nowBuffering[i] = Math.random() \* 2 - 1;
  }
}

// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
const source = audioCtx.createBufferSource();

// set the buffer in the AudioBufferSourceNode
source.buffer = myArrayBuffer;

// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioCtx.destination);

// start the source playing
source.start();
```

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

| Specification |
| --- |
| Web Audio API # AudioBuffer |

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

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

See also
--------

* Using the Web Audio API


PushSubscription - Web APIs

PushSubscription
================

The `PushSubscription` interface of the Push API provides a subscription's URL endpoint and allows unsubscribing from a push service.

An instance of this interface can be serialized.

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

`PushSubscription.endpoint` Read only

A string containing the endpoint associated with the push subscription.

`PushSubscription.expirationTime` Read only

A `DOMHighResTimeStamp` of the subscription expiration time associated with the push subscription, if there is one, or null otherwise.

`PushSubscription.options` Read only

An object containing the options used to create the subscription.

`PushSubscription.subscriptionId`
Deprecated
 Read only

A string containing the subscription ID associated with the push subscription.

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

`PushSubscription.getKey()`

Returns an `ArrayBuffer` which contains the client's public key, which can then be sent to a server and used in encrypting push message data.

`PushSubscription.toJSON()`

Standard serializer — returns a JSON representation of the subscription properties.

`PushSubscription.unsubscribe()`

Starts the asynchronous process of unsubscribing from the push service, returning a `Promise` that resolves to a boolean value when the current subscription is successfully unregistered.

Example
-------

```js
navigator.serviceWorker.ready.then((reg) => {
  reg.pushManager.getSubscription().then((subscription) => {
    subscription
      .unsubscribe()
      .then((successful) => {
        // You've successfully unsubscribed
      })
      .catch((e) => {
        // Unsubscribing failed
      });
  });
});
```

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

| Specification |
| --- |
| Push API # pushsubscription-interface |

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

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

See also
--------

* Push API
* Service Worker API


ExtendableMessageEvent - Web APIs

ExtendableMessageEvent
======================

The **`ExtendableMessageEvent`** interface of the Service Worker API represents the event object of a `message` event fired on a service worker (when a message is received on the `ServiceWorkerGlobalScope` from another context) — extends the lifetime of such events.

This interface inherits from the `ExtendableEvent` interface.

Event

ExtendableEvent

ExtendableMessageEventConstructor
-----------

`ExtendableMessageEvent()`

Creates a new `ExtendableMessageEvent` object instance.

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

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

`ExtendableMessageEvent.data` Read only

Returns the event's data. It can be any data type. If dispatched in `messageerror` event, the property will be `null`.

`ExtendableMessageEvent.origin` Read only

Returns the origin of the `Client` that sent the message.

`ExtendableMessageEvent.lastEventId` Read only

Represents, in server-sent events, the last event ID of the event source.

`ExtendableMessageEvent.source` Read only

Returns a reference to the `Client` object that sent the message.

`ExtendableMessageEvent.ports` Read only

Returns the array containing the `MessagePort` objects representing the ports of the associated message channel.

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

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

Examples
--------

In the below example a page gets a handle to the `ServiceWorker` object via `ServiceWorkerRegistration.active`, and then calls its `postMessage()` function.

```js
// in the page being controlled
if (navigator.serviceWorker) {
  navigator.serviceWorker.register("service-worker.js");

  navigator.serviceWorker.addEventListener("message", (event) => {
    // event is a MessageEvent object
    console.log(`The service worker sent me a message: ${event.data}`);
  });

  navigator.serviceWorker.ready.then((registration) => {
    registration.active.postMessage("Hi service worker");
  });
}
```

The service worker can receive the message by listening to the `message` event:

```js
// in the service worker
addEventListener("message", (event) => {
  // event is an ExtendableMessageEvent object
  console.log(`The client sent me a message: ${event.data}`);

  event.source.postMessage("Hi client");
});
```

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

| Specification |
| --- |
| Service Workers # extendablemessageevent-interface |

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

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

See also
--------

* Using Service Workers
* Service workers basic code example
* Channel Messaging


HTMLHeadingElement - Web APIs

HTMLHeadingElement
==================

The **`HTMLHeadingElement`** interface represents the different heading elements, `<h1>` through `<h6>`. It inherits methods and properties from the `HTMLElement` interface.

EventTarget

Node

Element

HTMLElement

HTMLHeadingElementInstance properties
-------------------

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

`HTMLHeadingElement.align`
Deprecated

A string representing an enumerated attribute indicating alignment of the heading with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlheadingelement |

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: h1, h2, h3, h4, h5, and h6.


SVGFEComponentTransferElement - Web APIs

SVGFEComponentTransferElement
=============================

The **`SVGFEComponentTransferElement`** interface corresponds to the `<feComponentTransfer>` element.

EventTarget

Node

Element

SVGElement

SVGFEComponentTransferElementInstance properties
-------------------

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

`SVGFEComponentTransferElement.height` Read only

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

`SVGFEComponentTransferElement.in1` Read only

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

`SVGFEComponentTransferElement.result` Read only

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

`SVGFEComponentTransferElement.width` Read only

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

`SVGFEComponentTransferElement.x` Read only

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

`SVGFEComponentTransferElement.y` Read only

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

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

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

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

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

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

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

See also
--------

* `<feComponentTransfer>`


FontFaceSetLoadEvent - Web APIs

FontFaceSetLoadEvent
====================

The **`FontFaceSetLoadEvent`** interface of the CSS Font Loading API represents events fired at a `FontFaceSet` after it starts loading font faces.

Events are fired when font loading starts (`loading`), loading completes (`loadingdone`) or there is an error loading one of the fonts (`loadingerror`).

Event

FontFaceSetLoadEventConstructor
-----------

`FontFaceSetLoadEvent()`

Creates a new `FontFaceSetLoadEvent` object.

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

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

`FontFaceSetLoadEvent.fontfaces` Read only

 Returns an array of `FontFace` instances.
 Depending on the event, the array will contain font faces that are loading (`loading`), have successfully loaded (`loadingdone`), or have failed to load (`loadingerror`).

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

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

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # fontfacesetloadevent |

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

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

See also
--------

* `Document.fonts`
* `WorkerGlobalScope.fonts`


GPUError - Web APIs

GPUError
========

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

The **`GPUError`** interface of the WebGPU API is the base interface for errors surfaced by `GPUDevice.popErrorScope` and the `uncapturederror` event.

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

`message`
Experimental
 Read only

A string providing a human-readable message that explains why the error occurred.

Examples
--------

For usage examples of error objects based on `GPUError`, see:

* `GPUDevice.popErrorScope`
* The `GPUDevice uncapturederror` event
* `GPUInternalError`, `GPUOutOfMemoryError`, and `GPUValidationError`
Specifications
--------------

| Specification |
| --- |
| WebGPU # gpuerror |

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

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

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices


TrackEvent - Web APIs

TrackEvent
==========

The **`TrackEvent`** interface, which is part of the HTML DOM specification, is used for events which represent changes to a set of available tracks on an HTML media element; these events are `addtrack` and `removetrack`.

It's important not to confuse `TrackEvent` with the `RTCTrackEvent` interface, which is used for tracks which are part of an `RTCPeerConnection`.

Events based on `TrackEvent` are always sent to one of the media track list types:

* Events involving video tracks are always sent to the `VideoTrackList` found in `HTMLMediaElement.videoTracks`
* Events involving audio tracks are always sent to the `AudioTrackList` specified in `HTMLMediaElement.audioTracks`
* Events affecting text tracks are sent to the `TextTrackList` object indicated by `HTMLMediaElement.textTracks`.

Event

TrackEventConstructor
-----------

`TrackEvent()`

Creates and initializes a new `TrackEvent` object with the event type specified, as well as optional additional properties.

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

*`TrackEvent` is based on `Event`, so properties of `Event` are also available on `TrackEvent` objects.*

`track` Read only

The DOM track object the event is in reference to. If not `null`, this is always an object of one of the media track types: `AudioTrack`, `VideoTrack`, or `TextTrack`).

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

*`TrackEvent` has no methods of its own; however, it is based on `Event`, so it provides the methods available on `Event` objects.*

Example
-------

This example sets up a function, `handleTrackEvent()`, which is called for any `addtrack` or `removetrack` event on the first `<video>` element found in the document.

```js
const videoElem = document.querySelector("video");

videoElem.videoTracks.addEventListener("addtrack", handleTrackEvent, false);
videoElem.videoTracks.addEventListener("removetrack", handleTrackEvent, false);
videoElem.audioTracks.addEventListener("addtrack", handleTrackEvent, false);
videoElem.audioTracks.addEventListener("removetrack", handleTrackEvent, false);
videoElem.textTracks.addEventListener("addtrack", handleTrackEvent, false);
videoElem.textTracks.addEventListener("removetrack", handleTrackEvent, false);

function handleTrackEvent(event) {
  let trackKind;

  if (event.target instanceof VideoTrackList) {
    trackKind = "video";
  } else if (event.target instanceof AudioTrackList) {
    trackKind = "audio";
  } else if (event.target instanceof TextTrackList) {
    trackKind = "text";
  } else {
    trackKind = "unknown";
  }

  switch (event.type) {
    case "addtrack":
      console.log(`Added a ${trackKind} track`);
      break;
    case "removetrack":
      console.log(`Removed a ${trackKind} track`);
      break;
  }
}
```

The event handler uses the JavaScript `instanceof` operator to determine which type of track the event occurred on, then outputs to console a message indicating what kind of track it is and whether it's being added to or removed from the element.

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

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

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

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


Serial - Web APIs

Serial
======

**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 `Serial` interface of the `Web Serial API` provides attributes and methods for finding and connecting to serial ports from a web page.

EventTarget

SerialInstance methods
----------------

`Serial.requestPort()`
Experimental

Returns a `Promise` that resolves with an instance of `SerialPort` representing the device chosen by the user or rejects if no device was selected.

This method must be called with user activation.

`Serial.getPorts()`
Experimental

 Returns a `Promise` that resolves with an array of `SerialPort` objects representing serial ports connected to
 the host which the origin has permission to access.

Events
------

The following events are available to `Serial` via event bubbling from `SerialPort`:

`SerialPort` `connect` event

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

`SerialPort` `disconnect` event

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

Examples
--------

The following example shows how a site can check for available ports and allow the user to grant it permission to access additional ports.

On load event listeners are added for the `connect` and `disconnect` events so that the site can react when a device is connected or disconnected from the system. The `getPorts()` method is then called to see which ports are connected that the site already has access to.

If the site doesn't have access to any connected ports it has to wait until it has user activation to proceed. In this example we use a `click` event handler on a button for this task. A filter is passed to `requestPort()` with a USB vendor ID in order to limit the set of devices shown to the user to only USB devices built by a particular manufacturer.

```js
navigator.serial.addEventListener("connect", (e) => {
  // Connect to `e.target` or add it to a list of available ports.
});

navigator.serial.addEventListener("disconnect", (e) => {
  // Remove `e.target` from the list of available ports.
});

navigator.serial.getPorts().then((ports) => {
  // Initialize the list of available ports with `ports` on page load.
});

button.addEventListener("click", () => {
  const usbVendorId = 0xabcd;
  navigator.serial
    .requestPort({ filters: [{ usbVendorId }] })
    .then((port) => {
      // Connect to `port` or add it to the list of available ports.
    })
    .catch((e) => {
      // The user didn't select a port.
    });
});
```

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

| Specification |
| --- |
| Web Serial API # serial-interface |

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

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


FileReader - Web APIs

FileReader
==========

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

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

File objects may be obtained from a `FileList` object returned as a result of a user selecting files using the `<input>` element, or from a drag and drop operation's `DataTransfer` object.

`FileReader` can only access the contents of files that the user has explicitly selected, either using an HTML `<input type="file">` element or by drag and drop. It cannot be used to read a file by pathname from the user's file system. To read files on the client's file system by pathname, use the File System Access API. To read server-side files, use `fetch()`, with CORS permission if reading cross-domain.

EventTarget

FileReaderConstructor
-----------

`FileReader()`

Returns a new `FileReader` object.

See Using files from web applications for details and examples.

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

`FileReader.error` Read only

A `DOMException` representing the error that occurred while reading the file.

`FileReader.readyState` Read only

A number indicating the state of the `FileReader`. This is one of the following:

| Name | Value | Description |
| --- | --- | --- |
| `EMPTY` | `0` | No data has been loaded yet. |
| `LOADING` | `1` | Data is currently being loaded. |
| `DONE` | `2` | The entire read request has been completed. |

`FileReader.result` Read only

The file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.

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

`FileReader.abort()`

Aborts the read operation. Upon return, the `readyState` will be `DONE`.

`FileReader.readAsArrayBuffer()`

Starts reading the contents of the specified `Blob`, once finished, the `result` attribute contains an `ArrayBuffer` representing the file's data.

`FileReader.readAsBinaryString()`
Deprecated

Starts reading the contents of the specified `Blob`, once finished, the `result` attribute contains the raw binary data from the file as a string.

`FileReader.readAsDataURL()`

Starts reading the contents of the specified `Blob`, once finished, the `result` attribute contains a `data:` URL representing the file's data.

`FileReader.readAsText()`

Starts reading the contents of the specified `Blob`, once finished, the `result` attribute contains the contents of the file as a text string. An optional encoding name can be specified.

Events
------

Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface. Remove the event listeners with `removeEventListener()`, once `FileReader` is no longer used, to avoid memory leaks.

`abort`

Fired when a read has been aborted, for example because the program called `FileReader.abort()`.

`error`

Fired when the read failed due to an error.

`load`

Fired when a read has completed successfully.

`loadend`

Fired when a read has completed, successfully or not.

`loadstart`

Fired when a read has started.

`progress`

Fired periodically as data is read.

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

| Specification |
| --- |
| File API # APIASynch |

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

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

See also
--------

* Using files from web applications
* `File`
* `Blob`
* `FileReaderSync`


Highlight - Web APIs

Highlight
=========

The **`Highlight`** interface of the CSS Custom Highlight API is used to represent a collection of `Range` instances to be styled using the API.

To style arbitrary ranges in a page, instantiate a new `Highlight` object, add one or more `Range` objects to it, and register it using the `HighlightRegistry`.

A `Highlight` instance is a `Set`-like object that can hold one or more `Range` objects.

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

`Highlight()`

Returns a newly created `Highlight` object.

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

*The `Highlight` interface doesn't inherit any properties.*

`Highlight.priority`

A number that indicates the priority of this `Highlight` object. When multiple highlights overlap, the browser uses this priority to decide how to style the overlapping parts.

`Highlight.size` Read only

Returns the number of ranges in the `Highlight` object.

`Highlight.type`

An enumerated `String` used to specify the semantic meaning of the highlight. This allows assistive technologies to include this meaning when exposing the highlight to users.

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

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

`Highlight.add()`

Add a new range to this highlight.

`Highlight.clear()`

Remove all ranges from this highlight.

`Highlight.delete()`

Remove a range from this highlight.

`Highlight.entries()`

Returns a new iterator object that contains each range in the highlight object, in insertion order.

`Highlight.forEach()`

Calls the given callback once for each range in the highlight object, in insertion order.

`Highlight.has()`

Returns a boolean asserting whether a range is present the highlight object or not.

`Highlight.keys()`

An alias for `Highlight.values()`.

`Highlight.values()`

Returns a new iterator object that yields the ranges in the highlight object in insertion order.

Examples
--------

The following example demonstrates how to create ranges, instantiate a new `Highlight` object for them, and register it to be styled on the page:

```js
const parentNode = document.getElementById("foo");

// Create a couple of ranges.
const range1 = new Range();
range1.setStart(parentNode, 10);
range1.setEnd(parentNode, 20);

const range2 = new Range();
range2.setStart(parentNode, 40);
range2.setEnd(parentNode, 60);

// Create a custom highlight for these ranges.
const highlight = new Highlight(range1, range2);

// Register the ranges in the HighlightRegistry.
CSS.highlights.set("my-custom-highlight", highlight);
```

The following CSS code snippet demonstrates how to style the registered custom highlight by using the `::highlight` pseudo-element:

```css
::highlight(my-custom-highlight) {
  background-color: peachpuff;
}
```

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

| Specification |
| --- |
| CSS Custom Highlight API Module Level 1 # highlight |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


PluginArray - Web APIs

PluginArray
===========

**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 `PluginArray` interface is used to store a list of `Plugin` objects describing the available plugins; it's returned by the `navigator.plugins` property. The `PluginArray` is not a JavaScript array, but has the `length` property and supports accessing individual items using bracket notation (`plugins[2]`), as well as via `item(index)` and `namedItem("name")` methods.

**Note:** Own properties of `PluginArray` objects are no longer enumerable in the latest browser versions.

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

`PluginArray.length` Read only
Deprecated

The number of plugins in the array.

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

`PluginArray.item`
Deprecated

Returns the `Plugin` at the specified index into the array.

`PluginArray.namedItem`
Deprecated

Returns the `Plugin` with the specified name.

`PluginArray.refresh`
Deprecated

Refreshes all plugins on the current page, optionally reloading documents.

Examples
--------

The following example function returns the version of the Shockwave Flash plugin.

```js
const pluginsLength = navigator.plugins.length;

document.body.innerHTML =
  `${pluginsLength} Plugin(s)<br>` +
  `<table id="pluginTable"><thead>` +
  `<tr><th>Name</th><th>Filename</th><th>description</th><th>version</th></tr>` +
  `</thead><tbody></tbody></table>`;

const table = document.getElementById("pluginTable");

for (let i = 0; i < pluginsLength; i++) {
  let newRow = table.insertRow();
  newRow.insertCell().textContent = navigator.plugins[i].name;
  newRow.insertCell().textContent = navigator.plugins[i].filename;
  newRow.insertCell().textContent = navigator.plugins[i].description;
  newRow.insertCell().textContent = navigator.plugins[i].version ?? "";
}
```

The following example displays information about the installed plugin(s).

```js
const pluginsLength = navigator.plugins.length;

document.write(
  `${pluginsLength.toString()} Plugin(s)<br>` +
    `Name | Filename | description<br>`,
);

for (let i = 0; i < pluginsLength; i++) {
  document.write(
    `${navigator.plugins[i].name} | ${navigator.plugins[i].filename} | ${navigator.plugins[i].description} | ${navigator.plugins[i].version}<br>`,
  );
}
```

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

| Specification |
| --- |
| HTML Standard # pluginarray |

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

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

In addition to listing each plugin as a pseudo-array by zero-indexed numeric properties, Firefox provides properties that are the plugin name directly on the PluginArray object.


CSS Properties and Values API - Web APIs

CSS Properties and Values API
=============================

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

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

* Learn more
* See full compatibility
* Report feedback
The **CSS Properties and Values API** — part of the CSS Houdini umbrella of APIs — allows developers to explicitly define their `CSS custom properties`, allowing for property type checking, default values, and properties that do or do not inherit their value.

Interfaces
----------

`CSS.registerProperty`

Defines how a browser should parse `CSS custom properties`. Access this interface through `CSS.registerProperty` in JavaScript.

`@property`

Defines how a browser should parse `CSS custom properties`. Access this interface through `@property` at-rule in CSS.

Examples
--------

The following will register a `CSS custom property` named `--my-prop` using `CSS.registerProperty` in JavaScript. `--my-prop` will use the CSS color syntax, it will have a default value of `#c0ffee`, and it will not inherit its value:

```js
window.CSS.registerProperty({
  name: "--my-color",
  syntax: "<color>",
  inherits: false,
  initialValue: "#c0ffee",
});
```

The same registration can take place in CSS using the `@property` at-rule:

```css
@property --my-color {
  syntax: "<color>";
  inherits: false;
  initial-value: #c0ffee;
}
```

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

| Specification |
| --- |
| CSS Properties and Values API Level 1 # the-css-property-rule-interface |
| CSS Properties and Values API Level 1 # the-registerproperty-function |

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

### api.CSSPropertyRule

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

### api.CSS.registerProperty\_static

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

See also
--------

* Using the CSS properties and values API
* CSS Painting API
* CSS Typed Object Model
* Houdini APIs