fetch() global function - Web APIs

fetch() global function
=======================

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

The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise that is fulfilled once the response is available.

The promise resolves to the `Response` object representing the response to your request.

 A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar).
 A `fetch()` promise *does not* reject on HTTP errors (`404`, etc.).
 Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties.

The `fetch()` method is controlled by the `connect-src` directive of Content Security Policy rather than the directive of the resources it's retrieving.

**Note:** The `fetch()` method's parameters are identical to those of the `Request()` constructor.

Syntax
------

```js
fetch(resource)
fetch(resource, options)
```

### Parameters

`resource`

This defines the resource that you wish to fetch. This can either be:

* A string or any other object with a stringifier — including a `URL` object — that provides the URL of the resource you want to fetch.
* A `Request` object.

`options` Optional

 An object containing any custom settings you want to apply to the request.
 The possible options are:

`method`

 The request method, e.g., `"GET"`, `"POST"`.
 The default is `"GET"`.
 Note that the `Origin` header is not set on Fetch requests with a method of `HEAD` or `GET`.
 Any string that is a case-insensitive match for one of the methods in RFC 9110 will be uppercased automatically.
 If you want to use a custom method (like `PATCH`), you should uppercase it yourself.

`headers`

 Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values.
 Note that some names are forbidden.

**Note:** The `Authorization` HTTP header may be added to a request, but will be removed if the request is redirected cross-origin.

`body`

 Any body that you want to add to your request:
 this can be a `Blob`, an `ArrayBuffer`, a `TypedArray`, a `DataView`,
 a `FormData`, a `URLSearchParams`, string object or literal,
 or a `ReadableStream` object. This latest possibility is still experimental; check the compatibility information to verify you can use it.
 Note that a request using the `GET` or `HEAD` method cannot have a body.

`mode`

 The mode you want to use for the request, e.g., `cors`,
 `no-cors`, or `same-origin`.

`credentials`

Controls what browsers do with credentials (cookies, HTTP authentication entries, and TLS client certificates). Must be one of the following strings:

`omit`

Tells browsers to exclude credentials from the request, and ignore any credentials sent back in the response (e.g., any `Set-Cookie` header).

`same-origin`

Tells browsers to include credentials with requests to same-origin URLs, and use any credentials sent back in responses from same-origin URLs. **This is the default value.**

`include`

Tells browsers to include credentials in both same- and cross-origin requests, and always use any credentials sent back in responses.

**Note:** Credentials may be included in simple and "final" cross-origin requests, but should not be included in CORS preflight requests.

`cache`

A string indicating how the request will interact with the browser's HTTP cache. The possible values, `default`, `no-store`, `reload`, `no-cache`, `force-cache`, and `only-if-cached`, are documented in the article for the `cache` property of the `Request` object.

`redirect`

How to handle a `redirect` response:

`follow`

Automatically follow redirects. Unless otherwise stated the redirect mode is set to `follow`.

`error`

Abort with an error if a redirect occurs.

`manual`

 Caller intends to process the response in another context.
 See WHATWG fetch standard for more information.

`referrer`

 A string specifying the referrer of the request. This can be a
 same-origin URL, `about:client`, or an empty string.

`referrerPolicy`

 Specifies the referrer policy to use for the request. May be one of `no-referrer`,
 `no-referrer-when-downgrade`, `same-origin`,
 `origin`, `strict-origin`,
 `origin-when-cross-origin`,
 `strict-origin-when-cross-origin`, or `unsafe-url`.

`integrity`

 Contains the subresource integrity
 value of the request (e.g., `sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=`).

`keepalive`

 The `keepalive` option can be used to allow the request to outlive the page.
 Fetch with the `keepalive` flag is a replacement for the `Navigator.sendBeacon()` API.

`signal`

 An `AbortSignal` object instance; allows you to communicate with a
 fetch request and abort it if desired via an `AbortController`.

`priority`

Specifies the priority of the fetch request relative to other requests of the same type. Must be one of the following strings:

`high`

A high-priority fetch request relative to other requests of the same type.

`low`

A low-priority fetch request relative to other requests of the same type.

`auto`

Automatically determine the priority of the fetch request relative to other requests of the same type (default).

### Return value

A `Promise` that resolves to a `Response` object.

### Exceptions

`AbortError` `DOMException`

 The request was aborted due to a call to the `AbortController`
`abort()` method.

`TypeError`

Can occur for the following reasons:

| Reason | Failing examples |
| --- | --- |
| Invalid header name. |
```
// space in "C ontent-Type"
const headers = {
  'C ontent-Type': 'text/xml',
  'Breaking-Bad': '<3',
};
fetch('https://example.com/', { headers });

```
 |
| Invalid header value. The header object must contain exactly two elements. |
```
const headers = [
  ['Content-Type', 'text/html', 'extra'],
  ['Accept'],
];
fetch('https://example.com/', { headers });

```
 |
| Invalid URL or scheme, or using a scheme that fetch does not support, or using a scheme that is not supported for a particular request mode. |
```
fetch('blob://example.com/', { mode: 'cors' });

```
 |
| URL includes credentials. |
```
fetch('https://user:password@example.com/');

```
 |
| Invalid referrer URL. |
```
fetch('https://example.com/', { referrer: './abc\u0000df' });

```
 |
| Invalid modes (`navigate` and `websocket`). |
```
fetch('https://example.com/', { mode: 'navigate' });

```
 |
| If the request cache mode is "only-if-cached" and the request mode is other than "same-origin". |
```
fetch('https://example.com/', {
  cache: 'only-if-cached',
  mode: 'no-cors',
});

```
 |
|
 If the request method is an invalid name token or one of the forbidden headers
 (`'CONNECT'`, `'TRACE'` or `'TRACK'`).
  |
```
fetch('https://example.com/', { method: 'CONNECT' });

```
 |
|
 If the request mode is "no-cors" and the request method is not a CORS-safe-listed method
 (`'GET'`, `'HEAD'`, or `'POST'`).
  |
```
fetch('https://example.com/', {
  method: 'CONNECT',
  mode: 'no-cors',
});

```
 |
| If the request method is `'GET'` or `'HEAD'` and the body is non-null or not undefined. |
```
fetch('https://example.com/', {
  method: 'GET',
  body: new FormData(),
});

```
 |
| If fetch throws a network error. |  |

Examples
--------

 In our Fetch Request example (see Fetch Request live) we
 create a new `Request` object using the relevant constructor, then fetch it
 using a `fetch()` call. Since we are fetching an image, we run
 `Response.blob()` on the response to give it the proper MIME type so it will be
 handled properly, then create an Object URL of it and display it in an
 `<img>` element.

```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return response.blob();
  })
  .then((response) => {
    myImage.src = URL.createObjectURL(response);
  });
```

 In the Fetch with init then Request example (see Fetch Request init live), we do the same thing except that we pass in an
 `init` object when we invoke `fetch()`:

```js
const myImage = document.querySelector("img");

const myHeaders = new Headers();
myHeaders.append("Accept", "image/jpeg");

const myInit = {
  method: "GET",
  headers: myHeaders,
  mode: "cors",
  cache: "default",
};

const myRequest = new Request("flowers.jpg");

fetch(myRequest, myInit).then((response) => {
  // …
});
```

 You could also pass the `init` object in with the
 `Request` constructor to get the same effect:

```js
const myRequest = new Request("flowers.jpg", myInit);
```

 You can also use an object literal as `headers` in
 `init`.

```js
const myInit = {
  method: "GET",
  headers: {
    Accept: "image/jpeg",
  },
  mode: "cors",
  cache: "default",
};

const myRequest = new Request("flowers.jpg", myInit);
```

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

| Specification |
| --- |
| Fetch Standard # fetch-method |

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

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

See also
--------

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


GPURenderBundle - Web APIs

GPURenderBundle
===============

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

The **`GPURenderBundle`** interface of the WebGPU API represents a container for pre-recorded bundles of commands.

The command bundles are encoded using a `GPURenderBundleEncoder`; once the desired commands have been encoded, they are recorded into a `GPURenderBundle` object instance using the `GPURenderBundleEncoder.finish()` method.

These command bundles can then be reused across multiple render passes by passing the `GPURenderBundle` objects into `GPURenderPassEncoder.executeBundles()` calls. Reusing pre-recoded commands can significantly improve app performance in situations where JavaScript draw call overhead is a bottleneck. Render bundles are most effective in situations where a batch of objects will be drawn the same way across multiple views or frames, with the only differences being the buffer content being used (such as updated matrix uniforms).

A good example is VR rendering. Recording the rendering as a render bundle and then tweaking the view matrix and replaying it for each eye is a more efficient way to issue draw calls for both renderings of the scene.

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

`label`
Experimental

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

Examples
--------

In the WebGPU Samples Animometer example, a lot of like operations are done on many different objects simultaneously. A render bundle is encoded using the following function:

```js
function recordRenderPass(
  passEncoder: GPURenderBundleEncoder | GPURenderPassEncoder
) {
  if (settings.dynamicOffsets) {
    passEncoder.setPipeline(dynamicPipeline);
  } else {
    passEncoder.setPipeline(pipeline);
  }
  passEncoder.setVertexBuffer(0, vertexBuffer);
  passEncoder.setBindGroup(0, timeBindGroup);
  const dynamicOffsets = [0];
  for (let i = 0; i < numTriangles; ++i) {
    if (settings.dynamicOffsets) {
      dynamicOffsets[0] = i \* alignedUniformBytes;
      passEncoder.setBindGroup(1, dynamicBindGroup, dynamicOffsets);
    } else {
      passEncoder.setBindGroup(1, bindGroups[i]);
    }
    passEncoder.draw(3, 1, 0, 0);
  }
}
```

Later on, a `GPURenderBundleEncoder` is created, the function is invoked, and the render bundle is recorded using `GPURenderBundleEncoder.finish()`:

```js
const renderBundleEncoder = device.createRenderBundleEncoder({
  colorFormats: [presentationFormat],
});
recordRenderPass(renderBundleEncoder);
const renderBundle = renderBundleEncoder.finish();
```

`GPURenderPassEncoder.executeBundles()` is then used to reuse the work across multiple render passes to improve performance. Study the example code listing for the full context.

```js
// ...

return function doDraw(timestamp) {
  if (startTime === undefined) {
    startTime = timestamp;
  }
  uniformTime[0] = (timestamp - startTime) / 1000;
  device.queue.writeBuffer(uniformBuffer, timeOffset, uniformTime.buffer);

  renderPassDescriptor.colorAttachments[0].view = context
    .getCurrentTexture()
    .createView();

  const commandEncoder = device.createCommandEncoder();
  const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

  if (settings.renderBundles) {
    passEncoder.executeBundles([renderBundle]);
  } else {
    recordRenderPass(passEncoder);
  }

  passEncoder.end();
  device.queue.submit([commandEncoder.finish()]);
};

// ...
```

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

| Specification |
| --- |
| WebGPU # gpurenderbundle |

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

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

See also
--------

* The WebGPU API


BluetoothRemoteGATTService - Web APIs

BluetoothRemoteGATTService
==========================

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

 The `BluetoothRemoteGATTService` interface of the Web Bluetooth API represents a
 service provided by a GATT server, including a device, a list of referenced services,
 and a list of the characteristics of this service.

EventTarget

BluetoothRemoteGATTServiceInstance properties
-------------------

`BluetoothRemoteGATTService.device` Read only
Experimental

 Returns information about a Bluetooth device through an instance of
 `BluetoothDevice`.

`BluetoothRemoteGATTService.isPrimary` Read only
Experimental

 Returns a boolean value indicating whether this is a primary or secondary
 service.

`BluetoothRemoteGATTService.uuid` Read only
Experimental

Returns a string representing the UUID of this service.

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

`BluetoothRemoteGATTService.getCharacteristic()`
Experimental

 Returns a `Promise` to an instance of
 `BluetoothRemoteGATTCharacteristic` for a given universally unique identifier
 (UUID).

`BluetoothRemoteGATTService.getCharacteristics()`
Experimental

 Returns a `Promise` to an `Array` of
 `BluetoothRemoteGATTCharacteristic` instances for an optional universally
 unique identifier (UUID).

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

| Specification |
| --- |
| Web Bluetooth # bluetoothgattservice-interface |

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

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


FileSystemDirectoryReader - Web APIs

FileSystemDirectoryReader
=========================

The `FileSystemDirectoryReader` interface of the File and Directory Entries API lets you access the `FileSystemFileEntry`-based objects (generally `FileSystemFileEntry` or `FileSystemDirectoryEntry`) representing each entry in a directory.

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

`readEntries()`

Returns an array containing some number of the directory's entries. Each item in the array is an object based on `FileSystemEntry`—typically either `FileSystemFileEntry` or `FileSystemDirectoryEntry`.

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

| Specification |
| --- |
| File and Directory Entries API # api-directoryreader |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemDirectoryEntry`
* `FileSystem`


SVGPreserveAspectRatio - Web APIs

SVGPreserveAspectRatio
======================

SVG preserveAspectRatio interface
---------------------------------

The `SVGPreserveAspectRatio` interface corresponds to the `preserveAspectRatio` attribute, which is available for some of SVG's elements.

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

### Interface overview

|  |  |
| --- | --- |
| Also implement | *None* |
| Methods | *None* |
| Properties | * unsigned short `align`
* unsigned short `meetOrSlice`
 |
| Constants | * `SVG_PRESERVEASPECTRATIO_UNKNOWN` = 0
* `SVG_PRESERVEASPECTRATIO_NONE` = 1
* `SVG_PRESERVEASPECTRATIO_XMINYMIN` = 2
* `SVG_PRESERVEASPECTRATIO_XMIDYMIN` = 3
* `SVG_PRESERVEASPECTRATIO_XMAXYMIN` = 4
* `SVG_PRESERVEASPECTRATIO_XMINYMID` = 5
* `SVG_PRESERVEASPECTRATIO_XMIDYMID` = 6
* `SVG_PRESERVEASPECTRATIO_XMAXYMID` = 7
* `SVG_PRESERVEASPECTRATIO_XMINYMAX` = 8
* `SVG_PRESERVEASPECTRATIO_XMIDYMAX` = 9
* `SVG_PRESERVEASPECTRATIO_XMAXYMAX` = 10
* `SVG_MEETORSLICE_UNKNOWN` = 0
* `SVG_MEETORSLICE_MEET` = 1
* `SVG_MEETORSLICE_SLICE` = 2
 |
| Normative document | SVG 1.1 (2nd Edition) |

Constants
---------

| Name | Value | Description |
| --- | --- | --- |
| `SVG_PRESERVEASPECTRATIO_UNKNOWN` | 0 |
 The enumeration was set to a value that is not one of predefined types.
 It is invalid to attempt to define a new value of this type or to
 attempt to switch an existing value to this type.
  |
| `SVG_PRESERVEASPECTRATIO_NONE` | 1 |
 Corresponds to value `none` for attribute
 `preserveAspectRatio`.
  |
| `SVG_PRESERVEASPECTRATIO_XMINYMIN` | 2 |
 Corresponds to value `xMinYMin` for attribute
 `preserveAspectRatio`.
  |
| `SVG_PRESERVEASPECTRATIO_XMIDYMIN` | 3 |
 Corresponds to value `xMidYMin` for attribute
 `preserveAspectRatio`.
  |
| `SVG_PRESERVEASPECTRATIO_XMAXYMIN` | 4 |
 Corresponds to value `xMaxYMin` for attribute
 `preserveAspectRatio`.
  |
| `SVG_PRESERVEASPECTRATIO_XMINYMID` | 5 |
 Corresponds to value `xMinYMid` for attribute
 `preserveAspectRatio`.
  |
| `SVG_PRESERVEASPECTRATIO_XMIDYMID` | 6 |
 Corresponds to value `xMidYMid` for attribute
 `preserveAspectRatio`.
  |
| `SVG_PRESERVEASPECTRATIO_XMAXYMID` | 7 |
 Corresponds to value `xMaxYMid` for attribute
 `preserveAspectRatio`.
  |
| `SVG_PRESERVEASPECTRATIO_XMINYMAX` | 8 |
 Corresponds to value `xMinYMax` for attribute
 `preserveAspectRatio`.
  |
| `SVG_PRESERVEASPECTRATIO_XMIDYMAX` | 9 |
 Corresponds to value `xMidYMax` for attribute
 `preserveAspectRatio`.
  |
| `SVG_PRESERVEASPECTRATIO_XMAXYMAX` | 10 |
 Corresponds to value `xMaxYMax` for attribute
 `preserveAspectRatio`.
  |
| `SVG_MEETORSLICE_UNKNOWN` | 0 |
 The enumeration was set to a value that is not one of predefined types.
 It is invalid to attempt to define a new value of this type or to
 attempt to switch an existing value to this type.
  |
| `SVG_MEETORSLICE_MEET` | 1 |
 Corresponds to value `meet` for attribute
 `preserveAspectRatio`.
  |
| `SVG_MEETORSLICE_SLICE` | 2 |
 Corresponds to value `slice` for attribute
 `preserveAspectRatio`.
  |

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

| Name | Type | Description |
| --- | --- | --- |
| `align` | unsigned short |
 The type of the alignment value as specified by one of the
 `SVG_PRESERVEASPECTRATIO_*` constants defined on this interface.
  |
| `meetOrSlice` | unsigned short |
 The type of the meet-or-slice value as specified by one of the
 `SVG_MEETORSLICE_*` constants defined on this interface.
  |

**Exceptions on setting:** a `DOMException` with code `NO_MODIFICATION_ALLOWED_ERR` is raised on an attempt to change the value of an attribute on a read only object.

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

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

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

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


SVGAElement - Web APIs

SVGAElement
===========

The **`SVGAElement`** interface provides access to the properties of an `<a>` element, as well as methods to manipulate them.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGAElementInstance properties
-------------------

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

`SVGAElement.download`

See `HTMLAnchorElement.download`.

`SVGAElement.href` Read only

An `SVGAnimatedString` that reflects the `href` or `xlink:href`
Deprecated
 attribute.

`SVGAElement.hreflang`

A string that reflects the `hreflang` attribute, indicating the language of the linked resource.

`SVGAElement.ping`

A string that reflects the ping attribute, containing a space-separated list of URLs to which, when the hyperlink is followed, `POST` requests with the body `PING` will be sent by the browser (in the background). Typically used for tracking.

`SVGAElement.referrerPolicy`

See `HTMLAnchorElement.referrerPolicy`.

`SVGAElement.rel`

See `HTMLAnchorElement.rel`.

`SVGAElement.relList`

See `HTMLAnchorElement.relList`.

`SVGAElement.target` Read only

It corresponds to the `target` attribute of the given element.

`SVGAElement.text`

A string being a synonym for the `Node.textContent` property.

`SVGAElement.type`

A string that reflects the `type` attribute, indicating the MIME type of the linked resource.

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

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

Example
-------

In the example below, the `target` attribute of the `<a>` element is set to `_blank` and when the link is clicked, it logs to notify whether the condition is met or not.

```js
const linkRef = document.querySelector("a");
linkRef.target = "\_self";

linkRef.onclick = () => {
  if (linkRef.target === "\_blank") {
    console.log("BLANK!");
    linkRef.target = "\_self";
  } else {
    console.log("SORRY! not \_blank");
  }
};
```

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

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

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

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

See also
--------

* SVG `<a>` element


AudioBufferSourceNode - Web APIs

AudioBufferSourceNode
=====================

The **`AudioBufferSourceNode`** interface is an `AudioScheduledSourceNode` which represents an audio source consisting of in-memory audio data, stored in an `AudioBuffer`.

This interface is especially useful for playing back audio which has particularly stringent timing accuracy requirements, such as for sounds that must match a specific rhythm and can be kept in memory rather than being played from disk or the network. To play sounds which require accurate timing but must be streamed from the network or played from disk, use a `AudioWorkletNode` to implement its playback.

EventTarget

AudioNode

AudioScheduledSourceNode

AudioBufferSourceNode
An `AudioBufferSourceNode` has no inputs and exactly one output, which has the same number of channels as the `AudioBuffer` indicated by its `buffer` property. If there's no buffer set—that is, if `buffer` is `null`—the output contains a single channel of silence (every sample is 0).

An `AudioBufferSourceNode` can only be played once; after each call to `start()`, you have to create a new node if you want to play the same sound again. Fortunately, these nodes are very inexpensive to create, and the actual `AudioBuffer`s can be reused for multiple plays of the sound. Indeed, you can use these nodes in a "fire and forget" manner: create the node, call `start()` to begin playing the sound, and don't even bother to hold a reference to it. It will automatically be garbage-collected at an appropriate time, which won't be until sometime after the sound has finished playing.

Multiple calls to `stop()` are allowed. The most recent call replaces the previous one, if the `AudioBufferSourceNode` has not already reached the end of the buffer.

![The AudioBufferSourceNode takes the content of an AudioBuffer and m](/en-US/docs/Web/API/AudioBufferSourceNode/webaudioaudiobuffersourcenode.png)

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |
| Channel count | defined by the associated `AudioBuffer` |

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

`AudioBufferSourceNode()`

Creates and returns a new `AudioBufferSourceNode` object. As an alternative, you can use the `BaseAudioContext.createBufferSource()` factory method; see Creating an AudioNode.

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

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

`AudioBufferSourceNode.buffer`

An `AudioBuffer` that defines the audio asset to be played, or when set to the value `null`, defines a single channel of silence (in which every sample is 0.0).

`AudioBufferSourceNode.detune`

A k-rate `AudioParam` representing detuning of playback in cents. This value is compounded with `playbackRate` to determine the speed at which the sound is played. Its default value is `0` (meaning no detuning), and its nominal range is -∞ to ∞.

`AudioBufferSourceNode.loop`

A Boolean attribute indicating if the audio asset must be replayed when the end of the `AudioBuffer` is reached. Its default value is `false`.

`AudioBufferSourceNode.loopStart` Optional

A floating-point value indicating the time, in seconds, at which playback of the `AudioBuffer` must begin when `loop` is `true`. Its default value is `0` (meaning that at the beginning of each loop, playback begins at the start of the audio buffer).

`AudioBufferSourceNode.loopEnd` Optional

A floating-point number indicating the time, in seconds, at which playback of the `AudioBuffer` stops and loops back to the time indicated by `loopStart`, if `loop` is `true`. The default value is `0`.

`AudioBufferSourceNode.playbackRate`

A k-rate `AudioParam` that defines the speed factor at which the audio asset will be played, where a value of 1.0 is the sound's natural sampling rate. Since no pitch correction is applied on the output, this can be used to change the pitch of the sample. This value is compounded with `detune` to determine the final playback rate.

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

*Inherits methods from its parent, `AudioScheduledSourceNode`, and overrides the following method:*.

`start()`

Schedules playback of the audio data contained in the buffer, or begins playback immediately. Additionally allows the start offset and play duration to be set.

Event handlers
--------------

*Inherits event handlers from its parent, `AudioScheduledSourceNode`*.

Examples
--------

In this example, we create a two-second buffer, fill it with white noise, and then play it using an `AudioBufferSourceNode`. The comments should clearly explain what is going on.

**Note:** You can also run the code live, or view the source.

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

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

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

// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
const source = audioCtx.createBufferSource();
// set the buffer in the AudioBufferSourceNode
source.buffer = myArrayBuffer;
// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioCtx.destination);
// start the source playing
source.start();
```

**Note:** For a `decodeAudioData()` example, see the `AudioContext.decodeAudioData()` page.

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

| Specification |
| --- |
| Web Audio API # AudioBufferSourceNode |

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

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

See also
--------

* Using the Web Audio API
* Web Audio API


StyleSheetList - Web APIs

StyleSheetList
==============

The `StyleSheetList` interface represents a list of `CSSStyleSheet` objects. An instance of this object can be returned by `Document.styleSheets`.

It is an array-like object but can't be iterated over using `Array` methods. However it can be iterated over in a standard `for` loop over its indices, or converted to an `Array`.

**Note:** This interface was an attempt to create an unmodifiable list and only continues to be supported to not break code that's already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).

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

`StyleSheetList.length` Read only

Returns the number of `CSSStyleSheet` objects in the collection.

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

`StyleSheetList.item()`

Returns the `CSSStyleSheet` object at the index passed in, or `null` if no item exists for that index.

Examples
--------

### Get CSSStyleSheet objects with for loop

```js
const styleSheet = [];
const styleSheets = document.styleSheets;

for (let i = 0; i < styleSheets.length; i++) {
  styleSheet.push(styleSheets[i]);
}
```

### Get all CSS rules for the document using Array methods

```js
const allCSS = [...document.styleSheets]
  .map((styleSheet) => {
    try {
      return [...styleSheet.cssRules].map((rule) => rule.cssText).join("");
    } catch (e) {
      console.log(
        "Access to stylesheet %s is denied. Ignoring…",
        styleSheet.href,
      );
    }
  })
  .filter(Boolean)
  .join("\n");
```

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

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

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

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


WaveShaperNode - Web APIs

WaveShaperNode
==============

The **`WaveShaperNode`** interface represents a non-linear distorter.

It is an `AudioNode` that uses a curve to apply a wave shaping distortion to the signal. Beside obvious distortion effects, it is often used to add a warm feeling to the signal.

A `WaveShaperNode` always has exactly one input and one output.

EventTarget

AudioNode

WaveShaperNode

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"max"` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `"speakers"` |

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

`WaveShaperNode()`

Creates a new instance of an `WaveShaperNode` object.

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

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

`WaveShaperNode.curve`

A `Float32Array` of numbers describing the distortion to apply.

`WaveShaperNode.oversample`

An enumerated value indicating if oversampling must be used. Oversampling is a technique for creating more samples (up-sampling) before applying the distortion effect to the audio signal.

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

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

Example
-------

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

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

| Specification |
| --- |
| Web Audio API # WaveShaperNode |

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

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

See also
--------

* Using the Web Audio API


Window Controls Overlay API - Web APIs

Window Controls Overlay API
===========================

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

 The Window Controls Overlay API gives Progressive Web Apps installed on desktop operating systems the ability to hide the default window title bar and display their own content
 over the full surface area of the app window, turning the control buttons (maximize, minimize, and close) into an overlay.

Opting-in to the feature
------------------------

Before using this feature, the following conditions must be true:

* The Web App Manifest's `display_override` member must be set to `window-controls-overlay`.
* The Progressive Web App must be installed on a desktop operating system.
Main concepts
-------------

Progressive Web Apps installed on desktop devices can be displayed in standalone app windows, just like native apps. Here is what an application window looks like:

![Illustration of a PWA installed on desktop, with window control buttons, a title bar, and web content below that](/en-US/docs/Web/API/Window_Controls_Overlay_API/desktop-pwa-window.png)

As seen above, the app window is made of two main areas:

* The title bar area at the top.
* The application content area at the bottom, which displays the HTML content from the PWA.

The title bar area contains the system-critical maximize, minimize, and close buttons (their position may vary across operating systems), the name of the application (which comes from the `<title>` HTML element in the page), and possibly user-agent-specific PWA buttons.

With the Window Controls Overlay feature, Progressive Web Apps can display their web content over the whole app window surface area. Because the window control buttons and user-agent-specific PWA buttons must remain visible, they get turned into an overlay displayed on top of the web content.

![Illustration of a PWA installed on desktop with the Window Controls Overlay feature, with window control buttons, no title bar, and web content spanning the whole window](/en-US/docs/Web/API/Window_Controls_Overlay_API/desktop-pwa-window-wco.png)

The part of the title bar that normally contains the application name is hidden, and the area that it normally occupies becomes available via the Window Controls Overlay API.

PWAs can use the API to position content in this area, and avoid having content hidden behind the control buttons overlay, similar to how web authors can account for the presence of notches on certain mobile devices.

CSS environment variables
-------------------------

 Progressive Web Apps can position their web content in the area that the title bar normally occupies by using the `titlebar-area-x`, `titlebar-area-y`, `titlebar-area-width`, and `titlebar-area-height` CSS environment variables.
 See Using env() to ensure content is not obscured by window control buttons in desktop PWAs.

Interfaces
----------

`WindowControlsOverlay`
Experimental

Provides information about the visibility and geometry of the title bar and an event to know whenever it changes.

`WindowControlsOverlayGeometryChangeEvent`
Experimental

Represents events providing information related to the desktop Progress Web App's title var region when its size or visibility changes.

### Extensions to other interfaces

`Navigator.windowControlsOverlay`

Returns the `WindowControlsOverlay` interface, which exposes information about the title bar geometry in desktop Progressive Web Apps.

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

| Specification |
| --- |
| Window Controls Overlay  |

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

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

See also
--------

* Customize the window controls overlay of your PWA's title bar
* Breaking Out of the Box
* Display content in the title bar


OTPCredential - Web APIs

OTPCredential
=============

**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 **`OTPCredential`** interface of the WebOTP API is returned when a WebOTP `navigator.credentials.get()` call (i.e. invoked with an `otp` option) fulfills. It includes a `code` property that contains the retrieved one-time password (OTP).

Credential

OTPCredentialInstance properties
-------------------

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

`OTPCredential.code`
Experimental

The OTP.

`OTPCredential.id`

Inherited from `Credential`. The ID of the credential type.

`OTPCredential.type`

Inherited from `Credential`. Always set to `otp` for `OTPCredential` instances.

### Event handlers

None.

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

None.

Examples
--------

The below code triggers the browser's permission flow when an SMS message arrives. If permission is granted, then the promise resolves with an `OTPCredential` object. The contained `code` value is then set as the value of an `<input>` form element, which is then submitted.

```js
navigator.credentials
  .get({
    otp: { transport: ["sms"] },
    signal: ac.signal,
  })
  .then((otp) => {
    input.value = otp.code;
    if (form) form.submit();
  })
  .catch((err) => {
    console.error(err);
  });
```

**Note:** For a full explanation of the code, see the WebOTP API landing page. You can also see this code as part of a full working demo.

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

| Specification |
| --- |
| WebOTP API # OTPCredential |

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

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


PaymentResponse - Web APIs

PaymentResponse
===============

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

The **`PaymentResponse`** interface of the Payment Request API is returned after a user selects a payment method and approves a payment request.

EventTarget

PaymentResponseInstance properties
-------------------

`PaymentResponse.details` Read only

Returns a JSON-serializable object that provides a payment method specific message used by the merchant to process the transaction and determine successful fund transfer. The contents of the object depend on the payment method being used. Developers need to consult whomever controls the URL for the expected shape of the details object.

`PaymentResponse.methodName` Read only

Returns the payment method identifier for the payment method that the user selected, for example, Visa, Mastercard, Paypal, etc.

`PaymentResponse.payerEmail` Read only
Deprecated

Non-standard

Returns the email address supplied by the user. This option is only present when the `requestPayerEmail` option is set to `true` in the `options` parameter of the `PaymentRequest()` constructor.

`PaymentResponse.payerName` Read only
Deprecated

Non-standard

Returns the name supplied by the user. This option is only present when the `requestPayerName` option is set to true in the `options` parameter of the `PaymentRequest()` constructor.

`PaymentResponse.payerPhone` Read only
Deprecated

Non-standard

Returns the phone number supplied by the user. This option is only present when the `requestPayerPhone` option is set to `true` in the `options` parameter of the `PaymentRequest()` constructor.

`PaymentResponse.requestId` Read only

Returns the identifier of the `PaymentRequest` that produced the current response. This is the same value supplied in the `PaymentRequest()` constructor by `details.id`.

`PaymentResponse.shippingAddress` Read only
Deprecated

Non-standard

Returns the shipping Address supplied by the user. This option is only present when the `requestShipping` option is set to `true` in the `options` parameter of the `PaymentRequest()` constructor.

`PaymentResponse.shippingOption` Read only
Deprecated

Non-standard

Returns the ID attribute of the shipping option selected by the user. This option is only present when the `requestShipping` option is set to `true` in the `options` parameter of the `PaymentRequest()` constructor.

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

`PaymentResponse.retry()`

If something is wrong with the payment response's data (and there is a recoverable error), this method allows a merchant to request that the user retry the payment. The method takes an object as argument, which is used to signal to the user exactly what is wrong with the payment response so they can try to correct any issues.

`PaymentResponse.complete()`

Notifies the user agent that the user interaction is over. This causes any remaining user interface to be closed. This method should only be called after the Promise returned by the `PaymentRequest.show()` method.

`PaymentResponse.toJSON()`

Returns a JSON object representing this `PaymentResponse` object.

Events
------

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

`payerdetailchange`
Deprecated

Non-standard

Fired during a retry when the user makes changes to their personal information while filling out a payment request form. Allows the developer to revalidate any requested user data (e.g., the phone number or the email address) if it changes.

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

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

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

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


USBIsochronousInTransferPacket - Web APIs

USBIsochronousInTransferPacket
==============================

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 `USBIsochronousInTransferPacket` interface of the WebUSB API is part of the response from a call to the `isochronousTransferIn()` method of the `USBDevice` interface. It represents the status of an individual packet from a request to transfer data from the USB device to the USB host over an isochronous endpoint.

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

`USBIsochronousInTransferPacket()`
Experimental

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

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

`USBIsochronousInTransferPacket.data` Read only  Read only
Experimental

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

`USBIsochronousInTransferPacket.status` Read only  Read only
Experimental

Returns the status of the transfer request, one of:

* `"ok"` - The transfer was successful.
* `"stall"` - The device indicated an error by generating a stall condition on the endpoint. A stall on an isochronous endpoint does not need to be cleared.
* `"babble"` - The device responded with more data than was expected.

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

| Specification |
| --- |
| WebUSB API # usbisochronousintransferpacket |

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

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


BackgroundFetchRecord - Web APIs

BackgroundFetchRecord
=====================

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

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

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

The **`BackgroundFetchRecord`** interface of the Background Fetch API represents an individual request and response.

A `BackgroundFetchRecord` is created by the `BackgroundFetchRegistration.matchAll()` method, therefore there is no constructor for this interface.

There will be one `BackgroundFetchRecord` for each resource requested by `fetch()`.

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

`request` Read only
Experimental

Returns a `Request`.

`responseReady` Read only
Experimental

Returns a promise that resolves with a `Response`.

Examples
--------

In this example an individual `BackgroundFetchRecord` is returned using `BackgroundFetchRegistration.matchAll()`. The `BackgroundFetchRecord.request` and `BackgroundFetchRecord.responseReady` are returned and logged to the console.

```js
bgFetch.match("/ep-5.mp3").then(async (record) => {
  if (!record) {
    console.log("No record found");
    return;
  }

  console.log(`Here's the request`, record.request);
  const response = await record.responseReady;
  console.log(`And here's the response`, response);
});
```

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

| Specification |
| --- |
| Background Fetch # background-fetch-record-interface |

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

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


Web Bluetooth API - Web APIs

Web Bluetooth API
=================

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

The Web Bluetooth API provides the ability to connect and interact with Bluetooth Low Energy peripherals.

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

Interfaces
----------

`Bluetooth`

Returns a `Promise` to a `BluetoothDevice` object with the specified options.

`BluetoothCharacteristicProperties`

Provides properties of a particular `BluetoothRemoteGATTCharacteristic`.

`BluetoothDevice`

Represents a Bluetooth device inside a particular script execution environment.

`BluetoothRemoteGATTCharacteristic`

Represents a GATT Characteristic, which is a basic data element that provides further information about a peripheral's service.

`BluetoothRemoteGATTDescriptor`

Represents a GATT Descriptor, which provides further information about a characteristic's value.

`BluetoothRemoteGATTServer`

Represents a GATT Server on a remote device.

`BluetoothRemoteGATTService`

Represents a service provided by a GATT server, including a device, a list of referenced services, and a list of the characteristics of this service.

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

| Specification |
| --- |
| Web Bluetooth # bluetooth |

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

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


GPUDeviceLostInfo - Web APIs

GPUDeviceLostInfo
=================

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

The **`GPUDeviceLostInfo`** interface of the WebGPU API represents the object returned when the `GPUDevice.lost` `Promise` resolves. This provides information as to why a device has been lost.

See the `GPUDevice.lost` page for more information about "lost" state.

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

`message`
Experimental
 Read only

A string providing a human-readable message that explains why the device was lost.

`reason`
Experimental
 Read only

An enumerated value that defines the reason the device was lost in a machine-readable way.

Examples
--------

```js
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }
  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  // Create a GPUDevice
  let device = await adapter.requestDevice(descriptor);

  // Use lost to handle lost devices
  device.lost.then((info) => {
    console.error(`WebGPU device was lost: ${info.message}`);
    device = null;
    if (info.reason !== "destroyed") {
      init();
    }
  });
  // ...
}
```

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

| Specification |
| --- |
| WebGPU # gpudevicelostinfo |

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

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

See also
--------

* The WebGPU API


SVGFEBlendElement - Web APIs

SVGFEBlendElement
=================

The **`SVGFEBlendElement`** interface corresponds to the `<feBlend>` element.

EventTarget

Node

Element

SVGElement

SVGFEBlendElementConstants
---------

| Name | Value | Description |
| --- | --- | --- |
| `SVG_FEBLEND_MODE_UNKNOWN` | 0 |
 The type is not one of predefined types. It is invalid to attempt to
 define a new value of this type or to attempt to switch an existing
 value to this type.
  |
| `SVG_FEBLEND_MODE_NORMAL` | 1 | Corresponds to the value `normal`. |
| `SVG_FEBLEND_MODE_MULTIPLY` | 2 | Corresponds to the value `multiply`. |
| `SVG_FEBLEND_MODE_SCREEN` | 3 | Corresponds to the value `screen`. |
| `SVG_FEBLEND_MODE_DARKEN` | 4 | Corresponds to the value `darken`. |
| `SVG_FEBLEND_MODE_LIGHTEN` | 5 | Corresponds to the value `lighten`. |

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

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

`SVGFEBlendElement.height` Read only

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

`SVGFEBlendElement.in1` Read only

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

`SVGFEBlendElement.in2` Read only

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

`SVGFEBlendElement.mode` Read only

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

`SVGFEBlendElement.result` Read only

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

`SVGFEBlendElement.width` Read only

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

`SVGFEBlendElement.x` Read only

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

`SVGFEBlendElement.y` Read only

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

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

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

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

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

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

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

See also
--------

* `<feBlend>`


FileSystemWritableFileStream - Web APIs

FileSystemWritableFileStream
============================

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

The **`FileSystemWritableFileStream`** interface of the File System API is a `WritableStream` object with additional convenience methods, which operates on a single file on disk. The interface is accessed through the `FileSystemFileHandle.createWritable()` method.

WritableStream

FileSystemWritableFileStreamInstance properties
-------------------

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

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

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

`FileSystemWritableFileStream.write()`

Writes content into the file the method is called on, at the current file cursor offset.

`FileSystemWritableFileStream.seek()`

Updates the current file cursor offset to the position (in bytes) specified.

`FileSystemWritableFileStream.truncate()`

Resizes the file associated with the stream to be the specified size in bytes.

Examples
--------

The following asynchronous function opens the 'Save File' picker, which returns a `FileSystemFileHandle` once a file is selected. From this, a writable stream is created using the `FileSystemFileHandle.createWritable()` method.

A text string is then written to the stream, which is subsequently closed.

```js
async function saveFile() {
  // create a new handle
  const newHandle = await window.showSaveFilePicker();

  // create a FileSystemWritableFileStream to write to
  const writableStream = await newHandle.createWritable();

  // write our file
  await writableStream.write("This is my file content");

  // close the file and write the contents to disk.
  await writableStream.close();
}
```

The following examples show different options that can be passed into the `write()` method.

```js
// just pass in the data (no options)
writableStream.write(data);

// writes the data to the stream from the determined position
writableStream.write({ type: "write", position, data });

// updates the current file cursor offset to the position specified
writableStream.write({ type: "seek", position });

// resizes the file to be size bytes long
writableStream.write({ type: "truncate", size });
```

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

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

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

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

See also
--------

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


DOMImplementation - Web APIs

DOMImplementation
=================

The **`DOMImplementation`** interface represents an object providing methods which are not dependent on any particular document. Such an object is returned by the `Document.implementation` property.

Property
--------

*This interface has no specific property and doesn't inherit any.*

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

*No inherited method.*

`DOMImplementation.createDocument()`

Creates and returns an `XMLDocument`.

`DOMImplementation.createDocumentType()`

Creates and returns a `DocumentType`.

`DOMImplementation.createHTMLDocument()`

Creates and returns an HTML `Document`.

`DOMImplementation.hasFeature()`
Deprecated

Returns a boolean value indicating if a given feature is supported or not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns `true`. Old browsers are very inconsistent in their behavior.

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

| Specification |
| --- |
| DOM Standard # interface-domimplementation |

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

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

See also
--------

* The DOM interfaces index.


TimeRanges - Web APIs

TimeRanges
==========

When loading a media resource for use by an `<audio>` or `<video>` element, the **`TimeRanges`** interface is used for representing the time ranges of the media resource that have been buffered, the time ranges that have been played, and the time ranges that are seekable.

A `TimeRanges` object includes one or more ranges of time, each specified by a starting time offset and an ending time offset. You reference each time range by using the `start()` and `end()` methods, passing the index number of the time range you want to retrieve.

Normalized TimeRanges objects
-----------------------------

Several members of `HTMLMediaElement` objects return a **normalized TimeRanges object** — which the spec describes as having the following characteristics:

*The ranges in such an object are ordered, don't overlap, and don't touch (adjacent ranges are folded into one bigger range). A range can be empty (referencing just a single moment in time).*

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

`TimeRanges.length` Read only

Returns an `unsigned long` representing the number of time ranges represented by the time range object.

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

`TimeRanges.start()`

Returns the time for the start of the range with the specified index.

`TimeRanges.end()`

Returns the time for the end of the specified range.

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

| Specification |
| --- |
| HTML Standard # time-ranges |

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

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


WebGLTexture - Web APIs

WebGLTexture
============

The **WebGLTexture** interface is part of the WebGL API and represents an opaque texture object providing storage and state for texturing operations.

WebGLObject

WebGLTextureWebGL textures
--------------

The `WebGLTexture` object does not define any methods or properties of its own and its content is not directly accessible. When working with `WebGLTexture` objects, the following methods of the `WebGLRenderingContext` are useful:

* `WebGLRenderingContext.bindTexture()`
* `WebGLRenderingContext.createTexture()`
* `WebGLRenderingContext.deleteTexture()`
* `WebGLRenderingContext.isTexture()`

See also the WebGL tutorial on Using textures in WebGL.

WebXR opaque textures
---------------------

When using WebXR layers, the `XRWebGLBinding` object will return instances of an *opaque* `WebGLTexture` for the color and depth/stencil attachments.

WebXR methods that return *opaque* `WebGLTexture` objects:

* `XRWebGLBinding.getSubImage()`
* `XRWebGLBinding.getViewSubImage()`

The WebXR *opaque texture* is identical to the standard `WebGLTexture` with the following exceptions:

* A WebXR opaque texture is invalid outside a WebXR `requestAnimationFrame()` callback for its session.
* A WebXR opaque texture is invalid until it is returned by `XRWebGLBinding.getSubImage()` or `XRWebGLBinding.getViewSubImage()`.
* A WebXR opaque texture for the color attachment contains colors with premultiplied alpha.
* At the end of a `requestAnimationFrame()` callback a WebXR opaque texture is unbounded and detached from all `WebGLShader` objects.
* A WebXR opaque texture behaves as though it was allocated with `texStorage2D` or `texStorage3D`, as appropriate, even when using a WebGL 1.0 context.
* If a WebXR opaque texture calls `WebGLRenderingContext.deleteTexture()`, an `INVALID_OPERATION` error is thrown.
* Changes to the dimension or format of a WebXR opaque texture are not allowed. GL functions may only alter the texel values and texture parameters.
Examples
--------

### Creating a texture

```js
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");
const texture = gl.createTexture();
```

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

| Specification |
| --- |
| WebGL Specification # 5.9 |

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

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

See also
--------

* `WebGLRenderingContext.bindTexture()`
* `WebGLRenderingContext.createTexture()`
* `WebGLRenderingContext.deleteTexture()`
* `WebGLRenderingContext.isTexture()`
* `WebGLRenderingContext.compressedTexImage2D()`
* `WebGLRenderingContext.compressedTexSubImage2D()`
* `WebGLRenderingContext.copyTexImage2D()`
* `WebGLRenderingContext.copyTexSubImage2D()`
* `WebGLRenderingContext.generateMipmap()`
* `WebGLRenderingContext.getTexParameter()`
* `WebGLRenderingContext.texImage2D()`
* `WebGLRenderingContext.texSubImage2D()`
* `WebGLRenderingContext.texParameterf()`
* `WebGLRenderingContext.texParameteri()`


SVGAnimatedRect - Web APIs

SVGAnimatedRect
===============

The `SVGAnimatedRect` interface is used for attributes of basic `SVGRect` which can be animated.

### Interface overview

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

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

| Name | Type | Description |
| --- | --- | --- |
| `baseVal` | `SVGRect` | The base value of the given attribute before applying any animations. |
| `animVal` | `SVGRect` |
 A read only `SVGRect` representing the current
 animated value of the given attribute. If the given attribute is not
 currently being animated, then the `SVGRect` 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 `SVGAnimatedRect` interface do not provide any specific methods.*

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

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


WEBGL_debug_renderer_info extension - Web APIs

WEBGL\_debug\_renderer\_info extension
======================================

The **`WEBGL_debug_renderer_info`** extension is part of the WebGL API and exposes two constants with information about the graphics driver for debugging purposes.

Depending on the privacy settings of the browser, this extension might only be available to privileged contexts. Generally, the graphics driver information should only be used in edge cases to optimize your WebGL content or to debug GPU problems. The `WebGLRenderingContext.getParameter()` method can help you to detect which features are supported and the `failIfMajorPerformanceCaveat` context attribute lets you control if a context should be returned at all, if the performance would be dramatically slow.

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

**Note:** Depending on the privacy settings of the browser, this extension might only be available to privileged contexts or not work at all. In Firefox, if `privacy.resistFingerprinting` is set to `true`, this extensions is disabled.

This extension is available to both, WebGL1 and WebGL2 contexts.

Constants
---------

ext.UNMASKED\_VENDOR\_WEBGL

Vendor string of the graphics driver.

ext.UNMASKED\_RENDERER\_WEBGL

Renderer string of the graphics driver.

Examples
--------

With the help of this extension, privileged contexts are able to retrieve debugging information about the user's graphic driver:

```js
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");

const debugInfo = gl.getExtension("WEBGL\_debug\_renderer\_info");
const vendor = gl.getParameter(debugInfo.UNMASKED\_VENDOR\_WEBGL);
const renderer = gl.getParameter(debugInfo.UNMASKED\_RENDERER\_WEBGL);

console.log(vendor);
console.log(renderer);
```

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

| Specification |
| --- |
| WebGL WEBGL\_debug\_renderer\_info 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()`


WebXR Device API - Web APIs

WebXR Device API
================

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

**WebXR** is a group of standards which are used together to support rendering 3D scenes to hardware designed for presenting virtual worlds (**virtual reality**, or **VR**), or for adding graphical imagery to the real world, (**augmented reality**, or **AR**). The **WebXR Device API** implements the core of the WebXR feature set, managing the selection of output devices, render the 3D scene to the chosen device at the appropriate frame rate, and manage motion vectors created using input controllers.

WebXR-compatible devices include fully-immersive 3D headsets with motion and orientation tracking, eyeglasses which overlay graphics atop the real-world scene passing through the frames, and handheld mobile phones which augment reality by capturing the world with a camera and augment that scene with computer-generated imagery.

To accomplish these things, the WebXR Device API provides the following key capabilities:

* Find compatible VR or AR output devices
* Render a 3D scene to the device at an appropriate frame rate
* (Optionally) mirror the output to a 2D display
* Create vectors representing the movements of input controls

At the most basic level, a scene is presented in 3D by computing the perspective to apply to the scene in order to render it from the viewpoint of each of the user's eyes by computing the position of each eye and rendering the scene from that position, looking in the direction the user is currently facing. Each of these two images is rendered into a single framebuffer, with the left eye's rendered image on the left and the right eye's viewpoint rendered into the right half of the buffer. Once both eyes' perspectives on the scene have been rendered, the resulting framebuffer is delivered to the WebXR device to be presented to the user through their headset or other appropriate display device.

While the older WebVR API was designed solely to support Virtual Reality (VR), WebXR provides support for both VR and Augmented Reality (AR) on the web. Support for AR functionality is added by the WebXR Augmented Reality Module.

A typical XR device can have either 3 or 6 degrees of freedom and might or might not have an external positional sensor.

The equipment may also include an accelerometer, barometer, or other sensors which are used to sense when the user moves through space, rotates their head, or the like.

WebXR reference docs
--------------------

### Initialization

* `navigator.xr`
* `XRSystem`
* `XRPermissionStatus`
* `Permissions-Policy`: `xr-spatial-tracking`

### Session

* `XRSession`
* `XRSessionEvent`
* `XRRenderState`

### Frame loop

* `XRFrame`

### Spaces

* `XRSpace`
* `XRReferenceSpace`
* `XRBoundedReferenceSpace`
* `XRReferenceSpaceEvent`
* `XRJointSpace`

### Views

* `XRView`
* `XRViewport`

### Geometric primitives

* `XRRigidTransform`

### Pose

* `XRPose`
* `XRJointPose`
* `XRViewerPose`

### Input

* `XRHand`
* `XRInputSource`
* `XRInputSourceArray`
* `XRInputSourceEvent`
* `XRInputSourcesChangeEvent`

### Layers

* `XRLayer`
* `XRLayerEvent`
* `XRCompositionLayer`
* `XRCubeLayer`
* `XRCylinderLayer`
* `XREquirectLayer`
* `XRProjectionLayer`
* `XRQuadLayer`
* `XRMediaBinding`

### WebGL binding

* `XRWebGLBinding`
* `WebGLRenderingContext.makeXRCompatible()`
* `XRWebGLLayer`
* `XRSubImage`
* `XRWebGLSubImage`

### Anchors

* `XRAnchor`
* `XRAnchorSet`

### Depth sensing

* `XRDepthInformation`
* `XRCPUDepthInformation`
* `XRWebGLDepthInformation`

### Hit testing

* `XRHitTestSource`
* `XRTransientInputHitTestSource`
* `XRHitTestResult`
* `XRTransientInputHitTestResult`
* `XRRay`

### Lighting estimation

* `XRLightEstimate`
* `XRLightProbe`

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

The following guides and tutorials are a great resource to learn how to comprehend WebXR and the underlying 3D and VR/AR graphics concepts.

### Foundations and basics

* Fundamentals of WebXR
* Matrix math for the web
* WebXR application life cycle

### Creating a mixed reality experience

* Starting up and shutting down a WebXR session
* Geometry and reference spaces in WebXR
* Spatial tracking in WebXR
* Rendering and the WebXR frame animation callback
* Viewpoints and viewers: Simulating cameras in WebXR
* A perspective retrospective for WebXR developers
* Lighting a WebXR setting
* Using bounded reference spaces

### Making it interactive

* Movement, orientation, and motion: A WebXR example
* Inputs and input sources
* Targeting and hit detection

### Performance and security

* WebXR performance guide
* Permissions and security for WebXR

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

| Specification |
| --- |
| **WebXR Device API**
 (Source,
 Issues,
 Explainer)
  |
| **WebXR Anchors Module**
 (Source,
 Issues,
 Explainer)
  |
| **WebXR Augmented Reality Module**
 (Source,
 Issues,
 Explainer)
  |
| **WebXR Depth Sensing Module**
 (Source,
 Issues,
 Explainer)
  |
| **WebXR DOM Overlays Module**
 (Source,
 Issues,
 Explainer)
  |
| **WebXR Gamepads Module**
 (Source,
 Issues,
 Explainer)
  |
| **WebXR Hand Input Module**
 (Source,
 Issues,
 Explainer)
  |
| **WebXR Hit Test Module**
 (Source,
 Issues,
 Explainer)
  |
| **WebXR Layers API**
 (Source,
 Issues,
 Explainer)
  |
| **WebXR Lighting Estimation API**
 (Source,
 Issues,
 Explainer)
  |

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

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

See also
--------

* Graphics on the web
* Drawing graphics
* WebGL API: Accelerated 2D and 3D graphics on the web
* Canvas API: 2D drawing for the web
* Canvas tutorial


IDBOpenDBRequest - Web APIs

IDBOpenDBRequest
================

The **`IDBOpenDBRequest`** interface of the IndexedDB API provides access to the results of requests to open or delete databases (performed using `IDBFactory.open` and `IDBFactory.deleteDatabase`), using specific event handler attributes.

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

EventTarget

IDBRequest

IDBOpenDBRequestInstance properties
-------------------

*Also inherits properties from its parents `IDBRequest` and `EventTarget`*.

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

*No methods, but inherits methods from its parents `IDBRequest` and `EventTarget`.*

Events
------

*Events defined on parent interfaces, `IDBRequest` and `EventTarget`, can also be dispatched on `IDBOpenDBRequest` objects.*

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

Events specific to this interface are:

`blocked`

Fired when an open connection to a database is blocking a `versionchange` transaction on the same database. Also available via the `onblocked` property.

`upgradeneeded`

Fired when an attempt was made to open a database with a version number higher than its current version. Also available via the `onupgradeneeded` property.

Example
-------

In the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. For a full working example, see our To-do Notifications app (view example live.)

```js
let db;

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

// these event handlers act on the database being opened.
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 below
  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
// it is only implemented in recent browsers
DBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

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

  // Create an objectStore for this database
  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 });
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # idbopendbrequest |

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


VideoDecoder - Web APIs

VideoDecoder
============

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.

The **`VideoDecoder`** interface of the WebCodecs API decodes chunks of video.

EventTarget

VideoDecoderConstructor
-----------

`VideoDecoder()`

Creates a new `VideoDecoder` object.

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

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

`VideoDecoder.decodeQueueSize` Read only

An integer representing the number of queued decode requests.

`VideoDecoder.state` Read only

Indicates the current state of decoder. Possible values are:

* `"unconfigured"`
* `"configured"`
* `"closed"`

### Events

`dequeue`

Fires to signal a decrease in `VideoDecoder.decodeQueueSize`.

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

`VideoDecoder.isConfigSupported()`

Returns a promise indicating whether the provided `VideoDecoderConfig` is supported.

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

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

`VideoDecoder.configure()`

Enqueues a control message to configure the video decoder for decoding chunks.

`VideoDecoder.decode()`

Enqueues a control message to decode a given chunk of video.

`VideoDecoder.flush()`

Returns a promise that resolves once all pending messages in the queue have been completed.

`VideoDecoder.reset()`

Resets all states including configuration, control messages in the control message queue, and all pending callbacks.

`VideoDecoder.close()`

Ends all pending work and releases system resources.

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

| Specification |
| --- |
| WebCodecs # videodecoder-interface |

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

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

See also
--------

* Video processing with WebCodecs
* WebCodecs API Samples


XRInputSourceArray - Web APIs

XRInputSourceArray
==================

**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 interface **`XRInputSourceArray`** represents a *live* list of WebXR input sources, and is used as the return value of the `XRSession` property `inputSources`. Each entry is an `XRInputSource` representing one input device connected to the WebXR system.

In addition to being able to access the input sources in the list using standard array notation (that is, with index numbers inside square brackets), methods are available to allow the use of iterators and the `forEach()` method is also available.

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

*The following properties are available on `XRInputSourceArray` objects.*

`length` Read only
Experimental

The number of `XRInputSource` objects in the list.

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

*The following methods are available on `XRInputSourceArray` objects. You may also use the features of the `Symbol` type.*

`entries()`
Experimental

Returns an `iterator` you can use to walk the list of key/value pairs in the list. Each item returned is an array whose first value is the index and whose second value is the `XRInputSource` at that index.

`forEach()`
Experimental

Iterates over each item in the list, in order from first to last.

`keys()`
Experimental

A list of the keys corresponding to the entries in the input source list.

`values()`
Experimental

Returns an `iterator` you can use to go through all the values in the list. Each item is a single `XRInputSource` object.

In addition to these methods, you may use array notation to access items in the list by index For example, the snippet of code below calls a function `handleInput()`, passing into it the first item in the input source list, if the list isn't empty.

```js
let sources = xrSession.inputSources;
if (sources.length > 0) {
  handleInput(sources[0]);
}
```

Examples
--------

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

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

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

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


SVGScriptElement - Web APIs

SVGScriptElement
================

The **`SVGScriptElement`** interface corresponds to the SVG `<script>` element.

EventTarget

Node

Element

SVGElement

SVGScriptElementInstance properties
-------------------

`SVGScriptElement.href` Read only

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

`SVGScriptElement.type` Read only

A string corresponding to the `type` attribute of the given `<script>` element. A `DOMException` is raised with the code `NO_MODIFICATION_ALLOWED_ERR` on an attempt to change the value of a read only attribute.

`SVGScriptElement.crossOrigin` Read only

A string corresponding to the `crossorigin` attribute of the given `<script>` element.

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

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

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

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

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

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


Clipboard API - Web APIs

Clipboard API
=============

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

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

* Learn more
* See full compatibility
* Report feedback
The **Clipboard API** provides the ability to respond to clipboard commands (cut, copy, and paste), as well as to asynchronously read from and write to the system clipboard.

**Note:** Use this API in preference to the deprecated `document.execCommand()` method for accessing the clipboard.

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

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

 The *system clipboard* is a data buffer belonging to the operating system hosting the browser, which is used for short-term data storage and/or data transfers between documents or applications.
 It is usually implemented as an anonymous, temporary data buffer, sometimes called the *paste buffer*, that can be accessed from most or all programs within the environment via defined programming interfaces.

The Clipboard API allows users to programmatically read and write text and other kinds of data to and from the system clipboard in secure contexts, provided the user has met the criteria outlined in the Security considerations.

 Events are fired as the result of `cut`, `copy`, and `paste` operations modifying the clipboard.
 The events have a default action, for example the `copy` action copies the current selection to the system clipboard by default.
 The default action can be overriden by the event handler — see each of the events for more information.

Interfaces
----------

`Clipboard` Secure context

 Provides an interface for reading and writing text and data to or from the system clipboard.
 The specification refers to this as the 'Async Clipboard API'.

`ClipboardEvent`

 Represents events providing information related to modification of the clipboard, that is `cut`, `copy`, and `paste` events.
 The specification refers to this as the 'Clipboard Event API'.

`ClipboardItem` Secure context

Represents a single item format, used when reading or writing data.

### Extensions to other interfaces

The Clipboard API extends the following APIs, adding the listed features.

`Navigator.clipboard` Read only  Secure context

Returns a `Clipboard` object that provides read and write access to the system clipboard.

`Element: copy` event

An event fired whenever the user initiates a copy action.

`Element: cut` event

An event fired whenever the user initiates a cut action.

`Element: paste` event

An event fired whenever the user initiates a paste action.

Security considerations
-----------------------

The Clipboard API allows users to programmatically read and write text and other kinds of data to and from the system clipboard in secure contexts.

 The specification requires that a user has recently interacted with the page in order to read from the clipboard (transient user activation is required).
 If the read operation is caused by user interaction with a browser or OS "paste element" (such as a context menu), the browser is expected to prompt the user for acknowledgement.
 For writing to the clipboard the specification expects that the page has been granted the Permissions API `clipboard-write` permission, and the browser may also require transient user activation.
 Browsers may place additional restrictions over use of the methods to access the clipboard.

 Browser implementations have diverged from the specification.
 The differences are captured in the Browser compatibility section and the current state is summarized below:

Chromium browsers:

* Reading requires the Permissions API `clipboard-read` permission be granted.
 Transient activation is not required.
* Writing requires either the `clipboard-read` permission or transient activation.
 If the permission is granted, it persists, and further transient activation is not required.
* The HTTP Permissions-Policy permissions `clipboard-read` and `clipboard-write` must be allowed for `<iframe>` elements that access the clipboard.
* No persistent paste-prompt is displayed when a read operation is caused by a browser or OS "paste element".

Firefox & Safari:

* Reading and writing require transient activation.
* The paste-prompt is suppressed if reading same-origin clipboard content, but not cross-origin content.
* The `clipboard-read` and `clipboard-write` permissions are not supported (and not planned to be supported) by Firefox or Safari.

Firefox Web Extensions:

* Reading text is only available for extensions with the Web Extension `clipboardRead` permission.
 With this permission the extension does not require transient activation or a paste prompt.
* Writing text is available in secure context and with transient activation.
 With the Web Extension `clipboardWrite` permission transient activation is not required.
Examples
--------

### Accessing the clipboard

The system clipboard is accessed through the `Navigator.clipboard` global.

 This snippet fetches the text from the clipboard and appends it to the first element found with the class `editor`.
 Since `readText()` (and `read()`, for that matter) returns an empty string if the clipboard isn't text, this code is safe.

```js
navigator.clipboard
  .readText()
  .then(
    (clipText) => (document.querySelector(".editor").innerText += clipText),
  );
```

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

| Specification |
| --- |
| Clipboard API and events # clipboard-interface |
| Clipboard API and events # clipboard-event-interfaces |
| Clipboard API and events # clipboarditem |

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

### api.Clipboard

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

### api.ClipboardEvent

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

### api.ClipboardItem

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

See also
--------

* Image support for Async Clipboard article


GPUPipelineLayout - Web APIs

GPUPipelineLayout
=================

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

The **`GPUPipelineLayout`** interface of the WebGPU API defines the `GPUBindGroupLayout`s used by a pipeline. `GPUBindGroup`s used with the pipeline during command encoding must have compatible `GPUBindGroupLayout`s.

A `GPUPipelineLayout` object instance is created using the `GPUDevice.createPipelineLayout()` method.

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

`label`
Experimental

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

Examples
--------

**Note:** The WebGPU samples feature many more examples.

### Basic pipeline layout example

The following snippet:

* Creates a `GPUBindGroupLayout` that describes a binding with a buffer, a texture, and a sampler.
* Creates a `GPUPipelineLayout` based on the `GPUBindGroupLayout`.

```js
// ...

const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    {
      binding: 0,
      visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
      buffer: {},
    },
    {
      binding: 1,
      visibility: GPUShaderStage.FRAGMENT,
      texture: {},
    },
    {
      binding: 2,
      visibility: GPUShaderStage.FRAGMENT,
      sampler: {},
    },
  ],
});

const pipelineLayout = device.createPipelineLayout({
  bindGroupLayouts: [bindGroupLayout],
});

// ...
```

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

| Specification |
| --- |
| WebGPU # gpupipelinelayout |

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

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

See also
--------

* The WebGPU API


CharacterBoundsUpdateEvent - Web APIs

CharacterBoundsUpdateEvent
==========================

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

The **`CharacterBoundsUpdateEvent`** interface is a `DOM event` that represents a request from the operating system to know the bounds of certain characters within an editable region that's attached to an `EditContext` instance.

This interface inherits properties from `Event`.

Event

CharacterBoundsUpdateEventConstructor
-----------

`CharacterBoundsUpdateEvent()`
Experimental

Creates a new `CharacterBoundsUpdateEvent` object.

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

`CharacterBoundsUpdateEvent.rangeStart` Read only
Experimental

The offset of the first character within the editable region text for which the operating system needs the bounds.

`CharacterBoundsUpdateEvent.rangeEnd` Read only
Experimental

The offset of the last character within the editable region text for which the operating system needs the bounds.

Examples
--------

### Updating the character bounds when needed

This example shows how to use the `characterboundsupdate` event and the `updateCharacterBounds` method to inform the operating system of the character bounds it requires. Note that the event listener callback is only called when using an IME window, or other platform-specific editing UI surfaces, to compose text.

```html
<canvas id="editor-canvas"></canvas>
```

```js
const FONT\_SIZE = 40;
const FONT = `${FONT\_SIZE}px Arial`;

const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
ctx.font = FONT;

const editContext = new EditContext();
canvas.editContext = editContext;

function computeCharacterBound(offset) {
  // Measure the width from the start of the text to the character.
  const widthBeforeChar = ctx.measureText(
    editContext.text.substring(0, offset),
  ).width;

  // Measure the character width.
  const charWidth = ctx.measureText(editContext.text[offset]).width;

  const charX = canvas.offsetLeft + widthBeforeChar;
  const charY = canvas.offsetTop;

  // Return a DOMRect representing the character bounds.
  return DOMRect.fromRect({
    x: charX,
    y: charY - FONT\_SIZE,
    width: charWidth,
    height: FONT\_SIZE,
  });
}

editContext.addEventListener("characterboundsupdate", (e) => {
  const charBounds = [];
  for (let offset = e.rangeStart; offset < e.rangeEnd; offset++) {
    charBounds.push(computeCharacterBound(offset));
  }

  // Update the character bounds in the EditContext instance.
  editContext.updateCharacterBounds(e.rangeStart, charBounds);

  console.log(
    "The required character bounds are",
    charBounds
      .map((bound) => {
        return `(x: ${bound.x}, y: ${bound.y}, width: ${bound.width}, height: ${bound.height})`;
      })
      .join(", "),
  );
});
```

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

| Specification |
| --- |
| EditContext API # dom-characterboundsupdateevent |

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

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


DataTransfer - Web APIs

DataTransfer
============

The **`DataTransfer`** object is used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types. For more information about drag and drop, see HTML Drag and Drop API.

This object is available from the `dataTransfer` property of all `drag events`.

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

`DataTransfer()`

Creates and returns a new `DataTransfer` object.

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

### Standard properties

`DataTransfer.dropEffect`

Gets the type of drag-and-drop operation currently selected or sets the operation to a new type. The value must be `none`, `copy`, `link` or `move`.

`DataTransfer.effectAllowed`

Provides all of the types of operations that are possible. Must be one of `none`, `copy`, `copyLink`, `copyMove`, `link`, `linkMove`, `move`, `all` or `uninitialized`.

`DataTransfer.files` Read only

Contains a list of all the local files available on the data transfer. If the drag operation doesn't involve dragging files, this property is an empty list.

`DataTransfer.items` Read only

Gives a `DataTransferItemList` object which is a list of all of the drag data.

`DataTransfer.types` Read only

An array of strings giving the formats that were set in the `dragstart` event.

### Gecko properties

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

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

### Standard methods

`DataTransfer.clearData()`

Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect.

`DataTransfer.getData()`

Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data.

`DataTransfer.setData()`

Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same position.

`DataTransfer.setDragImage()`

Set the image to be used for dragging if a custom one is desired.

### Gecko methods

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

Examples
--------

Every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example.

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

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

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

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

See also
--------

* Drag and drop
* Drag Operations
* Recommended Drag Types
* DataTransfer test - Paste or Drag


DOMHighResTimeStamp - Web APIs

DOMHighResTimeStamp
===================

The **`DOMHighResTimeStamp`** type is a `double` and is used to store a time value in milliseconds.

This type can be used to describe a discrete point in time or a time interval (the difference in time between two discrete points in time). The starting time can be either a specific time determined by the script for a site or app, or the time origin.

The time, given in milliseconds, should be accurate to 5 µs (microseconds), with the fractional part of the number indicating fractions of a millisecond. However, if the browser is unable to provide a time value accurate to 5 µs (due, for example, to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond. Also note the section below on reduced time precision controlled by browser preferences to avoid timing attacks and fingerprinting.

Further, if the device or operating system the user agent is running on doesn't have a clock accurate to the microsecond level, they may only be accurate to the millisecond.

Security requirements
---------------------

To offer protection against timing attacks and fingerprinting, `DOMHighResTimeStamp` types are coarsened based on site isolation status.

* Resolution in isolated contexts: 5 microseconds
* Resolution in non-isolated contexts: 100 microseconds

 Cross-origin isolate your site using the `Cross-Origin-Opener-Policy` and
 `Cross-Origin-Embedder-Policy` headers:

```http
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```

 These headers ensure a top-level document does not share a browsing context group with
 cross-origin documents. COOP process-isolates your document and potential attackers
 can't access to your global object if they were opening it in a popup, preventing a set
 of cross-origin attacks dubbed XS-Leaks.

See also
--------

* `performance.now()`
* `performance.timeOrigin`


SVGMetadataElement - Web APIs

SVGMetadataElement
==================

The **`SVGMetadataElement`** interface corresponds to the `<metadata>` element.

EventTarget

Node

Element

SVGElement

SVGMetadataElementInstance properties
-------------------

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

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

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

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

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

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

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


PresentationRequest - Web APIs

PresentationRequest
===================

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

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

A `PresentationRequest` object is used to initiate or reconnect to a presentation made by a controlling browsing context. The `PresentationRequest` object *MUST* be implemented in a controlling browsing context provided by a controlling user agent.

When a `PresentationRequest` is constructed, the given `urls` *MUST* be used as the list of *presentation request URLs* which are each a possible presentation URL for the `PresentationRequest` instance.

EventTarget

PresentationRequestConstructor
-----------

`PresentationRequest()`
Experimental

Creates a `PresentationRequest`.

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

None

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

`PresentationRequest.start()`
Experimental

Returns a `Promise` that resolves with a `PresentationConnection` after the user agent prompts the user to select a display and grant permission to use that display.

`PresentationRequest.reconnect()`
Experimental

When the `reconnect(presentationId)` method is called on a `PresentationRequest` *presentationRequest*, the user agent *MUST* run the following steps to *reconnect to a presentation*.

`PresentationRequest.getAvailability()`
Experimental

When the `getAvailability()` method is called, the user agent *MUST* run the steps as the link.

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

| Specification |
| --- |
| Presentation API # interface-presentationrequest |

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

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