Range - Web APIs

Range
=====

The **`Range`** interface represents a fragment of a document that can contain nodes and parts of text nodes.

A range can be created by using the `Document.createRange()` method. Range objects can also be retrieved by using the `getRangeAt()` method of the `Selection` object or the `caretRangeFromPoint()` method of the `Document` object.

There also is the `Range()` constructor available.

AbstractRange

RangeInstance properties
-------------------

*There are no inherited properties.*

`Range.collapsed` Read only

Returns a boolean value indicating whether the range's start and end points are at the same position.

`Range.commonAncestorContainer` Read only

Returns the deepest `Node` that contains the `startContainer` and `endContainer` nodes.

`Range.endContainer` Read only

Returns the `Node` within which the `Range` ends.

`Range.endOffset` Read only

Returns a number representing where in the `endContainer` the `Range` ends.

`Range.startContainer` Read only

Returns the `Node` within which the `Range` starts.

`Range.startOffset` Read only

Returns a number representing where in the `startContainer` the `Range` starts.

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

`Range()`

Returns a `Range` object with the global `Document` as its start and end.

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

*There are no inherited methods.*

`Range.collapse()`

Collapses the `Range` to one of its boundary points.

`Range.compareBoundaryPoints()`

Compares the boundary points of the `Range` with another `Range`.

`Range.compareNode()`
Deprecated

Non-standard

Returns a constant representing whether the `Node` is before, after, inside, or surrounding the range.

`Range.comparePoint()`

Returns -1, 0, or 1 indicating whether the point occurs before, inside, or after the `Range`.

`Range.cloneContents()`

Returns a `DocumentFragment` copying the nodes of a `Range`.

`Range.cloneRange()`

Returns a `Range` object with boundary points identical to the cloned `Range`.

`Range.createContextualFragment()`

Returns a `DocumentFragment` created from a given string of code.

`Range.deleteContents()`

Removes the contents of a `Range` from the `Document`.

`Range.detach()`

Does nothing. Kept for compatibility.

`Range.extractContents()`

Moves contents of a `Range` from the document tree into a `DocumentFragment`.

`Range.getBoundingClientRect()`

Returns a `DOMRect` object which bounds the entire contents of the `Range`; this would be the union of all the rectangles returned by `range.getClientRects()`.

`Range.getClientRects()`

Returns a list of `DOMRect` objects that aggregates the results of `Element.getClientRects()` for all the elements in the `Range`.

`Range.isPointInRange()`

Returns a `boolean` indicating whether the given point is in the `Range`.

`Range.insertNode()`

Insert a `Node` at the start of a `Range`.

`Range.intersectsNode()`

Returns a `boolean` indicating whether the given node intersects the `Range`.

`Range.selectNode()`

Sets the `Range` to contain the `Node` and its contents.

`Range.selectNodeContents()`

Sets the `Range` to contain the contents of a `Node`.

`Range.setEnd()`

Sets the end position of a `Range`.

`Range.setStart()`

Sets the start position of a `Range`.

`Range.setEndAfter()`

Sets the end position of a `Range` relative to another `Node`.

`Range.setEndBefore()`

Sets the end position of a `Range` relative to another `Node`.

`Range.setStartAfter()`

Sets the start position of a `Range` relative to another `Node`.

`Range.setStartBefore()`

Sets the start position of a `Range` relative to another `Node`.

`Range.surroundContents()`

Moves content of a `Range` into a new `Node`.

`Range.toString()`

Returns the text of the `Range`.

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

| Specification |
| --- |
| DOM Standard # interface-range |
| DOM Parsing and Serialization # extensions-to-the-range-interface |
| CSSOM View Module # extensions-to-the-range-interface |

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

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

See also
--------

* The DOM interfaces index


Gyroscope - Web APIs

Gyroscope
=========

The **`Gyroscope`** interface of the Sensor APIs provides on each reading the angular velocity of the device along all three axes.

To use this sensor, the user must grant permission to the `'gyroscope'` device sensor through the Permissions API. In addition, this feature may be blocked by a Permissions Policy set on your server.

EventTarget

Sensor

GyroscopeConstructor
-----------

`Gyroscope()`

Creates a new `Gyroscope` object.

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

`Gyroscope.x` Read only

Returns a double, containing the angular velocity of the device along the device's x axis.

`Gyroscope.y` Read only

Returns a double, containing the angular velocity of the device along the device's y axis.

`Gyroscope.z` Read only

Returns a double, containing the angular velocity of the device along the device's z axis.

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

*`Gyroscope` doesn't have own methods. However, it inherits methods from its parent interfaces, `Sensor` and `EventTarget`.*

Events
------

*`Gyroscope` doesn't have own events. However, it inherits events from its parent interface, `Sensor`.*

Example
-------

The gyroscope is typically read in the `reading` event callback. In the example below this occurs sixty times a second.

```js
let gyroscope = new Gyroscope({ frequency: 60 });

gyroscope.addEventListener("reading", (e) => {
  console.log(`Angular velocity along the X-axis ${gyroscope.x}`);
  console.log(`Angular velocity along the Y-axis ${gyroscope.y}`);
  console.log(`Angular velocity along the Z-axis ${gyroscope.z}`);
});
gyroscope.start();
```

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

| Specification |
| --- |
| Gyroscope # gyroscope-interface |

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

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


DOMStringMap - Web APIs

DOMStringMap
============

The **`DOMStringMap`** interface is used for the `HTMLElement.dataset` attribute, to represent data for custom attributes added to elements.

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

| Specification |
| --- |
| HTML Standard # embedding-custom-non-visible-data-with-the-data-\*-attributes:domstringmap-3 |

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

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

See also
--------

* `HTMLElement.dataset`
* Global attributes - `data-*`


InputDeviceCapabilities - Web APIs

InputDeviceCapabilities
=======================

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

The **`InputDeviceCapabilities`** interface of the Input Device Capabilities API provides information about the physical device or a group of related devices responsible for generating input events. Events caused by the same physical input device get the same instance of this object, but the converse isn't true. For example, two mice with the same capabilities in a system may appear as a single `InputDeviceCapabilities` instance.

In some instances, `InputDeviceCapabilities` represents the capabilities of logical devices rather than physical devices. This allows, for example, touchscreen keyboards and physical keyboards to be represented the same way when they produce the same input.

Constructors
------------

`InputDeviceCapabilities()`
Experimental

Creates an `InputDeviceCapabilities` object.

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

`InputDeviceCapabilities.firesTouchEvents` Read only
Experimental

A `Boolean` that indicates whether the device dispatches touch events.

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

None.

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

| Specification |
| --- |
| Input Device Capabilities # dom-inputdevicecapabilities |

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

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


USBConnectionEvent - Web APIs

USBConnectionEvent
==================

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

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

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

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

The **`USBConnectionEvent`** interface of the WebUSB API is the event type passed to `USB` `connect` and `disconnect` events when the user agent detects that a new USB device has been connected or disconnected.

Event

USBConnectionEventConstructor
-----------

`USBConnectionEvent()`
Experimental

Returns a `USBConnectionEvent` object.

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

`USBConnectionEvent.device` Read only
Experimental

Returns a `USBDevice` object representing the current device.

Examples
--------

In the following example listening for connect and disconnect events is used to add and remove the devices from the user interface of an application.

```js
navigator.usb.addEventListener("connect", (event) => {
  // Add event.device to the UI.
});

navigator.usb.addEventListener("disconnect", (event) => {
  // Remove event.device from the UI.
});
```

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

| Specification |
| --- |
| WebUSB API # usbconnectionevent |

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

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


NavigationPreloadManager - Web APIs

NavigationPreloadManager
========================

The **`NavigationPreloadManager`** interface of the Service Worker API provides methods for managing the preloading of resources in parallel with service worker bootup.

 If supported, an object of this type is returned by `ServiceWorkerRegistration.navigationPreload`.
 The result of a preload fetch request is waited on using the promise returned by `FetchEvent.preloadResponse`.

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

`NavigationPreloadManager.enable()`

Enables navigation preloading, returning a `Promise` that resolves with `undefined`.

`NavigationPreloadManager.disable()`

Disables navigation preloading, returning a `Promise` that resolves with `undefined`.

`NavigationPreloadManager.setHeaderValue()`

Sets the value of the `Service-Worker-Navigation-Preload` HTTP header sent in preloading requests and returns an empty `Promise`.

`NavigationPreloadManager.getState()`

Returns a `Promise` that resolves to an object with properties that indicate whether preloading is enabled, and what value will be sent in the `Service-Worker-Navigation-Preload` HTTP header in preloading requests.

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

 Service workers handle `fetch()` events on behalf of a site, for pages within a given scope.
 When a user navigates to a page that uses a service worker, the browser boots up the worker (if it isn't already running), then sends it a fetch event and waits for the result.
 On receiving an event, the worker returns the resource from a cache if it is present, or otherwise fetches the resource from the remote server (storing a copy for returning in future requests).

 A service worker cannot process events from the browser until it has booted.
 This is unavoidable, but usually doesn't have much impact.
 Service workers are often already started (they remain active for some time after processing other requests).
 Even if a service worker does have to boot, much of the time it may be returning values from a cache, which is very fast.
 However, in those cases where a worker has to boot before it can start fetching a remote resource, then the delay can be significant.

 The `NavigationPreloadManager` provides a mechanism to allow fetching of the resources to run in parallel with service worker boot, so that by the time the worker is able to handle the fetch request from the browser, the resource may already have been fully or partially downloaded.
 This makes the case where the worker has to start up "no worse" than when the worker is already started, and in some cases better.

 The preload manager sends the `Service-Worker-Navigation-Preload` HTTP header with preload requests, allowing responses to be customized for preload requests.
 This might be used, for example, to reduce the data sent to just part of the original page, or to customize the response based on the user's log-in state.

Examples
--------

The examples here are from Speed up Service Worker with Navigation Preloads (developer.chrome.com).

### Feature detection and enabling navigation preloading

Below we enable navigation preloading in the service worker's `activate` event handler, after first using `ServiceWorkerRegistration.navigationPreload` to determine if the feature is supported (this returns either the `NavigationPreloadManager` for the service worker or `undefined` if the feature is not supported).

```js
addEventListener("activate", (event) => {
  event.waitUntil(
    (async () => {
      if (self.registration.navigationPreload) {
        // Enable navigation preloads!
        await self.registration.navigationPreload.enable();
      }
    })(),
  );
});
```

### Using a preloaded response

The following code shows a service worker fetch event handler that uses a preloaded response (`FetchEvent.preloadResponse`).

 The `fetch` event handler calls `FetchEvent.respondWith()` to pass a promise back to the controlled page.
 This promise will resolve with the requested resource, which may be from the cache, a preloaded fetch request, or a new network request.

 If there is a matching URL request in the `Cache` object, then the code returns a resolved promise for fetching the response from the cache.
 If no match is found in the cache, the code returns the resolved preloaded response (`FetchEvent.preloadResponse`).
 If there is no matching cache entry or preloaded response, the code starts a new fetch operation from the network and returns the (unresolved) promise for that fetch operation.

```js
addEventListener("fetch", (event) => {
  event.respondWith(
    (async () => {
      // Respond from the cache if we can
      const cachedResponse = await caches.match(event.request);
      if (cachedResponse) return cachedResponse;

      // Else, use the preloaded response, if it's there
      const response = await event.preloadResponse;
      if (response) return response;

      // Else try the network.
      return fetch(event.request);
    })(),
  );
});
```

### Custom responses

 The browser sends the HTTP header `Service-Worker-Navigation-Preload` with preload requests, with a default directive value of `true`.
 This allows servers to differentiate between normal and preload fetch requests, and to send different responses in each case if required.

**Note:** If the response from preload and normal fetch operations can be different, then the server must set `Vary: Service-Worker-Navigation-Preload` to ensure that the different responses are cached.

 The header value can be changed to any other string value using `NavigationPreloadManager.setHeaderValue()` in order to provide additional context for the prefetch operation.
 For example, you might set the value to the ID of your most recently cached resource, so that the server won't return any resources unless they are actually needed.
 Similarly, you could configure the returned information based on authentication status instead of using cookies.

The code below shows how to set the value of the header directive to some variable `newValue`.

```js
navigator.serviceWorker.ready
  .then((registration) =>
    registration.navigationPreload.setHeaderValue(newValue),
  )
  .then(() => {
    console.log("Done!");
  });
```

Speed up Service Worker with Navigation Preloads > Custom responses for preloads provides a more complete example of a site where the response for an article web page is constructed from a cached header and footer, so that only the article content is returned for a prefetch.

### Getting the state

 You can use `NavigationPreloadManager.getState()` to check whether navigation preloading is enabled and to determine what directive value is sent with the
 `Service-Worker-Navigation-Preload` HTTP header for preload requests.

The code below shows how to get the promise that resolves to a `state` object and log the result.

```js
navigator.serviceWorker.ready
  .then((registration) => registration.navigationPreload.getState())
  .then((state) => {
    console.log(state.enabled); // boolean
    console.log(state.headerValue); // string
  });
```

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

| Specification |
| --- |
| Service Workers # navigation-preload-manager |

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

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

See also
--------

* Speed up Service Worker with Navigation Preloads (developer.chrome.com)


Web Audio API - Web APIs

Web Audio API
=============

The Web Audio API provides a powerful and versatile system for controlling audio on the Web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning) and much more.

Web audio concepts and usage
----------------------------

The Web Audio API involves handling audio operations inside an **audio context**, and has been designed to allow **modular routing**. Basic audio operations are performed with **audio nodes**, which are linked together to form an **audio routing graph**. Several sources — with different types of channel layout — are supported even within a single context. This modular design provides the flexibility to create complex audio functions with dynamic effects.

Audio nodes are linked into chains and simple webs by their inputs and outputs. They typically start with one or more sources. Sources provide arrays of sound intensities (samples) at very small timeslices, often tens of thousands of them per second. These could be either computed mathematically (such as `OscillatorNode`), or they can be recordings from sound/video files (like `AudioBufferSourceNode` and `MediaElementAudioSourceNode`) and audio streams (`MediaStreamAudioSourceNode`). In fact, sound files are just recordings of sound intensities themselves, which come in from microphones or electric instruments, and get mixed down into a single, complicated wave.

Outputs of these nodes could be linked to inputs of others, which mix or modify these streams of sound samples into different streams. A common modification is multiplying the samples by a value to make them louder or quieter (as is the case with `GainNode`). Once the sound has been sufficiently processed for the intended effect, it can be linked to the input of a destination (`BaseAudioContext.destination`), which sends the sound to the speakers or headphones. This last connection is only necessary if the user is supposed to hear the audio.

A simple, typical workflow for web audio would look something like this:

1. Create audio context
2. Inside the context, create sources — such as `<audio>`, oscillator, stream
3. Create effects nodes, such as reverb, biquad filter, panner, compressor
4. Choose final destination of audio, for example your system speakers
5. Connect the sources up to the effects, and the effects to the destination.

![A simple box diagram with an outer box labeled Audio context, and three inner boxes labeled Sources, Effects and Destination. The three inner boxes have arrows between them pointing from left to right, indicating the flow of audio information.](/en-US/docs/Web/API/Web_Audio_API/audio-context_.png)

Timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events and is able to target specific samples, even at a high sample rate. So applications such as drum machines and sequencers are well within reach.

The Web Audio API also allows us to control how audio is *spatialized*. Using a system based on a *source-listener model*, it allows control of the *panning model* and deals with *distance-induced attenuation* induced by a moving source (or moving listener).

**Note:** You can read about the theory of the Web Audio API in a lot more detail in our article Basic concepts behind Web Audio API.

Web Audio API target audience
-----------------------------

The Web Audio API can seem intimidating to those that aren't familiar with audio or music terms, and as it incorporates a great deal of functionality it can prove difficult to get started if you are a developer.

It can be used to incorporate audio into your website or application, by providing atmosphere like futurelibrary.no, or auditory feedback on forms. However, it can also be used to create *advanced* interactive instruments. With that in mind, it is suitable for both developers and musicians alike.

We have a simple introductory tutorial for those that are familiar with programming but need a good introduction to some of the terms and structure of the API.

There's also a Basic Concepts Behind Web Audio API article, to help you understand the way digital audio works, specifically in the realm of the API. This also includes a good introduction to some of the concepts the API is built upon.

Learning coding is like playing cards — you learn the rules, then you play, then you go back and learn the rules again, then you play again. So if some of the theory doesn't quite fit after the first tutorial and article, there's an advanced tutorial which extends the first one to help you practice what you've learnt, and apply some more advanced techniques to build up a step sequencer.

We also have other tutorials and comprehensive reference material available that covers all features of the API. See the sidebar on this page for more.

If you are more familiar with the musical side of things, are familiar with music theory concepts, want to start building instruments, then you can go ahead and start building things with the advanced tutorial and others as a guide (the above-linked tutorial covers scheduling notes, creating bespoke oscillators and envelopes, as well as an LFO among other things.)

If you aren't familiar with the programming basics, you might want to consult some beginner's JavaScript tutorials first and then come back here — see our Beginner's JavaScript learning module for a great place to begin.

Web Audio API interfaces
------------------------

The Web Audio API has a number of interfaces and associated events, which we have split up into nine categories of functionality.

### General audio graph definition

General containers and definitions that shape audio graphs in Web Audio API usage.

`AudioContext`

The **`AudioContext`** interface represents an audio-processing graph built from audio modules linked together, each represented by an `AudioNode`. An audio context controls the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an `AudioContext` before you do anything else, as everything happens inside a context.

`AudioNode`

The **`AudioNode`** interface represents an audio-processing module like an *audio source* (e.g. an HTML `<audio>` or `<video>` element), *audio destination*, *intermediate processing module* (e.g. a filter like `BiquadFilterNode`, or *volume control* like `GainNode`).

`AudioParam`

The **`AudioParam`** interface represents an audio-related parameter, like one of an `AudioNode`. It can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern.

`AudioParamMap`

Provides a map-like interface to a group of `AudioParam` interfaces, which means it provides the methods `forEach()`, `get()`, `has()`, `keys()`, and `values()`, as well as a `size` property.

`BaseAudioContext`

The **`BaseAudioContext`** interface acts as a base definition for online and offline audio-processing graphs, as represented by `AudioContext` and `OfflineAudioContext` respectively. You wouldn't use `BaseAudioContext` directly — you'd use its features via one of these two inheriting interfaces.

The `ended` event

The `ended` event is fired when playback has stopped because the end of the media was reached.

### Defining audio sources

Interfaces that define audio sources for use in the Web Audio API.

`AudioScheduledSourceNode`

The **`AudioScheduledSourceNode`** is a parent interface for several types of audio source node interfaces. It is an `AudioNode`.

`OscillatorNode`

The **`OscillatorNode`** interface represents a periodic waveform, such as a sine or triangle wave. It is an `AudioNode` audio-processing module that causes a given *frequency* of wave to be created.

`AudioBuffer`

The **`AudioBuffer`** interface represents a short audio asset residing in memory, created from an audio file using the `BaseAudioContext.decodeAudioData` method, or created with raw data using `BaseAudioContext.createBuffer`. Once decoded into this form, the audio can then be put into an `AudioBufferSourceNode`.

`AudioBufferSourceNode`

The **`AudioBufferSourceNode`** interface represents an audio source consisting of in-memory audio data, stored in an `AudioBuffer`. It is an `AudioNode` that acts as an audio source.

`MediaElementAudioSourceNode`

The **`MediaElementAudioSourceNode`** interface represents an audio source consisting of an HTML `<audio>` or `<video>` element. It is an `AudioNode` that acts as an audio source.

`MediaStreamAudioSourceNode`

The **`MediaStreamAudioSourceNode`** interface represents an audio source consisting of a `MediaStream` (such as a webcam, microphone, or a stream being sent from a remote computer). If multiple audio tracks are present on the stream, the track whose `id` comes first lexicographically (alphabetically) is used. It is an `AudioNode` that acts as an audio source.

`MediaStreamTrackAudioSourceNode`

A node of type `MediaStreamTrackAudioSourceNode` represents an audio source whose data comes from a `MediaStreamTrack`. When creating the node using the `createMediaStreamTrackSource()` method to create the node, you specify which track to use. This provides more control than `MediaStreamAudioSourceNode`.

### Defining audio effects filters

Interfaces for defining effects that you want to apply to your audio sources.

`BiquadFilterNode`

The **`BiquadFilterNode`** interface represents a simple low-order filter. It is an `AudioNode` that can represent different kinds of filters, tone control devices, or graphic equalizers. A `BiquadFilterNode` always has exactly one input and one output.

`ConvolverNode`

The **`ConvolverNode`** interface is an `AudioNode` that performs a Linear Convolution on a given `AudioBuffer`, and is often used to achieve a reverb effect.

`DelayNode`

The **`DelayNode`** interface represents a delay-line; an `AudioNode` audio-processing module that causes a delay between the arrival of an input data and its propagation to the output.

`DynamicsCompressorNode`

The **`DynamicsCompressorNode`** interface provides a compression effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once.

`GainNode`

The **`GainNode`** interface represents a change in volume. It is an `AudioNode` audio-processing module that causes a given *gain* to be applied to the input data before its propagation to the output.

`WaveShaperNode`

The **`WaveShaperNode`** interface represents a non-linear distorter. It is an `AudioNode` that use a curve to apply a waveshaping distortion to the signal. Beside obvious distortion effects, it is often used to add a warm feeling to the signal.

`PeriodicWave`

Describes a periodic waveform that can be used to shape the output of an `OscillatorNode`.

`IIRFilterNode`

Implements a general infinite impulse response (IIR) filter; this type of filter can be used to implement tone-control devices and graphic equalizers as well.

### Defining audio destinations

Once you are done processing your audio, these interfaces define where to output it.

`AudioDestinationNode`

The **`AudioDestinationNode`** interface represents the end destination of an audio source in a given context — usually the speakers of your device.

`MediaStreamAudioDestinationNode`

The **`MediaStreamAudioDestinationNode`** interface represents an audio destination consisting of a WebRTC `MediaStream` with a single `AudioMediaStreamTrack`, which can be used in a similar way to a `MediaStream` obtained from `getUserMedia()`. It is an `AudioNode` that acts as an audio destination.

### Data analysis and visualization

If you want to extract time, frequency, and other data from your audio, the `AnalyserNode` is what you need.

`AnalyserNode`

The **`AnalyserNode`** interface represents a node able to provide real-time frequency and time-domain analysis information, for the purposes of data analysis and visualization.

### Splitting and merging audio channels

To split and merge audio channels, you'll use these interfaces.

`ChannelSplitterNode`

The **`ChannelSplitterNode`** interface separates the different channels of an audio source out into a set of *mono* outputs.

`ChannelMergerNode`

The **`ChannelMergerNode`** interface reunites different mono inputs into a single output. Each input will be used to fill a channel of the output.

### Audio spatialization

These interfaces allow you to add audio spatialization panning effects to your audio sources.

`AudioListener`

The **`AudioListener`** interface represents the position and orientation of the unique person listening to the audio scene used in audio spatialization.

`PannerNode`

The **`PannerNode`** interface represents the position and behavior of an audio source signal in 3D space, allowing you to create complex panning effects.

`StereoPannerNode`

The **`StereoPannerNode`** interface represents a simple stereo panner node that can be used to pan an audio stream left or right.

### Audio processing in JavaScript

Using audio worklets, you can define custom audio nodes written in JavaScript or WebAssembly. Audio worklets implement the `Worklet` interface, a lightweight version of the `Worker` interface.

`AudioWorklet`

The `AudioWorklet` interface is available through the `AudioContext` object's `audioWorklet`, and lets you add modules to the audio worklet to be executed off the main thread.

`AudioWorkletNode`

The `AudioWorkletNode` interface represents an `AudioNode` that is embedded into an audio graph and can pass messages to the corresponding `AudioWorkletProcessor`.

`AudioWorkletProcessor`

The `AudioWorkletProcessor` interface represents audio processing code running in a `AudioWorkletGlobalScope` that generates, processes, or analyzes audio directly, and can pass messages to the corresponding `AudioWorkletNode`.

`AudioWorkletGlobalScope`

The `AudioWorkletGlobalScope` interface is a `WorkletGlobalScope`-derived object representing a worker context in which an audio processing script is run; it is designed to enable the generation, processing, and analysis of audio data directly using JavaScript in a worklet thread rather than on the main thread.

#### Obsolete: script processor nodes

Before audio worklets were defined, the Web Audio API used the `ScriptProcessorNode` for JavaScript-based audio processing. Because the code runs in the main thread, they have bad performance. The `ScriptProcessorNode` is kept for historic reasons but is marked as deprecated.

`ScriptProcessorNode`
Deprecated

The **`ScriptProcessorNode`** interface allows the generation, processing, or analyzing of audio using JavaScript. It is an `AudioNode` audio-processing module that is linked to two buffers, one containing the current input, one containing the output. An event, implementing the `AudioProcessingEvent` interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data.

`audioprocess` (event)
Deprecated

The `audioprocess` event is fired when an input buffer of a Web Audio API `ScriptProcessorNode` is ready to be processed.

`AudioProcessingEvent`
Deprecated

The `AudioProcessingEvent` represents events that occur when a `ScriptProcessorNode` input buffer is ready to be processed.

### Offline/background audio processing

It is possible to process/render an audio graph very quickly in the background — rendering it to an `AudioBuffer` rather than to the device's speakers — with the following.

`OfflineAudioContext`

The **`OfflineAudioContext`** interface is an `AudioContext` interface representing an audio-processing graph built from linked together `AudioNode`s. In contrast with a standard `AudioContext`, an `OfflineAudioContext` doesn't really render the audio but rather generates it, *as fast as it can*, in a buffer.

`complete` (event)

The `complete` event is fired when the rendering of an `OfflineAudioContext` is terminated.

`OfflineAudioCompletionEvent`

The `OfflineAudioCompletionEvent` represents events that occur when the processing of an `OfflineAudioContext` is terminated. The `complete` event uses this interface.

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

Advanced techniques: Creating and sequencing audioIn this tutorial, we're going to cover sound creation and modification, as well as timing and scheduling. We will introduce sample loading, envelopes, filters, wavetables, and frequency modulation. If you're familiar with these terms and looking for an introduction to their application with the Web Audio API, you've come to the right place.

Background audio processing using AudioWorkletThis article explains how to create an audio worklet processor and use it in a Web Audio application.

Basic concepts behind Web Audio APIThis article explains some of the audio theory behind how the features of the Web Audio API work to help you make informed decisions while designing how your app routes audio. If you are not already a sound engineer, it will give you enough background to understand why the Web Audio API works as it does.

Controlling multiple parameters with ConstantSourceNodeThis article demonstrates how to use a `ConstantSourceNode` to link multiple parameters together so they share the same value, which can be changed by setting the value of the `ConstantSourceNode.offset` parameter.

Example and tutorial: Simple synth keyboardThis article presents the code and working demo of a video keyboard you can play using the mouse. The keyboard allows you to switch among the standard waveforms as well as one custom waveform, and you can control the main gain using a volume slider beneath the keyboard. This example makes use of the following Web API interfaces: `AudioContext`, `OscillatorNode`, `PeriodicWave`, and `GainNode`.

Tools for analyzing Web Audio usageWhile working on your Web Audio API code, you may find that you need tools to analyze the graph of nodes you create or to otherwise debug your work. This article discusses tools available to help you do that.

Using IIR filtersThe **`IIRFilterNode`** interface of the Web Audio API is an `AudioNode` processor that implements a general infinite impulse response (IIR) filter; this type of filter can be used to implement tone control devices and graphic equalizers, and the filter response parameters can be specified, so that it can be tuned as needed. This article looks at how to implement one, and use it in a simple example.

Using the Web Audio APILet's take a look at getting started with the Web Audio API. We'll briefly look at some concepts, then study a simple boombox example that allows us to load an audio track, play and pause it, and change its volume and stereo panning.

Visualizations with Web Audio APIOne of the most interesting features of the Web Audio API is the ability to extract frequency, waveform, and other data from your audio source, which can then be used to create visualizations. This article explains how, and provides a couple of basic use cases.

Web Audio API best practicesThere's no strict right or wrong way when writing creative code. As long as you consider security, performance, and accessibility, you can adapt to your own style. In this article, we'll share a number of *best practices* — guidelines, tips, and tricks for working with the Web Audio API.

Web audio spatialization basicsAs if its extensive variety of sound processing (and other) options wasn't enough, the Web Audio API also includes facilities to allow you to emulate the difference in sound as a listener moves around a sound source, for example panning as you move around a sound source inside a 3D game.
 The official term for this is **spatialization**, and this article will cover the basics of how to implement such a system.

Examples
--------

You can find a number of examples at our webaudio-example repo on GitHub.

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

| Specification |
| --- |
| Web Audio API # AudioContext |

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

### AudioContext

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

See also
--------

### Tutorials/guides

* Basic concepts behind Web Audio API
* Using the Web Audio API
* Advanced techniques: creating sound, sequencing, timing, scheduling
* Autoplay guide for media and Web Audio APIs
* Using IIR filters
* Visualizations with Web Audio API
* Web audio spatialization basics
* Controlling multiple parameters with ConstantSourceNode
* Mixing Positional Audio and WebGL (2012)
* Developing Game Audio with the Web Audio API (2012)
### Libraries

* Tones: a simple library for playing specific tones/notes using the Web Audio API.
* Tone.js: a framework for creating interactive music in the browser.
* howler.js: a JS audio library that defaults to Web Audio API and falls back to HTML Audio, as well as providing other useful features.
* Mooog: jQuery-style chaining of AudioNodes, mixer-style sends/returns, and more.
* XSound: Web Audio API Library for Synthesizer, Effects, Visualization, Recording, etc.
* OpenLang: HTML video language lab web application using the Web Audio API to record and combine video and audio from different sources into a single file (source on GitHub)
* Pts.js: Simplifies web audio visualization (guide)
### Related topics

* Web media technologies
* Guide to media types and formats on the web


MimeType - Web APIs

MimeType
========

**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 **`MimeType`** interface provides contains information about a MIME type associated with a particular plugin. `Navigator.mimeTypes` returns an array of this object.

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

`MimeType.type`
Deprecated

Returns the MIME type of the associated plugin.

`MimeType.description`
Deprecated

Returns a description of the associated plugin or an empty string if there is none.

`MimeType.suffixes`
Deprecated

A string containing valid file extensions for the data displayed by the plugin, or an empty string if an extension is not valid for the particular module. For example, a browser's content decryption module may appear in the plugin list but support more file extensions than can be anticipated. It might therefore return an empty string.

`MimeType.enabledPlugin`
Deprecated

Returns an instance of `Plugin` containing information about the plugin itself.

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

| Specification |
| --- |
| HTML Standard # mimetype |

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

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


MediaTrackSupportedConstraints - Web APIs

MediaTrackSupportedConstraints
==============================

The **`MediaTrackSupportedConstraints`** dictionary establishes the list of constrainable properties recognized by the user agent or browser in its implementation of the `MediaStreamTrack` object. An object conforming to `MediaTrackSupportedConstraints` is returned by `MediaDevices.getSupportedConstraints()`.

Because of the way interface definitions in WebIDL work, if a constraint is requested but not supported, no error will occur. Instead, the specified constraints will be applied, with any unrecognized constraints stripped from the request. That can lead to confusing and hard to debug errors, so be sure to use `getSupportedConstraints()` to retrieve this information before attempting to establish constraints if you need to know the difference between silently ignoring a constraint and a constraint being accepted.

An actual constraint set is described using an object based on the `MediaTrackConstraints` dictionary.

To learn more about how constraints work, see Capabilities, constraints, and settings.

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

Some combination—but not necessarily all—of the following properties will exist on the object.

`autoGainControl`

A Boolean whose value is `true` if the `autoGainControl` constraint is supported in the current environment.

`width`

A Boolean value whose value is `true` if the `width` constraint is supported in the current environment.

`height`

A Boolean value whose value is `true` if the `height` constraint is supported in the current environment.

`aspectRatio`

A Boolean value whose value is `true` if the `aspectRatio` constraint is supported in the current environment.

`frameRate`

A Boolean value whose value is `true` if the `frameRate` constraint is supported in the current environment.

`facingMode`

A Boolean value whose value is `true` if the `facingMode` constraint is supported in the current environment.

`resizeMode`

A Boolean value whose value is `true` if the `resizeMode` constraint is supported in the current environment.

`volume`
Deprecated

Non-standard

A Boolean value whose value is `true` if the `volume` constraint is supported in the current environment.

`sampleRate`

A Boolean value whose value is `true` if the `sampleRate` constraint is supported in the current environment.

`sampleSize`

A Boolean value whose value is `true` if the `sampleSize` constraint is supported in the current environment.

`echoCancellation`

A Boolean value whose value is `true` if the `echoCancellation` constraint is supported in the current environment.

`latency`

A Boolean value whose value is `true` if the `latency` constraint is supported in the current environment.

`noiseSuppression`

A Boolean whose value is `true` if the `noiseSuppression` constraint is supported in the current environment.

`channelCount`

A Boolean value whose value is `true` if the `channelCount` constraint is supported in the current environment.

`deviceId`

A Boolean value whose value is `true` if the `deviceId` constraint is supported in the current environment.

`groupId`

A Boolean value whose value is `true` if the `groupId` constraint is supported in the current environment.

### Instance properties specific to shared screen tracks

For tracks containing video sources from the user's screen contents, the following additional properties are may be included in addition to those available for video tracks.

`displaySurface`

A Boolean value which is `true` if the `displaySurface` constraint is supported in the current environment.

`logicalSurface`

A Boolean value which is `true` if the `logicalSurface` constraint is supported in the current environment.

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

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

See also
--------

* Media Capture and Streams API
* Capabilities, constraints, and settings
* Screen Capture API
* Using the Screen Capture API
* `MediaTrackConstraints`
* `MediaDevices.getUserMedia()`
* `MediaStreamTrack.getConstraints()`
* `MediaStreamTrack.applyConstraints()`
* `MediaStreamTrack.getSettings()`


ReadableStreamBYOBReader - Web APIs

ReadableStreamBYOBReader
========================

 The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a `ReadableStream` that supports zero-copy reading from an underlying byte source.
 It is used for efficient copying from underlying sources where the data is delivered as an "anonymous" sequence of bytes, such as files.

 An instance of this reader type should usually be obtained by calling `ReadableStream.getReader()` on the stream, specifying `mode: "byob"` in the options parameter.
 The readable stream must have an *underlying byte source*. In other words, it must have been constructed specifying an underlying source with `type: "bytes"`).

 Using this kind of reader, a `read()` request when the readable stream's internal queues are empty will result in a zero copy transfer from the underlying source (bypassing the stream's internal queues).
 If the internal queues are not empty, a `read()` will satisfy the request from the buffered data.

 Note that the methods and properties are similar to those for the default reader (`ReadableStreamDefaultReader`).
 The `read()` method differs in that it provide a view into which data should be written.

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

`ReadableStreamBYOBReader()`

Creates and returns a `ReadableStreamBYOBReader` object instance.

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

`ReadableStreamBYOBReader.closed` Read only

Returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process.

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

`ReadableStreamBYOBReader.cancel()`

Returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. The supplied `reason` argument will be given to the underlying source, which may or may not use it.

`ReadableStreamBYOBReader.read()`

Passes a view into which data must be written, and returns a `Promise` that resolves with the next chunk in the stream or rejects with an indication that the stream is closed or has errored.

`ReadableStreamBYOBReader.releaseLock()`

Releases the reader's lock on the stream.

Examples
--------

The example below is taken from the live examples in Using readable byte streams.

 First create the reader using `ReadableStream.getReader()` on the stream, specifying `mode: "byob"` in the options parameter.
 As this is a "Bring Your Own Buffer" reader, we also need to create an `ArrayBuffer` to read into.

```js
const reader = stream.getReader({ mode: "byob" });
let buffer = new ArrayBuffer(200);
```

 A function that uses the reader is shown below.
 This calls the `read()` method recursively to read data into the buffer.
 The method takes a `Uint8Array` typed array which is a view over the part of the original array buffer that has not yet been written.
 The parameters of the view are calculated from the data that was received in previous calls, which define an offset into the original array buffer.

```js
readStream(reader);

function readStream(reader) {
  let bytesReceived = 0;
  let offset = 0;

  // read() returns a promise that resolves when a value has been received
  reader
    .read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
    .then(function processText({ done, value }) {
      // Result objects contain two properties:
      // done - true if the stream has already given all its data.
      // value - some data. Always undefined when done is true.

      if (done) {
        logConsumer(`readStream() complete. Total bytes: ${bytesReceived}`);
        return;
      }

      buffer = value.buffer;
      offset += value.byteLength;
      bytesReceived += value.byteLength;

      logConsumer(
        `Read ${value.byteLength} (${bytesReceived}) bytes: ${value}`,
      );
      result += value;

      // Read some more, and call this function again
      return reader
        .read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
        .then(processText);
    });
}
```

When there is no more data in the stream, the `read()` method resolves with an object with the property `done` set to `true`, and the function returns.

The `ReadableStreamBYOBReader.closed` property returns a promise that can be used to monitor for the stream being closed or errored, or the reader lock being released.

```js
reader.closed
  .then(() => {
    // Resolved - code to handle stream closing
  })
  .catch(() => {
    // Rejected - code to handle error
  });
```

 To cancel the stream call `ReadableStreamBYOBReader.cancel()`, optionally specifying a *reason*.
 This returns a promise that will resolve when the stream has been cancelled.
 When the stream is cancelled the controller will in turn call `cancel()` on the underlying source, passing in the optional reason.

The example code in Using readable byte streams calls the cancel method when a button is pressed, as shown:

```js
button.addEventListener("click", () => {
  reader.cancel("user choice").then(() => console.log("cancel complete"));
});
```

The consumer can also call `releaseLock()` to release the reader's hold on the stream, but only when no read is pending:

```js
reader.releaseLock();
```

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

| Specification |
| --- |
| Streams Standard # byob-reader-class |

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

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

See also
--------

* Streams API concepts
* Using readable byte stream
* `ReadableStream`
* WHATWG Stream Visualizer, for a basic visualization of readable, writable, and transform streams.
* Web-streams-polyfill or sd-streams - polyfills


Web Periodic Background Synchronization API - Web APIs

Web Periodic Background Synchronization API
===========================================

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

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

The **Web Periodic Background Synchronization API** provides a way to register tasks to be run in a service worker at periodic intervals with network connectivity. These tasks are referred to as periodic background sync requests.

Concepts and Usage
------------------

The Periodic Background Sync API allows web applications to alert their service worker to make any updates, at a periodic time interval. Uses may include fetching latest content whilst a device is connected to Wi-Fi, or allowing background updates to an application.

The minimum time interval is set when the API is invoked; however the user agent might also take into account other factors which affect when the service worker receives the event. For instance previous website engagement, or connection to a known network.

The `PeriodicSyncManager` interface is available through `ServiceWorkerRegistration.periodicSync`. A unique tag identifier is set to 'name' the sync event, which can then be listened for within the `ServiceWorker` script. Once the event is received you can then run any functionality available, such as updating caches or fetching new resources.

As this API relies on service workers, functionality provided by this API is only available in a secure context.

Interfaces
----------

`PeriodicSyncManager`
Experimental

Registers tasks to be run in a service worker at periodic intervals with network connectivity. These tasks are referred to as periodic background sync requests.

`PeriodicSyncEvent`
Experimental

Represents a synchronization event, sent to the global scope of a ServiceWorker. It provides a way to run tasks in the service worker with network connectivity.

### Extensions to other interfaces

The following additions to the Service Worker API are specified in the Periodic Background Sync specification to provide an entry point for using Periodic Background Sync.

`ServiceWorkerRegistration.periodicSync` Read only
Experimental

Returns a reference to the `PeriodicSyncManager` interface for registering tasks to run at specific intervals.

`periodicsync` event
Experimental

Occurs at periodic intervals, which were specified when registering a `PeriodicSyncManager`.

Examples
--------

The following examples show how to use the interface.

### Requesting a Periodic Background Sync

The following asynchronous function registers a periodic background sync at a minimum interval of one day from a browsing context:

```js
async function registerPeriodicNewsCheck() {
  const registration = await navigator.serviceWorker.ready;
  try {
    await registration.periodicSync.register("get-latest-news", {
      minInterval: 24 \* 60 \* 60 \* 1000,
    });
  } catch {
    console.log("Periodic Sync could not be registered!");
  }
}
```

### Verifying a Background Periodic Sync by Tag

This code checks to see if a Periodic Background Sync task with a given tag is registered.

```js
navigator.serviceWorker.ready.then((registration) => {
  registration.periodicSync.getTags().then((tags) => {
    if (tags.includes("get-latest-news")) skipDownloadingLatestNewsOnPageLoad();
  });
});
```

### Removing a Periodic Background Sync Task

The following code removes a Periodic Background Sync task to stop articles syncing in the background.

```js
navigator.serviceWorker.ready.then((registration) => {
  registration.periodicSync.unregister("get-latest-news");
});
```

### Listening for a Periodic Background Sync within a Service Worker

The following example shows how to respond to a periodic sync event in the service worker.

```js
self.addEventListener("periodicsync", (event) => {
  if (event.tag === "get-latest-news") {
    event.waitUntil(fetchAndCacheLatestNews());
  }
});
```

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

| Specification |
| --- |
| Web Periodic Background Synchronization  |

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

### api.PeriodicSyncManager

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

### api.ServiceWorkerGlobalScope.periodicsync\_event

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

See also
--------

* An article on using Periodic Background Sync
* A Periodic Background Sync demo app


MediaStreamTrackAudioSourceNode - Web APIs

MediaStreamTrackAudioSourceNode
===============================

The **`MediaStreamTrackAudioSourceNode`** interface is a type of `AudioNode` which represents a source of audio data taken from a specific `MediaStreamTrack` obtained through the WebRTC or Media Capture and Streams APIs.

The audio itself might be input from a microphone or other audio sampling device, or might be received through a `RTCPeerConnection`, among other possible options.

A `MediaStreamTrackAudioSourceNode` has no inputs and exactly one output, and is created using the `AudioContext.createMediaStreamTrackSource()` method. This interface is similar to `MediaStreamAudioSourceNode`, except it lets you specifically state the track to use, rather than assuming the first audio track on a stream.

EventTarget

AudioNode

MediaStreamTrackAudioSourceNode

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |
| Channel count |
 defined by the first audio `MediaStreamTrack`
 passed to the
 `AudioContext.createMediaStreamTrackSource()`
 method that created it.
  |

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

`new MediaStreamTrackAudioSourceNode()`

Creates a new `MediaStreamTrackAudioSourceNode` object instance with the specified options.

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

*The `MediaStreamTrackAudioSourceNode` interface has no properties of its own; however, it inherits the properties of its parent, `AudioNode`.*

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

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

Example
-------

See `AudioContext.createMediaStreamSource()` for example code that uses this object.

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

| Specification |
| --- |
| Web Audio API # MediaStreamTrackAudioSourceNode |

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

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

See also
--------

* Using the Web Audio API
* WebRTC API
* Media Capture and Streams API (Media Streams)
* `MediaStreamAudioSourceNode`


Prioritized Task Scheduling API - Web APIs

Prioritized Task Scheduling API
===============================

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

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

* Learn more
* See full compatibility
* Report feedback

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

The **Prioritized Task Scheduling API** provides a standardized way to prioritize all tasks belonging to an application, whether they are defined in a website developer's code or in third-party libraries and frameworks.

The task priorities are very coarse-grained and based around whether tasks block user interaction or otherwise impact the user experience, or can run in the background. Developers and frameworks may implement more fine-grained prioritization schemes within the broad categories defined by the API.

The API is promise-based and supports the ability to set and change task priorities, to delay tasks being added to the scheduler, to abort tasks, and to monitor for priority change and abort events.

In this page, we also include information about the `navigator.scheduling.isInputPending()` method, which was defined in a different API specification but is very closely related to task scheduling. This method allows you to check whether there are pending input events in the event queue, and therefore handle task queues efficiently, only yielding to the main thread when it is needed.

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

### Prioritized task scheduling

The Prioritized Task Scheduling API is available in both window and worker threads using the `scheduler` property on the global object.

The main API method is `Scheduler.postTask()`, which takes a callback function ("the task") and returns a promise that resolves with the return value of the function, or rejects with an error.

The simplest form of the API is shown below. This creates a task with default priority `user-visible` that has a fixed priority and cannot be aborted.

```js
const promise = scheduler.postTask(myTask);
```

Because the method returns a promise you can wait on its resolution asynchronously using `then`, and catch errors thrown by the task callback function (or when the task is aborted) using `catch`. The callback function can be any kind of function (below we demonstrate an arrow function).

```js
scheduler
  .postTask(() => "Task executing")
  // Promise resolved: log task result when promise resolves
  .then((taskResult) => console.log(`${taskResult}`))
  // Promise rejected: log AbortError or errors thrown by task
  .catch((error) => console.error(`Error: ${error}`));
```

The same task might be waited on using `await`/`async` as shown below (note, this is run in an Immediately Invoked Function Expression (IIFE)):

```js
(async () => {
  try {
    const result = await scheduler.postTask(() => "Task executing");
    console.log(result);
  } catch (error) {
    // Log AbortError or error thrown in task function
    console.error(`Error: ${error}`);
  }
})();
```

 You can also specify an options object to the `postTask()` method if you want to change the default behavior.
 The options are:

* `priority` This allows you to specify a particular immutable priority.
 Once set, the priority cannot be changed.
* `signal` This allows you to specify a signal, which may be either a `TaskSignal` or `AbortSignal`
 The signal is associated with a controller, which can be used to abort the task.
 A `TaskSignal` can also be used to set and change the task priority if the task is mutable.
* `delay` This allows you to specify the delay before the task is added for scheduling, in milliseconds.

The same example as above with a priority option would look like this:

```js
scheduler
  .postTask(() => "Task executing", { priority: "user-blocking" })
  .then((taskResult) => console.log(`${taskResult}`)) // Log the task result
  .catch((error) => console.error(`Error: ${error}`)); // Log any errors
```

#### Task priorities

Scheduled tasks are run in priority order, followed by the order that they were added to the scheduler queue.

There are just three priorities, which are listed below (ordered from highest to lowest):

`user-blocking`

 Tasks that stop users from interacting with the page.
 This includes rendering the page to the point where it can be used, or responding to user input.

`user-visible`

 Tasks that are visible to the user but not necessarily blocking user actions.
 This might include rendering non-essential parts of the page, such as non-essential images or animations.

This is the default priority.

`background`

 Tasks that are not time-critical.
 This might include log processing or initializing third party libraries that aren't required for rendering.

#### Mutable and immutable task priority

 There are many use cases where the task priority never needs to change, while for others it does.
 For example fetching an image might change from a `background` task to `user-visible` as a carousel is scrolled into the viewing area.

Task priorities can be set as static (immutable) or dynamic (modifiable) depending on the arguments passed to `Scheduler.postTask()`.

 Task priority is immutable if a value is specified in the `options.priority` argument.
 The given value will be used for the task priority and cannot be changed.

 The priority is modifiable only if a `TaskSignal` is passed to the `options.signal` argument **and** `options.priority` is **not set**.
 In this case the task will take its initial priority from the `signal` priority, and the priority can subsequently be changed by calling `TaskController.setPriority()` on the controller associated with the signal.

If the priority is not set with `options.priority` or by passing a `TaskSignal` to `options.signal` then it defaults to `user-visible` (and is by definition immutable).

 Note that a task that needs to be aborted must set `options.signal` to either `TaskSignal` or `AbortSignal`.
 However for a task with an immutable priority, `AbortSignal` more clearly indicates that the task priority cannot be changed using the signal.

### isInputPending()

The `isInputPending()` API is intended to help with task execution, enabling you to make task runners more efficient by yielding to the main thread only when the user is trying to interact with your app, rather than having to do it at arbitrary intervals.

Let's run through an example to demonstrate what we mean by this. When you have several tasks that are of roughly the same priority, it makes sense to break them down into separate functions to aid with maintenance, debugging, and many other reasons.

For example:

```js
function main() {
  a();
  b();
  c();
  d();
  e();
}
```

However, this kind of structure doesn't help with main thread blocking. Since all five of the tasks are being run inside one main function, the browser runs them all as a single task.

To handle this, we tend to run a function periodically to get the code to *yield to the main thread*. This means that our code is split into multiple tasks, between the execution of which the browser is given the opportunity to handle high-priority tasks such as updating the UI. A common pattern for this function uses `setTimeout()` to postpone execution into a separate task:

```js
function yield() {
  return new Promise((resolve) => {
    setTimeout(resolve, 0);
  });
}
```

This can be used inside a task runner pattern like so, to yield to the main thread after each task has been run:

```js
async function main() {
  // Create an array of functions to run
  const tasks = [a, b, c, d, e];

  // Loop over the tasks
  while (tasks.length > 0) {
    // Shift the first task off the tasks array
    const task = tasks.shift();

    // Run the task
    task();

    // Yield to the main thread
    await yield();
  }
}
```

This helps with the main thread-blocking problem, but it could be better — we can use `navigator.scheduling.isInputPending()` to run the `yield()` function only when the user is attempting to interact with the page:

```js
async function main() {
  // Create an array of functions to run
  const tasks = [a, b, c, d, e];

  while (tasks.length > 0) {
    // Yield to a pending user input
    if (navigator.scheduling.isInputPending()) {
      await yield();
    } else {
      // Shift the first task off the tasks array
      const task = tasks.shift();

      // Run the task
      task();
    }
  }
}
```

This allows you to avoid blocking the main thread when the user is actively interacting with the page, potentially providing a smoother user experience. However, by only yielding when necessary, we can continue running the current task when there are no user inputs to process. This also avoids tasks being placed at the back of the queue behind other non-essential browser-initiated tasks that were scheduled after the current one.

Interfaces
----------

`Scheduler`

 Contains the `postTask()` method for adding prioritized tasks to be scheduled.
 An instance of this interface is available on the `Window` or `WorkerGlobalScope` global objects (`this.scheduler`).

`Scheduling`

Contains the `isInputPending()` method for checking whether there are pending input events in the event queue.

`TaskController`

Supports both aborting a task and changing its priority.

`TaskSignal`

A signal object that allows you to abort a task and change its priority, if required, using a `TaskController` object.

`TaskPriorityChangeEvent`

The interface for the `prioritychange` event, which is sent when the priority for a task is changed.

**Note:** If the task priority never needs to be changed, you can use an `AbortController` and its associated `AbortSignal` instead of `TaskController` and `TaskSignal`.

### Extensions to other interfaces

`Navigator.scheduling`

This property is the entry point for using the `Scheduling.isInputPending()` method.

`scheduler`

 This property is the entry point for using the `Scheduler.postTask()` method.
 It is implemented on `Window` and `WorkerGlobalScope`, making an instance of `Scheduler` available through `this` in most scopes.

Task scheduling examples
------------------------

 Note that the examples below use `mylog()` to write to a text area.
 The code for the log area and method is generally hidden to not distract from more relevant code.
```

<textarea id="log" style="min-height: 20px; width: 95%"></textarea>
```

```js
// hidden logger code - simplifies example
let log = document.getElementById("log");
function mylog(text) {
  log.textContent += `${text}\n`;
}
```

### Feature checking

Check whether prioritized task scheduling is supported by testing for the `scheduler` property in the global "`this`" exposed to the current scope.

The code below prints "Feature: Supported" if the API is supported on this browser.
```

<textarea id="log" style="min-height: 20px; width: 95%"></textarea>
```

```
//hidden logger code - simplifies example
let log = document.getElementById("log");
function mylog(text) {
  log.textContent += `${text}\n`;
}
```

```js
// Check that feature is supported
if ("scheduler" in this) {
  mylog("Feature: Supported");
} else {
  mylog("Feature: NOT Supported");
}
```

### Basic usage

 Tasks are posted using `Scheduler.postTask()`, specifying a callback function (task) in the first argument, and an optional second argument that can be used to specify a task priority, signal, and/or delay.
 The method returns a `Promise` that resolves with the return value of the callback function, or rejects with either an abort error or an error thrown in the function.
```

<textarea id="log" style="min-height: 100px; width: 95%"></textarea>
```

```
let log = document.getElementById("log");
function mylog(text) {
  log.textContent += `${text}\n`;
}
```

 Because it returns a promise, `Scheduler.postTask()` can be chained with other promises.
 Below we show how to wait on the promise to resolve using `then`.
 This uses the default priority (`user-visible`).

```js
// A function that defines a task
function myTask() {
  return "Task 1: user-visible";
}

if ("scheduler" in this) {
  // Post task with default priority: 'user-visible' (no other options)
  // When the task resolves, Promise.then() logs the result.
  scheduler.postTask(myTask).then((taskResult) => mylog(`${taskResult}`));
}
```

 The method can also be used with `await` inside an async function.
 The code below shows how you might use this approach to wait on a `user-blocking` task.

```js
function myTask2() {
  return "Task 2: user-blocking";
}

async function runTask2() {
  const result = await scheduler.postTask(myTask2, {
    priority: "user-blocking",
  });
  mylog(result); // Logs 'Task 2: user-blocking'.
}
runTask2();
```

 In some cases you might not need to wait on completion at all.
 For simplicity many of the examples here simply log the result as the task executes.

```js
// A function that defines a task
function myTask3() {
  mylog("Task 3: user-visible");
}

if ("scheduler" in this) {
  // Post task and log result when it runs
  scheduler.postTask(myTask3);
}
```

 The log below shows the output of the three tasks above.
 Note that the order they are run depends on the priority first, and then the declaration order.

### Permanent priorities

Task priorities may be set using `priority` parameter in the optional second argument.
 Priorities that are set in this way are immutable (cannot be changed).

 Below we post two groups of three tasks, each member in reverse order of priority.
 The final task has the default priority.
 When run, each task simply logs it's expected order (we're not waiting on the result because we don't need to in order to show execution order).
```

let log = document.getElementById("log");
function mylog(text) {
  log.textContent += `${text}\n`;
}
```

```js
if ("scheduler" in this) {
  // three tasks, in reverse order of priority
  scheduler.postTask(() => mylog("bckg 1"), { priority: "background" });
  scheduler.postTask(() => mylog("usr-vis 1"), { priority: "user-visible" });
  scheduler.postTask(() => mylog("usr-blk 1"), { priority: "user-blocking" });

  // three more tasks, in reverse order of priority
  scheduler.postTask(() => mylog("bckg 2"), { priority: "background" });
  scheduler.postTask(() => mylog("usr-vis 2"), { priority: "user-visible" });
  scheduler.postTask(() => mylog("usr-blk 2"), { priority: "user-blocking" });

  // Task with default priority: user-visible
  scheduler.postTask(() => mylog("usr-vis 3 (default)"));
}
```

```
<textarea id="log" style="min-height: 120px; width: 95%"></textarea>
```

The output below shows that the tasks are executed in priority order, and then declaration order.

### Changing task priorities

Task priorities can also take their initial value from a `TaskSignal` passed to `postTask()` in the optional second argument.
 If set in this way, the priority of the task can then be changed using the controller associated with the signal.

**Note:** Setting and changing task priorities using a signal only works when the `options.priority` argument to `postTask()` is not set, and when the `options.signal` is a `TaskSignal` (and not an `AbortSignal`).

The code below first shows how to create a `TaskController`, setting the initial priority of its signal to `user-blocking` in the `TaskController()` constructor.

 The code then uses `addEventListener()` to add an event listener to the controller's signal (we could alternatively use the `TaskSignal.onprioritychange` property to add an event handler).
 The event handler uses `previousPriority` on the event to get the original priority and `TaskSignal.priority` on the event target to get the new/current priority.

The task is then posted, passing in the signal, and then we immediately change the priority to `background` by calling `TaskController.setPriority()` on the controller.
```

<textarea id="log" style="min-height: 70px; width: 95%"></textarea>
```

```
let log = document.getElementById("log");
function mylog(text) {
  log.textContent += `${text}\n`;
}
```

```js
if ("scheduler" in this) {
  // Create a TaskController, setting its signal priority to 'user-blocking'
  const controller = new TaskController({ priority: "user-blocking" });

  // Listen for 'prioritychange' events on the controller's signal.
  controller.signal.addEventListener("prioritychange", (event) => {
    const previousPriority = event.previousPriority;
    const newPriority = event.target.priority;
    mylog(`Priority changed from ${previousPriority} to ${newPriority}.`);
  });

  // Post task using the controller's signal.
  // The signal priority sets the initial priority of the task
  scheduler.postTask(() => mylog("Task 1"), { signal: controller.signal });

  // Change the priority to 'background' using the controller
  controller.setPriority("background");
}
```

 The output below demonstrates that the priority was successfully changed to `background` from `user-blocking`.
 Note that in this case the priority is changed before the task is executed, but it could equally have been changed while the task was running.

### Aborting tasks

 Tasks can be aborted using either `TaskController` and `AbortController`, in exactly the same way.
 The only difference is that you must use `TaskController` if you also want to set the task priority.
```

<textarea id="log" style="min-height: 50px; width: 95%"></textarea>
```

```
let log = document.getElementById("log");
function mylog(text) {
  log.textContent += `${text}\n`;
}
```

 The code below creates a controller and passes its signal to the task.
 The task is then immediately aborted.
 This causes the promise to be rejected with an `AbortError`, which is caught in the `catch` block and logged.
 Note that we could also have listened for the `abort` event fired on the `TaskSignal` or `AbortSignal` and logged the abort there.

```js
if ("scheduler" in this) {
  // Declare a TaskController with default priority
  const abortTaskController = new TaskController();
  // Post task passing the controller's signal
  scheduler
    .postTask(() => mylog("Task executing"), {
      signal: abortTaskController.signal,
    })
    .then((taskResult) => mylog(`${taskResult}`)) // This won't run!
    .catch((error) => mylog(`Error: ${error}`)); // Log the error

  // Abort the task
  abortTaskController.abort();
}
```

The log below shows the aborted task.

### Delaying tasks

 Tasks can be delayed by specifying an integer number of milliseconds in the `options.delay` parameter to `postTask()`.
 This effectively adds the task to the prioritized queue on a timeout, as might be created using `setTimeout()`.
 The `delay` is the minimum amount of time before the task is added to the scheduler; it may be longer.
```

<textarea id="log" style="min-height: 50px; width: 95%"></textarea>
```

```
let log = document.getElementById("log");
function mylog(text) {
  log.textContent += `${text}\n`;
}
```

The code below shows two tasks added (as arrow functions) with a delay.

```js
if ("scheduler" in this) {
  // Post task as arrow function with delay of 2 seconds
  scheduler
    .postTask(() => "Task delayed by 2000ms", { delay: 2000 })
    .then((taskResult) => mylog(`${taskResult}`));
  scheduler
    .postTask(() => "Next task should complete in about 2000ms", { delay: 1 })
    .then((taskResult) => mylog(`${taskResult}`));
}
```

 Refresh the page.
 Note that the second string appears in log after about 2 seconds.

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

| Specification |
| --- |
| Prioritized Task Scheduling # scheduler |
| Early detection of input events # the-scheduling-interface |

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

### api.Scheduler

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

### api.Scheduling

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

See also
--------

* Building a Faster Web Experience with the postTask Scheduler on the Airbnb blog (2021)
* Optimizing long tasks on web.dev (2022)


StereoPannerNode - Web APIs

StereoPannerNode
================

The `StereoPannerNode` interface of the Web Audio API represents a simple stereo panner node that can be used to pan an audio stream left or right. It is an `AudioNode` audio-processing module that positions an incoming audio stream in a stereo image using a low-cost equal-power panning algorithm.

The `pan` property takes a unitless value between `-1` (full left pan) and `1` (full right pan). This interface was introduced as a much simpler way to apply a simple panning effect than having to use a full `PannerNode`.

![The Stereo Panner Node moved the sound's position from the center of two speakers to the left.](/en-US/docs/Web/API/StereoPannerNode/stereopannernode.png)

EventTarget

AudioNode

StereoPannerNode

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"clamped-max"` |
| Channel count | `2` |
| Channel interpretation | `"speakers"` |

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

`StereoPannerNode()`

Creates a new instance of a `StereoPannerNode` object.

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

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

`StereoPannerNode.pan` Read only

An a-rate `AudioParam` representing the amount of panning to apply.

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

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

Example
-------

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

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

| Specification |
| --- |
| Web Audio API # stereopannernode |

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

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

See also
--------

* Using the Web Audio API


DeviceMotionEventRotationRate - Web APIs

DeviceMotionEventRotationRate
=============================

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

A **`DeviceMotionEventRotationRate`** interface of the Device Orientation Events provides information about the rate at which the device is rotating around all three axes.

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

`DeviceMotionEventRotationRate.alpha` Read only

The amount of rotation around the Z axis, in degrees per second.

`DeviceMotionEventRotationRate.beta` Read only

The amount of rotation around the X axis, in degrees per second.

`DeviceMotionEventRotationRate.gamma` Read only

The amount of rotation around the Y axis, in degrees per second.

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

| Specification |
| --- |
| DeviceOrientation Event Specification # devicemotioneventrotationrate |

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

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


MediaElementAudioSourceNode - Web APIs

MediaElementAudioSourceNode
===========================

The `MediaElementAudioSourceNode` interface represents an audio source consisting of an HTML `<audio>` or `<video>` element. It is an `AudioNode` that acts as an audio source.

A `MediaElementAudioSourceNode` has no inputs and exactly one output, and is created using the `AudioContext.createMediaElementSource()` method. The number of channels in the output equals the number of channels of the audio referenced by the `HTMLMediaElement` used in the creation of the node, or is 1 if the `HTMLMediaElement` has no audio.

EventTarget

AudioNode

MediaElementAudioSourceNode

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |
| Channel count | 2 (but note that `AudioNode.channelCount` is only used for up-mixing and down-mixing `AudioNode` inputs, and `MediaElementAudioSourceNode` doesn't have any input) |

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

`MediaElementAudioSourceNode()`

Creates a new `MediaElementAudioSourceNode` object instance.

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

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

`mediaElement` Read only

The `HTMLMediaElement` used when constructing this `MediaStreamAudioSourceNode`.

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

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

Example
-------

See `AudioContext.createMediaElementSource()` for example code.

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

| Specification |
| --- |
| Web Audio API # MediaElementAudioSourceNode |

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

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

See also
--------

* Using the Web Audio API


CSSFontPaletteValuesRule - Web APIs

CSSFontPaletteValuesRule
========================

The **`CSSFontPaletteValuesRule`** interface represents an `@font-palette-values` at-rule.

CSSRule

CSSFontPaletteValuesRuleInstance properties
-------------------

*Inherits properties from its ancestor `CSSRule`.*

`CSSFontPaletteValuesRule.name` Read only

A string with the name of the font palette.

`CSSFontPaletteValuesRule.fontFamily` Read only

A string indicating the font families on which the rule has to be applied.

`CSSFontPaletteValuesRule.basePalette` Read only

A string indicating the base palette associated with the rule.

`CSSFontPaletteValuesRule.overrideColors` Read only

A string indicating the colors of the base palette that are overwritten and the new colors.

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

*Inherits methods from its ancestor `CSSRule`.*

Examples
--------

### Read associated font family using CSSOM

This example first defines an `@import` and an `@font-palette-values` at-rule. Then it reads the `@font-palette-values` rule and displays its name. As these rules live in the last stylesheet added to the document, the palette will be the second `CSSRule` returned by the last stylesheet in the document (`document.styleSheets[document.styleSheets.length-1].cssRules`). So, `rules[1]` returns a `CSSFontPaletteValuesRule` object, from which we can access `fontFamily`.

#### HTML

```html
<pre id="log">The @font-palette-values at-rule font families:</pre>
```

#### CSS

```css
@import url(https://fonts.googleapis.com/css2?family=Bungee+Spice);

@font-palette-values --Alternate {
  font-family: "Bungee Spice";
  override-colors:
    0 #00ffbb,
    1 #007744;
}

.alternate {
  font-palette: --Alternate;
}
```

#### JavaScript

```js
const log = document.getElementById("log");

const rules = document.styleSheets[document.styleSheets.length - 1].cssRules;
const fontPaletteValuesRule = rules[1]; // aA CSSFontPaletteValuesRule interface
log.textContent += ` ${fontPaletteValuesRule.fontFamily}`;
```

#### Result

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

| Specification |
| --- |
| CSS Fonts Module Level 4 # om-fontpalettevalues |

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

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

See also
--------

* `@font-palette-values`


RTCSessionDescription - Web APIs

RTCSessionDescription
=====================

The **`RTCSessionDescription`** interface describes one end of a connection—or potential connection—and how it's configured. Each `RTCSessionDescription` consists of a description `type` indicating which part of the offer/answer negotiation process it describes and of the SDP descriptor of the session.

The process of negotiating a connection between two peers involves exchanging `RTCSessionDescription` objects back and forth, with each description suggesting one combination of connection configuration options that the sender of the description supports. Once the two peers agree upon a configuration for the connection, negotiation is complete.

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

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

`RTCSessionDescription.type` Read only

An enum describing the session description's type.

`RTCSessionDescription.sdp` Read only

A string containing the SDP describing the session.

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

*The `RTCSessionDescription` doesn't inherit any methods.*

`RTCSessionDescription()`
Deprecated

This constructor returns a new `RTCSessionDescription`. The parameter is a `RTCSessionDescriptionInit` dictionary containing the values to assign the two properties.

`RTCSessionDescription.toJSON()`

Returns a JSON description of the object. The values of both properties, `type` and `sdp`, are contained in the generated JSON.

Example
-------

```js
signalingChannel.onmessage = (evt) => {
  if (!pc) start(false);

  const message = JSON.parse(evt.data);
  if (message.sdp) {
    pc.setRemoteDescription(
      new RTCSessionDescription(message),
      () => {
        // if we received an offer, we need to answer
        if (pc.remoteDescription.type === "offer") {
          pc.createAnswer(localDescCreated, logError);
        }
      },
      logError,
    );
  } else {
    pc.addIceCandidate(
      new RTCIceCandidate(message.candidate),
      () => {},
      logError,
    );
  }
};
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # rtcsessiondescription-class |

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

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

See also
--------

* WebRTC
* `RTCPeerConnection.setLocalDescription()` and `RTCPeerConnection.setRemoteDescription()`


Window Management API - Web APIs

Window Management API
=====================

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

The **Window Management API** allows you to get detailed information on the displays connected to your device and more easily place windows on specific screens, paving the way towards more effective multi-screen applications.

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

Historically, we have used `Window.open()` to manage browser windows related to the current application — opening new windows, resizing and closing existing windows, etc. For example, to open a 400×300 window 50 pixels from the left and top of your screen:

```js
const myWindow = window.open(
  "https://example.com/",
  "myWindow",
  "left=50,top=50,width=400,height=300",
);
```

You can retrieve information about your screen from the `Window.screen` property, such as how much screen space you have available to place windows in.

However, the above features are limited. `Window.screen` only returns data about the primary screen, and not secondary displays available to a device. To move a window to a secondary display, you could use `Window.moveTo()`, but you'd have to guess what coordinates to use based on where it is placed in your setup relative to the primary display.

The Window Management API provides more robust, flexible window management. It allows you to query whether your display is extended with multiple screens and get information on each screen separately: windows can then be placed on each screen as desired. It also provides event handlers to allow you to respond to changes in the available screens, new fullscreen functionality to choose which screen to put into fullscreen mode (if any), and permissions functionality to control access to the API.

For details on how to use it, see Using the Window Management API.

**Note:** In modern browsers, a separate user gesture event is required for each `Window.open()` call, for security purposes. This prevents sites from spamming users with lots of windows. However, this poses an issue for multi-window applications. To work around this limitation, you can design your applications to open no more than one new window at once, reuse existing windows to display different pages, or advise users on how to update their browser settings to allow multiple windows.

### Use cases

The Window Management API is useful in cases such as:

* Multi-window graphics editors and audio processors that may wish to arrange editing tools and panels across different screens.
* Virtual trading desks that want to show market trends in multiple windows and put specific windows of interest in fullscreen mode.
* Slideshow apps that want to show speaker notes on the internal primary screen and the presentation on an external projector.
Permissions policy integration
------------------------------

The `window-management` Permissions-Policy can be used to control permission to use the Window Management API. Specifically:

* Usage of the `Window.getScreenDetails()` method. If blocked, its `Promise` will reject with a `NotAllowedError` exception.
* Querying the `Window.screen.isExtended` property. If blocked, it will always return `false`.

Developers can explicitly grant permission for an `<iframe>` to use Window Management via the `allow` attribute:

```html
<iframe src="3rd-party.example" allow="window-management"></iframe>
```

Interfaces
----------

`ScreenDetails` Secure context

Represents the details of all the screens available to the user's device.

`ScreenDetailed` Secure context

Represents detailed information about one specific screen available to the user's device.

### Extensions to other interfaces

The `Screen` `change` event Secure context

Fired on a specific screen when it changes in some way — for example available width or height, or orientation.

`Screen.isExtended` Secure context

A boolean property that returns `true` if the user's device has multiple screens, and `false` if not.

`Element.requestFullscreen()`, the `screen` option

Specifies on which screen you want to put the element in fullscreen mode.

`Window.getScreenDetails()` Secure context

Returns a `Promise` that fulfills with a `ScreenDetails` object instance.

Examples
--------

You can find full examples here:

* Basic multi-window learning environment (see the source code).
* Multi-window Platformer Game (see the source code).
* Elmer-inspired trading desk demo (see the source code).
* Window placement demo (see the source code).
Specifications
--------------

| Specification |
| --- |
| Window Management  |

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

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


XMLHttpRequestEventTarget - Web APIs

XMLHttpRequestEventTarget
=========================

`XMLHttpRequestEventTarget` is the interface that describes the event handlers shared on `XMLHttpRequest` and `XMLHttpRequestUpload`.

You don't use `XMLHttpRequestEventTarget` directly; instead you interact with the sub classes.

Inheritance for `XMLHttpRequest`
--------------------------------

EventTarget

XMLHttpRequestEventTarget

XMLHttpRequest
The following events are made available to `XMLHttpRequest`:

* `abort`
* `error`
* `load`
* `loadend`
* `loadstart`
* `progress`
* `readystatechange`
* `timeout`
Inheritance for `XMLHttpRequestUpload`
--------------------------------------

EventTarget

XMLHttpRequestEventTarget

XMLHttpRequestUpload
The following events are made available to `XMLHttpRequestUpload`:

* `abort`
* `error`
* `load`
* `loadend`
* `loadstart`
* `progress`
* `timeout`
Specifications
--------------

| Specification |
| --- |
| XMLHttpRequest Standard # xmlhttprequesteventtarget |

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

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

See also
--------

* `XMLHttpRequest`
* `XMLHttpRequestUpload`


RadioNodeList - Web APIs

RadioNodeList
=============

The **`RadioNodeList`** interface represents a collection of elements in a `<form>` or a `<fieldset>` element, returned by a call to `HTMLFormControlsCollection.namedItem()`.

NodeList

RadioNodeListInstance properties
-------------------

*The `RadioNodeList` interface inherits the properties of* `NodeList`.

`RadioNodeList.value`

If the underlying element collection contains radio buttons, the `value` property represents the checked radio button. On retrieving the `value` property, the `value` of the currently `checked` radio button is returned as a string. If the collection does not contain any radio buttons or none of the radio buttons in the collection is in `checked` state, the empty string is returned. On setting the `value` property, the first radio button input element whose `value` property is equal to the new value will be set to `checked`.

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

*The `RadioNodeList` interface inherits the methods of* `NodeList`.

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

| Specification |
| --- |
| HTML Standard # radionodelist |

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

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

See also
--------

* The `<form>`, `<fieldset>`, `<input>` elements.


RTCErrorEvent - Web APIs

RTCErrorEvent
=============

The WebRTC API's **`RTCErrorEvent`** interface represents an error sent to a WebRTC object. It's based on the standard `Event` interface, but adds RTC-specific information describing the error, as shown below.

Event

RTCErrorEventConstructor
-----------

`RTCErrorEvent()`

Creates and returns a new `RTCErrorEvent` object.

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

*In addition to the standard properties available on the `Event` interface, `RTCErrorEvent` also includes the following:*

`error` Read only

An `RTCError` object specifying the error which occurred; this object includes the type of error that occurred, information about where the error occurred (such as which line number in the SDP or what SCTP cause code was at issue).

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

*No additional methods are provided beyond any found on the parent interface, `Event`.*

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

There are other data types used for error events in WebRTC, as needed for errors with special information sharing requirements. The most common of these is probably `RTCPeerConnectionIceErrorEvent`, used by the `icecandidateerror` event, which signals an error that has occurred while gathering ICE candidates during connection negotiation.

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

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

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

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

See also
--------

* WebRTC API
* `RTCError`
* The `error` event occurs on the following interfaces: `RTCDataChannel` and `RTCDtlsTransport`
* `RTCPeerConnectionIceErrorEvent`


Magnetometer - Web APIs

Magnetometer
============

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

The **`Magnetometer`** interface of the Sensor APIs provides information about the magnetic field as detected by the device's primary magnetometer sensor.

To use this sensor, the user must grant permission to the `'magnetometer'` device sensor through the Permissions API. In addition, this feature may be blocked by a Permissions Policy set on your server.

EventTarget

Sensor

MagnetometerConstructor
-----------

`Magnetometer()`
Experimental

Creates a new `Magnetometer` object.

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

`Magnetometer.x` Read only
Experimental

Returns a double containing the magnetic field around the device's x axis.

`Magnetometer.y` Read only
Experimental

Returns a double containing the magnetic field around the device's y axis.

`Magnetometer.z` Read only
Experimental

Returns a double containing the magnetic field around the device's z axis.

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

*`Magnetometer` doesn't have own methods. However, it inherits methods from its parent interfaces, `Sensor` and `EventTarget`.*

Events
------

*`Magnetometer` doesn't have own events. However, it inherits events from its parent interface, `Sensor`.*

Example
-------

The magnetometer is typically read in the `reading` event callback. In the example below this occurs sixty times a second.

```js
let magSensor = new Magnetometer({ frequency: 60 });

magSensor.addEventListener("reading", (e) => {
  console.log(`Magnetic field along the X-axis ${magSensor.x}`);
  console.log(`Magnetic field along the Y-axis ${magSensor.y}`);
  console.log(`Magnetic field along the Z-axis ${magSensor.z}`);
});
magSensor.start();
```

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

| Specification |
| --- |
| Magnetometer # magnetometer-interface |

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

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


DataTransferItem - Web APIs

DataTransferItem
================

The **`DataTransferItem`** object represents one drag data item. During a *drag operation*, each `drag event` has a `dataTransfer` property which contains a `list` of drag data items. Each item in the list is a `DataTransferItem` object.

This interface has no constructor.

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

`DataTransferItem.kind` Read only

The *kind* of drag data item, `string` or `file`.

`DataTransferItem.type` Read only

The drag data item's type, typically a MIME type.

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

`DataTransferItem.getAsFile()`

Returns the `File` object associated with the drag data item (or null if the drag item is not a file).

`DataTransferItem.getAsFileSystemHandle()`
Experimental

Returns a `FileSystemFileHandle` if the dragged item is a file, or a `FileSystemDirectoryHandle` if the dragged item is a directory.

`DataTransferItem.getAsString()`

Invokes the specified callback with the drag data item string as its argument.

`DataTransferItem.webkitGetAsEntry()`

Returns an object based on `FileSystemEntry` representing the selected file's entry in its file system. This will generally be either a `FileSystemFileEntry` or `FileSystemDirectoryEntry` object.

Example
-------

All of this interface's methods and properties have their own reference page, and each reference page has an example of its usage.

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

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

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

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