AudioContext: createMediaStreamTrackSource() method - Web APIs

AudioContext: createMediaStreamTrackSource() method
===================================================

 The **`createMediaStreamTrackSource()`** method of the `AudioContext` interface creates and returns a
 `MediaStreamTrackAudioSourceNode` which represents an audio source whose
 data comes from the specified `MediaStreamTrack`.

 This differs from `createMediaStreamSource()`, which creates a
 `MediaStreamAudioSourceNode` whose audio comes from the audio track in a
 specified `MediaStream` whose `id` is
 first, lexicographically (alphabetically).

Syntax
------

```js
createMediaStreamTrackSource(track)
```

### Parameters

`track`

 The `MediaStreamTrack` to use as the source of all audio data for the
 new node.

### Return value

 A `MediaStreamTrackAudioSourceNode` object which acts as a source for
 audio data found in the specified audio track.

Examples
--------

 In this example, `getUserMedia()` is used to
 request access to the user's microphone. Once that access is attained, an audio context
 is established and a `MediaStreamTrackAudioSourceNode` is created using
 `createMediaStreamTrackSource()`, taking its audio from the first audio track
 in the stream returned by `getUserMedia()`.

 Then a `BiquadFilterNode` is created using
 `createBiquadFilter()`, and it's
 configured as desired to perform a lowshelf filter on the audio coming from the source.
 The output from the microphone is then routed into the new biquad filter, and the
 filter's output is in turn routed to the audio context's
 `destination`.

```js
navigator.mediaDevices
  .getUserMedia({ audio: true, video: false })
  .then((stream) => {
    audio.srcObject = stream;
    audio.onloadedmetadata = (e) => {
      audio.play();
      audio.muted = true;
    };

    const audioCtx = new AudioContext();
    const audioTracks = stream.getAudioTracks();
    const source = audioCtx.createMediaStreamTrackSource(audioTracks[0]);

    const biquadFilter = audioCtx.createBiquadFilter();
    biquadFilter.type = "lowshelf";
    biquadFilter.frequency.value = 3000;
    biquadFilter.gain.value = 20;

    source.connect(biquadFilter);
    biquadFilter.connect(audioCtx.destination);
  })
  .catch((err) => {
    // Handle getUserMedia() error
  });
```

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-createmediastreamtracksource |

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

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

See also
--------

* Web Audio API
* Using the Web Audio API
* `MediaStreamTrackAudioSourceNode`


AudioContext: createMediaStreamDestination() method - Web APIs

AudioContext: createMediaStreamDestination() method
===================================================

The `createMediaStreamDestination()` method of the `AudioContext` Interface is used to create a new `MediaStreamAudioDestinationNode` object associated with a WebRTC `MediaStream` representing an audio stream, which may be stored in a local file or sent to another computer.

The `MediaStream` is created when the node is created and is accessible via the `MediaStreamAudioDestinationNode`'s `stream` attribute. This stream can be used in a similar way as a `MediaStream` obtained via `navigator.getUserMedia` — it can, for example, be sent to a remote peer using the `addStream()` method of `RTCPeerConnection`.

For more details about media stream destination nodes, check out the `MediaStreamAudioDestinationNode` reference page.

Syntax
------

```js
createMediaStreamDestination()
```

### Parameters

None.

### Return value

A `MediaStreamAudioDestinationNode`.

Examples
--------

In the following simple example, we create a `MediaStreamAudioDestinationNode`, an `OscillatorNode` and a `MediaRecorder` (the example will therefore only work in Firefox and Chrome at this time.) The `MediaRecorder` is set up to record information from the `MediaStreamDestinationNode`.

When the button is clicked, the oscillator starts, and the `MediaRecorder` is started. When the button is stopped, the oscillator and `MediaRecorder` both stop. Stopping the `MediaRecorder` causes the `dataavailable` event to fire, and the event data is pushed into the `chunks` array. After that, the `stop` event fires, a new `blob` is made of type opus — which contains the data in the `chunks` array, and a new window (tab) is then opened that points to a URL created from the blob.

From here, you can play and save the opus file.

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>createMediaStreamDestination() demo</title>
  </head>
  <body>
    <h1>createMediaStreamDestination() demo</h1>

    <p>Encoding a pure sine wave to an Opus file</p>
    <button>Make sine wave</button>
    <audio controls></audio>
    <script>
 const b = document.querySelector("button");
 let clicked = false;
 const chunks = [];
 const ac = new AudioContext();
 const osc = ac.createOscillator();
 const dest = ac.createMediaStreamDestination();
 const mediaRecorder = new MediaRecorder(dest.stream);
 osc.connect(dest);

 b.addEventListener("click", (e) => {
 if (!clicked) {
 mediaRecorder.start();
 osc.start(0);
 e.target.textContent = "Stop recording";
 clicked = true;
 } else {
 mediaRecorder.stop();
 osc.stop(0);
 e.target.disabled = true;
 }
 });

 mediaRecorder.ondataavailable = (evt) => {
 // Push each chunk (blobs) in an array
 chunks.push(evt.data);
 };

 mediaRecorder.onstop = (evt) => {
 // Make blob out of our blobs, and open it.
 const blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
 document.querySelector("audio").src = URL.createObjectURL(blob);
 };
 </script>
  </body>
</html>
```

**Note:** You can view this example live, or study the source code, on GitHub.

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-createmediastreamdestination |

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

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

See also
--------

* Using the Web Audio API


AudioContext: suspend() method - Web APIs

AudioContext: suspend() method
==============================

The `suspend()` method of the `AudioContext` Interface suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing CPU/battery usage in the process — this is useful if you want an application to power down the audio hardware when it will not be using an audio context for a while.

This method will cause an `INVALID_STATE_ERR` exception to be thrown if called on an `OfflineAudioContext`.

Syntax
------

```js
suspend()
```

### Parameters

None.

### Return value

A `Promise` that resolves with `undefined`. The promise is rejected if the context has already been closed.

Examples
--------

The following snippet is taken from our AudioContext states demo (see it running live.) When the suspend/resume button is clicked, the `AudioContext.state` is queried — if it is `running`, `suspend()` is called; if it is `suspended`, `resume()` is called. In each case, the text label of the button is updated as appropriate once the promise resolves.

```js
susresBtn.onclick = () => {
  if (audioCtx.state === "running") {
    audioCtx.suspend().then(() => {
      susresBtn.textContent = "Resume context";
    });
  } else if (audioCtx.state === "suspended") {
    audioCtx.resume().then(() => {
      susresBtn.textContent = "Suspend context";
    });
  }
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-suspend |

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

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

See also
--------

* Using the Web Audio API
* Web Audio API


AudioContext: createMediaStreamSource() method - Web APIs

AudioContext: createMediaStreamSource() method
==============================================

 The `createMediaStreamSource()` method of the `AudioContext`
 Interface is used to create a new `MediaStreamAudioSourceNode`
 object, given a media stream (say, from a `MediaDevices.getUserMedia`
 instance), the audio from which can then be played and manipulated.

For more details about media stream audio source nodes, check out the `MediaStreamAudioSourceNode` reference page.

Syntax
------

```js
createMediaStreamSource(stream)
```

### Parameters

`stream`

 A `MediaStream` to serve as an audio source to be fed into an audio
 processing graph for use and manipulation.

### Return value

 A new `MediaStreamAudioSourceNode` object representing the audio node
 whose media is obtained from the specified source stream.

Examples
--------

 In this example, we grab a media (audio + video) stream from `navigator.getUserMedia`, feed the media into a `<video>`
 element to play then mute the audio, but then also feed the audio into a `MediaStreamAudioSourceNode`. Next, we feed this source audio into a low
 pass `BiquadFilterNode` (which effectively serves as a bass booster),
 then a `AudioDestinationNode`.

 The range slider below the `<video>` element controls the amount of
 gain given to the lowpass filter — increase the value of the slider to make the audio
 sound more bass heavy!

**Note:** You can see this example running live, or view the source.

```js
const pre = document.querySelector("pre");
const video = document.querySelector("video");
const myScript = document.querySelector("script");
const range = document.querySelector("input");

// getUserMedia block - grab stream
// put it into a MediaStreamAudioSourceNode
// also output the visuals into a video element

if (navigator.mediaDevices) {
  console.log("getUserMedia supported.");
  navigator.mediaDevices
    .getUserMedia({ audio: true, video: true })
    .then((stream) => {
      video.srcObject = stream;
      video.onloadedmetadata = (e) => {
        video.play();
        video.muted = true;
      };

      // Create a MediaStreamAudioSourceNode
      // Feed the HTMLMediaElement into it
      const audioCtx = new AudioContext();
      const source = audioCtx.createMediaStreamSource(stream);

      // Create a biquadfilter
      const biquadFilter = audioCtx.createBiquadFilter();
      biquadFilter.type = "lowshelf";
      biquadFilter.frequency.value = 1000;
      biquadFilter.gain.value = range.value;

      // connect the AudioBufferSourceNode to the gainNode
      // and the gainNode to the destination, so we can play the
      // music and adjust the volume using the mouse cursor
      source.connect(biquadFilter);
      biquadFilter.connect(audioCtx.destination);

      // Get new mouse pointer coordinates when mouse is moved
      // then set new gain value

      range.oninput = () => {
        biquadFilter.gain.value = range.value;
      };
    })
    .catch((err) => {
      console.log(`The following gUM error occurred: ${err}`);
    });
} else {
  console.log("getUserMedia not supported on your browser!");
}

// dump script to pre element

pre.innerHTML = myScript.innerHTML;
```

**Note:** As a consequence of calling
 `createMediaStreamSource()`, audio playback from the media stream will
 be re-routed into the processing graph of the `AudioContext`. So
 playing/pausing the stream can still be done through the media element API and the
 player controls.

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-createmediastreamsource |

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

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

See also
--------

* Using the Web Audio API


AudioContext: AudioContext() constructor - Web APIs

AudioContext: AudioContext() constructor
========================================

 The **`AudioContext()`** constructor
 creates a new `AudioContext` object which represents an audio-processing
 graph, built from audio modules linked together, each represented by an
 `AudioNode`.

Syntax
------

```js
new AudioContext()
new AudioContext(options)
```

### Parameters

`options` Optional

An object used to configure the context. The available properties are:

`latencyHint` Optional

 The type of playback that the context will be used for, as a predefined string (`"balanced"`, `"interactive"` or `"playback"`)
 or a double-precision floating-point value indicating the preferred maximum latency of the context in seconds.
 The user agent may or may not choose to meet this request;
 check the value of `AudioContext.baseLatency` to determine the true latency after creating the context.

* `"balanced"`: The browser balances audio output latency and power consumption when selecting a latency value.
* `"interactive"` (default value): The audio is involved in interactive elements,
 such as responding to user actions or needing to coincide with visual cues such as a video or game action.
 The browser selects the lowest possible latency that doesn't cause glitches in the audio. This is likely to require increased power consumption.
* `"playback"`: The browser selects a latency that will maximize playback time by minimizing power consumption at the expense of latency.
 Useful for non-interactive playback, such as playing music.

`sampleRate` Optional

 Indicates the sample rate to use for the new context. The value must be a floating-point value indicating the sample rate,
 in samples per second, for which to configure the new context;
 additionally, the value must be one which is supported by `AudioBuffer.sampleRate`.
 The value will typically be between 8,000 Hz and 96,000 Hz; the default will vary depending on the output device, but the sample rate 44,100 Hz is the most common.
 If the `sampleRate` property is not included in the options, or the options are not specified when creating the audio context,
 the new context's output device's preferred sample rate is used by default.

`sinkId` Optional
Experimental

Specifies the sink ID of the audio output device to use for the `AudioContext`. This can take one of the following value types:

* A string representing the sink ID, retrieved for example via the `deviceId` property of the `MediaDeviceInfo` objects returned by `MediaDevices.enumerateDevices()`.
* An object representing different options for a sink ID. Currently, this takes a single property, `type`, with a value of `none`. Setting this parameter causes the audio to be processed without being played through any audio output device.

### Return value

A new `AudioContext` instance.

### Exceptions

`NotSupportedError` `DOMException`

Thrown if the specified `sampleRate` isn't supported by the context.

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

 The specification doesn't go into a lot of detail about things like how many audio
 contexts a user agent should support, or minimum or maximum latency requirements (if
 any), so these details can vary from browser to browser. Be sure to check the values if
 they matter to you.

 In particular, the specification doesn't indicate a maximum or minimum number of audio
 contexts that must be able to be open at the same time, so this is left up to the
 browser implementations to decide.

### Google Chrome

#### Per-tab audio context limitation in Chrome

Prior to version 66 Google Chrome only supported up to six audio contexts *per
tab* at a time.

#### Non-standard exceptions in Chrome

 If the value of the `latencyHint` property isn't valid,
 Chrome throws a `TypeError` exception with the message
 "The provided value '...' is not a valid enum value of type
 AudioContextLatencyCategory".

Example
-------

 This example creates a new `AudioContext` for interactive audio
 (optimizing for latency), with a sample rate of 44.1kHz and a specific audio output.

```js
const audioCtx = new AudioContext({
  latencyHint: "interactive",
  sampleRate: 44100,
  sinkId: "bb04fea9a8318c96de0bd...", // truncated for brevity
});
```

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-audiocontext |

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

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

See also
--------

* `new OfflineAudioContext()` constructor


AudioContext: sinkId property - Web APIs

AudioContext: sinkId property
=============================

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

 The **`sinkId`** read-only property of the
 `AudioContext` interface returns the sink ID of the current output audio device.

Value
-----

This property returns one of the following values, depending on how the sink ID was set:

An empty string

If a sink ID has not explicitly been set, the default system audio output device will be used, and `sinkId` will return an empty string.

A string

If the sink ID is set as a string value (using `setSinkId()`, or the `sinkId` `AudioContext()` constructor option), `sinkId` will return that same string value.

An `AudioSinkInfo` object

If the sink ID is set as an options object (using `setSinkId()`, or the `sinkId` `AudioContext()` constructor option), `sinkId` will return an `AudioSinkInfo` object reflecting the same values set in the initial options object.

Examples
--------

In our SetSinkId test example, we create an audio graph that generates a three-second burst of white noise via an `AudioBufferSourceNode`, which we also run through a `GainNode` to quiet things down a bit. We also provide the user with a dropdown menu to allow them to change the audio output device.

When the Play button is clicked, we assemble the audio graph and start it playing, and we also log information about the current device to the console based on the value of `sinkId`:

* An empty string means the default device is still being used.
* If the value is an object, the audio will not be playing on any device because we set an options object containing `type: 'none'`.
* Otherwise the value will be a sink ID string, so we log that.

```js
playBtn.addEventListener("click", () => {
  const source = audioCtx.createBufferSource();
  source.buffer = myArrayBuffer;
  source.connect(gain);
  gain.connect(audioCtx.destination);
  source.start();

  if (audioCtx.sinkId === "") {
    console.log("Audio playing on default device");
  } else if (
    typeof audioCtx.sinkId === "object" &&
    audioCtx.sinkId.type === "none"
  ) {
    console.log("Audio not playing on any device");
  } else {
    console.log(`Audio playing on device ${audioCtx.sinkId}`);
  }
});
```

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-sinkid |

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

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

See also
--------

* SetSinkId test example
* Change the destination output device in Web Audio
* `AudioContext.setSinkId()`
* `sinkchange`


AudioContext: setSinkId() method - Web APIs

AudioContext: setSinkId() method
================================

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

The **`setSinkId()`** method of the `AudioContext` interface sets the output audio device for the `AudioContext`. If a sink ID is not explicitly set, the default system audio output device will be used.

To set the audio device to a device different than the default one, the developer needs permission to access to audio devices. If required, the user can be prompted to grant the required permission via a `MediaDevices.getUserMedia()` call.

In addition, this feature may be blocked by a `speaker-selection` Permissions Policy.

Syntax
------

```js
setSinkId(sinkId)
```

### Parameters

`sinkId`

The sink ID of the device you want to set as the output audio device. This can take one of the following value types:

String

A string representing the sink ID, retrieved for example via the `deviceId` property of the `MediaDeviceInfo` objects returned by `MediaDevices.enumerateDevices()`.

`AudioSinkOptions`

An object representing different options for a sink ID. Currently this takes a single property, `type`, with a value of `none`. Setting this parameter causes the audio to be processed without being played through any audio output device. This is a useful option to minimize power consumption when you don't need playback along with processing.

### Return value

A `Promise` that fulfills with a value of `undefined`.

Attempting to set the sink ID to its existing value (i.e. returned by `AudioContext.sinkId`), throws no errors, but it aborts the process immediately.

### Exceptions

`InvalidAccessError` `DOMException`

Thrown if accessing the selected audio output device failed.

`NotAllowedError` `DOMException`

Thrown if the browser does not have permission to access audio devices.

`NotFoundError` `DOMException`

Thrown if the passed `sinkId` does not match any audio device found on the system.

Examples
--------

In our SetSinkId test example (check out the source code), we create an audio graph that generates a three-second burst of white noise via an `AudioBufferSourceNode`, which we also run through a `GainNode` to quiet things down a bit.

We also provide the user with a dropdown menu to allow them to change the audio output device on the fly. To do this, we:

1. Provide a button to populate the dropdown menu. We first invoke `MediaDevices.getUserMedia()` to trigger the permissions prompt we need to allow device enumeration, then use `MediaDevices.enumerateDevices()` to get all the available devices. We loop through the different devices and make each one available as an option in a `<select>` element. We also create a "None" option for the case where you don't want to play your audio in any output.

```js
mediaDeviceBtn.addEventListener('click', async () => {
  if ("setSinkId" in AudioContext.prototype) {
    selectDiv.innerHTML = '';

    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    const devices = await navigator.mediaDevices.enumerateDevices();

    // Most of the DOM scripting to generate the dropdown cut out for brevity

    const audioOutputs = devices.filter(
       (device) => device.kind === 'audiooutput' && device.deviceId !== 'default'
    );

    audioOutputs.forEach((device) => {
      const option = document.createElement('option')
      option.value = device.deviceId;
      option.textContent = device.label;
      select.appendChild(option);
    });

    const option = document.createElement('option')
    option.value = 'none';
    option.textContent = 'None';
    select.appendChild(option);

    //...
```

2. Add a `change` event listener to the `<select>` element to change the sink ID and therefore the audio output device when a new value is selected. If "None" is selected in the dropdown, we invoke `setSinkId()` with the `{ type : 'none' }` object parameter to select no audio device, otherwise we run it with the audio device ID contained in the `<select>` element `value` attribute` as the parameter.

```js
    // ...

    select.addEventListener('change', async () => {
      if(select.value === 'none') {
        await audioCtx.setSinkId({ type : 'none' });
      } else {
        await audioCtx.setSinkId(select.value);
      }
    })
  }
});
```

The output device can be changed during audio playback, as well as before, or between plays.

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-setsinkid |

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

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

See also
--------

* SetSinkId test example
* Change the destination output device in Web Audio
* `AudioContext.sinkId`
* `sinkchange`


AudioContext: baseLatency property - Web APIs

AudioContext: baseLatency property
==================================

 The **`baseLatency`** read-only property of the
 `AudioContext` interface returns a double that represents the number of
 seconds of processing latency incurred by the `AudioContext` passing an audio
 buffer from the `AudioDestinationNode` — i.e. the end of the audio graph —
 into the host system's audio subsystem ready for playing.

**Note:** You can request a certain latency during
 construction time with the
 `latencyHint` option, but the browser may ignore the option.

Value
-----

A double representing the base latency in seconds.

Examples
--------

```js
// default latency ("interactive")
const audioCtx1 = new AudioContext();
console.log(audioCtx1.baseLatency); // 0.00

// higher latency ("playback")
const audioCtx2 = new AudioContext({ latencyHint: "playback" });
console.log(audioCtx2.baseLatency); // 0.15
```

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-baselatency |

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

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

See also
--------

* Using the Web Audio API
* Web Audio API


Text: splitText() method - Web APIs

Text: splitText() method
========================

 The **`splitText()`** method of the `Text` interface
 breaks the `Text` node into two nodes at the specified offset,
 keeping both nodes in the tree as siblings.

 After the split, the current node contains all the content
 up to the specified offset point,
 and a newly created node of the same type contains the remaining text.
 The newly created node is returned to the caller.
 If the original node had a parent, the new node is inserted as the next sibling of the original node.
 If the offset is equal to the length of the original node,
 the newly created node has no data.

 Separated text nodes can be concatenated using the `Node.normalize()`
 method.

Syntax
------

```js
newNode = textNode.splitText(offset)
```

### Parameters

`offset`

The index immediately before which to break the text node.

### Return value

 Returns the newly created `Text` node that contains the text after the
 specified offset point.

### Exceptions

`IndexSizeError` `DOMException`

 Thrown if the specified offset is negative or is greater
 than the number of 16-bit units in the node's text.

`NoModificationAllowedError` `DOMException`

Thrown if the node is read-only.

Example
-------

 In this example, the text of a `<p>` is split into two text nodes, and a
 `<u>` is inserted between them.

```html
<p>foobar</p>
```

```js
const p = document.querySelector("p");

// Get contents of <p> as a text node
const foobar = p.firstChild;

// Split 'foobar' into two text nodes, 'foo' and 'bar',
// and save 'bar' as a const
const bar = foobar.splitText(3);

// Create a <u> element containing ' new content '
const u = document.createElement("u");
u.appendChild(document.createTextNode(" new content "));

// Add <u> before 'bar'
p.insertBefore(u, bar);

// The result is: <p>foo<u> new content </u>bar</p>
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-text-splittext① |

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

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

See also
--------

* The `Text` interface it belongs to.
* The opposite method: `Node.normalize`.


Text: assignedSlot property - Web APIs

Text: assignedSlot property
===========================

 The read-only **`assignedSlot`** property of the `Text` interface
 returns the `HTMLSlotElement` object associated with the element.

Value
-----

 An `HTMLSlotElement`,
 or `null` if no `<slot>` element is associated with the text node.

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

| Specification |
| --- |
| DOM Standard # dom-slotable-assignedslot |

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

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


Text: Text() constructor - Web APIs

Text: Text() constructor
========================

 The **`Text()`** constructor returns a new `Text` object
 with the optional string given in parameter as its textual content.

Syntax
------

```js
new Text()
new Text(string)
```

### Parameters

* `string` Optional
### Return value

A new `Text` object with the content of the `string` parameter, or the empty string if no parameter was given.

Example
-------

```js
let text = new Text("Test");
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-text-text① |

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

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

See also
--------

* The DOM API


Text: wholeText property - Web APIs

Text: wholeText property
========================

 The read-only **`wholeText`** property of the `Text` interface
 returns the full text of all `Text` nodes logically adjacent to the node.
 The text is concatenated in document order.
 This allows specifying any text node and obtaining all adjacent text as a single string.

**Note:** This is similar to call `Node.normalize()` followed by reading the text value,
 but without modifying the tree.

Value
-----

A string with the concatenated text.

Example
-------

Suppose you have the following simple paragraph within your webpage:

```html
<p>
  Through-hiking is great!
  <strong>No insipid election coverage!</strong> However,
  <a href="https://en.wikipedia.org/wiki/Absentee\_ballot">casting a ballot</a>
  is tricky.
</p>
```

You decide you don't like the middle sentence, so you remove it:

```js
const paragraph = document.querySelector("p"); // Reads the paragraph
paragraph.removeChild(para.childNodes[1]); // Delete the strong element
```

Now you end up with *"Through-hiking is great! However, casting a ballot is tricky."*, with two nodes before the hyperlink:

1. A `Text` containing the string `"Through-hiking is great!"`
2. A second `Text` node containing the string `" However, "`

To get those two nodes at once, you would call `para.childNodes[0].wholeText`:

```js
console.log(`'${paragraph.childNodes[0].wholeText}'`); // 'Through-hiking is great! However, '
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-text-wholetext① |

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

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

See also
--------

* The `Text` interface it belongs to.


ScreenDetailed: top property - Web APIs

ScreenDetailed: top property
============================

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

 The **`top`** read-only property of the
 `ScreenDetailed` interface is a number representing the y-coordinate (top edge) of the total screen area inside the OS virtual screen arrangement, relative to the multi-screen origin.

This is equal to the true top edge, ignoring any OS UI element drawn at the top of the screen. Windows cannot be placed in those areas; to get the top coordinate of the screen area that windows can be placed in, use `ScreenDetailed.availTop`.

**Note:** In Firefox, a non-standard implementation of the `top` property is available on the `Screen` interface. See the Non-standard example below for usage details, and see the `Screen` reference page for browser support information relating to the non-standard implementation.

Value
-----

A number.

Examples
--------

### Window Management API example

```js
// Available in browsers that support the Window Management API
const screenDetails = await window.getScreenDetails();

// Return the absolute top value of the first screen
const screen1Top = screenDetails.screens[0].top;
```

### Non-standard example

```js
// Available in Firefox
// Return the absolute top value of the current screen
const screenTop = window.screen.top;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-top |

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

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

See also
--------

* Window Management API


ScreenDetailed: devicePixelRatio property - Web APIs

ScreenDetailed: devicePixelRatio property
=========================================

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

 The **`devicePixelRatio`** read-only property of the
 `ScreenDetailed` interface is a number representing the screen's device pixel ratio.

This is the same as the value returned by `Window.devicePixelRatio`, except that `Window.devicePixelRatio`:

* always returns the device pixel ratio for the current screen.
* also includes scaling of the window itself, i.e. page zoom (at least on some browser implementations).
Value
-----

A number.

Examples
--------

```js
const screenDetails = await window.getScreenDetails();

// Return the device pixel ratio of the first screen
const screen1DPR = screenDetails.screens[0].devicePixelRatio;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-devicepixelratio |

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

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

See also
--------

* Window Management API


ScreenDetailed: availLeft property - Web APIs

ScreenDetailed: availLeft property
==================================

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

 The **`availLeft`** read-only property of the
 `ScreenDetailed` interface is a number representing the x-coordinate (left-hand edge) of the available screen area inside the OS virtual screen arrangement, relative to the multi-screen origin.

This is equal to the `ScreenDetailed.left` property, plus the width of any OS UI element drawn on the left of the screen. Windows cannot be placed in those areas, so `availLeft` is useful for giving you the left boundary of the actual area available to open or place windows.

**Note:** A non-standard implementation of the `availLeft` property is available on the `Screen` interface in all browsers. See the Non-standard example below for usage details, and see the `Screen` reference page for browser support information relating to the non-standard implementation.

Value
-----

A number.

Examples
--------

### Window Management API example

```js
// Available in browsers that support the Window Management API
const screenDetails = await window.getScreenDetails();

// Return the availLeft value of the first screen
const screen1AvailLeft = screenDetails.screens[0].availLeft;
```

### Non-standard example

```js
// Available in all browsers
// Return the availLeft value of the current screen
const screenAvailLeft = window.screen.availLeft;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-availleft |

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

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

See also
--------

* Window Management API


ScreenDetailed: left property - Web APIs

ScreenDetailed: left property
=============================

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

 The **`left`** read-only property of the
 `ScreenDetailed` interface is a number representing the x-coordinate (left-hand edge) of the total screen area inside the OS virtual screen arrangement, relative to the multi-screen origin.

This is equal to the true left-hand edge, ignoring any OS UI element drawn at the left of the screen. Windows cannot be placed in those areas; to get the left-hand coordinate of the screen area that windows can be placed in, use `ScreenDetailed.availLeft`.

**Note:** In Firefox, a non-standard implementation of the `left` property is available on the `Screen` interface. See the Non-standard example below for usage details, and see the `Screen` reference page for browser support information relating to the non-standard implementation.

Value
-----

A number.

Examples
--------

### Window Management API example

```js
// Available in browsers that support the Window Management API
const screenDetails = await window.getScreenDetails();

// Return the absolute left value of the first screen
const screen1Left = screenDetails.screens[0].left;
```

### Non-standard example

```js
// Available in Firefox
// Return the absolute left value of the current screen
const screenLeft = window.screen.left;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-left |

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

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

See also
--------

* Window Management API


ScreenDetailed: label property - Web APIs

ScreenDetailed: label property
==============================

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

 The **`label`** read-only property of the
 `ScreenDetailed` interface is a string providing a descriptive label for the screen, for example "Built-in Retina Display".

This is useful for constructing a list of options to display to the user if you want them to choose a screen to display content on.

Value
-----

A string.

Examples
--------

```js
const screenDetails = await window.getScreenDetails();

// Return the label of the first screen
const screen1Label = screenDetails.screens[0].label;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-label |

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

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

See also
--------

* Window Management API


ScreenDetailed: isInternal property - Web APIs

ScreenDetailed: isInternal property
===================================

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

 The **`isInternal`** read-only property of the
 `ScreenDetailed` interface is a boolean indicating whether the screen is internal to the device or external. External devices are generally manufactured separately from the device they are attached to and can be connected and disconnected as needed, whereas internal screens are part of the device and not intended to be disconnected.

Value
-----

A boolean value — `true` if the screen is internal, and `false` if it is external.

Examples
--------

```js
const screenDetails = await window.getScreenDetails();

// Is the first screen internal?
const screen1Internal = screenDetails.screens[0].isInternal;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-isinternal |

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

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

See also
--------

* Window Management API


ScreenDetailed: availTop property - Web APIs

ScreenDetailed: availTop property
=================================

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

 The **`availTop`** read-only property of the
 `ScreenDetailed` interface is a number representing the y-coordinate (top edge) of the available screen area inside the OS virtual screen arrangement, relative to the multi-screen origin.

This is equal to the `ScreenDetailed.top` property, plus the height of any OS UI element drawn at the top of the screen. Windows cannot be placed in those areas, so `availTop` is useful for giving you the top boundary of the actual area available to open or place windows.

**Note:** A non-standard implementation of the `availTop` property is available on the `Screen` interface in all browsers. See the Non-standard example below for usage details, and see the `Screen` reference page for browser support information relating to the non-standard implementation.

Value
-----

A number.

Examples
--------

### Window Management API example

```js
// Available in browsers that support the Window Management API
const screenDetails = await window.getScreenDetails();

// Return the availTop value of the first screen
const screen1AvailTop = screenDetails.screens[0].availTop;
```

### Non-standard example

```js
// Available in all browsers
// Return the availTop value of the current screen
const screenAvailTop = window.screen.availTop;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-availtop |

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

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

See also
--------

* Window Management API


ScreenDetailed: isPrimary property - Web APIs

ScreenDetailed: isPrimary property
==================================

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

 The **`isPrimary`** read-only property of the
 `ScreenDetailed` interface is a boolean indicating whether the screen is set as the operating system (OS) primary screen or not.

The OS hosting the browser will have one primary screen, and one or more secondary screens. The primary screen can usually be specified by the user via OS settings, and generally contains OS UI features such as the taskbar/icon dock. The primary screen may change for a number of reasons, such as a screen being unplugged.

Value
-----

A boolean value — `true` if the screen is primary, and `false` if it is secondary.

Examples
--------

```js
const screenDetails = await window.getScreenDetails();

// Is the first screen primary?
const screen1Primary = screenDetails.screens[0].isPrimary;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-isprimary |

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

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

See also
--------

* Window Management API


ExtendableEvent: waitUntil() method - Web APIs

ExtendableEvent: waitUntil() method
===================================

 The **`ExtendableEvent.waitUntil()`**
 method tells the event dispatcher that work is ongoing. It can also be used to detect
 whether that work was successful. In service workers, `waitUntil()` tells
 the browser that work is ongoing until the promise settles, and it shouldn't terminate
 the service worker if it wants that work to complete.

 The `install` events in service workers use
 `waitUntil()` to hold the service worker in
 the `installing` phase until tasks
 complete. If the promise passed to `waitUntil()` rejects, the install is
 considered a failure, and the installing service worker is discarded. This is primarily
 used to ensure that a service worker is not considered installed until all of the core
 caches it depends on are successfully populated.

 The `activate` events in service workers use
 `waitUntil()` to buffer functional events such as `fetch` and
 `push` until the promise passed to `waitUntil()` settles. This
 gives the service worker time to update database schemas and delete outdated
 `caches`, so other events can rely on a completely upgraded state.

 The `waitUntil()` method must be initially called within the event callback,
 but after that it can be called multiple times, until all the promises passed to it
 settle.

**Note:** The behavior described in the above paragraph was fixed in
 Firefox 43 (see Firefox bug 1180274).

Syntax
------

```js
waitUntil(promise)
```

### Parameters

A `Promise`.

### Return value

None (`undefined`).

Examples
--------

Using `waitUntil()` within a service worker's `install` event:

```js
addEventListener("install", (event) => {
  const preCache = async () => {
    const cache = await caches.open("static-v1");
    return cache.addAll(["/", "/about/", "/static/styles.css"]);
  };
  event.waitUntil(preCache());
});
```

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

| Specification |
| --- |
| Service Workers # dom-extendableevent-waituntil |

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

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

See also
--------

* Using Service Workers


ExtendableEvent: ExtendableEvent() constructor - Web APIs

ExtendableEvent: ExtendableEvent() constructor
==============================================

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

Syntax
------

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

### Parameters

`type`

A string with the name of the event. It is case-sensitive.

`options` Optional

 An object that, *in addition of the properties defined in `Event()`*, can contain any custom settings
 that you want to apply to the event object.
 Currently no possible options are mandatory,
 but this has been defined for forward compatibility across the different derived events.

### Return value

A new `ExtendableEvent` object.

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

| Specification |
| --- |
| Service Workers # dom-extendableevent-extendableevent |

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

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

See also
--------

* Using Service Workers
* Service workers basic code example
* Using web workers


AudioBuffer: length property - Web APIs

AudioBuffer: length property
============================

 The **`length`** property of the `AudioBuffer`
 interface returns an integer representing the length, in sample-frames, of the PCM data
 stored in the buffer.

Value
-----

An integer.

Examples
--------

```js
// Stereo
const channels = 2;

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

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

  console.log(myArrayBuffer.length);
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audiobuffer-length |

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

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

See also
--------

* Using the Web Audio API


AudioBuffer: AudioBuffer() constructor - Web APIs

AudioBuffer: AudioBuffer() constructor
======================================

 The **`AudioBuffer`** constructor of
 the Web Audio API creates a new
 `AudioBuffer` object.

Syntax
------

```js
new AudioBuffer(options)
```

### Parameters

`options`

Options are as follows:

`length`

 The size of the audio buffer in sample-frames. To determine
 the `length` to use for a specific number of seconds of audio, use
 `numSeconds * sampleRate`.

`numberOfChannels`

 The number of channels for the buffer. The
 default is 1, and all user agents are required to support at least 32 channels.

`sampleRate`

 The sample rate in Hz for the buffer. The default is
 the sample rate of the `context` used in constructing this object. User
 agents are required to support sample rates from 8,000 Hz to 96,000 Hz (but are
 allowed to go farther outside this range).

`channelCount`

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

`channelCountMode`

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

`channelInterpretation`

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

#### Deprecated parameters

`context`
Deprecated

 A reference to an `AudioContext`. This parameter was removed from the
 spec.

### Exceptions

`NotSupportedError` `DOMException`

 Thrown if one or more of the options are negative or otherwise has an invalid value
 (such as `numberOfChannels` being higher than supported,
 or a `sampleRate` outside the nominal range).

`RangeError`

Thrown if there isn't enough memory available to allocate the buffer.

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

| Specification |
| --- |
| Web Audio API # dom-audiobuffer-audiobuffer |

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

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


AudioBuffer: copyFromChannel() method - Web APIs

AudioBuffer: copyFromChannel() method
=====================================

 The
 **`copyFromChannel()`** method of the
 `AudioBuffer` interface copies the audio sample data from the specified
 channel of the `AudioBuffer` to a specified
 `Float32Array`.

Syntax
------

```js
copyFromChannel(destination, channelNumber, startInChannel)
```

### Parameters

`destination`

A `Float32Array` to copy the channel's samples to.

`channelNumber`

 The channel number of the current `AudioBuffer` to copy the channel data
 from.

`startInChannel` Optional

 An optional offset into the source channel's buffer from which to begin copying
 samples. If not specified, a value of 0 (the beginning of the buffer) is assumed by
 default.

### Return value

None (`undefined`).

### Exceptions

`indexSizeError`

One of the input parameters has a value that is outside the accepted range:

* The value of `channelNumber` specifies a channel number
 which doesn't exist (that is, it's greater than or equal to the value of
 `numberOfChannels` on the channel).
* The value of `startInChannel` is outside the current range
 of samples that already exist in the source buffer; that is, it's greater than its
 current `length`.

Examples
--------

 This example creates a new audio buffer, then copies the samples from another channel
 into it.

```js
const myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
const anotherArray = new Float32Array(length);
myArrayBuffer.copyFromChannel(anotherArray, 1, 0);
```

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

| Specification |
| --- |
| Web Audio API # dom-audiobuffer-copyfromchannel |

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

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

See also
--------

* Using the Web Audio API


AudioBuffer: copyToChannel() method - Web APIs

AudioBuffer: copyToChannel() method
===================================

 The `copyToChannel()` method of the `AudioBuffer` interface copies
 the samples to the specified channel of the `AudioBuffer`, from the source array.

Syntax
------

```js
copyToChannel(source, channelNumber)
copyToChannel(source, channelNumber, startInChannel)
```

### Parameters

`source`

A `Float32Array` that the channel data will be copied from.

`channelNumber`

 The channel number of the current `AudioBuffer` to copy the channel
 data to. If *channelNumber* is greater than or equal to
 `AudioBuffer.numberOfChannels`, an `INDEX_SIZE_ERR` will be
 thrown.

`startInChannel` Optional

 An optional offset to copy the data to. If *startInChannel* is greater than
 `AudioBuffer.length`, an `INDEX_SIZE_ERR` will be thrown.

### Return value

None (`undefined`).

Examples
--------

```js
const myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
const anotherArray = new Float32Array();
// Copy channel data from second channel of myArrayBuffer.
myArrayBuffer.copyFromChannel(anotherArray, 1, 0);
// Copy data from anotherArray to first channel of myArrayBuffer. Both channels have the same data now.
myArrayBuffer.copyToChannel(anotherArray, 0, 0);
```

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

| Specification |
| --- |
| Web Audio API # dom-audiobuffer-copytochannel |

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

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

See also
--------

* Using the Web Audio API


AudioBuffer: getChannelData() method - Web APIs

AudioBuffer: getChannelData() method
====================================

The **`getChannelData()`** method of the `AudioBuffer` Interface returns a `Float32Array` containing the PCM data associated with the channel, defined by the channel parameter (with 0 representing the first channel).

Syntax
------

```js
getChannelData(channel)
```

### Parameters

`channel`

The channel property is an index representing the particular channel to get data for. An index value of 0 represents the first channel. If the `channel` index value is greater than of equal to `AudioBuffer.numberOfChannels`, an `INDEX_SIZE_ERR` exception will be thrown.

### Return value

A `Float32Array`.

Examples
--------

In the following example we create a two second buffer, fill it with white noise, and then play it via an `AudioBufferSourceNode`. The comments should clearly explain what is going on. You can also run the code live, or view the source.

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const button = document.querySelector("button");
const pre = document.querySelector("pre");
const myScript = document.querySelector("script");

pre.innerHTML = myScript.innerHTML;

// Stereo
const channels = 2;
// Create an empty two second stereo buffer at the
// sample rate of the AudioContext
const frameCount = audioCtx.sampleRate \* 2.0;

const myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);

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

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

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

| Specification |
| --- |
| Web Audio API # dom-audiobuffer-getchanneldata |

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

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

See also
--------

* Using the Web Audio API


AudioBuffer: sampleRate property - Web APIs

AudioBuffer: sampleRate property
================================

 The **`sampleRate`** property of the `AudioBuffer` interface returns a float representing the sample rate, in
 samples per second, of the PCM data stored in the buffer.

Value
-----

 A floating-point value indicating the current sample rate of the buffers data, in
 samples per second.

Examples
--------

```js
// Stereo
const channels = 2;

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

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

  console.log(myArrayBuffer.sampleRate);
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audiobuffer-samplerate |

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

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

See also
--------

* Using the Web Audio API


AudioBuffer: numberOfChannels property - Web APIs

AudioBuffer: numberOfChannels property
======================================

 The `numberOfChannels` property of the `AudioBuffer`
 interface returns an integer representing the number of discrete audio channels
 described by the PCM data stored in the buffer.

Value
-----

An integer.

Examples
--------

```js
// Stereo
const channels = 2;

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

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

  console.log(myArrayBuffer.numberOfChannels);
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audiobuffer-numberofchannels |

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

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

See also
--------

* Using the Web Audio API


AudioBuffer: duration property - Web APIs

AudioBuffer: duration property
==============================

 The **`duration`** property of the `AudioBuffer` interface returns a double representing the duration, in seconds, of the PCM data
 stored in the buffer.

Value
-----

A double.

Examples
--------

```js
// Stereo
const channels = 2;

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

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

  console.log(myArrayBuffer.duration);
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audiobuffer-duration |

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

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

See also
--------

* Using the Web Audio API


WorkerGlobalScope: securitypolicyviolation event - Web APIs

WorkerGlobalScope: securitypolicyviolation event
================================================

The **`securitypolicyviolation`** event is fired when a Content Security Policy is violated in a worker.

The handler can be assigned using the `onsecuritypolicyviolation` event handler property or using `EventTarget.addEventListener()`.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("securitypolicyviolation", (event) => {});

onsecuritypolicyviolation = (event) => {};
```

Event type
----------

A `SecurityPolicyViolationEvent`. Inherits from `Event`.

Event

SecurityPolicyViolationEventExamples
--------

The code below shows how you might add an event handler function using the `onsecuritypolicyviolation` event handler property or call `addEventListener()` method.

```js
self.onsecuritypolicyviolation = (e) => {
  // Handle SecurityPolicyViolationEvent e here
};

self.addEventListener("securitypolicyviolation", (e) => {
  // Handle SecurityPolicyViolationEvent e here
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # eventdef-globaleventhandlers-securitypolicyviolation |

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

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

See also
--------

* The `securitypolicyviolation` event of the `Document` interface
* The `securitypolicyviolation` event of the `Element` interface
* HTTP > Content Security Policy


WorkerGlobalScope: importScripts() method - Web APIs

WorkerGlobalScope: importScripts() method
=========================================

The **`importScripts()`** method of the `WorkerGlobalScope` interface synchronously imports one or more scripts into the worker's scope.

Syntax
------

```js
importScripts(path0)
importScripts(path0, path1)
importScripts(path0, path1, /\* …, \*/ pathN)
```

### Parameters

`pathN`

A string value representing the URL of the script to be imported. The URL may be absolute or relative. If the URL is relative, it is relative to the HTML document's base URL.

### Return value

None (`undefined`).

### Exceptions

`NetworkError`

Imported scripts were served without a `text/javascript` MIME type or without one of the permitted legacy JavaScript MIME types.

Examples
--------

If you had some functionality written in a separate script called `foo.js` that you wanted to use inside worker.js, you could import it using the following line:

```js
importScripts("foo.js");
```

`importScripts()` and `self.importScripts()` are effectively equivalent — both represent `importScripts()` being called from inside the worker's inner scope.

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

| Specification |
| --- |
| HTML Standard # dom-workerglobalscope-importscripts-dev |

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

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

See also
--------

* `WorkerGlobalScope`


WorkerGlobalScope: navigator property - Web APIs

WorkerGlobalScope: navigator property
=====================================

The **`navigator`** read-only property of the `WorkerGlobalScope` interface returns the `WorkerNavigator` associated with the worker. It is a specific navigator object, mostly a subset of the `Navigator` for browsing scopes, but adapted to workers.

Value
-----

A `WorkerNavigator` object.

Examples
--------

If you call the following

```js
console.log(navigator);
```

inside a worker (which would basically be the equivalent of `self.console.log(self.navigator);`, as these are being called on the worker scope, which can be referenced with `WorkerGlobalScope.self`), you will get a `WorkerNavigator` object written to the console — something like the following:
```

Object {onLine: true, userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) Ap…ML, like Gecko) Chrome/40.0.2214.93 Safari/537.36", product: "Gecko", platform: "MacIntel", appVersion: "5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKi…ML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"…}
    appCodeName: "Mozilla"
    appName: "Netscape"
    appVersion: "5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"
    hardwareConcurrency: 4
    onLine: true
    platform: "MacIntel"
    product: "Gecko"
    userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"
    __proto__: Object
```

You could use this navigator object to return more information about the runtime environment, as you might do with a normal `Navigator` object.

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

| Specification |
| --- |
| HTML Standard # dom-worker-navigator-dev |

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

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

See also
--------

`WorkerNavigator`


WorkerGlobalScope: dump() method - Web APIs

WorkerGlobalScope: dump() method
================================

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

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

The **`WorkerGlobalScope.dump()`** method logs messages to the browser's standard output (`stdout`). If the browser was started from a terminal, output sent to `dump()` will appear in the terminal. This is the same as `Window.dump()`, but for workers.

Output from `dump()` is *not* sent to the browser's developer tools console. To log to the developer tools console, use `console.log()`.

Syntax
------

```js
dump(message)
```

### Parameters

`message`

A string containing the message to log.

### Return value

None (`undefined`).

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

This feature is not part of any specification.

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

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


WorkerGlobalScope: offline event - Web APIs

WorkerGlobalScope: offline event
================================

The **`offline`** event of the `WorkerGlobalScope` fires when the device loses connection to the internet.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("offline", (event) => {});

onoffline = (event) => {};
```

Event type
----------

A generic `Event`.

Example
-------

The following code snippet shows an `onoffline` handler set inside a worker:

```js
self.onoffline = () => {
  console.log("Your worker is now offline");
};
```

The same snippet, but using `addEventListener()`:

```js
self.addEventListener("offline", () => {
  console.log("Your worker is now offline");
});
```

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

| Specification |
| --- |
| HTML Standard # handler-workerglobalscope-onoffline |

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

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

See also
--------

The `WorkerGlobalScope` interface it belongs to.


WorkerGlobalScope: location property - Web APIs

WorkerGlobalScope: location property
====================================

The **`location`** read-only property of the `WorkerGlobalScope` interface returns the `WorkerLocation` associated with the worker. It is a specific location object, mostly a subset of the `Location` for browsing scopes, but adapted to workers.

Value
-----

A `WorkerLocation` object.

Examples
--------

If you called the following in a document served at `localhost:8000`

```js
console.log(location);
```

inside a worker (which would basically be the equivalent of `self.console.log(self.location);`, as these are being called on the worker scope, which can be referenced with `WorkerGlobalScope.self`), you will get a `WorkerLocation` object written to the console — something like the following:
```

WorkerLocation {hash: "", search: "", pathname: "/worker.js", port: "8000", hostname: "localhost"…}
  hash: ""
  host: "localhost:8000"
  hostname: "localhost"
  href: "http://localhost:8000/worker.js"
  origin: "http://localhost:8000"
  pathname: "/worker.js"
  port: "8000"
  protocol: "http:"
  search: ""
  __proto__: WorkerLocation
```

You could use this location object to return more information about the document's location, as you might do with a normal `Location` object.

**Note:** Firefox has a bug with using `console.log` inside shared/service workers (see Firefox bug 1058644), which may return strange results, but this should be fixed soon.

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

| Specification |
| --- |
| HTML Standard # dom-workerglobalscope-location-dev |

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

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

See also
--------

`WorkerGlobalScope`


WorkerGlobalScope: self property - Web APIs

WorkerGlobalScope: self property
================================

The **`self`** read-only property of the `WorkerGlobalScope` interface returns a reference to the `WorkerGlobalScope` itself. Most of the time it is a specific scope like `DedicatedWorkerGlobalScope`, `SharedWorkerGlobalScope`, or `ServiceWorkerGlobalScope`.

Value
-----

A global scope object (differs depending on the type of worker you are dealing with, as indicated above).

Examples
--------

If you called

```js
console.log(self);
```

inside a worker, you will get a worker global scope of the same type as that worker object written to the console — something like the following:
```

DedicatedWorkerGlobalScope {
undefined: undefined, Infinity: Infinity, Math: MathConstructor, NaN: NaN, Intl: Object…}
    Infinity: Infinity
    Array: function Array() { [native code] }
      arguments: null
      caller: null
      isArray: function isArray() { [native code] }
      length: 1
      name: "Array"
      observe: function observe() { [native code] }
      prototype: Array[0]
      unobserve: function unobserve() { [native code] }
      __proto__: function Empty() {}
      <function scope>
    ArrayBuffer: function ArrayBuffer() { [native code] }
    Blob: function Blob() { [native code] }
    Boolean: function Boolean() { [native code] }
    DataView: function DataView() { [native code] }
    Date: function Date() { [native code] }
    DedicatedWorkerGlobalScope: function DedicatedWorkerGlobalScope() { [native code] }
    Error: function Error() { [native code] }
// etc. etc.
```

This provides a full list of the objects available to that worker scope, so it is quite a useful test if you want to see whether something is available to your worker or not. We also maintain a list of Functions and classes available to Web Workers.

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

| Specification |
| --- |
| HTML Standard # dom-workerglobalscope-self-dev |

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

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

See also
--------

`WorkerGlobalScope`


WorkerGlobalScope: unhandledrejection event - Web APIs

WorkerGlobalScope: unhandledrejection event
===========================================

The **`unhandledrejection`** event is sent to the global scope (typically `WorkerGlobalScope`) of a script when a `Promise` that has no rejection handler is rejected.

This is useful for debugging and for providing fallback error handling for unexpected situations.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
self.addEventListener("unhandledrejection", (event) => {});
self.onunhandledrejection = (event) => {};
```

Event type
----------

A `PromiseRejectionEvent`. Inherits from `Event`.

Event

PromiseRejectionEventEvent properties
----------------

`PromiseRejectionEvent.promise` Read only

The JavaScript `Promise` that was rejected.

`PromiseRejectionEvent.reason` Read only

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

Examples
--------

### Basic error logging

This example logs information about the unhandled promise rejection to the console.

```js
self.addEventListener("unhandledrejection", (event) => {
  console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
});
```

You can also use the `onunhandledrejection` event handler property to set up the event listener:

```js
self.onunhandledrejection = (event) => {
  console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
};
```

### Preventing default handling

Many environments (such as Node.js) report unhandled promise rejections to the console by default. You can prevent that from happening by adding a handler for `unhandledrejection` events that—in addition to any other tasks you wish to perform—calls `preventDefault()` to cancel the event, preventing it from bubbling up to be handled by the runtime's logging code. This works because `unhandledrejection` is cancelable.

```js
self.addEventListener("unhandledrejection", (event) => {
  // code for handling the unhandled rejection
  // …

  // Prevent the default handling (such as outputting the
  // error to the console)

  event.preventDefault();
});
```

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

#### No specification found

No specification data found for `api.WorkerGlobalScope.unhandledrejection_event`.
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
--------

* Promise rejection events
* `PromiseRejectionEvent`
* `Promise`
* `rejectionhandled` event


WorkerGlobalScope: fonts property - Web APIs

WorkerGlobalScope: fonts property
=================================

The **`fonts`** property of the `WorkerGlobalScope` interface returns the `FontFaceSet` interface of the worker.

This property is part of the CSS Font Loading API.

Value
-----

 The returned value is the `FontFaceSet` interface of the worker.
 The `FontFaceSet` interface is useful for loading new fonts, checking the status of previously loaded fonts etc.

Examples
--------

### Doing operation after all fonts are loaded

```js
fonts.ready.then(() => {
  // Any operation that needs to be done only after all the fonts
  // have finished loading can go here.
});
```

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontfacesource-fonts |

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

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

See also
--------

* `FontFaceSet` interface
* `FontFace`


WorkerGlobalScope: rejectionhandled event - Web APIs

WorkerGlobalScope: rejectionhandled event
=========================================

The **`rejectionhandled`** event is sent to the script's global scope (typically `WorkerGlobalScope`) whenever a rejected `Promise` is handled late, i.e., when a handler is attached to the promise after its rejection had caused an `unhandledrejection` event.

This can be used in debugging and for general application resiliency, in tandem with the `unhandledrejection` event, which is sent when a promise is rejected but there is no handler for the rejection at the time.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
self.addEventListener("rejectionhandled", (event) => {});
self.onrejectionhandled = (event) => {};
```

Event type
----------

A `PromiseRejectionEvent`. Inherits from `Event`.

Event

PromiseRejectionEventEvent properties
----------------

`PromiseRejectionEvent.promise` Read only

The `Promise` that was rejected.

`PromiseRejectionEvent.reason` Read only

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

Example
-------

You can use the `rejectionhandled` event to log promises that get rejected to the console, along with the reasons why they were rejected:

```js
self.addEventListener("rejectionhandled", (event) => {
  console.log(`Promise rejected; reason: ${event.reason}`);
});
```

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

#### No specification found

No specification data found for `api.WorkerGlobalScope.rejectionhandled_event`.
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
--------

* Promise rejection events
* `PromiseRejectionEvent`
* `Promise`
* `unhandledrejection`


WorkerGlobalScope: online event - Web APIs

WorkerGlobalScope: online event
===============================

The **`online`** event of the `WorkerGlobalScope` fires when the device reconnects to the internet.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("online", (event) => {});

ononline = (event) => {};
```

Event type
----------

A generic `Event`.

Example
-------

The following code snippet shows an `onoffline` handler set inside a worker:

```js
self.ononline = () => {
  console.log("Your worker is now online");
};
```

The same snippet, but using `addEventListener()`:

```js
self.addEventListener("online", () => {
  console.log("Your worker is now online");
});
```

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

| Specification |
| --- |
| HTML Standard # handler-workerglobalscope-ononline |

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

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

See also
--------

The `WorkerGlobalScope` interface it belongs to.


WorkerGlobalScope: error event - Web APIs

WorkerGlobalScope: error event
==============================

The **`error`** event of the `WorkerGlobalScope` interface fires when an error occurs in the worker.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("error", (event) => {});

onerror = (event) => {};
```

Event type
----------

A generic `Event`.

Example
-------

The following code snippet shows an `onerror` handler set inside a worker:

```js
self.onerror = () => {
  console.log("There is an error inside your worker!");
};
```

The same snippet, but using `addEventListener()`:

```js
self.addEventListener("error", () => {
  console.log("There is an error inside your worker!");
});
```

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

| Specification |
| --- |
| HTML Standard # handler-workerglobalscope-onerror |

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

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

See also
--------

The `WorkerGlobalScope` interface it belongs to.


WorkerGlobalScope: languagechange event - Web APIs

WorkerGlobalScope: languagechange event
=======================================

The **`languagechange`** event is fired at the global scope object when the user's preferred language changes.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("languagechange", (event) => {});

onlanguagechange = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

You can use the `languagechange` event in an `addEventListener` method:

```js
worker.addEventListener("languagechange", () => {
  console.log("languagechange event detected!");
});
```

Or use the `onlanguagechange` event handler property:

```js
worker.onlanguagechange = (event) => {
  console.log("languagechange event detected!");
};
```

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

| Specification |
| --- |
| HTML Standard # event-languagechange |
| HTML Standard # handler-workerglobalscope-onlanguagechange |

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

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

See also
--------

* `navigator.language`
* `navigator.languages`
* `Navigator`


PerformanceNavigation: type property - Web APIs

PerformanceNavigation: type property
====================================

**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 legacy
 **`PerformanceNavigation.type`**
 read-only property returns an `unsigned short` containing a constant
 describing how the navigation to this page was done.

**Warning:** This interface of this property is deprecated in the Navigation Timing Level 2 specification.
 Please use the `PerformanceNavigationTiming` interface instead.

Value
-----

An `unsigned short`.

Possible values are:

| Value | Constant name | Meaning |
| --- | --- | --- |
| `0` | `TYPE_NAVIGATE` |
 The page was accessed by following a link, a bookmark, a form
 submission, a script, or typing the URL in the address bar.
  |
| `1` | `TYPE_RELOAD` |
 The page was accessed by clicking the Reload button or via the
 `Location.reload()` method.
  |
| `2` | `TYPE_BACK_FORWARD` | The page was accessed by navigating into the history. |
| `255` | `TYPE_RESERVED` | Any other way. |

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

 This feature is no longer on track to become a standard, as the Navigation Timing specification has marked it as deprecated.
 Use the `PerformanceNavigationTiming` interface instead.

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

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

See also
--------

* The `PerformanceNavigation` interface it belongs to.


PerformanceNavigation: redirectCount property - Web APIs

PerformanceNavigation: redirectCount property
=============================================

**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 legacy
 **`PerformanceNavigation.redirectCount`**
 read-only property returns an `unsigned short` representing the number of
 REDIRECTs done before reaching the page.

**Warning:** This interface of this property is deprecated in the Navigation Timing Level 2 specification.
 Please use the `PerformanceNavigationTiming` interface instead.

Value
-----

An `unsigned short`.

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

 This feature is no longer on track to become a standard, as the Navigation Timing specification has marked it as deprecated.
 Use the `PerformanceNavigationTiming` interface instead.

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

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

See also
--------

* The `PerformanceNavigation` interface it belongs to.


PerformanceNavigation: toJSON() method - Web APIs

PerformanceNavigation: toJSON() 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.

**Warning:** This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the `PerformanceNavigationTiming`
 interface instead.

The **`toJSON()`** method of the `PerformanceNavigation` interface is a serializer; it returns a JSON representation of the `PerformanceNavigation` object.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A `JSON` object that is the serialization of the `PerformanceNavigation` object.

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigation-tojson |

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

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

See also
--------

* `JSON`


XMLHttpRequestUpload: error event - Web APIs

XMLHttpRequestUpload: error event
=================================

The `error` event is fired when the request encountered an error.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("error", (event) => {});

onerror = (event) => {};
```

Event type
----------

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

### Using the `error` event

You can use the `error` event to detect a problem with the upload. For a complete code example that uploads a file and displays a progress bar, see the main `XMLHttpRequestUpload` page.

```js
// In case of an error we hide the progress bar
// Note that this event can be listened to on the xhr object too
function errorAction(event) {
  progressBar.classList.remove("visible");
  log.textContent = `Upload failed: ${event.type}`;
}
xhr.upload.addEventListener("error", errorAction);
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-error |
| XMLHttpRequest Standard # handler-xhr-onerror |

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

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

See also
--------

* Related events: `loadstart`, `load`, `progress`, `abort`, `loadend`, `timeout`
* `XMLHttpRequestUpload`


XMLHttpRequestUpload: load event - Web APIs

XMLHttpRequestUpload: load event
================================

The `load` event is fired when an `XMLHttpRequestUpload` transaction completes successfully.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("load", (event) => {});

onload = (event) => {};
```

Event type
----------

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

### Examples

Using the `load` event
----------------------

You can use the `load` event to detect the successful termination of an upload. For a complete code example that uploads a file and displays a progress bar, see the main `XMLHttpRequestUpload` page.

```js
// When the upload is finished, we hide the progress bar.
xhr.upload.addEventListener("load", (event) => {
  progressBar.classList.remove("visible");
  log.textContent = "Upload finished.";
  abortButton.disabled = true;
});
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-load |
| XMLHttpRequest Standard # handler-xhr-onload |

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

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

See also
--------

* Related events: `loadstart`, `progress`, `error`, `loadend`, `abort`, `timeout`
* `XMLHttpRequestUpload`


XMLHttpRequestUpload: progress event - Web APIs

XMLHttpRequestUpload: progress event
====================================

The **`progress`** event is fired periodically when a request receives more data.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("progress", (event) => {});

onprogress = (event) => {};
```

Event type
----------

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

Using the `progress` event
--------------------------

You can use the `progress` event to get info about the progress of a lengthy upload. For a complete code example that uploads a file and displays a progress bar, see the main `XMLHttpRequestUpload` page.

```js
// Each time a progress event is received we update the progress bar
// and the progress message
xhr.upload.addEventListener("progress", (event) => {
  progressBar.value = event.loaded; // Update the progress bar
  log.textContent = `Uploading (${((event.loaded / event.total) \* 100).toFixed(
 2,
 )}%)…`;
});
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-progress |
| XMLHttpRequest Standard # handler-xhr-onprogress |

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

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

See also
--------

* Related events: `loadstart`, `load`, `error`, `loadend`, `timeout`, `abort`
* Monitoring progress
* `XMLHttpRequestUpload`


XMLHttpRequestUpload: loadstart event - Web APIs

XMLHttpRequestUpload: loadstart event
=====================================

The **`loadstart`** event is fired when a request has started to load data.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("loadstart", (event) => {});

onloadstart = (event) => {};
```

Event type
----------

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

Using the `loadstart` event
---------------------------

You can use the `loadstart` event to detect the beginning of an upload. For a complete code example that uploads a file and displays a progress bar, see the main `XMLHttpRequestUpload` page.

```js
// When the upload starts, we display the progress bar
xhr.upload.addEventListener("loadstart", (event) => {
  progressBar.classList.add("visible");
  progressBar.value = 0;
  progressBar.max = event.total;
  log.textContent = "Uploading (0%)…";
  abortButton.disabled = false;
});
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-loadstart |
| XMLHttpRequest Standard # handler-xhr-onloadstart |

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

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

See also
--------

* Related events: `load`, `progress`, `error`, `loadend`, `abort`, `timeout`
* `XMLHttpRequestUpload`


XMLHttpRequestUpload: abort event - Web APIs

XMLHttpRequestUpload: abort event
=================================

The `abort` event is fired at `XMLHttpRequestUpload` when a request has been aborted, for example because the program called `XMLHttpRequest.abort()`.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("abort", (event) => {});

onabort = (event) => {};
```

Event type
----------

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

### Using the `abort` event

You can use the `abort` event to stop the upload before it finishes. For a complete code example that uploads a file and displays a progress bar, see the main `XMLHttpRequestUpload` page.

```js
// In case of an abort we hide the progress bar
// Note that this event can be listened to on the xhr object too
function errorAction(event) {
  progressBar.classList.remove("visible");
  log.textContent = `Upload failed: ${event.type}`;
}
xhr.upload.addEventListener("abort", errorAction);
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-abort |
| XMLHttpRequest Standard # handler-xhr-onabort |

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

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

See also
--------

* Related events: `loadstart`, `load`, `progress`, `error`, `loadend`, `timeout`
* `XMLHttpRequestUpload`