MediaStreamTrackGenerator - Web APIs

MediaStreamTrackGenerator
=========================

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

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

 The **`MediaStreamTrackGenerator`** interface of the `Insertable Streams for MediaStreamTrack API` creates a `WritableStream` that acts as a `MediaStreamTrack` source.
 The object consumes a stream of media frames as input, which can be audio or video frames.

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

`MediaStreamTrackGenerator()`
Experimental

Non-standard

Creates a new `MediaStreamTrackGenerator` object which accepts either `VideoFrame` or `AudioData` objects.

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

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

`MediaStreamTrackGenerator.writable`
Experimental

Non-standard

A `WritableStream`.

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

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

Examples
--------

The following example is from the article Insertable streams for MediaStreamTrack, and demonstrates a barcode scanner application, which process barcodes and highlights them before writing the transformed frames to the writable stream of `MediaStreamTrackGenerator.writable`.

```js
const stream = await getUserMedia({ video: true });
const videoTrack = stream.getVideoTracks()[0];

const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });

const transformer = new TransformStream({
  async transform(videoFrame, controller) {
    const barcodes = await detectBarcodes(videoFrame);
    const newFrame = highlightBarcodes(videoFrame, barcodes);
    videoFrame.close();
    controller.enqueue(newFrame);
  },
});

trackProcessor.readable
  .pipeThrough(transformer)
  .pipeTo(trackGenerator.writable);
```

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

#### No specification found

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

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

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


Client - Web APIs

Client
======

The `Client` interface represents an executable context such as a `Worker`, or a `SharedWorker`. `Window` clients are represented by the more-specific `WindowClient`. You can get `Client`/`WindowClient` objects from methods such as `Clients.matchAll()` and `Clients.get()`.

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

`Client.postMessage()`

Sends a message to the client.

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

`Client.frameType` Read only

The client's frame type as a string. It can be `"auxiliary"`, `"top-level"`, `"nested"`, or `"none"`.

`Client.id` Read only

The universally unique identifier of the client as a string.

`Client.type` Read only

The client's type as a string. It can be `"window"`, `"worker"`, or `"sharedworker"`.

`Client.url` Read only

The URL of the client as a string.

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

| Specification |
| --- |
| Service Workers # client-interface |

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

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

See also
--------

* Using Service Workers


MediaStreamTrackEvent - Web APIs

MediaStreamTrackEvent
=====================

The **`MediaStreamTrackEvent`** interface of the Media Capture and Streams API represents events which indicate that a `MediaStream` has had tracks added to or removed from the stream through calls to Media Capture and Streams API methods. These events are sent to the stream when these changes occur.

Event

MediaStreamTrackEvent
The events based on this interface are `addtrack` and `removetrack`.

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

`MediaStreamTrackEvent()`

Constructs a new `MediaStreamTrackEvent` with the specified configuration.

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

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

`MediaStreamTrackEvent.track` Read only

Returns a `MediaStreamTrack` object representing the track associated with the event.

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

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

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

| Specification |
| --- |
| Media Capture and Streams # mediastreamtrackevent |

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

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

See also
--------

* `MediaStream`: `addtrack` and `removetrack` events
* `MediaStreamTrack`
* Media Capture and Streams API


ScrollTimeline - Web APIs

ScrollTimeline
==============

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

The **`ScrollTimeline`** interface of the Web Animations API represents a scroll progress timeline (see CSS scroll-driven animations for more details).

Pass a `ScrollTimeline` instance to the `Animation()` constructor or the `animate()` method to specify it as the timeline that will control the progress of the animation.

AnimationTimeline

ScrollTimelineConstructor
-----------

`ScrollTimeline()`
Experimental

Creates a new `ScrollTimeline` object instance.

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

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

`source` Read only
Experimental

Returns a reference to the scrollable element (*scroller*) whose scroll position is driving the progress of the timeline and therefore the animation.

`axis` Read only
Experimental

Returns an enumerated value representing the scroll axis that is driving the progress of the timeline.

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

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

Examples
--------

### Displaying the source and axis of a scroll progress timeline

In this example, we animate an element with a `class` of `box` along a view progress timeline — it animates across the screen as the document scrolls. We output the `source` element and scroll `axis` to an `output` element in the top-right corner.

#### HTML

The HTML for the example is shown below.

```html
<div class="content"></div>
<div class="box"></div>
<div class="output"></div>
```

#### CSS

The CSS for the example looks like this:

```css
.content {
  height: 2000px;
}

.box {
  width: 100px;
  height: 100px;
  border-radius: 10px;
  background-color: rebeccapurple;
  position: fixed;
  top: 20px;
  left: 0%;
}

.output {
  font-family: Arial, Helvetica, sans-serif;
  position: fixed;
  top: 5px;
  right: 5px;
}
```

#### JavaScript

In the JavaScript, we grab references to the `box` and `output` `<div>`s, then create a new `ScrollTimeline`, specifying that the element that will drive the scroll timeline progress is the document (`<html>`) element, and the scroll axis is the `block` axis. We then animate the `box` element with the Web Animations API. Last of all, we display the source element and axis in the `output` element.

```js
const box = document.querySelector(".box");
const output = document.querySelector(".output");

const timeline = new ScrollTimeline({
  source: document.documentElement,
  axis: "block",
});

box.animate(
  {
    rotate: ["0deg", "720deg"],
    left: ["0%", "100%"],
  },
  {
    timeline,
  },
);

output.textContent = `Timeline source element: ${timeline.source.nodeName}. Timeline scroll axis: ${timeline.axis}`;
```

#### Result

Scroll to see the box being animated.

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

| Specification |
| --- |
| Scroll-driven Animations # scrolltimeline-interface |

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

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

See also
--------

* Web Animations API
* CSS scroll-driven animations
* `AnimationTimeline`, `ViewTimeline`


CSSRule - Web APIs

CSSRule
=======

The **`CSSRule`** interface represents a single CSS rule. There are several types of rules which inherit properties from `CSSRule`.

* `CSSGroupingRule`
* `CSSStyleRule`
* `CSSImportRule`
* `CSSMediaRule`
* `CSSFontFaceRule`
* `CSSPageRule`
* `CSSNamespaceRule`
* `CSSKeyframesRule`
* `CSSKeyframeRule`
* `CSSCounterStyleRule`
* `CSSSupportsRule`
* `CSSFontFeatureValuesRule`
* `CSSFontPaletteValuesRule`
* `CSSLayerBlockRule`
* `CSSLayerStatementRule`
* `CSSPropertyRule`
Instance properties
-------------------

The `CSSRule` interface specifies the properties common to all rules, while properties unique to specific rule types are specified in the more specialized interfaces for those rules' respective types.

`CSSRule.cssText`

Represents the textual representation of the rule, e.g. "`h1,h2 { font-size: 16pt }`" or "`@import 'url'`". To access or modify parts of the rule (e.g. the value of "font-size" in the example) use the properties on the specialized interface for the rule's type.

`CSSRule.parentRule` Read only

Returns the containing rule, otherwise `null`. E.g. if this rule is a style rule inside an `@media` block, the parent rule would be that `CSSMediaRule`.

`CSSRule.parentStyleSheet` Read only

Returns the `CSSStyleSheet` object for the style sheet that contains this rule

`CSSRule.type` Read only
Deprecated

Returns one of the Type constants to determine which type of rule is represented.

Examples
--------

References to a `CSSRule` may be obtained by looking at a `CSSStyleSheet`'s `cssRules` list.

```js
let myRules = document.styleSheets[0].cssRules; // Returns a CSSRuleList
console.log(myRules);
```

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

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

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

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

See also
--------

* Using dynamic styling information


OES_texture_float extension - Web APIs

OES\_texture\_float extension
=============================

The **`OES_texture_float`** extension is part of the WebGL API and exposes floating-point pixel types for textures.

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

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

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

This extension extends `WebGLRenderingContext.texImage2D()` and `WebGLRenderingContext.texSubImage2D()`:

* The `type` parameter now accepts `gl.FLOAT`.
* The `pixels` parameter now accepts a `Float32Array`.
Limitation: Linear filtering
----------------------------

Linear filtering on floating-point textures is not allowed with this extension. If you set the magnification or minification filter in the `WebGLRenderingContext.texParameter()` method to one of `gl.LINEAR`, `gl.LINEAR_MIPMAP_NEAREST`, `gl.NEAREST_MIPMAP_LINEAR`, or `gl.LINEAR_MIPMAP_LINEAR`, and use floating-point textures, the texture will be marked as incomplete.

To use linear filtering on floating-point textures, enable the `OES_texture_float_linear` extension in addition to this extension.

Floating-point color buffers
----------------------------

This extension implicitly enables the `WEBGL_color_buffer_float` extension (if supported), which allows rendering to 32-bit floating-point color buffers.

Examples
--------

```js
const ext = gl.getExtension("OES\_texture\_float");

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

gl.texImage2D(gl.TEXTURE\_2D, 0, gl.RGBA, gl.RGBA, gl.FLOAT, image);
```

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

| Specification |
| --- |
| WebGL OES\_texture\_float Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.texImage2D()`
* `WebGLRenderingContext.texSubImage2D()`
* `OES_texture_float_linear`
* `OES_texture_half_float`
* `OES_texture_half_float_linear`


FontFace - Web APIs

FontFace
========

The **`FontFace`** interface of the CSS Font Loading API represents a single usable font face.

 This interface defines the source of a font face, either a URL to an external resource or a buffer, and font properties such as `style`, `weight`, and so on.
 For URL font sources it allows authors to trigger when the remote font is fetched and loaded, and to track loading status.

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

`FontFace()`

Constructs and returns a new `FontFace` object, built from an external resource described by a URL or from an `ArrayBuffer`.

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

`FontFace.ascentOverride`

A string that retrieves or sets the *ascent metric* of the font. It is equivalent to the `ascent-override` descriptor.

`FontFace.descentOverride`

A string that retrieves or sets the *descent metric* of the font. It is equivalent to the `descent-override` descriptor.

`FontFace.display`

A string that determines how a font face is displayed based on whether and when it is downloaded and ready to use.

`FontFace.family`

A string that retrieves or sets the *family* of the font. It is equivalent to the `font-family` descriptor.

`FontFace.featureSettings`

A string that retrieves or sets infrequently used font features that are not available from a font's variant properties. It is equivalent to the CSS `font-feature-settings` property.

`FontFace.lineGapOverride`

A string that retrieves or sets the *line-gap metric* of the font. It is equivalent to the `line-gap-override` descriptor.

`FontFace.loaded` Read only

Returns a `Promise` that resolves with the current `FontFace` object when the font specified in the object's constructor is done loading or rejects with a `SyntaxError` `DOMException`.

`FontFace.status` Read only

Returns an enumerated value indicating the status of the font, one of `"unloaded"`, `"loading"`, `"loaded"`, or `"error"`.

`FontFace.stretch`

A string that retrieves or sets how the font *stretches*. It is equivalent to the `font-stretch` descriptor.

`FontFace.style`

A string that retrieves or sets the *style* of the font. It is equivalent to the `font-style` descriptor.

`FontFace.unicodeRange`

A string that retrieves or sets the *range of unicode code points* encompassing the font. It is equivalent to the `unicode-range` descriptor.

`FontFace.variant`

A string that retrieves or sets the *variant* of the font.

`FontFace.variationSettings`
Experimental

A string that retrieves or sets the *variation settings* of the font. It is equivalent to the `font-variation-settings` descriptor.

`FontFace.weight`

A string that contains the *weight* of the font. It is equivalent to the `font-weight` descriptor.

`FontFace.load()`

Loads a font based on current object's constructor-passed requirements, including a location or source buffer, and returns a `Promise` that resolves with the current FontFace object.

Examples
--------

 The code below defines a font face using data at the URL "myfont.woff" with a few font descriptors.
 Just to show how it works, we then define the `stretch` descriptor using a property.

```js
//Define a FontFace
const font = new FontFace("myfont", "url(myfont.woff)", {
  style: "italic",
  weight: "400",
});

font.stretch = "condensed";
```

Next we load the font using `FontFace.load()` and use the returned promise to track completion or report an error.

```js
//Load the font
font.load().then(
  () => {
    // Resolved - add font to document.fonts
  },
  (err) => {
    console.error(err);
  },
);
```

 To actually *use* the font we will need to add it to a `FontFaceSet`.
 We could do that before or after loading the font.

For additional examples see CSS Font Loading API > Examples.

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

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

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

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

See also
--------

* @font-face


NavigationHistoryEntry - Web APIs

NavigationHistoryEntry
======================

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

The **`NavigationHistoryEntry`** interface of the Navigation API represents a single navigation history entry.

These objects are commonly accessed via the `Navigation.currentEntry` property and `Navigation.entries()` method.

The Navigation API only exposes history entries created in the current browsing context that have the same origin as the current page (e.g. not navigations inside embedded `<iframe>`s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than with the older History API.

EventTarget

NavigationHistoryEntryInstance properties
-------------------

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

`id` Read only
Experimental

Returns the `id` of the history entry. This is a unique, UA-generated value that always represents a specific history entry, useful to correlate it with an external resource such as a storage cache.

`index` Read only
Experimental

Returns the index of the history entry in the history entries list (that is, the list returned by `Navigation.entries()`), or `-1` if the entry does not appear in the list.

`key` Read only
Experimental

Returns the `key` of the history entry. This is a unique, UA-generated value that represents the history entry's slot in the entries list rather than the entry itself. It is used to navigate that particular slot via `Navigation.traverseTo()`. The `key` will be reused by other entries that replace the entry in the list (that is, if the `NavigateEvent.navigationType` is `replace`).

`sameDocument` Read only
Experimental

Returns `true` if this history entry is for the same `document` as the current `Document` value, or `false` otherwise.

`url` Read only
Experimental

Returns the absolute URL of this history entry. If the entry corresponds to a different document than the current one (like `sameDocument` property is `false`), and that document was fetched with a `referrer policy` header set to `no-referrer` or `origin`, the property returns `null`.

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

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

`getState()`
Experimental

Returns a clone of the available state associated with this history entry.

Events
------

`dispose`
Experimental

Fires when the entry is no longer part of the history entry list.

Examples
--------

```js
function initHomeBtn() {
  // Get the key of the first loaded entry
  // so the user can always go back to this view.
  const { key } = navigation.currentEntry;
  backToHomeButton.onclick = () => {
    navigation.traverseTo(key);
  };
}
// Intercept navigate events, such as link clicks, and
// replace them with single-page navigations
navigation.addEventListener("navigate", (event) => {
  event.intercept({
    async handler() {
      // Navigate to a different view,
      // but the "home" button will always work.
    },
  });
});
```

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

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

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Console API - Web APIs

Console API
===========

The Console API provides functionality to allow developers to perform debugging tasks, such as logging messages or the values of variables at set points in your code, or timing how long an operation takes to complete.

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

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

The Console API started as a largely proprietary API, with different browsers implementing it, albeit in inconsistent ways. The Console API spec was created to define consistent behavior, and all modern browsers eventually settled on implementing this behavior — although some implementations still have their own additional proprietary functions. Find out about these at:

* Google Chrome DevTools implementation
* Safari DevTools implementation

Usage is very simple — the `console` object contains many methods that you can call to perform rudimentary debugging tasks, generally focused around logging various values to the browser's Web Console.

By far the most commonly-used method is `console.log()`, which is used to log the current value contained inside a specific variable.

Interfaces
----------

`console`

Provides rudimentary debugging functionality, including logging, stack traces, timers, and counters.

Examples
--------

```js
let myString = "Hello world";

// Output "Hello world" to the console
console.log(myString);
```

See the console reference page for more examples.

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

| Specification |
| --- |
| Console Standard # console-namespace |

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

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

See also
--------

* Tools
* Web Console — how the Web Console in Firefox handles console API calls
* about:debugging — how to see console output when the debugging target is a mobile device


Performance APIs - Web APIs

Performance APIs
================

The Performance API is a group of standards used to measure the performance of web applications.

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

To ensure web applications are fast, it's important to measure and analyze various performance metrics. The Performance API provides important built-in metrics and the ability to add your own measurements to the browser's performance timeline. The performance timeline contains high precision timestamps and can be displayed in developer tools. You can also send its data to analytics end points to record performance metrics over time.

Each performance metric is represented by a single `PerformanceEntry`. A performance entry has a `name`, a `duration`, a `startTime`, and a `type`. All performance metrics extend the `PerformanceEntry` interface and qualify it further.

Most of the performance entries are recorded for you without you having to do anything, and are then accessible either through `Performance.getEntries()` or (preferably) through `PerformanceObserver`. For example, `PerformanceEventTiming` entries are recorded for events that take longer than a set threshold. But the Performance API also enables you to define and record your own custom events, using the `PerformanceMark` and `PerformanceMeasure` interfaces.

The main `Performance` interface is available for each global using `self.performance` and enables you to add custom performance entries, to clear performance entries, and to retrieve performance entries.

The `PerformanceObserver` interface enables you to listen for various types of performance entry as they are recorded.

For more conceptual information, see the Performance API guides below.

![UML diagram of Performance APIs](/en-US/docs/Web/API/Performance_API/diagram.svg)

Reference
---------

The following interfaces are present in the Performance API:

`EventCounts`

A read-only map returned by `performance.eventCounts` containing the number of events which have been dispatched per event type.

`LargestContentfulPaint`

Measures the render time of the largest image or text block visible within the viewport, recorded from when the page first begins to load.

`LayoutShift`

Provides insights into the layout stability of web pages based on movements of the elements on the page.

`LayoutShiftAttribution`

Provides debugging information about elements which have shifted.

`Performance`

Main interface to access performance measurements. Available to window and worker contexts using `self.performance`.

`PerformanceElementTiming`

Measures rendering timestamps of specific elements.

`PerformanceEntry`

An entry on the performance timeline encapsulating a single performance metric. All performance metrics inherit from this interface.

`PerformanceEventTiming`

Measures latency of events and first input delay (FID).

`PerformanceLongTaskTiming`

Detects long tasks that occupy rendering and block other tasks from being executed.

`PerformanceMark`

Custom marker for your own entry on the performance timeline.

`PerformanceMeasure`

Custom time measurement between two performance entries.

`PerformanceNavigationTiming`

Measures document navigation events, like how much time it takes to load a document.

`PerformanceObserver`

Listens for new performance entries as they are recorded in the performance timeline.

`PerformanceObserverEntryList`

List of entries that were observed in a performance observer.

`PerformancePaintTiming`

Measures render operations during web page construction.

`PerformanceResourceTiming`

Measures network loading metrics such as redirect start and end times, fetch start, DNS lookup start and end times, response start and end times for resources such as images, scripts, fetch calls, etc.

`PerformanceServerTiming`

Surfaces server metrics that are sent with the response in the `Server-Timing` HTTP header.

`TaskAttributionTiming`

Identifies the type of task and the container that is responsible for the long task.

`VisibilityStateEntry`

Measures the timing of page visibility state changes, i.e., when a tab changes from the foreground to the background or vice versa.

Guides
------

The following guides help you to understand key concepts of the Performance API and provide an overview about its abilities:

* Performance data: Collecting, accessing, and working with performance data.
* High precision timing: Measuring with high precision time and monotonic clocks.
* Resource timing: Measuring network timing for fetched resources, such as images, CSS, and JavaScript.
* Navigation timing: Measuring navigation timing of a document.
* User timing: Measuring and recording performance data custom to your application.
* Server timing: Collecting server-side metrics.
Specifications
--------------

| Specification |
| --- |
| Element Timing API  |
| Event Timing API  |
| High Resolution Time  |
| Largest Contentful Paint  |
| Layout Instability  |
| Long Tasks API  |
| Navigation Timing Level 2  |
| Paint Timing  |
| Performance Timeline  |
| Resource Timing  |
| Server Timing  |
| User Timing  |

See also
--------

* Web performance
* Learn: Web performance


HTMLQuoteElement - Web APIs

HTMLQuoteElement
================

The **`HTMLQuoteElement`** interface provides special properties and methods (beyond the regular `HTMLElement` interface it also has available to it by inheritance) for manipulating quoting elements, like `<blockquote>` and `<q>`, but not the `<cite>` element.

EventTarget

Node

Element

HTMLElement

HTMLQuoteElementInstance properties
-------------------

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

`HTMLQuoteElement.cite`

A string reflecting the `cite` HTML attribute, containing a URL for the source of the quotation.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlquoteelement |

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

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

See also
--------

* The HTML elements implementing this interface: `<blockquote>` and `<q>`, but not `<cite>`.


WEBGL_compressed_texture_s3tc_srgb extension - Web APIs

WEBGL\_compressed\_texture\_s3tc\_srgb extension
================================================

The **`WEBGL_compressed_texture_s3tc_srgb`** extension is part of the WebGL API and exposes four S3TC compressed texture formats for the sRGB colorspace.

Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures.

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

**Note:** This extension is available to both WebGL1 and WebGL2 contexts.

Constants
---------

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

`ext.COMPRESSED_SRGB_S3TC_DXT1_EXT`

A DXT1-compressed image in an sRGB image format.

`ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT`

A DXT1-compressed image in an sRGB image format with a simple on/off alpha value.

`ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT`

A DXT3-compressed image in an sRGBA image format.

`ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT`

A DXT5-compressed image in an sRGBA image format.

Examples
--------

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

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

gl.compressedTexImage2D(
  gl.TEXTURE\_2D,
  0,
  ext.COMPRESSED\_SRGB\_S3TC\_DXT1\_EXT,
  512,
  512,
  0,
  textureData,
);

gl.texParameteri(gl.TEXTURE\_2D, gl.TEXTURE\_MAG\_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE\_2D, gl.TEXTURE\_MIN\_FILTER, gl.LINEAR);
```

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

| Specification |
| --- |
| WebGL WEBGL\_compressed\_texture\_s3tc\_srgb Extension Specification  |

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

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

See also
--------

* S3 Texture Compression – OpenGL wiki
* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.compressedTexImage2D()`
* `WebGLRenderingContext.compressedTexSubImage2D()`
* `WebGLRenderingContext.getParameter()`


NodeList - Web APIs

NodeList
========

**`NodeList`** objects are collections of nodes, usually returned by properties such as `Node.childNodes` and methods such as `document.querySelectorAll()`.

**Note:** Although `NodeList` is not an `Array`, it is possible to iterate over it with `forEach()`. It can also be converted to a real `Array` using `Array.from()`.

Live vs. Static NodeLists
-------------------------

Although they are both considered `NodeList` objects, there are 2 varieties of NodeList: *live* and *static*.

### Live NodeLists

In some cases, the `NodeList` is *live*, which means that changes in the DOM automatically update the collection.

For example, `Node.childNodes` is live:

```js
const parent = document.getElementById("parent");
let childNodes = parent.childNodes;
console.log(childNodes.length); // let's assume "2"
parent.appendChild(document.createElement("div"));
console.log(childNodes.length); // outputs "3"
```

### Static NodeLists

In other cases, the `NodeList` is *static,* where any changes in the DOM do not affect the content of the collection. The ubiquitous `document.querySelectorAll()` method returns a *static* `NodeList`.

It's good to keep this distinction in mind when you choose how to iterate over the items in the `NodeList`, and whether you should cache the list's `length`.

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

`NodeList.length` Read only

The number of nodes in the `NodeList`.

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

`NodeList.item()`

Returns an item in the list by its index, or `null` if the index is out-of-bounds.

An alternative to accessing `nodeList[i]` (which instead returns `undefined` when `i` is out-of-bounds). This is mostly useful for non-JavaScript DOM implementations.

`NodeList.entries()`

Returns an `iterator`, allowing code to go through all key/value pairs contained in the collection. (In this case, the keys are integers starting from `0` and the values are nodes.)

`NodeList.forEach()`

Executes a provided function once per `NodeList` element, passing the element as an argument to the function.

`NodeList.keys()`

Returns an `iterator`, allowing code to go through all the keys of the key/value pairs contained in the collection. (In this case, the keys are integers starting from `0`.)

`NodeList.values()`

Returns an `iterator` allowing code to go through all values (nodes) of the key/value pairs contained in the collection.

Example
-------

It's possible to loop over the items in a `NodeList` using a for loop:

```js
for (let i = 0; i < myNodeList.length; i++) {
  let item = myNodeList[i];
}
```

**Don't use `for...in` to enumerate the items in `NodeList`s**, since they will *also* enumerate its `length` and `item` properties and cause errors if your script assumes it only has to deal with `element` objects. Also, `for...in` is not guaranteed to visit the properties in any particular order.

`for...of` loops loop over `NodeList` objects correctly:

```js
const list = document.querySelectorAll("input[type=checkbox]");
for (const checkbox of list) {
  checkbox.checked = true;
}
```

Browsers also support the iterator method (`forEach()`) as well as `entries()`, `values()`, and `keys()`.

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

| Specification |
| --- |
| DOM Standard # interface-nodelist |

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

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


IDBDatabase - Web APIs

IDBDatabase
===========

The **`IDBDatabase`** interface of the IndexedDB API provides a connection to a database; you can use an `IDBDatabase` object to open a transaction on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database.

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

**Note:** Everything you do in IndexedDB always happens in the context of a transaction, representing interactions with data in the database. All objects in IndexedDB — including object stores, indexes, and cursors — are tied to a particular transaction. Thus, you cannot execute commands, access data, or open anything outside of a transaction.

EventTarget

IDBDatabaseInstance properties
-------------------

`IDBDatabase.name` Read only

A string that contains the name of the connected database.

`IDBDatabase.version` Read only

A 64-bit integer that contains the version of the connected database. When a database is first created, this attribute is an empty string.

`IDBDatabase.objectStoreNames` Read only

A `DOMStringList` that contains a list of the names of the object stores currently in the connected database.

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

Inherits from: EventTarget

`IDBDatabase.close()`

Returns immediately and closes the connection to a database in a separate thread.

`IDBDatabase.createObjectStore()`

Creates and returns a new object store or index.

`IDBDatabase.deleteObjectStore()`

Destroys the object store with the given name in the connected database, along with any indexes that reference it.

`IDBDatabase.transaction()`

Immediately returns a transaction object (`IDBTransaction`) containing the `IDBTransaction.objectStore` method, which you can use to access your object store. Runs in a separate thread.

Events
------

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

`close`

An event fired when the database connection is unexpectedly closed.

`versionchange`

An event fired when a database structure change was requested.

The following events are available to `IDBDatabase` via event bubbling from `IDBTransaction`:

`IDBTransaction` `abort`

An event fired when a transaction is aborted.

`IDBTransaction` `error`

An event fired when a request returns an error and the event bubbles up to the connection object.

Example
-------

In the following code snippet, we open a database asynchronously (`IDBFactory`), handle success and error cases, and create a new object store in the case that an upgrade is needed (`IDBdatabase`). For a complete working example, see our To-do Notifications app (view example live).

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the IDBDatabase object,
// when the database is opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db
  // variable. This is used a lot later on
  db = DBOpenRequest.result;

  // Run the displayData() function to populate the task
  // list with all the to-do list data already in the IDB
  displayData();
};

// This event handles the event whereby a new version of
// the database needs to be created Either one has not
// been created before, or a new version number has been
// submitted via the window.indexedDB.open line above

DBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = (event) => {
    note.innerHTML += "<li>Error loading database.</li>";
  };

  // Create an objectStore for this database using
  // IDBDatabase.createObjectStore

  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain

  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });

  objectStore.createIndex("notified", "notified", { unique: false });

  note.innerHTML += "<li>Object store created.</li>";
};
```

This next line opens up a transaction on the Database, then opens an object store that we can then manipulate the data inside of.

```js
const objectStore = db
  .transaction("toDoList", "readwrite")
  .objectStore("toDoList");
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # database-interface |

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

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

See also
--------

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


SVGAnimatedNumberList - Web APIs

SVGAnimatedNumberList
=====================

SVG animated number list interface
----------------------------------

The `SVGAnimatedNumber` interface is used for attributes which take a list of numbers and which can be animated.

### Interface overview

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

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

`SVGAnimatedNumberList.baseVal` Read only

A `SVGNumberList` that represents the base value of the given attribute before applying any animations.

`SVGAnimatedNumberList.animVal` Read only

A read only `SVGNumberList` that represents the current animated value of the given attribute. If the given attribute is not currently being animated, then the `SVGNumberList` will have the same contents as `baseVal`. The object referenced by `animVal` will always be distinct from the one referenced by `baseVal`, even when the attribute is not animated.

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

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

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

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


HTMLMediaElement - Web APIs

HTMLMediaElement
================

The **`HTMLMediaElement`** interface adds to `HTMLElement` the properties and methods needed to support basic media-related capabilities that are common to audio and video.

The `HTMLVideoElement` and `HTMLAudioElement` elements both inherit this interface.

EventTarget

Node

Element

HTMLElement

HTMLMediaElementInstance properties
-------------------

*This interface also inherits properties from its ancestors `HTMLElement`, `Element`, `Node`, and `EventTarget`.*

`HTMLMediaElement.audioTracks`

An `AudioTrackList` that lists the `AudioTrack` objects contained in the element.

`HTMLMediaElement.autoplay`

A boolean value that reflects the `autoplay` HTML attribute, indicating whether playback should automatically begin as soon as enough media is available to do so without interruption.

**Note:** Automatically playing audio when the user doesn't expect or desire it is a poor user experience and should be avoided in most cases, though there are exceptions. See the Autoplay guide for media and Web Audio APIs for more information. Keep in mind that browsers may ignore autoplay requests, so you should ensure that your code isn't dependent on autoplay working.

`HTMLMediaElement.buffered` Read only

Returns a `TimeRanges` object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the `buffered` property is accessed.

`HTMLMediaElement.controls`

A boolean that reflects the `controls` HTML attribute, indicating whether user interface items for controlling the resource should be displayed.

`HTMLMediaElement.controlsList` Read only

Returns a `DOMTokenList` that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls. The `DOMTokenList` takes one or more of three possible values: `nodownload`, `nofullscreen`, and `noremoteplayback`.

`HTMLMediaElement.crossOrigin`

A string indicating the CORS setting for this media element.

`HTMLMediaElement.currentSrc` Read only

Returns a string with the absolute URL of the chosen media resource.

`HTMLMediaElement.currentTime`

A double-precision floating-point value indicating the current playback time in seconds; if the media has not started to play and has not been seeked, this value is the media's initial playback time. Setting this value seeks the media to the new time. The time is specified relative to the media's timeline.

`HTMLMediaElement.defaultMuted`

A boolean that reflects the `muted` HTML attribute, which indicates whether the media element's audio output should be muted by default.

`HTMLMediaElement.defaultPlaybackRate`

A `double` indicating the default playback rate for the media.

`HTMLMediaElement.disableRemotePlayback`

A boolean that sets or returns the remote playback state, indicating whether the media element is allowed to have a remote playback UI.

`HTMLMediaElement.duration` Read only

A read-only double-precision floating-point value indicating the total duration of the media in seconds. If no media data is available, the returned value is `NaN`. If the media is of indefinite length (such as streamed live media, a WebRTC call's media, or similar), the value is `+Infinity`.

`HTMLMediaElement.ended` Read only

Returns a boolean that indicates whether the media element has finished playing.

`HTMLMediaElement.error` Read only

Returns a `MediaError` object for the most recent error, or `null` if there has not been an error.

`HTMLMediaElement.loop`

A boolean that reflects the `loop` HTML attribute, which indicates whether the media element should start over when it reaches the end.

`HTMLMediaElement.mediaKeys` Read only

Returns a `MediaKeys` object, that is a set of keys that the element can use for decryption of media data during playback. If no key is available, it can be `null`.

`HTMLMediaElement.muted`

A boolean that determines whether audio is muted. `true` if the audio is muted and `false` otherwise.

`HTMLMediaElement.networkState` Read only

Returns a `unsigned short` (enumeration) indicating the current state of fetching the media over the network.

`HTMLMediaElement.paused` Read only

Returns a boolean that indicates whether the media element is paused.

`HTMLMediaElement.playbackRate`

A `double` that indicates the rate at which the media is being played back.

`HTMLMediaElement.played` Read only

Returns a `TimeRanges` object that contains the ranges of the media source that the browser has played, if any.

`HTMLMediaElement.preload`

A string that reflects the `preload` HTML attribute, indicating what data should be preloaded, if any. Possible values are: `none`, `metadata`, `auto`.

`HTMLMediaElement.preservesPitch`

A boolean value that determines if the pitch of the sound will be preserved. If set to `false`, the pitch will adjust to the speed of the audio.

`HTMLMediaElement.readyState` Read only

Returns a `unsigned short` (enumeration) indicating the readiness state of the media.

`HTMLMediaElement.remote` Read only

Return a `RemotePlayback` object instance associated with the media element.

`HTMLMediaElement.seekable` Read only

Returns a `TimeRanges` object that contains the time ranges that the user is able to seek to, if any.

`HTMLMediaElement.seeking` Read only

Returns a boolean that indicates whether the media is in the process of seeking to a new position.

`HTMLMediaElement.sinkId` Read only

Returns a string that is the unique ID of the audio device delivering output, or an empty string if the user agent default audio device is being used.

`HTMLMediaElement.src`

A string that reflects the `src` HTML attribute, which contains the URL of a media resource to use.

`HTMLMediaElement.srcObject`

A `MediaStream` representing the media to play or that has played in the current `HTMLMediaElement`, or `null` if not assigned.

`HTMLMediaElement.textTracks` Read only

Returns a `TextTrackList` object containing the list of `TextTrack` objects contained in the element.

`HTMLMediaElement.videoTracks` Read only

Returns a `VideoTrackList` object containing the list of `VideoTrack` objects contained in the element.

`HTMLMediaElement.volume`

A `double` indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).

Obsolete properties
-------------------

These properties are obsolete and should not be used, even if a browser still supports them.

`HTMLMediaElement.controller`
Deprecated

Non-standard

A `MediaController` object that represents the media controller assigned to the element, or `null` if none is assigned.

`HTMLMediaElement.mediaGroup`
Deprecated

Non-standard

A string that reflects the `mediagroup` HTML attribute, which indicates the name of the group of elements it belongs to. A group of media elements shares a common `MediaController`.

`HTMLMediaElement.mozAudioCaptured` Read only
Non-standard

Deprecated

Returns a boolean. Related to audio stream capture.

`HTMLMediaElement.mozFragmentEnd`
Non-standard

Deprecated

A `double` that provides access to the fragment end time if the media element has a fragment URI for `currentSrc`, otherwise it is equal to the media duration.

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

*This interface also inherits methods from its ancestors `HTMLElement`, `Element`, `Node`, and `EventTarget`.*

`HTMLMediaElement.addTextTrack()`

Adds a new `TextTrack` object (such as a track for subtitles) to a media element. This is a programmatic interface only and does not affect the DOM.

`HTMLMediaElement.captureStream()`

Returns `MediaStream`, captures a stream of the media content.

`HTMLMediaElement.canPlayType()`

Given a string specifying a MIME media type (potentially with the `codecs` parameter included), `canPlayType()` returns the string `probably` if the media should be playable, `maybe` if there's not enough information to determine whether the media will play or not, or an empty string if the media cannot be played.

`HTMLMediaElement.fastSeek()`

Quickly seeks to the given time with low precision.

`HTMLMediaElement.load()`

Resets the media to the beginning and selects the best available source from the sources provided using the `src` attribute or the `<source>` element.

`HTMLMediaElement.pause()`

Pauses the media playback.

`HTMLMediaElement.play()`

Begins playback of the media.

`HTMLMediaElement.seekToNextFrame()`
Deprecated

Non-standard

Seeks to the next frame in the media. This non-standard, experimental method makes it possible to manually drive reading and rendering of media at a custom speed, or to move through the media frame-by-frame to perform filtering or other operations.

`HTMLMediaElement.setMediaKeys()`

Returns `Promise`. Sets the `MediaKeys` keys to use when decrypting media during playback.

`HTMLMediaElement.setSinkId()`

Sets the ID of the audio device to use for output and returns a `Promise`. This only works when the application is authorized to use the specified device.

Obsolete methods
----------------

*These methods are obsolete and should not be used, even if a browser still supports them.*

`HTMLMediaElement.mozCaptureStream()`
Non-standard

[enter description]

`HTMLMediaElement.mozCaptureStreamUntilEnded()`
Non-standard

Deprecated

[enter description]

`HTMLMediaElement.mozGetMetadata()`
Non-standard

Deprecated

Returns `Object`, which contains properties that represent metadata from the playing media resource as `{key: value}` pairs. A separate copy of the data is returned each time the method is called. This method must be called after the `loadedmetadata` event fires.

Events
------

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

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

`abort`

Fired when the resource was not fully loaded, but not as the result of an error.

`canplay`

Fired when the user agent can play the media, but estimates that **not** enough data has been loaded to play the media up to its end without having to stop for further buffering of content.

`canplaythrough`

Fired when the user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.

`durationchange`

Fired when the duration property has been updated.

`emptied`

Fired when the media has become empty; for example, when the media has already been loaded (or partially loaded), and the `HTMLMediaElement.load()` method is called to reload it.

`ended`

Fired when playback stops when end of the media (<audio> or <video>) is reached or because no further data is available.

`error`

Fired when the resource could not be loaded due to an error.

`loadeddata`

Fired when the first frame of the media has finished loading.

`loadedmetadata`

Fired when the metadata has been loaded.

`loadstart`

Fired when the browser has started to load a resource.

`pause`

Fired when a request to pause play is handled and the activity has entered its paused state, most commonly occurring when the media's `HTMLMediaElement.pause()` method is called.

`play`

Fired when the `paused` property is changed from `true` to `false`, as a result of the `HTMLMediaElement.play()` method, or the `autoplay` attribute.

`playing`

Fired when playback is ready to start after having been paused or delayed due to lack of data.

`progress`

Fired periodically as the browser loads a resource.

`ratechange`

Fired when the playback rate has changed.

`resize`

Fired when one or both of the `videoWidth` and `videoHeight` properties have just been updated.

`seeked`

Fired when a seek operation completes.

`seeking`

Fired when a seek operation begins.

`stalled`

Fired when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming.

`suspend`

Fired when the media data loading has been suspended.

`timeupdate`

Fired when the time indicated by the `currentTime` property has been updated.

`volumechange`

Fired when the volume has changed.

`waiting`

Fired when playback has stopped because of a temporary lack of data.

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

| Specification |
| --- |
| HTML Standard # htmlmediaelement |

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

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

See also
--------

### References

* `<video>` and `<audio>` HTML elements
* `HTMLVideoElement` and `HTMLAudioElement` interfaces, derived from `HTMLMediaElement`
### Guides

* Web media technologies
* Learning area: Video and audio content
* Media type and format guide
* Handling media support issues in web content


ImageDecoder - Web APIs

ImageDecoder
============

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

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

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

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

The **`ImageDecoder`** interface of the WebCodecs API provides a way to unpack and decode encoded image data.

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

`ImageDecoder()`
Experimental

Creates a new `ImageDecoder` object.

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

`ImageDecoder.complete` Read only
Experimental

Returns a boolean value indicating whether encoded data is completely buffered.

`ImageDecoder.completed` Read only
Experimental

Returns a `Promise` that resolves once `complete` is true.

`ImageDecoder.tracks` Read only
Experimental

Returns an `ImageTrackList` object listing the available tracks and providing a method for selecting a track to decode.

`ImageDecoder.type` Read only
Experimental

Returns a string reflecting the MIME type configured during construction.

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

`ImageDecoder.isTypeSupported()`
Experimental

Indicates if the provided MIME type is supported for unpacking and decoding.

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

`ImageDecoder.close()`
Experimental

Ends all pending work and releases system resources.

`ImageDecoder.decode()`
Experimental

Enqueues a control message to decode the frame of an image.

`ImageDecoder.reset()`
Experimental

Aborts all pending `decode()` operations.

Examples
--------

Given a `<canvas>` element:

```html
<canvas></canvas>
```

the following code decodes and renders an animated image to that canvas:

```js
let imageDecoder = null;
let imageIndex = 0;

function renderImage(result) {
  const canvas = document.querySelector("canvas");
  const canvasContext = canvas.getContext("2d");

  canvasContext.drawImage(result.image, 0, 0);

  const track = imageDecoder.tracks.selectedTrack;

  // We check complete here since `frameCount` won't be stable until all
  // data has been received. This may cause us to receive a RangeError
  // during the decode() call below which needs to be handled.
  if (imageDecoder.complete) {
    if (track.frameCount === 1) return;

    if (imageIndex + 1 >= track.frameCount) imageIndex = 0;
  }

  // Decode the next frame ahead of display so it's ready in time.
  imageDecoder
    .decode({ frameIndex: ++imageIndex })
    .then((nextResult) =>
      setTimeout(() => {
        renderImage(nextResult);
      }, result.image.duration / 1000.0),
    )
    .catch((e) => {
      // We can end up requesting an imageIndex past the end since
      // we're using a ReadableStream from fetch(), when this happens
      // just wrap around.
      if (e instanceof RangeError) {
        imageIndex = 0;
        imageDecoder.decode({ frameIndex: imageIndex }).then(renderImage);
      } else {
        throw e;
      }
    });
}

function decodeImage(imageByteStream) {
  imageDecoder = new ImageDecoder({ data: imageByteStream, type: "image/gif" });
  imageDecoder.decode({ frameIndex: imageIndex }).then(renderImage);
}

fetch("fancy.gif").then((response) => decodeImage(response.body));
```

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

| Specification |
| --- |
| WebCodecs # imagedecoder-interface |

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

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


StorageEvent - Web APIs

StorageEvent
============

 The **`StorageEvent`** interface is implemented by the `storage` event, which is
 sent to a window
 when a storage area the window has access to is changed within the context of another document.

Event

StorageEventConstructor
-----------

`StorageEvent()`

Returns a newly constructed `StorageEvent` object.

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

*In addition to the properties listed below, this interface inherits the properties of its parent interface, `Event`.*

`key` Read only

 Returns a string with the key for the storage item that was changed.
 The `key` attribute is `null` when the change is caused by the storage `clear()` method.

`newValue` Read only

 Returns a string with the new value of the storage item that was changed.
 This value is `null` when the change has been invoked by storage `clear()` method,
 or the storage item has been removed from the storage.

`oldValue` Read only

 Returns a string with the original value of the storage item that was changed.
 This value is `null` when the storage item has been newly added
 and therefore doesn't have any previous value.

`storageArea` Read only

Returns a `Storage` object that represents the storage object that was affected.

`url` Read only

Returns string with the URL of the document whose storage changed.

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

*In addition to the methods listed below, this interface inherits the methods of its parent interface, `Event`.*

`initStorageEvent()`
Deprecated

Initializes the event in a manner analogous to the similarly-named `initEvent()` method in the DOM Events interfaces. Use the constructor instead.

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

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

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

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

See also
--------

* Web Storage API


PerformanceServerTiming - Web APIs

PerformanceServerTiming
=======================

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

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

The **`PerformanceServerTiming`** interface surfaces server metrics that are sent with the response in the `Server-Timing` HTTP header.

This interface is restricted to the same origin, but you can use the `Timing-Allow-Origin` header to specify the domains that are allowed to access the server metrics. Note that this interface is only available in secure contexts (HTTPS) in some browsers.

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

`PerformanceServerTiming.description` Read only

A string value of the server-specified metric description, or an empty string.

`PerformanceServerTiming.duration` Read only

A double that contains the server-specified metric duration, or value `0.0`.

`PerformanceServerTiming.name` Read only

A string value of the server-specified metric name.

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

`PerformanceServerTiming.toJSON()`

Returns a JSON representation of the `PerformanceServerTiming` object.

Example
-------

Given a server that sends the `Server-Timing` header, for example a Node.js server like this:

```js
const http = require("http");

function requestHandler(request, response) {
  const headers = {
    "Server-Timing": `
 cache;desc="Cache Read";dur=23.2,
 db;dur=53,
 app;dur=47.2
 `.replace(/\n/g, ""),
  };
  response.writeHead(200, headers);
  response.write("");
  return setTimeout(() => {
    response.end();
  }, 1000);
}

http.createServer(requestHandler).listen(3000).on("error", console.error);
```

The `PerformanceServerTiming` entries are now observable from JavaScript via the `PerformanceResourceTiming.serverTiming` property and live on `navigation` and `resource` entries.

Example using a `PerformanceObserver`, which notifies of new `navigation` and `resource` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation.

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    entry.serverTiming.forEach((serverEntry) => {
      console.log(
        `${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`,
      );
      // Logs "cache (Cache Read) duration: 23.2"
      // Logs "db () duration: 53"
      // Logs "app () duration: 47.2"
    });
  });
});

["navigation", "resource"].forEach((type) =>
  observer.observe({ type, buffered: true }),
);
```

Example using `Performance.getEntriesByType()`, which only shows `navigation` and `resource` performance entries present in the browser's performance timeline at the time you call this method:

```js
for (const entryType of ["navigation", "resource"]) {
  for (const { name: url, serverTiming } of performance.getEntriesByType(
    entryType,
  )) {
    if (serverTiming) {
      for (const { name, description, duration } of serverTiming) {
        console.log(`${name} (${description}) duration: ${duration}`);
        // Logs "cache (Cache Read) duration: 23.2"
        // Logs "db () duration: 53"
        // Logs "app () duration: 47.2"
      }
    }
  }
}
```

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

| Specification |
| --- |
| Server Timing # the-performanceservertiming-interface |

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

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

See also
--------

* `Server-Timing`
* `PerformanceResourceTiming.serverTiming`


MouseEvent - Web APIs

MouseEvent
==========

 The **`MouseEvent`** interface represents events that occur due to the user interacting with a pointing device (such as a mouse).
 Common events using this interface include `click`, `dblclick`, `mouseup`, `mousedown`.

`MouseEvent` derives from `UIEvent`, which in turn derives from `Event`.
 Though the `MouseEvent.initMouseEvent()` method is kept for backward compatibility, creating of a `MouseEvent` object should be done using the `MouseEvent()` constructor.

Several more specific events are based on `MouseEvent`, including `WheelEvent`, `DragEvent`, and `PointerEvent`.

Event

UIEvent

MouseEventConstructor
-----------

`MouseEvent()`

Creates a `MouseEvent` object.

Static properties
-----------------

`MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN`
Non-standard
 Read only

Minimum force necessary for a normal click.

`MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN`
Non-standard
 Read only

Minimum force necessary for a force click.

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

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`MouseEvent.altKey` Read only

Returns `true` if the `alt` key was down when the mouse event was fired.

`MouseEvent.button` Read only

The button number that was pressed (if applicable) when the mouse event was fired.

`MouseEvent.buttons` Read only

The buttons being pressed (if any) when the mouse event was fired.

`MouseEvent.clientX` Read only

The X coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.clientY` Read only

The Y coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.ctrlKey` Read only

Returns `true` if the `control` key was down when the mouse event was fired.

`MouseEvent.layerX`
Non-standard
 Read only

Returns the horizontal coordinate of the event relative to the current layer.

`MouseEvent.layerY`
Non-standard
 Read only

Returns the vertical coordinate of the event relative to the current layer.

`MouseEvent.metaKey` Read only

Returns `true` if the `meta` key was down when the mouse event was fired.

`MouseEvent.movementX` Read only

The X coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.movementY` Read only

The Y coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.offsetX` Read only

The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.offsetY` Read only

The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.pageX` Read only

The X coordinate of the mouse pointer relative to the whole document.

`MouseEvent.pageY` Read only

The Y coordinate of the mouse pointer relative to the whole document.

`MouseEvent.relatedTarget` Read only

The secondary target for the event, if there is one.

`MouseEvent.screenX` Read only

The X coordinate of the mouse pointer in screen coordinates.

`MouseEvent.screenY` Read only

The Y coordinate of the mouse pointer in screen coordinates.

`MouseEvent.shiftKey` Read only

Returns `true` if the `shift` key was down when the mouse event was fired.

`MouseEvent.mozInputSource`
Non-standard
 Read only

 The type of device that generated the event (one of the `MOZ_SOURCE_*` constants).
 This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

`MouseEvent.webkitForce`
Non-standard
 Read only

The amount of pressure applied when clicking.

`MouseEvent.x` Read only

Alias for `MouseEvent.clientX`.

`MouseEvent.y` Read only

Alias for `MouseEvent.clientY`.

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

*This interface also inherits methods of its parents, `UIEvent` and `Event`.*

`MouseEvent.getModifierState()`

Returns the current state of the specified modifier key. See `KeyboardEvent.getModifierState()` for details.

`MouseEvent.initMouseEvent()`
Deprecated

Initializes the value of a `MouseEvent` created. If the event has already been dispatched, this method does nothing.

Example
-------

 This example demonstrates simulating a click (programmatically generating a click event) on a checkbox using DOM methods.
 Event state (canceled or not) is then determined with the return value of method `EventTarget.dispatchEvent()`.

### HTML

```html
<p>
  <label><input type="checkbox" id="checkbox" /> Checked</label>
</p>
<p>
  <button id="button">Click me to send a MouseEvent to the checkbox</button>
</p>
```

### JavaScript

```js
function simulateClick() {
  // Get the element to send a click event
  const cb = document.getElementById("checkbox");

  // Create a synthetic click MouseEvent
  let evt = new MouseEvent("click", {
    bubbles: true,
    cancelable: true,
    view: window,
  });

  // Send the event to the checkbox element
  cb.dispatchEvent(evt);
}
document.getElementById("button").addEventListener("click", simulateClick);
```

### Result

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

| Specification |
| --- |
| UI Events # interface-mouseevent |
| CSSOM View Module # extensions-to-the-mouseevent-interface |
| Pointer Lock 2.0 # extensions-to-the-mouseevent-interface |

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

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

See also
--------

* Its direct parent, `UIEvent`
* `PointerEvent`: For advanced pointer events, including multi-touch


XMLDocument - Web APIs

XMLDocument
===========

The **XMLDocument** interface represents an XML document. It inherits from the generic `Document` and does not add any specific methods or properties to it: nevertheless, several algorithms behave differently with the two types of documents.

EventTarget

Node

Document

XMLDocumentProperty
--------

*Also inherits properties from: `Document`*.

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

*Also inherits methods from: `Document`*.

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

| Specification |
| --- |
| DOM Standard # xmldocument |

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

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

See also
--------

* The Document Object Model (DOM)


PromiseRejectionEvent - Web APIs

PromiseRejectionEvent
=====================

The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript `Promise`s are rejected. These events are particularly useful for telemetry and debugging purposes.

For details, see Promise rejection events.

Event

PromiseRejectionEventConstructor
-----------

`PromiseRejectionEvent()`

Creates a `PromiseRejectionEvent` event, given the type of event (`unhandledrejection` or `rejectionhandled`) and other details.

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

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

`PromiseRejectionEvent.promise` Read only

The JavaScript `Promise` that was rejected.

`PromiseRejectionEvent.reason` Read only

A value or `Object` indicating why the promise was rejected, as passed to `Promise.reject()`.

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

*This interface has no unique methods; inherits methods from its parent `Event`*.

Events
------

`rejectionhandled`

Fired when a JavaScript `Promise` is rejected, and after the rejection is handled by the promise's rejection handling code.

`unhandledrejection`

Fired when a JavaScript `Promise` is rejected but there is no rejection handler to deal with the rejection.

Examples
--------

This simple example catches unhandled promise rejections and logs them for debugging purposes.

```js
window.onunhandledrejection = (e) => {
  console.log(e.reason);
};
```

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

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

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

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

See also
--------

* Using promises
* `Promise`
* `rejectionhandled`
* `unhandledrejection`


XRCPUDepthInformation - Web APIs

XRCPUDepthInformation
=====================

**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 **`XRCPUDepthInformation`** interface contains depth information from the CPU (returned by `XRFrame.getDepthInformation()`).

XRDepthInformation

XRCPUDepthInformation
This interface inherits properties from its parent, `XRDepthInformation`.

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

`XRCPUDepthInformation.data` Read only
Experimental

An `ArrayBuffer` containing depth-buffer information in raw format.

`XRDepthInformation.height` Read only

Contains the height of the depth buffer (number of rows).

`XRDepthInformation.normDepthBufferFromNormView` Read only

An `XRRigidTransform` that needs to be applied when indexing into the depth buffer. The transformation that the matrix represents changes the coordinate system from normalized view coordinates to normalized depth-buffer coordinates that can then be scaled by depth buffer's `width` and `height` to obtain the absolute depth-buffer coordinates.

`XRDepthInformation.rawValueToMeters` Read only

Contains the scale factor by which the raw depth values must be multiplied in order to get the depths in meters.

`XRDepthInformation.width` Read only

Contains the width of the depth buffer (number of columns).

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

`XRCPUDepthInformation.getDepthInMeters()`
Experimental

Returns the depth in meters at (x, y) in normalized view coordinates.

Examples
--------

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

| Specification |
| --- |
| WebXR Depth Sensing Module # xr-cpu-depth-info-section |

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

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

See also
--------

* `XRDepthInformation`
* `XRWebGLDepthInformation`
* `XRFrame.getDepthInformation()`


TimeEvent - Web APIs

TimeEvent
=========

The **`TimeEvent`** interface, a part of SVG SMIL animation, provides specific contextual information associated with Time events.

Event

TimeEventInstance properties
-------------------

`TimeEvent.detail` Read only

A `long` that specifies some detail information about the Event, depending on the type of the event. For this event type, indicates the repeat number for the animation.

`TimeEvent.view` Read only

A WindowProxy that identifies the Window from which the event was generated.

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

`TimeEvent.initTimeEvent()`

Used to initialize the value of a TimeEvent created through the DocumentEvent interface. This method may only be called before the TimeEvent has been dispatched via the dispatchEvent method, though it may be called multiple times during that phase if necessary.


IDBCursor - Web APIs

IDBCursor
=========

**Note:** Not to be confused with `IDBCursorWithValue` which is just an **`IDBCursor`** interface with an additional **`value`** property.

The **`IDBCursor`** interface of the IndexedDB API represents a cursor for traversing or iterating over multiple records in a database.

The cursor has a source that indicates which index or object store it is iterating over. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. The cursor enables an application to asynchronously process all the records in the cursor's range.

You can have an unlimited number of cursors at the same time. You always get the same `IDBCursor` object representing a given cursor. Operations are performed on the underlying index or object store.

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

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

**Note:** `IDBCursorWithValue` is an **`IDBCursor`** interface with an additional **`value`** property.

`IDBCursor.source` Read only

Returns the `IDBObjectStore` or `IDBIndex` that the cursor is iterating. This function never returns null or throws an exception, even if the cursor is currently being iterated, has iterated past its end, or its transaction is not active.

`IDBCursor.direction` Read only

Returns the direction of traversal of the cursor. See Constants for possible values.

`IDBCursor.key` Read only

Returns the key for the record at the cursor's position. If the cursor is outside its range, this is set to `undefined`. The cursor's key can be any data type.

`IDBCursor.primaryKey` Read only

Returns the cursor's current effective primary key. If the cursor is currently being iterated or has iterated outside its range, this is set to `undefined`. The cursor's primary key can be any data type.

`IDBCursor.request` Read only

Returns the `IDBRequest` that was used to obtain the cursor.

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

`IDBCursor.advance()`

Sets the number of times a cursor should move its position forward.

`IDBCursor.continue()`

Advances the cursor to the next position along its direction, to the item whose key matches the optional `key` parameter.

`IDBCursor.continuePrimaryKey()`

Sets the cursor to the given index key and primary key given as arguments.

`IDBCursor.delete()`

Returns an `IDBRequest` object, and, in a separate thread, deletes the record at the cursor's position, without changing the cursor's position. This can be used to delete specific records.

`IDBCursor.update()`

Returns an `IDBRequest` object, and, in a separate thread, updates the value at the current position of the cursor in the object store. This can be used to update specific records.

Constants
---------

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

**Warning:** These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. (Firefox bug 891944)

* `NEXT`: `"next"` : The cursor shows all records, including duplicates. It starts at the lower bound of the key range and moves upwards (monotonically increasing in the order of keys).
* `NEXTUNIQUE` : `"nextunique"` : The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the lower bound of the key range and moves upwards.
* `PREV`: `"prev"` : The cursor shows all records, including duplicates. It starts at the upper bound of the key range and moves downwards (monotonically decreasing in the order of keys).
* `PREVUNIQUE`: `"prevunique"` : The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the upper bound of the key range and moves downwards.
Examples
--------

In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our IDBCursor example (view example live.)

```js
function displayData() {
  const transaction = db.transaction(["rushAlbumList"], "readonly");
  const objectStore = transaction.objectStore("rushAlbumList");

  objectStore.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
      list.appendChild(listItem);

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

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

| Specification |
| --- |
| Indexed Database API 3.0 # cursor-interface |

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

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

See also
--------

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


SVGPathElement - Web APIs

SVGPathElement
==============

The **`SVGPathElement`** interface corresponds to the `<path>` element.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGGeometryElement

SVGPathElement

**Note:** In SVG 2 the `getPathSegAtLength()` and `createSVGPathSeg*` methods were removed and the `pathLength` property and the `getTotalLength()` and `getPointAtLength()` methods were moved to `SVGGeometryElement`.

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

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

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

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

`SVGPathElement.getPathSegAtLength()`
Deprecated

Returns an unsigned long representing the index within the `pathSegList` utilizing the user agent's distance-along-a-path algorithm.

`SVGPathElement.createSVGPathSegClosePath()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegClosePath` object.

`SVGPathElement.createSVGPathSegMovetoAbs()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegMovetoAbs` object.

`SVGPathElement.createSVGPathSegMovetoRel()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegMovetoRel` object.

`SVGPathElement.createSVGPathSegLinetoAbs()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegLinetoAbs` object.

`SVGPathElement.createSVGPathSegLinetoRel()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegLinetoRel` object.

`SVGPathElement.createSVGPathSegCurvetoCubicAbs()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegCurvetoCubicAbs` object.

`SVGPathElement.createSVGPathSegCurvetoCubicRel()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegCurvetoCubicRel` object.

`SVGPathElement.createSVGPathSegCurvetoQuadraticAbs()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegCurvetoQuadraticAbs` object.

`SVGPathElement.createSVGPathSegCurvetoQuadraticRel()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegCurvetoQuadraticRel` object.

`SVGPathElement.createSVGPathSegArcAbs()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegArcAbs` object.

`SVGPathElement.createSVGPathSegArcRel()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegArcRel` object.

`SVGPathElement.createSVGPathSegLinetoHorizontalAbs()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegLinetoHorizontalAbs` object.

`SVGPathElement.createSVGPathSegLinetoHorizontalRel()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegLinetoHorizontalRel` object.

`SVGPathElement.createSVGPathSegLinetoVerticalAbs()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegLinetoVerticalAbs` object.

`SVGPathElement.createSVGPathSegLinetoVerticalRel()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegLinetoVerticalRel` object.

`SVGPathElement.createSVGPathSegCurvetoCubicSmoothAbs()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegCurvetoCubicSmoothAbs` object.

`SVGPathElement.createSVGPathSegCurvetoCubicSmoothRel()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegCurvetoCubicSmoothRel` object.

`SVGPathElement.createSVGPathSegCurvetoQuadraticSmoothAbs()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegCurvetoQuadraticSmoothAbs` object.

`SVGPathElement.createSVGPathSegCurvetoQuadraticSmoothRel()`
Deprecated

Returns a stand-alone, parentless `SVGPathSegCurvetoQuadraticSmoothRel` object.

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

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

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

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

See also
--------

* `<path>` SVG Element


NDEFReader - Web APIs

NDEFReader
==========

**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 **`NDEFReader`** interface of the Web NFC API is used to read from and write data to compatible NFC devices, e.g. NFC tags supporting NDEF, when these devices are within the reader's magnetic induction field.

EventTarget

NDEFReaderConstructor
-----------

`NDEFReader()`
Experimental

Returns a new `NDEFReader` object.

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

*The `NDEFReader` interface inherits the methods of `EventTarget`, its parent interface.*

`NDEFReader.scan()`
Experimental

Activates a reading device and returns a `Promise` that either resolves when an NFC tag read operation is scheduled or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted.

`NDEFReader.write()`
Experimental

Attempts to write an NDEF message to a tag and returns a `Promise` that either resolves when a message has been written to the tag or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted.

Events
------

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

`reading`
Experimental

Fires when a new reading is available from compatible NFC devices.

`readingerror`
Experimental

Fires when a tag is in proximity of a reading device, but cannot be read.

Examples
--------

### Handling initial reads while writing

The example below shows how to coordinate between a common reading handler and one used specifically for a single write. In order to write, a tag needs to be found and read. This gives you the ability to check whether it is actually a tag that you want to write to. That's why it's recommended that you call `write()` from a reading event.

```js
const ndef = new NDEFReader();
let ignoreRead = false;

ndef.onreading = (event) => {
  if (ignoreRead) {
    return; // write pending, ignore read.
  }

  console.log("We read a tag, but not during pending write!");
};

function write(data) {
  ignoreRead = true;
  return new Promise((resolve, reject) => {
    ndef.addEventListener(
      "reading",
      (event) => {
        // Check if we want to write to this tag, or reject.
        ndef
          .write(data)
          .then(resolve, reject)
          .finally(() => (ignoreRead = false));
      },
      { once: true },
    );
  });
}

await ndef.scan();
try {
  await write("Hello World");
  console.log("We wrote to a tag!");
} catch (err) {
  console.error("Something went wrong", err);
}
```

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

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

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

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


RTCIceCandidatePairStats - Web APIs

RTCIceCandidatePairStats
========================

The **`RTCIceCandidatePairStats`** dictionary of the WebRTC API is used to report statistics that provide insight into the quality and performance of an `RTCPeerConnection` while connected and configured as described by the specified pair of ICE candidates.

The statistics can be obtained by iterating the `RTCStatsReport` returned by `RTCPeerConnection.getStats()` until you find an entry with the `type` of `"candidate-pair"`.

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

`availableIncomingBitrate` Optional

Provides a value representing the available inbound capacity of the network by reporting the total number of bits per second available for all of the candidate pair's incoming RTP streams. This does not take into account the size of the IP overhead, nor any other transport layers such as TCP or UDP.

`availableOutgoingBitrate` Optional

Provides an informative value representing the available outbound capacity of the network by reporting the total number of bits per second available for all of the candidate pair's outgoing RTP streams. This does not take into account the size of the IP overhead, nor any other transport layers such as TCP or UDP.

`bytesReceived` Optional

The total number of payload bytes received (that is, the total number of bytes received minus any headers, padding, or other administrative overhead) on this candidate pair so far.

`bytesSent` Optional

The total number of payload bytes sent (that is, the total number of bytes sent minus any headers, padding, or other administrative overhead) so far on this candidate pair.

`currentRoundTripTime` Optional

A floating-point value indicating the total time, in seconds, that elapsed between the most recently-sent STUN request and the response being received. This may be based upon requests that were involved in confirming permission to open the connection.

`lastPacketReceivedTimestamp` Optional

A `DOMHighResTimeStamp` value indicating the time at which the last packet was received by the local peer from the remote peer for this candidate pair. Timestamps are not recorded for STUN packets.

`lastPacketSentTimestamp` Optional

A `DOMHighResTimeStamp` value indicating the time at which the last packet was sent from the local peer to the remote peer for this candidate pair. Timestamps are not recorded for STUN packets.

`localCandidateId` Optional

The unique ID string corresponding to the `RTCIceCandidate` from the data included in the `RTCIceCandidateStats` object providing statistics for the candidate pair's local candidate.

`nominated` Optional

A Boolean value which, if `true`, indicates that the candidate pair described by this object is one which has been proposed for use, and will be (or was) used if its priority is the highest among the nominated candidate pairs. See RFC 5245, section 7.1.3.2.4 for details.

`remoteCandidateId` Optional

The unique ID string corresponding to the remote candidate from which data was taken to construct the `RTCIceCandidateStats` object describing the remote end of the connection.

`requestsReceived` Optional

The total number of connectivity check requests that have been received, including retransmissions. This value includes both connectivity checks and STUN consent checks.

`requestsSent` Optional

The total number of connectivity check requests that have been sent, *not* including retransmissions.

`responsesReceived` Optional

The total number of connectivity check responses that have been received.

`responsesSent` Optional

The total number of connectivity check responses that have been sent. This includes both connectivity check requests and STUN consent requests.

`state` Optional

A string which indicates the state of the connection between the two candidates.

`totalRoundTripTime` Optional

A floating-point value indicating the total time, in seconds, that has elapsed between sending STUN requests and receiving responses to them, for all such requests made to date on this candidate pair. This includes both connectivity check and consent check requests. You can compute the average round trip time (RTT) by dividing this value by `responsesReceived`.

`transportId` Optional

A string that uniquely identifies the `RTCIceTransport` that was inspected to obtain the transport-related statistics (as found in `RTCTransportStats`) used in generating this object.

### 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 `"candidate-pair"`, indicating the type of statistics that the object contains.

### Deprecated properties

 The following properties have been removed from the specification and should no longer be used.
 You should update any existing code to avoid using them as soon as is practical.
 Check the compatibility table for details on which browsers support them and in which versions.

`priority`
Deprecated
 Optional

An integer value indicating the candidate pair's priority.

`readable`
Deprecated
 Optional
Non-standard

A Boolean value indicating whether or not data can be sent over the connection described by the candidate pair.

`writable`
Deprecated
 Optional
Non-standard

A Boolean value indicating whether or not data can be received on the connection described by the candidate pair.

### Non-standard properties

`selected`
Non-standard
 Optional

 A Firefox-specific Boolean value which is `true` if the candidate pair described by this object is the one currently in use.
 The spec-compliant way to determine the selected candidate pair is to look for a stats object of type `transport`, which is an `RTCTransportStats` object.
 That object's `selectedCandidatePairId` property indicates whether or not the specified transport is the one being used.

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

 The currently-active ICE candidate pair—if any—can be obtained by calling the `RTCIceTransport` method `getSelectedCandidatePair()`, which returns an `RTCIceCandidatePair` object, or `null` if there isn't a pair selected.
 The active candidate pair describes the current configuration of the two ends of the `RTCPeerConnection`.

 Any candidate pair that isn't the active pair of candidates for a transport gets deleted if the `RTCIceTransport` performs an ICE restart, at which point the `state` of the ICE transport returns to `new` and negotiation starts once again.
 For more information, see ICE restart.

Example
-------

This example computes the average time elapsed between connectivity checks.

```js
if (rtcStats && rtcStats.type === "candidate-pair") {
  let elapsed =
    (rtcStats.lastRequestTimestamp - rtcStats.firstRequestTimestamp) /
    rtcStats.requestsSent;

  console.log(`Average time between ICE connectivity checks: ${elapsed} ms.`);
}
```

 The code begins by looking at `rtcStats` to see if its `type` is `candidate-pair`.
 If it is, then we know that `rtcStats` is in fact an `RTCIceCandidatePairStats` object.
 We can then compute the average time elapsed between STUN connectivity checks and log that information.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstatstype-candidate-pair |

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

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


SVGFEFuncBElement - Web APIs

SVGFEFuncBElement
=================

The **`SVGFEFuncBElement`** interface corresponds to the `<feFuncB>` element.

EventTarget

Node

Element

SVGElement

SVGComponentTransferFunctionElement

SVGFEFuncBElementInstance properties
-------------------

*This interface not provide any specific properties, but inherits properties from its parent interface, `SVGComponentTransferFunctionElement`.*

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

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

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

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

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

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

See also
--------

* `<feFuncB>`


GPUQueue - Web APIs

GPUQueue
========

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

The **`GPUQueue`** interface of the WebGPU API controls execution of encoded commands on the GPU.

A device's primary queue is accessed via the `GPUDevice.queue` property.

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

`label`
Experimental

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

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

`copyExternalImageToTexture()`
Experimental

Copies a snapshot taken from a source image, video, or canvas into a given `GPUTexture`.

`onSubmittedWorkDone()`
Experimental

Returns a `Promise` that resolves when all the work submitted to the GPU via this `GPUQueue` at the point the method is called has been processed.

`submit()`
Experimental

Schedules the execution of command buffers represented by one or more `GPUCommandBuffer` objects by the GPU.

`writeBuffer()`
Experimental

Writes a provided data source into a given `GPUBuffer`.

`writeTexture()`
Experimental

Writes a provided data source into a given `GPUTexture`.

Examples
--------

In our basic render demo, we define some vertex data in a `Float32Array` that we'll use to draw a triangle:

```js
const vertices = new Float32Array([
  0.0, 0.6, 0, 1, 1, 0, 0, 1, -0.5, -0.6, 0, 1, 0, 1, 0, 1, 0.5, -0.6, 0, 1, 0,
  0, 1, 1,
]);
```

To use this data in a render pipeline, we need to put it into a `GPUBuffer`. First we'll create the buffer:

```js
const vertexBuffer = device.createBuffer({
  size: vertices.byteLength, // make it big enough to store vertices in
  usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY\_DST,
});
```

To get the data into the buffer we can use the `writeBuffer()` function, which lets the user agent determine most efficient way to copy the data over:

```js
device.queue.writeBuffer(vertexBuffer, 0, vertices, 0, vertices.length);
```

Later on, a set of commands is encoded into a `GPUCommandBuffer` using the `GPUCommandEncoder.finish()` method. The command buffer is then passed into the queue via a `submit()` call, ready to be processed by the GPU.

```js
device.queue.submit([commandEncoder.finish()]);
```

**Note:** Study the WebGPU samples to find more queue examples.

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

| Specification |
| --- |
| WebGPU # gpu-queue |

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

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

See also
--------

* The WebGPU API