ReadableStream: ReadableStream() constructor - Web APIs

ReadableStream: ReadableStream() constructor
============================================

The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers.

Note that while all parameters are technically optional, omitting the `underlyingSource` will result in a stream that has no source, and that can't be read from (readers return a promise that will never be resolved).

Syntax
------

```js
new ReadableStream()
new ReadableStream(underlyingSource)
new ReadableStream(underlyingSource, queuingStrategy)
```

### Parameters

`underlyingSource` Optional

 An object containing methods and properties that define how the constructed stream instance will behave.
 `underlyingSource` can contain the following:

`start` (controller) Optional

 This is a method, called immediately when the object is constructed. The
 contents of this method are defined by the developer, and should aim to get access
 to the stream source, and do anything else required to set up the stream
 functionality. If this process is to be done asynchronously, it can return a
 promise to signal success or failure. The `controller` parameter passed
 to this method is a `ReadableStreamDefaultController` or a
 `ReadableByteStreamController`, depending on the value of the
 `type` property. This can be used by the developer to control the
 stream during set up.

`pull` (controller) Optional

 This method, also defined by the developer, will be called repeatedly when the
 stream's internal queue of chunks is not full, up until it reaches its high water
 mark. If `pull()` returns a promise, then it won't be called again
 until that promise fulfills; if the promise rejects, the stream will become
 errored. The `controller` parameter passed to this method is a
 `ReadableStreamDefaultController` or a
 `ReadableByteStreamController`, depending on the value of the
 `type` property. This can be used by the developer to control the
 stream as more chunks are fetched. This function will not be called until `start()`
 successfully completes. Additionally, it will only be called repeatedly if it
 enqueues at least one chunk or fulfills a BYOB request; a no-op `pull()`
 implementation will not be continually called.

`cancel` (reason) Optional

 This method, also defined by the developer, will be called if the app signals
 that the stream is to be cancelled (e.g. if `ReadableStream.cancel()`
 is called). The contents should do whatever is necessary to release access to the
 stream source. If this process is asynchronous, it can return a promise to signal
 success or failure. The `reason` parameter contains a
 string describing why the stream was cancelled.

`type` Optional

 This property controls what type of readable stream is being dealt with. If it
 is included with a value set to `"bytes"`, the passed controller object
 will be a `ReadableByteStreamController` capable of handling a BYOB
 (bring your own buffer)/byte stream. If it is not included, the passed controller
 will be a `ReadableStreamDefaultController`.

`autoAllocateChunkSize` Optional

 For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature.
 With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required.

 This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`.
 If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues.

`queuingStrategy` Optional

 An object that optionally defines a queuing strategy for the stream. This takes two
 parameters:

`highWaterMark`

 A non-negative integer — this defines the total number of chunks that can be
 contained in the internal queue before backpressure is applied.

`size(chunk)`

 A method containing a parameter `chunk` — this indicates the size to
 use for each chunk, in bytes.

**Note:** You could define your own custom
 `queuingStrategy`, or use an instance of
 `ByteLengthQueuingStrategy` or `CountQueuingStrategy`
 for this object value. If no `queuingStrategy` is supplied, the default
 used is the same as a `CountQueuingStrategy` with a high water mark of
 1.

### Return value

An instance of the `ReadableStream` object.

### Exceptions

`RangeError`

Thrown if the supplied type value is neither `"bytes"` nor `undefined`.

Examples
--------

 In the following simple example, a custom `ReadableStream` is created using
 a constructor (see our Simple random stream example for the full code). The `start()` function generates a
 random string of text every second and enqueues it into the stream. A
 `cancel()` function is also provided to stop the generation if
 `ReadableStream.cancel()` is called for any reason.

 When a button is pressed, the generation is stopped, the stream is closed using
 `ReadableStreamDefaultController.close()`, and another function is run,
 which reads the data back out of the stream.

```js
let interval;
const stream = new ReadableStream({
  start(controller) {
    interval = setInterval(() => {
      let string = randomChars();

      // Add the string to the stream
      controller.enqueue(string);

      // show it on the screen
      let listItem = document.createElement("li");
      listItem.textContent = string;
      list1.appendChild(listItem);
    }, 1000);

    button.addEventListener("click", () => {
      clearInterval(interval);
      fetchStream();
      controller.close();
    });
  },
  pull(controller) {
    // We don't really need a pull in this example
  },
  cancel() {
    // This is called if the reader cancels,
    // so we should stop generating strings
    clearInterval(interval);
  },
});
```

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

| Specification |
| --- |
| Streams Standard # ref-for-rs-constructor⑤ |

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

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

See also
--------

* `ReadableStream`
* `ReadableByteStreamController`
* `ReadableStreamDefaultController`
* Using readable streams


ReadableStream: cancel() method - Web APIs

ReadableStream: cancel() method
===============================

 The **`cancel()`** method of the
 `ReadableStream` interface returns a `Promise` that
 resolves when the stream is canceled.

 Cancel is used when you've completely finished with the stream and don't need any more
 data from it, even if there are chunks enqueued waiting to be read. That data is lost
 after cancel is called, and the stream is not readable any more. To read those chunks
 still and not completely get rid of the stream, you'd use
 `ReadableStreamDefaultController.close()`.

Syntax
------

```js
cancel()
cancel(reason)
```

### Parameters

`reason` Optional

A human-readable reason for the cancellation. The underlying source may or may not use it.

### Return value

A `Promise`, which fulfills with the value given in the `reason` parameter.

### Exceptions

`TypeError`

The stream you are trying to cancel is not a `ReadableStream`, or it is locked.

Examples
--------

 In Jake Archibald's cancelling a fetch example, a stream is used to fetch the WHATWG HTML spec chunk by chunk; each
 chunk is searched for the string "service workers". When the search terms is found, `cancel()` is used to cancel the stream — the job is finished so it is no longer needed.

```js
const searchTerm = "service workers";
// Chars to show either side of the result in the match
const contextBefore = 30;
const contextAfter = 30;
const caseInsensitive = true;
const url = "https://html.spec.whatwg.org/";

console.log(`Searching '${url}' for '${searchTerm}'`);

fetch(url)
  .then((response) => {
    console.log("Received headers");

    const decoder = new TextDecoder();
    const reader = response.body.getReader();
    const toMatch = caseInsensitive ? searchTerm.toLowerCase() : searchTerm;
    const bufferSize = Math.max(toMatch.length - 1, contextBefore);

    let bytesReceived = 0;
    let buffer = "";
    let matchFoundAt = -1;

    return reader.read().then(function process(result) {
      if (result.done) {
        console.log("Failed to find match");
        return;
      }

      bytesReceived += result.value.length;
      console.log(`Received ${bytesReceived} bytes of data so far`);

      buffer += decoder.decode(result.value, { stream: true });

      // already found match & just context-gathering?
      if (matchFoundAt === -1) {
        matchFoundAt = (
          caseInsensitive ? buffer.toLowerCase() : buffer
        ).indexOf(toMatch);
      }

      if (matchFoundAt === -1) {
        buffer = buffer.slice(-bufferSize);
      } else if (
        buffer.slice(matchFoundAt + toMatch.length).length >= contextAfter
      ) {
        console.log("Here's the match:");
        console.log(
          buffer.slice(
            Math.max(0, matchFoundAt - contextBefore),
            matchFoundAt + toMatch.length + contextAfter,
          ),
        );
        console.log("Cancelling fetch");
        reader.cancel();
        return;
      } else {
        console.log("Found match, but need more context…");
      }

      // keep reading
      return reader.read().then(process);
    });
  })
  .catch((err) => {
    console.error(
      "Something went wrong. See devtools for details. Does the response lack CORS headers?",
    );
    throw err;
  });
```

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

| Specification |
| --- |
| Streams Standard # ref-for-rs-cancel③ |

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

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

See also
--------

* `ReadableStream()` constructor
* Using readable streams


ReadableStream: from() static method - Web APIs

ReadableStream: from() static method
====================================

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

The **`ReadableStream.from()`** static method returns a `ReadableStream` from a provided iterable or async iterable object.

The method can be used to wrap iterable and async iterable objects as readable streams, including arrays, sets, arrays of promises, async generators, `ReadableStreams`, Node.js `readable` streams, and so on.

Syntax
------

```js
ReadableStream.from(anyIterable)
```

### Parameters

`anyIterable`

An iterable or async iterable object.

### Return value

A `ReadableStream`.

### Exceptions

`TypeError`

 Thrown if the passed parameter is not an iterable or async iterable (does not define the `@@iterator` or `@@asyncIterator` method).
 Also thrown if, during iteration, the result of the next step is not an object or is a promise that does not resolve to an object.

Examples
--------

### Convert an async iterator to a ReadableStream

This live example demonstrates how you can convert an async iterable to a `ReadableStream`, and then how this stream might be consumed.

#### HTML

The HTML is consists of single `<pre>` element, which is used for logging.

```html
<pre id="log"></pre>
```

#### JavaScript

The example code creates a `log()` function to write to the log HTML element.

```js
const logElement = document.getElementById("log");
function log(text) {
  logElement.innerText += `${text}\n`;
}
```

It then checks if the static method is supported, and if not, logs the result.

```js
if (!ReadableStream.from) {
  log("ReadableStream.from() is not supported");
}
```

 The async iterable is an anonymous generator function that yields the values of 1, 2 and 3 when it is called three times.
 This is passed to `ReadableStream.from()` to create the `ReadableStream`.

```js
// Define an asynchronous iterator
const asyncIterator = (async function\* () {
  yield 1;
  yield 2;
  yield 3;
})();

// Create ReadableStream from iterator
const myReadableStream = ReadableStream.from(asyncIterator);
```

Using readable streams demonstrates several ways to consume a stream.
 The code below uses a `for ...await` loop, as this method is the simplest.
 Each iteration of the loop logs the current chunk from the stream.

```js
consumeStream(myReadableStream);

// Iterate a ReadableStream asynchronously
async function consumeStream(readableStream) {
  for await (const chunk of myReadableStream) {
    // Do something with each chunk
    // Here we just log the values
    log(`chunk: ${chunk}`);
  }
}
```

#### Result

The output of consuming the stream is shown below (if `ReadableStream.from()` is supported).

### Convert an Array to a ReadableStream

This example demonstrates how you can convert an `Array` to a `ReadableStream`.
```

<pre id="log"></pre>
```

```
const logElement = document.getElementById("log");
function log(text) {
  logElement.innerText += `${text}\n`;
}

if (!ReadableStream.from) {
  log("ReadableStream.from() is not supported");
}
```

#### JavaScript

The iterable is just an array of strings that is passed to `ReadableStream.from()` to create the `ReadableStream`.

```js
// An Array of vegetable names
const vegetables = ["Carrot", "Broccoli", "Tomato", "Spinach"];

// Create ReadableStream from the Array
const myReadableStream = ReadableStream.from(vegetables);
```

```
consumeStream(myReadableStream);

// Iterate a ReadableStream asynchronously
async function consumeStream(readableStream) {
  for await (const chunk of myReadableStream) {
    // Do something with each chunk
    // Here we just log the values
    log(`chunk: ${chunk}`);
  }
}
```

We use the same approach as in the previous example log and to consume the stream, so that is not shown here.

#### Result

The output is shown below.

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

| Specification |
| --- |
| Streams Standard # ref-for-rs-from |

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

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

See also
--------

* `ReadableStream`
* Using readable streams


ReadableStream: tee() method - Web APIs

ReadableStream: tee() method
============================

 The **`tee()`** method of the
 `ReadableStream` interface tees the current readable stream, returning a
 two-element array containing the two resulting branches as
 new `ReadableStream` instances.

 This is useful for allowing two readers to read a stream sequentially or simultaneously,
 perhaps at different speeds.
 For example, you might do this in a ServiceWorker if you want to fetch
 a response from the server and stream it to the browser, but also stream it to the
 ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need
 two copies to do this.

 A teed stream will partially signal backpressure at the rate of the *faster* consumer
 of the two `ReadableStream` branches,
 and unread data is enqueued internally on the slower consumed `ReadableStream`
 without any limit or backpressure.
 That is, when *both* branches have an unread element in their internal queue,
 then the original `ReadableStream`'s controller's internal queue will start to fill up,
 and once its `desiredSize` ≤ 0
 or byte stream controller `desiredSize` ≤ 0,
 then the controller will stop calling `pull(controller)` on the
 underlying source passed to `new ReadableStream()`.
 If only one branch is consumed, then the entire body will be enqueued in memory.
 Therefore, you should not use the built-in `tee()` to read very large streams
 in parallel at different speeds.
 Instead, search for an implementation that fully backpressures
 to the speed of the *slower* consumed branch.

 To cancel the stream you then need to cancel both resulting branches. Teeing a stream
 will generally lock it for the duration, preventing other readers from locking it.

Syntax
------

```js
tee()
```

### Parameters

None.

### Return value

An `Array` containing two `ReadableStream` instances.

### Exceptions

`TypeError`

Thrown if the source stream is not a `ReadableStream`.

Examples
--------

 In the following simple example, a previously-created stream is teed, then both
 resulting streams (contained in two members of a generated array) are passed to a
 function that reads the data out of the two streams and prints each stream's chunks
 sequentially to a different part of the UI. See Simple tee example for the full code.

```js
function teeStream() {
  const teedOff = stream.tee();
  fetchStream(teedOff[0], list2);
  fetchStream(teedOff[1], list3);
}

function fetchStream(stream, list) {
  const reader = stream.getReader();
  let charsReceived = 0;

  // read() returns a promise that resolves
  // when a value has been received
  reader.read().then(function processText({ done, value }) {
    // Result objects contain two properties:
    // done - true if the stream has already given you all its data.
    // value - some data. Always undefined when done is true.
    if (done) {
      console.log("Stream complete");
      return;
    }

    // value for fetch streams is a Uint8Array
    charsReceived += value.length;
    const chunk = value;
    let listItem = document.createElement("li");
    listItem.textContent = `Read ${charsReceived} characters so far. Current chunk = ${chunk}`;
    list.appendChild(listItem);

    // Read some more, and call this function again
    return reader.read().then(processText);
  });
}
```

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

| Specification |
| --- |
| Streams Standard # ref-for-rs-tee② |

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

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

See also
--------

* `ReadableStream()` constructor
* Teeing a stream


ReadableStream: pipeTo() method - Web APIs

ReadableStream: pipeTo() method
===============================

The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered.

Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it.

Syntax
------

```js
pipeTo(destination)
pipeTo(destination, options)
```

### Parameters

`destination`

A `WritableStream` that acts as the final destination for the `ReadableStream`.

`options` Optional

 The options that should be used when piping to the `writable` stream.
 Available options are:

`preventClose`

 If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed.
 The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error.

`preventAbort`

 If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`.
 The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination.

`preventCancel`

 If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`.
 In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source.
 In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled.
 In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.

`signal`

If set to an `AbortSignal` object, ongoing pipe operations can then be aborted via the corresponding `AbortController`.

### Return value

A `Promise` that resolves when the piping process has completed.

### Exceptions

`TypeError`

The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked.

Examples
--------

```js
// Fetch the original image
fetch("png-logo.png")
  // Retrieve its body as ReadableStream
  .then((response) => response.body)
  .then((body) => body.pipeThrough(new PNGTransformStream()))
  .then((rs) => rs.pipeTo(new FinalDestinationStream()));
```

The same example, but using `await`:

```js
(async () => {
  // Fetch the original image
  const response = await fetch("png-logo.png");
  // Retrieve its body as ReadableStream
  response.body
    .pipeThrough(new PNGTransformStream())
    .pipeTo(new FinalDestinationStream());
})();
```

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

| Specification |
| --- |
| Streams Standard # ref-for-rs-pipe-to④ |

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

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

See also
--------

* `ReadableStream()` constructor
* Pipe chains


ReadableStream: pipeThrough() method - Web APIs

ReadableStream: pipeThrough() method
====================================

The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair.

Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it.

Syntax
------

```js
pipeThrough(transformStream)
pipeThrough(transformStream, options)
```

### Parameters

`transformStream`

 A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another.
 Data written to the `writable` stream can be read in some transformed state by the `readable` stream.
 For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it.

`options` Optional

 The options that should be used when piping to the `writable` stream.
 Available options are:

`preventClose`

If this is set to `true`, closing the source `ReadableStream` will no longer cause the destination `WritableStream` to be closed.

`preventAbort`

If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`.

`preventCancel`

If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`.

`signal`

If set to an `AbortSignal` object, ongoing pipe operations can then be aborted via the corresponding `AbortController`.

### Return value

The `readable` side of the `transformStream`.

### Exceptions

`TypeError`

Thrown if the `writable` and/or `readable` property of `transformStream` are undefined.

Examples
--------

In the following example (see Unpack chunks of a PNG for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a `ReadableStream`.

Next, we log the contents of the readable stream, use `pipeThrough()` to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too.

```js
// Fetch the original image
fetch("png-logo.png")
  // Retrieve its body as ReadableStream
  .then((response) => response.body)
  .then((rs) => logReadableStream("Fetch Response Stream", rs))
  // Create a gray-scaled PNG stream out of the original
  .then((body) => body.pipeThrough(new PNGTransformStream()))
  .then((rs) => logReadableStream("PNG Chunk Stream", rs));
```

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

| Specification |
| --- |
| Streams Standard # ref-for-rs-pipe-through② |

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

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

See also
--------

* `ReadableStream()` constructor
* Pipe chains


ReadableStream: locked property - Web APIs

ReadableStream: locked property
===============================

The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader.

 A readable stream can have at most one active reader at a time, and is locked to that reader until it is released.
 A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method.

Value
-----

A boolean value indicating whether or not the readable stream is locked.

Examples
--------

```js
const stream = new ReadableStream({
  // ...
});

const reader = stream.getReader();

stream.locked;
// should return true, as the stream has been locked to a reader
```

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

| Specification |
| --- |
| Streams Standard # ref-for-rs-locked② |

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

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

See also
--------

* `ReadableStream()` constructor
* Using readable streams


AudioData: copyTo() method - Web APIs

AudioData: copyTo() method
==========================

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 **`copyTo()`** method of the `AudioData` interface copies a plane of an `AudioData` object to a destination buffer.

Syntax
------

```js
copyTo(destination, options)
```

### Parameters

`destination`

An `ArrayBuffer`, a `TypedArray`, or a `DataView` to copy the plane to.

`options`

An object containing the following:

`planeIndex`

The index of the plane to copy from.

`frameOffset` Optional

An integer giving an offset into the plane data indicating which plane to begin copying from. Defaults to `0`.

`frameCount` Optional

An integer giving the number of frames to copy. If omitted then all frames in the plane will be copied, beginning with the frame specified in `frameOffset`.

### Return value

Undefined.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `AudioData` object has been transferred.

`RangeError`

Thrown if one of the following conditions is met:

* The length of the sample is longer than the destination length.
* The format of the `AudioData` object describes a planar format, but `options.planeIndex` is outside of the number of planes available.
* The format of the `AudioData` object describes an interleaved format, but `options.planeIndex` is greater than `0`.

Examples
--------

The following example copies the plane at index `1` to a destination buffer.

```js
AudioData.copyTo(AudioBuffer, { planeIndex: 1 });
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-copyto |

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

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


AudioData: timestamp property - Web APIs

AudioData: timestamp property
=============================

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 **`duration`** read-only property of the `AudioData` interface returns the timestamp of this `AudioData` object.

Value
-----

An integer.

Examples
--------

The below example prints the value of `timestamp` to the console.

```js
console.log(AudioData.timestamp);
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-timestamp |

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

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


AudioData: AudioData() constructor - Web APIs

AudioData: AudioData() constructor
==================================

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 **`AudioData()`** constructor creates a new `AudioData` object which represents an individual audio sample.

Syntax
------

```js
new AudioData(init)
```

### Parameters

`init`

An object containing the following:

`format`

One of:

* "u8"
* "s16"
* "s32"
* "f32"
* "u8-planar"
* "s16-planar"
* "s32-planar"
* "f32-planar"

`sampleRate`

A decimal containing the sample rate in Hz.

`numberOfFrames`

An integer containing the number of frames in this sample.

`numberOfChannels`

An integer containing the number of channels in this sample.

`timestamp`

An integer indicating the data's time in microseconds .

`data`

A typed array of the audio data for this sample.

`transfer`

An array of `ArrayBuffer`s that `AudioData` will detach and take ownership of. If the array contains the `ArrayBuffer` backing `data`, `AudioData` will use that buffer directly instead of copying from it.

Exceptions
----------

`TypeError`

Thrown if `init` is in an incorrect format.

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-audiodata |

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

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


AudioData: clone() method - Web APIs

AudioData: clone() method
=========================

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 **`clone()`** method of the `AudioData` interface creates a new `AudioData` object with reference to the same media resource as the original.

Syntax
------

```js
clone()
```

### Parameters

None.

### Return value

The cloned `AudioData` object.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `AudioData` object has been transferred.

Examples
--------

The following example clones a copy of `AudioData` as `audioData2`.

```js
let audioData2 = AudioData.clone();
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-clone |

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

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


AudioData: format property - Web APIs

AudioData: format property
==========================

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 **`format`** read-only property of the `AudioData` interface returns the sample format of the `AudioData` object.

Value
-----

A string. One of:

`"u8"`

8-bit unsigned integer samples, in an interleaved format.

`"s16"`

16-bit signed integer samples, in an interleaved format.

`"s32"`

32-bit signed integer samples, in an interleaved format.

`"f32"`

32-bit float samples, in an interleaved format.

`"u8-planar"`

8-bit unsigned integer samples, in a planar format.

`"s16-planar"`

16-bit signed integer samples, in a planar format.

`"s32-planar"`

32-bit signed integer samples, in a planar format.

`"f32-planar"`

32-bit float samples, in a planar format.

Examples
--------

The below example prints the value of `format` to the console.

```js
console.log(AudioData.format);
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-format |

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

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


AudioData: numberOfFrames property - Web APIs

AudioData: numberOfFrames property
==================================

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 **`numberOfFrames`** read-only property of the `AudioData` interface returns the number of frames in the `AudioData` object.

Value
-----

An integer.

Examples
--------

The below example prints the value of `numberOfFrames` to the console.

```js
console.log(AudioData.numberOfFrames);
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-numberofframes |

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

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


AudioData: sampleRate property - Web APIs

AudioData: sampleRate property
==============================

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 **`sampleRate`** read-only property of the `AudioData` interface returns the sample rate in Hz.

Value
-----

A decimal value.

Examples
--------

The below example prints the value of `sampleRate` to the console.

```js
console.log(audioData.sampleRate);
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-samplerate |

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

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


AudioData: numberOfChannels property - Web APIs

AudioData: numberOfChannels property
====================================

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 **`numberOfChannels`** read-only property of the `AudioData` interface returns the number of channels in the `AudioData` object.

Value
-----

An integer.

Examples
--------

The below example prints the value of `numberOfChannels` to the console.

```js
console.log(AudioData.numberOfChannels);
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-numberofchannels |

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

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


AudioData: allocationSize() method - Web APIs

AudioData: allocationSize() method
==================================

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 **`allocationSize()`** method of the `AudioData` interface returns the size in bytes required to hold the current sample as filtered by options passed into the method.

Syntax
------

```js
allocationSize(options)
```

### Parameters

`options`

An object containing the following:

`planeIndex`

The index of the plane to return the size of.

`frameOffset` Optional

An integer giving an offset into the plane data indicating which plane to begin from. Defaults to `0`.

`frameCount` Optional

An integer giving the number of frames to return the size of. If omitted then all frames in the plane will be used, beginning with the frame specified in `frameOffset`.

### Return value

An integer containing the number of bytes needed to hold the samples described by `options`.

Examples
--------

The following example gets the size of the plane at index `1`.

```js
let size = AudioData.allocationSize({ planeIndex: 1 });
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-allocationsize |

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

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


AudioData: duration property - Web APIs

AudioData: duration property
============================

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 **`duration`** read-only property of the `AudioData` interface returns the duration in microseconds of this `AudioData` object.

Value
-----

An integer.

Examples
--------

The below example prints the value of `duration` to the console.

```js
console.log(AudioData.duration);
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-duration |

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

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


AudioData: close() method - Web APIs

AudioData: close() method
=========================

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 **`close()`** method of the `AudioData` interface clears all states and releases the reference to the media resource.

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

Undefined.

Examples
--------

The following example shows the `AudioData` object being closed.

```js
AudioData.close();
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodata-close |

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

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


DOMImplementation: createHTMLDocument() method - Web APIs

DOMImplementation: createHTMLDocument() method
==============================================

 The
 **`DOMImplementation.createHTMLDocument()`** method creates a
 new HTML `Document`.

Syntax
------

```js
createHTMLDocument()
createHTMLDocument(title)
```

### Parameters

`title` Optional

A string containing the title to give the new HTML document.

### Return value

A new HTML `Document` object.

Examples
--------

This example creates a new HTML document and inserts it into an `<iframe>` in the current document.

Here's the HTML for this example:

```html
<body>
  <p>
    Click <a href="javascript:makeDocument()">here</a> to create a new document
    and insert it below.
  </p>
  <iframe id="theFrame" src="about:blank" />
</body>
```

The JavaScript implementation of `makeDocument()` follows:

```js
function makeDocument() {
  let frame = document.getElementById("theFrame");

  let doc = document.implementation.createHTMLDocument("New Document");
  let p = doc.createElement("p");
  p.textContent = "This is a new paragraph.";

  try {
    doc.body.appendChild(p);
  } catch (e) {
    console.log(e);
  }

  // Copy the new HTML document into the frame

  let destDocument = frame.contentDocument;
  let srcNode = doc.documentElement;
  let newNode = destDocument.importNode(srcNode, true);

  destDocument.replaceChild(newNode, destDocument.documentElement);
}
```

 The code in lines 4–12 handle creating the new HTML document and inserting some content
 into it. Line 4 uses `createHTMLDocument()` to construct a new HTML document
 whose `<title>` is `"New Document"`. Lines 5 and 6 create a
 new paragraph element with some simple content, and then lines 8–12 handle inserting the
 new paragraph into the new document.

 Line 16 pulls the `contentDocument` of the frame; this is the document into
 which we'll be injecting the new content. The next two lines handle importing the
 contents of our new document into the new document's context. Finally, line 20 actually
 replaces the contents of the frame with the new document's contents.

View Live Examples

The returned document is pre-constructed with the following HTML:

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>title</title>
  </head>
  <body>
    …
  </body>
</html>
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-domimplementation-createhtmldocument① |

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

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

See also
--------

* The `DOMImplementation` interface it belongs to.


DOMImplementation: createDocument() method - Web APIs

DOMImplementation: createDocument() method
==========================================

 The **`DOMImplementation.createDocument()`** method creates and
 returns an `XMLDocument`.

Syntax
------

```js
createDocument(namespaceURI, qualifiedNameStr)
createDocument(namespaceURI, qualifiedNameStr, documentType)
```

### Parameters

`namespaceURI`

 A string containing the namespace URI of the document to be
 created, or `null` if the document doesn't belong to one.

`qualifiedNameStr`

 A string containing the qualified name, that is an optional
 prefix and colon plus the local root element name, of the document to be created.

`documentType` Optional

 Is the `DocumentType` of the document to be created. It defaults to
 `null`.

### Return value

None (`undefined`).

Examples
--------

```js
const doc = document.implementation.createDocument(
  "http://www.w3.org/1999/xhtml",
  "html",
  null,
);
const body = document.createElementNS("http://www.w3.org/1999/xhtml", "body");
body.setAttribute("id", "abc");
doc.documentElement.appendChild(body);
alert(doc.getElementById("abc")); // [object HTMLBodyElement]
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-domimplementation-createdocument② |

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

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

See also
--------

* The `DOMImplementation` interface it belongs to.


DOMImplementation: hasFeature() method - Web APIs

DOMImplementation: hasFeature() method
======================================

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

 The
 **`DOMImplementation.hasFeature()`** method returns a
 boolean flag indicating if a given feature is supported. It is
 deprecated and modern browsers return `true` in all cases.

 The different implementations fairly diverged in what kind of features were reported.
 The latest version of the spec settled to force this method to always return
 `true`, where the functionality was accurate and in use.

Syntax
------

```js
hasFeature(feature, version)
```

### Parameters

`feature`

A string representing the feature name.

`version`

 A string representing the version of the specification defining
 the feature.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| DOM Standard # dom-domimplementation-hasfeature |

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

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

See also
--------

* The `DOMImplementation` interface it belongs to.


DOMImplementation: createDocumentType() method - Web APIs

DOMImplementation: createDocumentType() method
==============================================

 The **`DOMImplementation.createDocumentType()`** method returns
 a `DocumentType` object which can either be used with
 `DOMImplementation.createDocument` upon document creation or can be put
 into the document via methods like `Node.insertBefore()` or
 `Node.replaceChild()`.

Syntax
------

```js
createDocumentType(qualifiedNameStr, publicId, systemId)
```

### Parameters

`qualifiedNameStr`

 A string containing the qualified name, like
 `svg:svg`.

`publicId`

A string containing the `PUBLIC` identifier.

`systemId`

A string containing the `SYSTEM` identifiers.

### Return value

A `DocumentType`.

Examples
--------

```js
const dt = document.implementation.createDocumentType(
  "svg:svg",
  "-//W3C//DTD SVG 1.1//EN",
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd",
);
const d = document.implementation.createDocument(
  "http://www.w3.org/2000/svg",
  "svg:svg",
  dt,
);
alert(d.doctype.publicId); // -//W3C//DTD SVG 1.1//EN
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-domimplementation-createdocumenttype① |

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

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

See also
--------

* The `DOMImplementation` interface it belongs to.


SharedStorage: clear() method - Web APIs

SharedStorage: clear() method
=============================

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

The **`clear()`** method of the `SharedStorage` interface clears the current origin's shared storage, removing all data from it.

Syntax
------

```js
clear()
```

### Parameters

None.

### Return value

A `Promise` that fulfills with `undefined`.

### Exceptions

* The `Promise` rejects with a `TypeError` if:
    + The database was not cleared successfully due to shared storage not being available (for example it is disabled using a browser setting).
    + The calling site does not have the Shared Storage API included in a successful privacy sandbox enrollment process.
* In the case of `WorkletSharedStorage`, the `Promise` rejects with a `TypeError` if the worklet module has not been added with `SharedStorageWorklet.addModule()`.

**Note:** In the case of `WindowSharedStorage`, if the `clear()` operation doesn't successfully write to the database for a reason other than shared storage not being available, no error is thrown — the operation still fulfills with `undefined`.

Examples
--------

```js
window.sharedStorage.clear().then(console.log("Shared storage cleared"));
```

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

| Specification |
| --- |
| Shared Storage API # dom-sharedstorage-clear |

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

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

See also
--------

* Shared Storage API


SharedStorage: append() method - Web APIs

SharedStorage: append() method
==============================

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

The **`append()`** method of the `SharedStorage` interface appends a string to the value of an existing key-value pair in the current origin's shared storage.

Syntax
------

```js
append(key, value)
```

### Parameters

`key`

A string representing the key of the key-value pair to which you want to append a value.

`value`

A string that you want to append to the existing value of the key-value pair.

**Note:** If the specified `key` isn't found in the shared storage, the `append()` operation is equivalent to `set()`, that is, a new key-value pair with the specified `key` is added to the shared storage.

### Return value

A `Promise` that fulfills with `undefined`.

### Exceptions

* The `Promise` rejects with a `TypeError` if:
    + The appended entry was not successfully stored in the database due to shared storage not being available (for example it is disabled using a browser setting).
    + `key` and/or `value` exceed the browser-defined maximum length.
    + The calling site does not have the Shared Storage API included in a successful privacy sandbox enrollment process.
* In the case of `WorkletSharedStorage`, the `Promise` rejects with a `TypeError` if the worklet module has not been added with `SharedStorageWorklet.addModule()`.

**Note:** In the case of `WindowSharedStorage`, if the `append()` operation doesn't successfully write to the database for a reason other than shared storage not being available, no error is thrown — the operation still fulfills with `undefined`.

Examples
--------

```js
window.sharedStorage
  .append("integer-list", ",9")
  .then(console.log("Value appended to integer list"));
```

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

| Specification |
| --- |
| Shared Storage API # dom-sharedstorage-append |

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

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

See also
--------

* Shared Storage API


SharedStorage: delete() method - Web APIs

SharedStorage: delete() method
==============================

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

The **`delete()`** method of the `SharedStorage` interface deletes an existing key-value pair from the current origin's shared storage.

Syntax
------

```js
delete(key)
```

### Parameters

`key`

A string representing the key of the key-value pair you want to delete.

### Return value

A `Promise` that fulfills with `undefined`.

### Exceptions

* The `Promise` rejects with a `TypeError` if:
    + The database was not cleared successfully due to shared storage not being available (for example it is disabled using a browser setting).
    + `key` exceeds the browser-defined maximum length.
    + The calling site does not have the Shared Storage API included in a successful privacy sandbox enrollment process.
* In the case of `WorkletSharedStorage`, the `Promise` rejects with a `TypeError` if:
    + The worklet module has not been added with `SharedStorageWorklet.addModule()`.

**Note:** If the key-value pair doesn't exist in the shared storage, no error is thrown — the operation still fulfills with `undefined`.

**Note:** In the case of `WindowSharedStorage`, if the `delete()` operation doesn't successfully write to the database for a reason other than shared storage not being available, no error is thrown — the operation still fulfills with `undefined`.

Examples
--------

```js
window.sharedStorage
  .delete("ab-testing-group")
  .then(console.log("Value deleted"));
```

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

| Specification |
| --- |
| Shared Storage API # dom-sharedstorage-delete |

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

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

See also
--------

* Shared Storage API


SharedStorage: set() method - Web APIs

SharedStorage: set() method
===========================

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

The **`set()`** method of the `SharedStorage` interface either stores a new key-value pair in the current origin's shared storage or updates an existing one.

Syntax
------

```js
set(key, value)
set(key, value, options)
```

### Parameters

`key`

A string representing the key in the key-value pair that you want to add or update.

`value`

A string representing the value you want to add or update.

`options` Optional

An options object containing the following properties:

`ignoreIfPresent`

A boolean value. The value `true` causes the set operation to abort if a key-value pair with the specified `key` already exists. The default value `false` causes the set operation to overwrite the previous value.

### Return value

A `Promise` that fulfills with `undefined`.

### Exceptions

* The `Promise` rejects with a `TypeError` if:
    + The created entry was not successfully stored in the database due to shared storage not being available (for example it is disabled using a browser setting).
    + `key` and/or `value` exceed the browser-defined maximum length.
    + The calling site does not have the Shared Storage API included in a successful privacy sandbox enrollment process.
* In the case of `WorkletSharedStorage`, the `Promise` rejects with a `TypeError` if the worklet module has not been added with `SharedStorageWorklet.addModule()`.

**Note:** In the case of `WindowSharedStorage`, if the `set()` operation doesn't successfully write to the database for a reason other than shared storage not being available, no error is thrown — the operation still fulfills with `undefined`.

Examples
--------

```js
window.sharedStorage
  .set("ab-testing-group", "0", {
    ignoreIfPresent: true,
  })
  .then(console.log("Set operation completed"));
```

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

| Specification |
| --- |
| Shared Storage API # dom-sharedstorage-set |

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

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

See also
--------

* Shared Storage API


StorageEvent: key property - Web APIs

StorageEvent: key property
==========================

The **`key`** property of the `StorageEvent` interface returns the key for the storage item that was changed.

Value
-----

A string containing the key for the storage item that was changed.

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

| Specification |
| --- |
| HTML Standard # dom-storageevent-key-dev |

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

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

See also
--------

* Web Storage API


StorageEvent: url property - Web APIs

StorageEvent: url property
==========================

The **`url`** property of the `StorageEvent` interface returns the URL of the document whose storage changed.

Value
-----

A string containing the URL of the document whose storage changed.

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

| Specification |
| --- |
| HTML Standard # dom-storageevent-url-dev |

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

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

See also
--------

* Web Storage API


StorageEvent: StorageEvent() constructor - Web APIs

StorageEvent: StorageEvent() constructor
========================================

The **`StorageEvent()`** constructor creates a new `StorageEvent` object.

Syntax
------

```js
new StorageEvent(type)
new StorageEvent(type, options)
```

### Parameters

`type`

A string with the name of the type of the `StorageEvent`. It is case-sensitive and browsers set it to `storage`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, has the following properties:

`key` Optional

A string that represents the key for the storage item that changed. Defaults to `null`.

`oldValue` Optional

A string containing the original value of the storage item. Defaults to `null`.

`newValue` Optional

A string with the new value of the `key`. Defaults to `null`.

`url`

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

`storageArea` Optional

A `Storage` object that represents the storage that was affected. Defaults to `null`.

### Return value

A new `StorageEvent` object.

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

#### No specification found

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

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

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

See also
--------

* Web Storage API


StorageEvent: newValue property - Web APIs

StorageEvent: newValue property
===============================

The **`newValue`** property of the `StorageEvent` interface returns the new value of the storage item whose value was changed.

Value
-----

A string containing the new value of the storage item.

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

| Specification |
| --- |
| HTML Standard # dom-storageevent-newvalue-dev |

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

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

See also
--------

* Web Storage API


StorageEvent: storageArea property - Web APIs

StorageEvent: storageArea property
==================================

The **`storageArea`** property of the `StorageEvent` interface returns the storage object that was affected.

Value
-----

A `Storage` object that represents the storage object that was affected.

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

| Specification |
| --- |
| HTML Standard # dom-storageevent-storagearea-dev |

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

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

See also
--------

* Web Storage API


StorageEvent: oldValue property - Web APIs

StorageEvent: oldValue property
===============================

The **`oldValue`** property of the `StorageEvent` interface returns the original value of the storage item whose value changed.

Value
-----

A string containing the original value of the storage item.

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

| Specification |
| --- |
| HTML Standard # dom-storageevent-oldvalue-dev |

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

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

See also
--------

* Web Storage API


StorageEvent: initStorageEvent() method - Web APIs

StorageEvent: initStorageEvent() method
=======================================

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

The **`StorageEvent.initStorageEvent()`** method is used to initialize the value of a `StorageEvent`.

Syntax
------

```js
initStorageEvent(type)
initStorageEvent(type, canBubble)
initStorageEvent(type, canBubble, cancelable)
initStorageEvent(type, canBubble, cancelable, key)
initStorageEvent(type, canBubble, cancelable, key, oldValue)
initStorageEvent(type, canBubble, cancelable, key, oldValue, newValue)
initStorageEvent(type, canBubble, cancelable, key, oldValue, newValue, url)
initStorageEvent(type, canBubble, cancelable, key, oldValue, newValue, url, storageArea)
```

### Parameters

`typeArg`

The name of the event.

`canBubble` Optional

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

`cancelable` Optional

A boolean indicating whether the event is cancelable.

`key` Optional

The key whose value is changing as a result of this event.

`oldValue` Optional

The key's old value.

`newValue` Optional

The key's new value.

`url` Optional

The URL of the document initiating the change.

`storageArea` Optional

The `Storage` object representing the storage area on which this event occurred.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| HTML Standard # dom-storageevent-initstorageevent |

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

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

See also
--------

* Web Storage API
* The constructor to use instead of this deprecated method: `StorageEvent()`.


ChannelSplitterNode: ChannelSplitterNode() constructor - Web APIs

ChannelSplitterNode: ChannelSplitterNode() constructor
======================================================

The **`ChannelSplitterNode()`** constructor of the Web Audio API creates a new `ChannelSplitterNode` object instance, representing a node that splits the input into a separate output for each of the source node's audio channels.

Syntax
------

```js
new ChannelSplitterNode(context)
new ChannelSplitterNode(context, options)
```

### Parameters

`context`

A `BaseAudioContext` representing the audio context you want the node to be associated with.

`options` Optional

An object defining the properties you want the `ChannelSplitterNode` to have:

`numberOfOutputs` Optional

A number defining the number of outputs the `ChannelSplitterNode` should have. If not specified, the default value used is 6.

`channelCount` Optional

 An integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node.
 (See `AudioNode.channelCount` for more information.)
 Its usage and precise definition depend on the value of `channelCountMode`.

`channelCountMode` Optional

 A string describing the way channels must be matched between the node's inputs and outputs.
 (See `AudioNode.channelCountMode` for more information including default values.)

`channelInterpretation` Optional

 A string describing the meaning of the channels.
 This interpretation will define how audio up-mixing and down-mixing will happen.
 The possible values are `"speakers"` or `"discrete"`.
 (See `AudioNode.channelCountMode` for more information including default values.)

### Return value

A new `ChannelSplitterNode` object instance.

Examples
--------

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

const options = {
  numberOfOutputs: 2,
};

const mySplitter = new ChannelSplitterNode(ac, options);
```

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

| Specification |
| --- |
| Web Audio API # dom-channelsplitternode-constructor-channelsplitternode |

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

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


PopStateEvent: PopStateEvent() constructor - Web APIs

PopStateEvent: PopStateEvent() constructor
==========================================

The **`PopStateEvent()`** constructor creates a new `PopStateEvent` object.

**Note:** A web developer doesn't typically need to call this constructor, as the browser creates these objects itself when firing `popstate` events.

Syntax
------

```js
new PopStateEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers set it to `popstate`.

`options` Optional

An object that, *in addition to the properties defined in `Event()`*, has the following property:

`state` Optional

An object representing the state. Practically it is a value provided by the call to `history.pushState()` or `history.replaceState()`. If not set, it defaults to `null`.

### Return value

A new `PopStateEvent` object.

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

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

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

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

See also
--------

* `history.pushState()`
* `history.replaceState()`
* `popstate` event


PopStateEvent: state property - Web APIs

PopStateEvent: state property
=============================

The **`state`** read-only property of the `PopStateEvent` interface represents the state stored when the event was created.

Practically it is a value provided by the call to `history.pushState()` or `history.replaceState()`

Value
-----

An object, or `null`.

Examples
--------

 The code below logs the value of `state` when using the
 `pushState()` method to push a value to the history.

```js
// Log the state of
addEventListener("popstate", (event) => {
  console.log("State received: ", event.state);
});

// Now push something on the stack
history.pushState({ name: "Example" }, "pushState example", "page1.html");
history.pushState(
  { name: "Another example" },
  "pushState example",
  "page1.html",
);
```

This will log:
```

State received: { name: "Example" }
State received: { name: "Another example" }
```

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

| Specification |
| --- |
| HTML Standard # dom-popstateevent-state-dev |

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

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

See also
--------

* `PopStateEvent()` constructor
* `History.state`


AudioTrack: kind property - Web APIs

AudioTrack: kind property
=========================

 The **`kind`** property contains a
 string indicating the category of audio contained in the
 **`AudioTrack`**.

 The `kind` can be used
 to determine the scenarios in which specific tracks should be enabled or disabled. See
 Audio track kind strings for a list of the kinds available for audio tracks.

Value
-----

 A string specifying the type of content the media represents. The
 string is one of those found in Audio track kind strings below.

Audio track kind strings
------------------------

The kinds available for audio tracks are:

`"alternative"`

 A potential alternative to the main track, such as a different audio take or a
 version of the soundtrack with only the music and no dialogue.

`"descriptions"`

 An audio track providing audible descriptions of the action depicted in a video
 track.

`"main"`

The primary audio track.

`"main-desc"`

The primary audio track with audio descriptions mixed into it.

`"translation"`

A translated version of the primary audio track.

`"commentary"`

 An audio track containing a commentary. This might be used to contain the director's
 commentary track on a movie, for example.

`""` (empty string)

 The track doesn't have an explicit kind, or the kind provided by the track's
 metadata isn't recognized by the user agent.

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

| Specification |
| --- |
| HTML Standard # dom-audiotrack-kind-dev |

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

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


AudioTrack: language property - Web APIs

AudioTrack: language property
=============================

 The read-only **`AudioTrack`**
 property **`language`** returns a string identifying the
 language used in the audio track.

 For tracks that include multiple languages
 (such as a movie in English in which a few lines are spoken in other languages), this
 should be the video's primary language.

Value
-----

 A string specifying the BCP 47 (RFC 5646) format language tag of
 the primary language used in the audio track, or an empty string (`""`) if
 the language is not specified or known, or if the track doesn't contain speech.

 For example, if the primary language used in the track is United States English, this
 value would be `"en-US"`. For Brazilian Portuguese, the value would be
 `"pt-BR"`.

Examples
--------

 This example locates all of a media element's primary language and translated audio
 tracks and returns a list of objects containing each of those tracks'
 `id`, `kind`, and
 `language`.

 This could then be used to build a user interface for selecting the language the user
 would like to listen to while watching a movie, for example.

```js
function getAvailableLanguages(el) {
  const trackList = [];
  const wantedKinds = ["main", "translation"];

  el.audioTracks.forEach((track) => {
    if (wantedKinds.includes(track.kind)) {
      trackList.push({
        id: track.id,
        kind: track.kind,
        language: track.language,
      });
    }
  });
  return trackList;
}
```

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

| Specification |
| --- |
| HTML Standard # dom-audiotrack-language-dev |

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

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


AudioTrack: label property - Web APIs

AudioTrack: label property
==========================

 The read-only **`AudioTrack`**
 property **`label`** returns a string specifying the audio
 track's human-readable label, if one is available; otherwise, it returns an empty
 string.

Value
-----

 A string specifying the track's human-readable label, if one is
 available in the track metadata. Otherwise, an empty string (`""`) is
 returned.

 For example, a track whose `kind` is
 `"commentary"` might have a `label` such as
 `"Commentary with director Mark Markmarkimark and star Donna Donnalidon"`.

Examples
--------

 This example returns an array of track kinds and labels for potential use in a user
 interface to select audio tracks for a specified media element. The list is filtered to
 only allow certain track kinds through.

```js
function getTrackList(el) {
  const trackList = [];
  const wantedKinds = [
    "main",
    "alternative",
    "main-desc",
    "translation",
    "commentary",
  ];

  el.audioTracks.forEach((track) => {
    if (wantedKinds.includes(track.kind)) {
      trackList.push({
        id: track.id,
        kind: track.kind,
        label: track.label,
      });
    }
  });
  return trackList;
}
```

 The resulting `trackList` contains an array of audio tracks whose
 `kind` is one of those in the array `wantedKinds`, with each entry
 providing the track's `id`, `kind`, and `label`.

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

| Specification |
| --- |
| HTML Standard # dom-audiotrack-label-dev |

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

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


AudioTrack: sourceBuffer property - Web APIs

AudioTrack: sourceBuffer property
=================================

 The read-only **`AudioTrack`**
 property **`sourceBuffer`** returns the
 `SourceBuffer` that created the track, or null if the track was not
 created by a `SourceBuffer` or the `SourceBuffer` has been
 removed from the `MediaSource.sourceBuffers` attribute of its parent
 media source.

Value
-----

A `SourceBuffer` or null.

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

| Specification |
| --- |
| Media Source Extensions™ # dom-audiotrack-sourcebuffer |

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

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


AudioTrack: enabled property - Web APIs

AudioTrack: enabled property
============================

 The **`AudioTrack`** property
 **`enabled`** specifies whether or not the described audio
 track is currently enabled for use. If the track is disabled by setting
 `enabled` to `false`, the track is muted and does not produce
 audio.

Value
-----

 The `enabled` property is a Boolean whose value is `true` if the
 track is enabled; enabled tracks produce audio while the media is playing. Setting
 `enabled` to `false` effectively mutes the audio track, preventing
 it from contributing to the media's audio performance.

Example
-------

This example switches between the main and commentary audio tracks of a media element.

```js
function swapCommentaryMain() {
  const videoElem = document.getElementById("main-video");
  let audioTrackMain;
  let audioTrackCommentary;

  videoElem.audioTracks.forEach((track) => {
    if (track.kind === "main") {
      audioTrackMain = track;
    } else if (track.kind === "commentary") {
      audioTrackCommentary = track;
    }
  });

  if (audioTrackMain && audioTrackCommentary) {
    const commentaryEnabled = audioTrackCommentary.enabled;
    audioTrackCommentary.enabled = audioTrackMain.enabled;
    audioTrackMain.enabled = commentaryEnabled;
  }
}
```

 The `swapCommentaryMain()` function above finds within the audio tracks of
 the `<video>` element `"main-video"` the audio tracks whose
 `kind` values are `"main"` and
 `"commentary"`. These represent the primary audio track and the commentary
 track.

**Note:** This example assumes that there is only one of each kind of
 track in the video, but this is not necessarily the case.

 The element's audio tracks are then scanned through using the JavaScript
 `forEach()` method (although the
 `audioTracks` property of a media element
 isn't actually a JavaScript array, it can be accessed like one for the most part).

 The scan looks for the tracks whose `kind` values are
 `"main"` and `"commentary"` and remembers those
 `AudioTrack` objects. Once those have been found, the values of the two
 tracks' `enabled` properties are exchanged, which results in swapping which
 of the two tracks is currently active.

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

| Specification |
| --- |
| HTML Standard # dom-audiotrack-enabled-dev |

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

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


AudioTrack: id property - Web APIs

AudioTrack: id property
=======================

 The **`id`** property contains a
 string which uniquely identifies the track represented by the
 **`AudioTrack`**.

 This ID can be used with the
 `AudioTrackList.getTrackById()` method to locate a specific track within
 the media associated with a media element. The track ID can also be used as the fragment of a URL that loads the specific track
 (if the media supports media fragments).

Value
-----

 A string which identifies the track, suitable for use when calling
 `getTrackById()` on an
 `AudioTrackList` such as the one specified by a media element's
 `audioTracks` property.

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

| Specification |
| --- |
| HTML Standard # dom-audiotrack-id-dev |

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

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


DOMRectReadOnly: DOMRectReadOnly() constructor - Web APIs

DOMRectReadOnly: DOMRectReadOnly() constructor
==============================================

The **`DOMRectReadOnly()`** constructor creates a new `DOMRectReadOnly` object.

Syntax
------

```js
new DOMRectReadOnly(x, y, width, height)
```

### Parameters

`x`

 The `x` coordinate of the `DOMRectReadOnly`'s
 origin.

`y`

 The `y` coordinate of the `DOMRectReadOnly`'s
 origin.

`width`

The width of the `DOMRectReadOnly`.

`height`

The height of the `DOMRectReadOnly`.

Examples
--------

To create a new `DOMRectReadOnly`, you could run a line of code like so:

```js
const myDOMRect = new DOMRectReadOnly(0, 0, 100, 100);
// running 'myDOMRect' in the console would then return
// DOMRectReadOnly { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 }
```

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-domrectreadonly-domrectreadonly |

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

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

See also
--------

* `DOMPoint`
* `DOMRect`


DOMRectReadOnly: bottom property - Web APIs

DOMRectReadOnly: bottom property
================================

The **`bottom`** read-only property of the **`DOMRectReadOnly`** interface returns the bottom coordinate value of the `DOMRect`. (Has the same value as `y + height`, or `y` if `height` is negative.)

Value
-----

A double.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-domrectreadonly-bottom |

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

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

See also
--------

* `DOMRect`


DOMRectReadOnly: fromRect() static method - Web APIs

DOMRectReadOnly: fromRect() static method
=========================================

 The **`fromRect()`** static method of the
 `DOMRectReadOnly` object creates a new `DOMRectReadOnly`
 object with a given location and dimensions.

Syntax
------

```js
DOMRectReadOnly.fromRect()
DOMRectReadOnly.fromRect(rectangle)
```

### Parameters

`rectangle` Optional

 An object specifying the location and dimensions of a rectangle. All properties
 default to `0`. The properties are:

* `x`: The coordinate of the left side of the rectangle.
* `y`: The coordinate of the top side of the rectangle.
* `width`: The width of the rectangle.
* `height`: The height of the rectangle.

### Return value

An instance of `DOMRectReadOnly`.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-domrectreadonly-fromrect |

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

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


DOMRectReadOnly: height property - Web APIs

DOMRectReadOnly: height property
================================

The **`height`** read-only property of the **`DOMRectReadOnly`** interface represents the height of the `DOMRect`.

Value
-----

A double.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-domrectreadonly-height |

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

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

See also
--------

* `DOMRect`


DOMRectReadOnly: right property - Web APIs

DOMRectReadOnly: right property
===============================

The **`right`** read-only property of the **`DOMRectReadOnly`** interface returns the right coordinate value of the `DOMRect`. (Has the same value as `x + width`, or `x` if `width` is negative.)

Value
-----

A double.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-domrectreadonly-right |

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

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

See also
--------

* `DOMRect`


DOMRectReadOnly: x property - Web APIs

DOMRectReadOnly: x property
===========================

The **`x`** read-only property of the **`DOMRectReadOnly`** interface represents the x coordinate of the `DOMRect`'s origin.

Value
-----

A double.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-domrectreadonly-x |

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

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

See also
--------

* `DOMRect`


DOMRectReadOnly: left property - Web APIs

DOMRectReadOnly: left property
==============================

The **`left`** read-only property of the **`DOMRectReadOnly`** interface returns the left coordinate value of the `DOMRect`. (Has the same value as `x`, or `x + width` if `width` is negative.)

Value
-----

A double.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-domrectreadonly-left |

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

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

See also
--------

* `DOMRect`


DOMRectReadOnly: y property - Web APIs

DOMRectReadOnly: y property
===========================

The **`y`** read-only property of the **`DOMRectReadOnly`** interface represents the y coordinate of the `DOMRect`'s origin.

Value
-----

A double.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-domrectreadonly-y |

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

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

See also
--------

* `DOMRect`


DOMRectReadOnly: top property - Web APIs

DOMRectReadOnly: top property
=============================

The **`top`** read-only property of the **`DOMRectReadOnly`** interface returns the top coordinate value of the `DOMRect`. (Has the same value as `y`, or `y + height` if `height` is negative.)

Value
-----

A double.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-domrectreadonly-top |

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

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

See also
--------

* `DOMRect`


DOMRectReadOnly: width property - Web APIs

DOMRectReadOnly: width property
===============================

The **`width`** read-only property of the **`DOMRectReadOnly`** interface represents the width of the `DOMRect`.

Value
-----

A double.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-domrectreadonly-width |

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

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

See also
--------

* `DOMRect`


RTCError: errorDetail property - Web APIs

RTCError: errorDetail property
==============================

 The `RTCError` interface's read-only
 **`errorDetail`** property is a string indicating the WebRTC-specific error code that occurred.

Value
-----

 A read-only string whose value indicates the type of WebRTC-specific error that
 occurred on an `RTCPeerConnection`. The possible values are:

`data-channel-failure`

The connection's `RTCDataChannel` has failed.

`dtls-failure`

 The negotiation of the DTLS connection failed, or the connection was
 terminated with a fatal error. The error's `message`
 contains details about the nature of the error. If a fatal error is *received*,
 the error object's `receivedAlert` property is
 set to the value of the DTLSL alert received. If, on the other hand, a fatal error was
 *sent*, the `sentAlert` is set to the
 alert's value.

`fingerprint-failure`

 The remote certificate for the `RTCDtlsTransport` didn't match any of
 the fingerprints listed in the SDP. If the remote peer can't match the local
 certificate against the provided fingerprints, this error doesn't occur, though this
 situation may result instead in a `dtls-failure` error.

`hardware-encoder-error`

The hardware encoder doesn't support the given configuration parameters.

`hardware-encoder-not-available`

 The hardware encoder resources required to accomplish the requested operation aren't
 available.

`sctp-failure`

 The SCTP negotiation has failed, or the connection has terminated
 with a fatal error. The SCTP cause code can be found in the `RTCError`
 object's `sctpCauseCode`. SCTP error cause
 codes 1-13 are defined in the SCTP specification: RFC 4960, section 3.3.10.

`sdp-syntax-error`

 The SDP syntax is invalid. The error's `sdpLineNumber` property indicates the line number within the SDP at which the
 error was detected.

Examples
--------

tbd

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcerror-errordetail |

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

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


RTCError: sctpCauseCode property - Web APIs

RTCError: sctpCauseCode property
================================

 The read-only **`sctpCauseCode`** property in an
 `RTCError` object provides the SCTP cause code explaining
 why the SCTP negotiation failed, if the `RTCError` represents an SCTP error.

Value
-----

 An unsigned long integer value specifying SCTP cause code explaining why the error
 occurred. This property is `null` if the error isn't an SCTP error, with its
 `errorDetail` property set to
 `sctp-failure`.

 The standard SCTP error cause codes, numbered 1-13, are defined in the SCTP
 specification: RFC 4960, section 3.3.10.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcerror-sctpcausecode |

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

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


RTCError: receivedAlert property - Web APIs

RTCError: receivedAlert property
================================

 The `RTCError` read-only property
 **`receivedAlert`** specifies the fatal DTLS
 error which resulted in an alert being received from the remote peer.

Value
-----

 An unsigned long integer value specifying the fatal DTLS error which
 resulted in an alert being received from the remote peer.

**Note:** This property is `null` if the `RTCError` doesn't represent a
 DTLS error (with `errorDetail` set to
 `dtls-failure`).

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcerror-receivedalert |

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

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


RTCError: sentAlert property - Web APIs

RTCError: sentAlert property
============================

 The read-only **`sentAlert`** property in an
 `RTCError` object specifies the DTLS alert number occurred
 while sending data to the remote peer, if the error represents an outbound DTLS error.

Value
-----

 An unsigned integer value providing the DTLS alert number corresponding to the DTLS
 error which was sent to the remote peer, as represented by this `RTCError`
 object. This property is `null` if `errorDetail` isn't `dtls-failure`.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcerror-sentalert |

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

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


RTCError: sdpLineNumber property - Web APIs

RTCError: sdpLineNumber property
================================

 The `RTCError` interface's read-only property
 **`sdpLineNumber`** specifies the line number within the
 SDP at which a syntax error occurred while parsing it.

Value
-----

 An unsigned integer value indicating the line within the SDP at which the syntax error
 described by the `RTCError` object occurred. The lines are numbed starting
 with line 1.

 This property is `null` unless the value of
 `errorDetail` is `sdp-syntax-error`.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcerror-sdplinenumber |

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

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


AnimationEvent: animationName property - Web APIs

AnimationEvent: animationName property
======================================

 The **`AnimationEvent.animationName`** read-only property is a
 string containing the value of the `animation-name` CSS
 property associated with the transition.

Value
-----

A string containing the value of the `animation-name` CSS property.

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

| Specification |
| --- |
| CSS Animations Level 1 # dom-animationevent-animationname |

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

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

See also
--------

* Using CSS animations
* Animation-related CSS properties and at-rules: `animation`,
 `animation-delay`, `animation-direction`,
 `animation-duration`, `animation-fill-mode`,
 `animation-iteration-count`, `animation-name`,
 `animation-play-state`, `animation-timing-function`,
 `@keyframes`.
* The `AnimationEvent` interface it belongs to.


AnimationEvent: elapsedTime property - Web APIs

AnimationEvent: elapsedTime property
====================================

 The **`AnimationEvent.elapsedTime`** read-only property is a
 `float` giving the amount of time the animation has been running, in seconds,
 when this event fired, excluding any time the animation was paused. For an
 `animationstart` event,
 `elapsedTime` is `0.0` unless there was a negative value for
 `animation-delay`, in which case the event will be fired with
 `elapsedTime` containing `(-1 * delay)`.

Value
-----

A `float` giving the amount of time in seconds.

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

| Specification |
| --- |
| CSS Animations Level 1 # dom-animationevent-elapsedtime |

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

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

See also
--------

* Using CSS animations
* Animation-related CSS properties and at-rules: `animation`,
 `animation-delay`, `animation-direction`,
 `animation-duration`, `animation-fill-mode`,
 `animation-iteration-count`, `animation-name`,
 `animation-play-state`, `animation-timing-function`,
 `@keyframes`.
* The `AnimationEvent` interface it belongs to.


AnimationEvent: AnimationEvent() constructor - Web APIs

AnimationEvent: AnimationEvent() constructor
============================================

The **`AnimationEvent()`** constructor returns a new `AnimationEvent` object, representing an event in relation with an animation.

Syntax
------

```js
new AnimationEvent(type)
new AnimationEvent(type, options)
```

### Parameters

`type`

 A string with the name of the type of the `AnimationEvent`.
 It is case-sensitive and browsers set it to `animationstart`, `animationend`, or `animationiteration`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, has the following properties:

`animationName` Optional

A string containing the value of the `animation-name` CSS property associated with the transition. It defaults to `""`.

`elapsedTime` Optional

 A `float` giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused.
 For an `animationstart` event, `elapsedTime` is `0.0` unless there was a negative value for `animation-delay`,
 in which case the event will be fired with `elapsedTime` containing `(-1 * delay)`. It defaults to `0.0`.

`pseudoElement` Optional

A string, starting with `"::"`, containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element itself, specify an empty string: `""`. It defaults to `""`.

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

| Specification |
| --- |
| CSS Animations Level 1 # dom-animationevent-animationevent |

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

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

See also
--------

* Using CSS animations
* Animation-related CSS properties and at-rules: `animation`,
 `animation-delay`, `animation-direction`,
 `animation-duration`, `animation-fill-mode`,
 `animation-iteration-count`, `animation-name`,
 `animation-play-state`, `animation-timing-function`,
 `@keyframes`
* The `AnimationEvent` interface it belongs to.


AnimationEvent: pseudoElement property - Web APIs

AnimationEvent: pseudoElement property
======================================

 The **`AnimationEvent.pseudoElement`** read-only property is a
 string, starting with `'::'`, containing the name of the pseudo-element the animation runs on.
 If the animation doesn't run on a pseudo-element but on the element, an empty string: `''`.

Value
-----

A string, starting with `'::'`, containing the name of the pseudo-element the animation runs on.

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

| Specification |
| --- |
| CSS Animations Level 1 # dom-animationevent-pseudoelement |

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

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

See also
--------

* Using CSS animations
* Animation-related CSS properties and at-rules: `animation`,
 `animation-delay`, `animation-direction`,
 `animation-duration`, `animation-fill-mode`,
 `animation-iteration-count`, `animation-name`,
 `animation-play-state`, `animation-timing-function`,
 `@keyframes`.
* The `AnimationEvent` interface it belongs to.


FontData: fullName property - Web APIs

FontData: fullName property
===========================

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

The **`fullName`** read-only property of the `FontData` interface returns the full name of the font face. This is usually a human-readable name used to identify the font, e.g., "Optima Bold".

Examples include:

* Apple SD Gothic Neo UltraLight
* Arial Black
* Avenir Next Heavy
* Katari Medium Italic
* YuMincho +36p Kana Extrabold
Value
-----

A string.

Examples
--------

The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.

```js
async function logFontData() {
  try {
    const availableFonts = await window.queryLocalFonts();
    for (const fontData of availableFonts) {
      console.log(fontData.postscriptName);
      console.log(fontData.fullName);
      console.log(fontData.family);
      console.log(fontData.style);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

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

| Specification |
| --- |
| Local Font Access # ref-for-dom-fontdata-fullname |

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

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

See also
--------

* Use advanced typography with local fonts
* `@font-face`


FontData: postscriptName property - Web APIs

FontData: postscriptName property
=================================

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

The **`postscriptName`** read-only property of the `FontData` interface returns the PostScript name of the font face.

This is the name used to uniquely identify the PostScript font, and is generally an unbroken sequence of characters that includes the font's name and style.

Examples include:

* AppleSDGothicNeo-UltraLight
* Arial-Black
* AvenirNext-Heavy
* Katari-MediumItalic
* YuMin\_36pKn-Extrabold
Value
-----

A string.

Examples
--------

The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.

```js
async function logFontData() {
  try {
    const availableFonts = await window.queryLocalFonts();
    for (const fontData of availableFonts) {
      console.log(fontData.postscriptName);
      console.log(fontData.fullName);
      console.log(fontData.family);
      console.log(fontData.style);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

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

| Specification |
| --- |
| Local Font Access # ref-for-dom-fontdata-postscriptname |

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

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

See also
--------

* Use advanced typography with local fonts
* `@font-face`


FontData: style property - Web APIs

FontData: style property
========================

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

The **`style`** read-only property of the `FontData` interface returns the style of the font face.

This is the value used to select the style of the font you want to use, for example inside the `font-style` property.

Examples include:

* UltraLight
* Regular
* Heavy
* Medium Italic
* Extrabold
Value
-----

A string.

Examples
--------

The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.

```js
async function logFontData() {
  try {
    const availableFonts = await window.queryLocalFonts();
    for (const fontData of availableFonts) {
      console.log(fontData.postscriptName);
      console.log(fontData.fullName);
      console.log(fontData.family);
      console.log(fontData.style);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

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

| Specification |
| --- |
| Local Font Access # ref-for-dom-fontdata-style |

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

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

See also
--------

* Use advanced typography with local fonts
* `@font-face`


FontData: blob() method - Web APIs

FontData: blob() method
=======================

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

The **`blob()`** method of the `FontData` interface returns a `Promise` that fulfills with a `Blob` containing the raw bytes of the underlying font file.

Syntax
------

```js
blob()
```

### Parameters

None.

### Return value

A `Promise` that fulfills with a `Blob` containing the raw bytes of the underlying font file.

Examples
--------

The `blob()` method provides access to low-level SFNT data — this is a font file format that can contain other font formats, such as PostScript, TrueType, OpenType, or Web Open Font Format (WOFF).

```js
async function computeOutlineFormat() {
  try {
    const availableFonts = await window.queryLocalFonts({
      postscriptNames: ["ComicSansMS"],
    });
    for (const fontData of availableFonts) {
      // `blob()` returns a Blob containing valid and complete
      // SFNT-wrapped font data.
      const sfnt = await fontData.blob();
      // Slice out only the bytes we need: the first 4 bytes are the SFNT
      // version info.
      // Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
      const sfntVersion = await sfnt.slice(0, 4).text();

      let outlineFormat = "UNKNOWN";
      switch (sfntVersion) {
        case "\x00\x01\x00\x00":
        case "true":
        case "typ1":
          outlineFormat = "truetype";
          break;
        case "OTTO":
          outlineFormat = "cff";
          break;
      }
      console.log("Outline format:", outlineFormat);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

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

| Specification |
| --- |
| Local Font Access # ref-for-dom-fontdata-blob① |

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

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

See also
--------

* Use advanced typography with local fonts
* `@font-face`