WebTransport - Web APIs

WebTransport
============

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

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

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

The **`WebTransport`** interface of the WebTransport API provides functionality to enable a user agent to connect to an HTTP/3 server, initiate reliable and unreliable transport in either or both directions, and close the connection once it is no longer needed.

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

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

`WebTransport()`

Creates a new `WebTransport` object instance.

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

`closed` Read only

Returns a promise that resolves when the transport is closed.

`datagrams` Read only

Returns a `WebTransportDatagramDuplexStream` instance that can be used to send and receive datagrams.

`congestionControl` Read only
Experimental

Returns a string that indicates the application preference for either high throughput or low-latency when sending data.

`incomingBidirectionalStreams` Read only

Represents one or more bidirectional streams opened by the server. Returns a `ReadableStream` of `WebTransportBidirectionalStream` objects. Each one can be used to read data from the server and write data back to it.

`incomingUnidirectionalStreams` Read only

Represents one or more unidirectional streams opened by the server. Returns a `ReadableStream` of `WebTransportReceiveStream` objects. Each one can be used to read data from the server.

`ready` Read only

Returns a promise that resolves when the transport is ready to use.

`reliability` Read only
Experimental

Returns a string that indicates whether the connection supports reliable transports only, or whether it also supports unreliable transports (such as UDP).

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

`close()`

Closes an ongoing WebTransport session.

`createBidirectionalStream()`

Asynchronously opens a bidirectional stream (`WebTransportBidirectionalStream`) that can be used to read from and write to the server.

`createUnidirectionalStream()`

Asynchronously opens a unidirectional stream (`WritableStream`) that can be used to write to the server.

`getStats()`
Experimental

Asynchronously returns a `Promise` that fulfills with an object containing HTTP/3 connection statistics.

Examples
--------

 The example code below shows how you'd connect to an HTTP/3 server by passing its URL to the `WebTransport()` constructor.
 Note that the scheme needs to be HTTPS, and the port number needs to be explicitly specified.
 Once the `WebTransport.ready` promise fulfills, you can start using the connection.

```js
async function initTransport(url) {
  // Initialize transport connection
  const transport = new WebTransport(url);

  // The connection can be used once ready fulfills
  await transport.ready;
  return transport;
}
```

 You can respond to the connection closing by waiting for the `WebTransport.closed` promise to fulfill.
 Errors returned by `WebTransport` operations are of type `WebTransportError`, and contain additional data on top of the standard `DOMException` set.

 The `closeTransport()` method below shows a possible implementation.
 Within a `try...catch` block it uses `await` to wait for the `closed` promise to fulfill or reject, and then reports whether or not the connection closed intentionally or due to error.

```js
async function closeTransport(transport) {
  // Respond to connection closing
  try {
    await transport.closed;
    console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
  } catch (error) {
    console.error(`The HTTP/3 connection to ${url} closed due to ${error}.`);
  }
}
```

We might call the asynchronous functions above in their own asynchronous function, as shown below.

```js
// Use the transport
async function useTransport(url) {
  const transport = await initTransport(url);

  // Use the transport object to send and receive data
  // ...

  // When done, close the transport
  await closeTransport(transport);
}

const url = "https://example.com:4999/wt";
useTransport(url);
```

For other example code, see the individual property and method pages.

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

| Specification |
| --- |
| WebTransport # web-transport |

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

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

See also
--------

* Using WebTransport
* WebSockets API
* Streams API
* WebTransport over HTTP/3


AudioTrack - Web APIs

AudioTrack
==========

The **`AudioTrack`** interface represents a single audio track from one of the HTML media elements, `<audio>` or `<video>`.

The most common use for accessing an `AudioTrack` object is to toggle its `enabled` property in order to mute and unmute the track.

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

`enabled`

A Boolean value which controls whether or not the audio track's sound is enabled. Setting this value to `false` mutes the track's audio.

`id` Read only

A string which uniquely identifies the track within the media. This ID can be used to locate a specific track within an audio track list by calling `AudioTrackList.getTrackById()`. The ID can also be used as the fragment part of the URL if the media supports seeking by media fragment per the Media Fragments URI specification.

`kind` Read only

A string specifying the category into which the track falls. For example, the main audio track would have a `kind` of `"main"`.

`label` Read only

A string providing a human-readable label for the track. For example, an audio commentary track for a movie might have a `label` of `"Commentary with director John Q. Public and actors John Doe and Jane Eod."` This string is empty if no label is provided.

`language` Read only

A string specifying the audio track's primary language, or an empty string if unknown. The language is specified as a BCP 47 (RFC 5646) language code, such as `"en-US"` or `"pt-BR"`.

`sourceBuffer` Read only

The `SourceBuffer` that created the track. Returns null if the track was not created by a `SourceBuffer` or the `SourceBuffer` has been removed from the `MediaSource.sourceBuffers` attribute of its parent media source.

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

To get an `AudioTrack` for a given media element, use the element's `audioTracks` property, which returns an `AudioTrackList` object from which you can get the individual tracks contained in the media:

```js
const el = document.querySelector("video");
const tracks = el.audioTracks;
```

You can then access the media's individual tracks using either array syntax or functions such as `forEach()`.

This first example gets the first audio track on the media:

```js
const firstTrack = tracks[0];
```

The next example scans through all of the media's audio tracks, enabling any that are in the user's preferred language (taken from a variable `userLanguage`) and disabling any others.

```js
tracks.forEach((track) => {
  track.enabled = track.language === userLanguage;
});
```

The `language` is in standard (RFC 5646) format. For US English, this would be `"en-US"`, for example.

Example
-------

See `AudioTrack.label` for a simple example that shows how to get an array of track kinds and labels for a specified media element, filtered by kind.

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

| Specification |
| --- |
| HTML Standard # audiotrack |

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

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


RTCPeerConnectionStats - Web APIs

RTCPeerConnectionStats
======================

The **`RTCPeerConnectionStats`** dictionary of the WebRTC API provides information about the high level peer connection (`RTCPeerConnection`).

 In particular, it provides the number of unique data channels that have been opened, and the number of opened channels that have been closed.
 This allows the current number of open channels to be calculated.

These statistics can be obtained by iterating the `RTCStatsReport` returned by `RTCPeerConnection.getStats()` until you find a report with the `type` of `peer-connection`.

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

`dataChannelsOpened`

A positive integer value indicating the number of unique `RTCDataChannel` objects that have entered the `open` state during their lifetime.

`dataChannelsClosed`

 A positive integer value indicating the number of unique `RTCDataChannel` objects that have left the `open` state during their lifetime (channels that transition to `closing` or `closed` without ever being `open` are not counted in this number).
 A channel will leave the `open` state if either end of the connection or the underlying transport is closed.

### Common instance properties

The following properties are common to all WebRTC statistics objects.

`id`

A string that uniquely identifies the object that is being monitored to produce this set of statistics.

`timestamp`

A `DOMHighResTimeStamp` object indicating the time at which the sample was taken for this statistics object.

`type`

A string with the value `"peer-connection"`, indicating the type of statistics that the object contains.

Examples
--------

 This example shows a function to return the total number of open connections, or `null` if no statistics are provided.
 This might be called in a loop, similar to the approach used in `RTCPeerConnection.getStats()` example

 The function waits for the result of a call to `RTCPeerConnection.getStats()` and then iterates the returned `RTCStatsReport` to get just the stats of type `"peer-connection"`.
 It then returns the total number of open channels, or `null`, using the data in the report.

```js
async function numberOpenConnections (peerConnection) {
  const stats = await peerConnection.getStats();
  let peerConnectionStats = null;

  stats.forEach((report) => {
    if (report.type === "peer-connection") {
      peerConnectionStats = report;
      break;
    }
  });

result = (typeof peerConnectionStats.dataChannelsOpened === 'undefined' || typeof peerConnectionStats.dataChannelsClosed=== 'undefined') ? null : peerConnectionStats.dataChannelsOpened - peerConnectionStats.dataChannelsClosed;
return result
}
```

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstatstype-peer-connection |

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

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


PresentationConnectionAvailableEvent - Web APIs

PresentationConnectionAvailableEvent
====================================

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

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

The **`PresentationConnectionAvailableEvent`** interface of the Presentation API is fired on a `PresentationRequest` when a connection associated with the object is created.

A controlling user agent fires a trusted event named `connectionavailable` on a `PresentationRequest` when a connection associated with the object is created. It is fired at the `PresentationRequest` instance, using the `PresentationConnectionAvailableEvent` interface, with the `connection` attribute set to the `PresentationConnection` object that was created. The event is fired for each connection that is created for the controller, either by the controller calling `start()` or `reconnect()`, or by the controlling user agent creating a connection on the controller's behalf via `defaultRequest`.

Event

PresentationConnectionAvailableEventConstructor
-----------

`PresentationConnectionAvailableEvent()`
Experimental

Creates a new PresentationConnectionAvailableEvent.

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

`PresentationConnectionAvailableEvent.connection` Read only
Experimental

Returns a references to the `PresentationConnection` object that fired the event.

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

| Specification |
| --- |
| Presentation API # interface-presentationconnectionavailableevent |

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

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


XRTransientInputHitTestResult - Web APIs

XRTransientInputHitTestResult
=============================

**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 **`XRTransientInputHitTestResult`** interface of the WebXR Device API contains an array of results of a hit test for transient input, grouped by input source.

You can get an array of `XRHitTestResult` objects for a frame by calling `XRFrame.getHitTestResultsForTransientInput()`.

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

`XRTransientInputHitTestResult.inputSource` Read only
Experimental

Represents the `XRInputSource` that was used to compute the `results` array.

`XRTransientInputHitTestResult.results` Read only
Experimental

Represents an array of `XRHitTestResult` objects containing the hit test results for the input source, ordered by the distance along the ray used to perform the hit test, with the closest result at position 0.

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

None.

Examples
--------

### Accessing transient input hit test results

Two arrays are used to access transient input hit test results. First, you get an array of `XRTransientInputHitTestResult` objects by calling `XRFrame.getHitTestResultsForTransientInput()`. Second, to get to the actual `XRHitTestResult` objects for an input source, you dereference the `results` property on one of the `XRTransientInputHitTestResult` objects.

```js
// frame loop
function onXRFrame(time, xrFrame) {
  let hitTestResults = xrFrame.getHitTestResultsForTransientInput(
    transientHitTestSource,
  );

  hitTestResults.forEach((resultsPerInputSource) => {
    resultsPerInputSource.results.forEach((hitTest) => {
      // do something with the hit test
      hitTest.getPose(referenceSpace);
    });
  });
}
```

### Filtering input sources

The `inputSource` property allows you to filter hit test results by input source.

```js
// frame loop
function onXRFrame(time, xrFrame) {
  let hitTestResults = xrFrame.getHitTestResultsForTransientInput(
    transientHitTestSource,
  );

  hitTestResults.forEach((resultsPerInputSource) => {
    if (resultsPerInputSource.inputSource === myPreferredInputSource) {
      // act on hit test results from the preferred input source
    }
  });
}
```

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

| Specification |
| --- |
| WebXR Hit Test Module # xr-transient-input-hit-test-result-interface |

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

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

See also
--------

* `XRHitTestResult`
* `XRInputSource`


DocumentPictureInPicture - Web APIs

DocumentPictureInPicture
========================

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

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

The **`DocumentPictureInPicture`** interface of the Document Picture-in-Picture API is the entry point for creating and handling document picture-in-picture windows.

It is accessed via the `Window.documentPictureInPicture` property.

EventTarget

DocumentPictureInPictureInstance properties
-------------------

`window` Read only
Experimental

Returns a `Window` instance representing the browsing context inside the Picture-in-Picture window.

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

`requestWindow()`
Experimental

Opens the Picture-in-Picture window for the current main browsing context. Returns a `Promise` that fulfills with a `Window` instance representing the browsing context inside the Picture-in-Picture window.

Events
------

`enter`
Experimental

Fired when the Picture-in-Picture window is successfully opened.

Examples
--------

```js
const videoPlayer = document.getElementById("player");

// ...

// Open a Picture-in-Picture window.
const pipWindow = await window.documentPictureInPicture.requestWindow({
  width: videoPlayer.clientWidth,
  height: videoPlayer.clientHeight,
});

// ...
```

See Document Picture-in-Picture API Example for a full working demo (see the full source code also).

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

| Specification |
| --- |
| Document Picture-in-Picture Specification # documentpictureinpicture |

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

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

See also
--------

* Document Picture-in-Picture API
* Using the Document Picture-in-Picture API


GPURenderBundleEncoder - Web APIs

GPURenderBundleEncoder
======================

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

The **`GPURenderBundleEncoder`** interface of the WebGPU API is used to pre-record bundles of commands.

The command bundles are encoded by calling the methods of `GPURenderBundleEncoder`; once the desired commands have been encoded, they are recorded into a `GPURenderBundle` object instance using the `GPURenderBundleEncoder.finish()` method. These render bundles can then be reused across multiple render passes by passing the `GPURenderBundle` objects into `GPURenderPassEncoder.executeBundles()` calls.

In effect, this is like a partial render pass — `GPURenderBundleEncoder`s have all the same functionality available as `GPURenderPassEncoder`s, except that they can't begin and end occlusion queries, and can't set the scissor rect, viewport, blend constant, and stencil reference. The `GPURenderBundle` will inherit all these values from the `GPURenderPassEncoder` that executes it.

**Note:** Currently set vertex buffers, index buffers, bind groups, and pipeline are all cleared prior to executing a render bundle, and once the render bundle has finished executing.

Reusing pre-recoded commands can significantly improve app performance in situations where JavaScript draw call overhead is a bottleneck. Render bundles are most effective in situations where a batch of objects will be drawn the same way across multiple views or frames, with the only differences being the buffer content being used (such as updated matrix uniforms). A good example is VR rendering. Recording the rendering as a render bundle and then tweaking the view matrix and replaying it for each eye is a more efficient way to issue draw calls for both renderings of the scene.

A `GPURenderBundleEncoder` object instance is created via the `GPUDevice.createRenderBundleEncoder()` property.

**Note:** The methods of `GPURenderBundleEncoder` are functionally identical to their equivalents available on `GPURenderPassEncoder`, except for `GPURenderBundleEncoder.finish()`, which is similar in purpose to `GPUCommandEncoder.finish()`.

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

`label`
Experimental

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

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

`draw()`
Experimental

Draw primitives based on the vertex buffers provided by `setVertexBuffer()`.

`drawIndexed()`
Experimental

Draw indexed primitives based on the vertex and index buffers provided by `setVertexBuffer()` and `setIndexBuffer()`

`drawIndirect()`
Experimental

Draw primitives using parameters read from a `GPUBuffer`.

`drawIndexedIndirect()`
Experimental

Draw indexed primitives using parameters read from a `GPUBuffer`.

`finish()`
Experimental

Completes recording of the current render pass command sequence.

`insertDebugMarker()`
Experimental

Marks a specific point in a series of encoded commands with a label.

`popDebugGroup()`
Experimental

Ends a debug group, which is begun with a `pushDebugGroup()` call.

`pushDebugGroup()`
Experimental

Begins a debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a `popDebugGroup()` method is invoked.

`setBindGroup()`
Experimental

Sets the `GPUBindGroup` to use for subsequent render bundle commands, for a given index.

`setIndexBuffer()`
Experimental

Sets the current `GPUBuffer` that will provide index data for subsequent drawing commands.

`setPipeline()`
Experimental

Sets the `GPURenderPipeline` to use for this render bundle.

`setVertexBuffer()`
Experimental

Sets or unsets the current `GPUBuffer` that will provide vertex data for subsequent drawing commands.

Examples
--------

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

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

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

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

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

```js
// ...

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

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

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

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

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

// ...
```

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

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

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

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

See also
--------

* The WebGPU API


SVGSwitchElement - Web APIs

SVGSwitchElement
================

The **`SVGSwitchElement`** interface corresponds to the `<switch>` element.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGSwitchElementInstance properties
-------------------

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

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

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

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

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

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

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


InputDeviceInfo - Web APIs

InputDeviceInfo
===============

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

The **`InputDeviceInfo`** interface of the Media Capture and Streams API gives access to the capabilities of the input device that it represents.

`InputDeviceInfo` objects are returned by `MediaDevices.enumerateDevices()` if the returned device is an audio or video input device.

MediaDeviceInfo

InputDeviceInfoInstance properties
-------------------

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

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

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

`InputDeviceInfo.getCapabilities()`

Returns a `MediaTrackCapabilities` object describing the primary audio or video track of a device's `MediaStream`.

Examples
--------

The following example gets all media devices with `MediaDevices.enumerateDevices()`. If any of the devices are input devices then `console.log(device)` will print an `InputDeviceInfo` object to the console.

```js
navigator.mediaDevices.enumerateDevices().then((devices) => {
  devices.forEach((device) => {
    console.log(device); // an InputDeviceInfo object if the device is an input device, otherwise a MediaDeviceInfo object.
  });
});
```

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

| Specification |
| --- |
| Media Capture and Streams # dom-inputdeviceinfo |

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

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


IdentityProvider - Web APIs

IdentityProvider
================

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

The **`IdentityProvider`** interface of the Federated Credential Management (FedCM) API represents an identity provider (IdP) and provides access to related information.

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

`getUserInfo()`
Experimental

Returns information about a previously signed in user on their return to an IdP, which can be used to provide a personalized welcome message and sign-in button.

Examples
--------

```js
// Iframe displaying a page from the https://idp.example origin
const user_info = await IdentityProvider.getUserInfo({
  configUrl: "https://idp.example/fedcm.json",
  clientId: "client1234",
});

// IdentityProvider.getUserInfo() returns an array of user information.
if (user_info.length > 0) {
  // Returning accounts should be first, so the first account received
  // is guaranteed to be a returning account
  const name = user_info[0].name;
  const given_name = user_info[0].given_name;
  const display_name = given_name ? given_name : name;
  const picture = user_info[0].picture;
  const email = user_info[0].email;

  // ...

  // Render the personalized sign-in button using the information returned above
}
```

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

| Specification |
| --- |
| Federated Credential Management API # browser-api-identity-provider-interface |

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

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

See also
--------

* Federated Credential Management API on developer.chrome.com (2023)


Payment Handler API - Web APIs

Payment Handler 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 Payment Handler API provides a standardized set of functionality for web applications to directly handle payments, rather than having to be redirected to a separate site for payment handling.

When a merchant website initiates payment via the Payment Request API, the Payment Handler API handles discovery of applicable payment apps, presenting them as choices to the user, opening a payment handler window once a choice has been made to allow the user to enter their payment details, and handling the payment transaction with the payment app.

Communication with payment apps (authorization, passing of payment credentials) is handled via Service Workers.

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

On a merchant website, a payment request is initiated by the construction of a new `PaymentRequest` object:

```js
const request = new PaymentRequest(
  [
    {
      supportedMethods: "https://bobbucks.dev/pay",
    },
  ],
  {
    total: {
      label: "total",
      amount: { value: "10", currency: "USD" },
    },
  },
);
```

The `supportedMethods` property specifies a URL representing the payment method supported by the merchant. To use more than one payment method, you would specify them in an array of objects, like this:

```js
const request = new PaymentRequest(
  [
    {
      supportedMethods: "https://alicebucks.dev/pay",
    },
    {
      supportedMethods: "https://bobbucks.dev/pay",
    },
  ],
  {
    total: {
      label: "total",
      amount: { value: "10", currency: "USD" },
    },
  },
);
```

### Making payment apps available

In supporting browsers, the process starts by requesting a payment method manifest file from each URL. A payment method manifest is typically called something like `payment-manifest.json` (the exact name can be whatever you like), and should be structured like this:

```json
{
  "default\_applications": ["https://bobbucks.dev/manifest.json"],
  "supported\_origins": ["https://alicepay.friendsofalice.example"]
}
```

Given a payment method identifier like `https://bobbucks.dev/pay`, the browser:

1. Starts loading `https://bobbucks.dev/pay` and checks its HTTP headers.
    1. If a `Link` header is found with `rel="payment-method-manifest"`, then it downloads the payment method manifest at that location instead (see Optionally route the browser to find the payment method manifest in another location for details).
    2. Otherwise, parse the response body of `https://bobbucks.dev/pay` as the payment method manifest.
2. Parses the downloaded content as JSON with `default_applications` and `supported_origins` members.

These members have the following purposes:

* `default_applications` tells the browser where to find the default payment app that can use the BobBucks payment method if it doesn't already have one installed.
* `supported_origins` tells the browser what other payment apps are permitted to handle the BobBucks payment if needed. If they are already installed on the device, they will be presented to the user as alternative payment options alongside the default application.

From the payment method manifest, the browser gets the URL of the default payment apps' web app manifest files, which can be called whatever you like, and look something like this:

```json
{
  "name": "Pay with BobBucks",
  "short\_name": "BobBucks",
  "description": "This is an example of the Payment Handler API.",
  "icons": [
    {
      "src": "images/manifest/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "images/manifest/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "serviceworker": {
    "src": "service-worker.js",
    "scope": "/",
    "use\_cache": false
  },
  "start\_url": "/",
  "display": "standalone",
  "theme\_color": "#3f51b5",
  "background\_color": "#3f51b5",
  "related\_applications": [
    {
      "platform": "play",
      "id": "com.example.android.samplepay",
      "min\_version": "1",
      "fingerprints": [
        {
          "type": "sha256\_cert",
          "value": "4C:FC:14:C6:97:DE:66:4E:66:97:50:C0:24:CE:5F:27:00:92:EE:F3:7F:18:B3:DA:77:66:84:CD:9D:E9:D2:CB"
        }
      ]
    }
  ]
}
```

When the `PaymentRequest.show()` method is invoked by the merchant app in response to a user gesture, the browser uses the `name` and `icons` information found in each manifest to present the payment apps to the user in the browser-provided Payment Request UI.

* If there are multiple payment app options, a list of options is presented to the user for them to choose from. Selecting a payment app will start the payment flow, which causes the browser to Just-In-Time (JIT) install the web app if necessary, registering the service worker specified in the `serviceworker` member so it can handle the payment.
* If there is only one payment app option, the `PaymentRequest.show()` method will start the payment flow with this payment app, JIT-installing it if necessary, as described above. This is an optimization to avoid presenting the user with a list that contains only one payment app choice.

**Note:** If `prefer_related_applications` is set to `true` in the payment app manifest, the browser will launch the platform-specific payment app specified in `related_applications` to handle the payment (if it is available) instead of the web payment app.

See Serve a web app manifest for more details.

### Checking whether the payment app is ready to pay with

The Payment Request API's `PaymentRequest.canMakePayment()` method returns `true` if a payment app is available on the customer's device, meaning that a payment app that supports the payment method is discovered, and that the platform-specific payment app is installed, or the web-based payment app is ready to be registered.

```js
async function checkCanMakePayment() {
  // ...

  const canMakePayment = await request.canMakePayment();
  if (!canMakePayment) {
    // Fallback to other means of payment or hide the button.
  }
}
```

The Payment Handler API adds an additional mechanism to prepare for handling a payment. The `canmakepayment` event is fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls `new PaymentRequest()`. The service worker can then use the `CanMakePaymentEvent.respondWith()` method to respond appropriately:

```js
self.addEventListener("canmakepayment", (e) => {
  e.respondWith(
    new Promise((resolve, reject) => {
      someAppSpecificLogic()
        .then((result) => {
          resolve(result);
        })
        .catch((error) => {
          reject(error);
        });
    }),
  );
});
```

The promise returned by `respondWith()` resolves with a boolean to signal that it is ready to handle a payment request (`true`), or not (`false`).

### Handling the payment

After the `PaymentRequest.show()` method is invoked, a `paymentrequest` event is fired on the service worker of the payment app. This event is listened for inside the payment app's service worker to begin the next stage of the payment process.

```js
let payment_request_event;
let resolver;
let client;

// `self` is the global object in service worker
self.addEventListener("paymentrequest", async (e) => {
  if (payment_request_event) {
    // If there's an ongoing payment transaction, reject it.
    resolver.reject();
  }
  // Preserve the event for future use
  payment_request_event = e;

  // ...
});
```

When a `paymentrequest` event is received, the payment app can open a payment handler window by calling `PaymentRequestEvent.openWindow()`. The payment handler window will present the customers with a payment app interface where they can authenticate, choose shipping address and options, and authorize the payment.

When the payment has been handled, `PaymentRequestEvent.respondWith()` is used to pass the payment result back to the merchant website.

See Receive a payment request event from the merchant for more details of this stage.

### Managing payment app functionality

Once a payment app service worker is registered, you can use the service worker's `PaymentManager` instance (accessed via `ServiceWorkerRegistration.paymentManager`) to manage various aspects of the payment app's functionality.

For example:

```js
navigator.serviceWorker.register("serviceworker.js").then((registration) => {
  registration.paymentManager.userHint = "Card number should be 16 digits";

  registration.paymentManager
    .enableDelegations(["shippingAddress", "payerName"])
    .then(() => {
      // ...
    });

  // ...
});
```

* `PaymentManager.userHint` is used to provide a hint for the browser to display along with the payment app's name and icon in the Payment Handler UI.
* `PaymentManager.enableDelegations()` is used to delegate responsibility for providing various parts of the required payment information to the payment app rather than collecting it from the browser (for example, via autofill).
Interfaces
----------

`CanMakePaymentEvent`

The event object for the `canmakepayment` event, fired on a payment app's service worker when it has been successfully registered to signal that it is ready to handle payments.

`PaymentManager`

Used to manage various aspects of payment app functionality. Accessed via the `ServiceWorkerRegistration.paymentManager` property.

`PaymentRequestEvent`
Experimental

The event object for the `paymentrequest` event, fired on a payment app's service worker when a payment flow has been initiated on the merchant website via the `PaymentRequest.show()` method.

Extensions to other interfaces
------------------------------

`canmakepayment` event

Fired on a payment app's `ServiceWorkerGlobalScope` when it has been successfully registered, to signal that it is ready to handle payments.

`paymentrequest` event

Fired on a payment app's `ServiceWorkerGlobalScope` when a payment flow has been initiated on the merchant website via the `PaymentRequest.show()` method.

`ServiceWorkerRegistration.paymentManager`

Returns a payment app's `PaymentManager` instance, which is used to manage various payment app functionality.

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

| Specification |
| --- |
| Payment Handler API # the-paymentrequestevent |

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

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

See also
--------

* BobBucks sample payment app
* Web-based payment apps overview
* Setting up a payment method
* Life of a payment transaction
* Using the Payment Request API
* Payment processing concepts


SecurePaymentConfirmationRequest - Web APIs

SecurePaymentConfirmationRequest
================================

The **`SecurePaymentConfirmationRequest`** dictionary describes input to the Payment Request API when used to authenticate a user during an e-commerce transaction using SPC with Payment Request API.

An instance of this dictionary must be passed into the `PaymentRequest()` constructor as the value of the `data` field corresponding to a `supportedMethods` value of `"secure-payment-confirmation"`.

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

`challenge`

An `ArrayBuffer`, `TypedArray`, or `DataView` provided by the relying party's server and used as a cryptographic challenge. This value will be signed by the authenticator and the signature will be sent back as part of `AuthenticatorAttestationResponse.attestationObject`. This helps prevent replay attacks.

`credentialIds`

A list of `ArrayBuffer`, `TypedArray`, or `DataView`. These Credential IDs represent Web Authentication credentials that have been registered with the relying party for authenticating during a payment with the associated `instrument`.

`extensions` Optional

Any WebAuthn extensions that should be used for the passed credential(s). The caller does not need to specify the `payment` extension; this is added automatically.

`instrument`

The description of the instrument name and icon to display during registration and to be signed along with the transaction details. This is an object with the following properties:

`displayName`

A string containing the payment instrument's name, which will be displayed to the user.

`icon`

A string containing the URL of the payment instrument's icon.

`iconMustBeShown` Optional

A boolean value indicating whether the icon must be successfully fetched and shown for the request to succeed. Defaults to `true`.

`locale` Optional

An optional list of well-formed RFC 5646: Tags for Identifying Languages (also known as BCP 47) language tags, in descending order of priority, that identify the local preferences of the website. That is, this represents a language priority list RFC 4647: Matching of Language Tags, which the user agent can use to perform language negotiation and locale-affected formatting with the caller.

**Note:** The locale is distinct from language or direction metadata associated with specific input members, in that it represents the caller's requested localized experience rather than assertion about a specific string value. See SPC internationalization Considerations for more discussion.

`payeeName` Optional

A string that serves as the display name of the payee that this SPC call is for (e.g., the merchant). Optional, may be provided alongside or instead of `payeeOrigin`.

`payeeOrigin` Optional

A string that is the origin of the payee that this SPC call is for (e.g., the merchant). Optional, may be provided alongside or instead of `payeeName`.

`rpId`

A string that specifies the relying party's identifier (for example "login.example.org").

`showOptOut` Optional

A boolean indicating whether the user should be given a chance to opt-out during the transaction dialog UX. Defaults to `false`.

`timeout` Optional

The number of milliseconds before the request to sign the transaction details times out. At most 1 hour.

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

| Specification |
| --- |
| Secure Payment Confirmation # sctn-securepaymentconfirmationrequest-dictionary |


GPUSupportedFeatures - Web APIs

GPUSupportedFeatures
====================

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

The **`GPUSupportedFeatures`** interface of the WebGPU API is a `Set`-like object that describes additional functionality supported by a `GPUAdapter`.

The `GPUSupportedFeatures` object for the current adapter is accessed via the `GPUAdapter.features` property.

You should note that not all features will be available to WebGPU in all browsers that support it, even if the features are supported by the underlying hardware. This could be due to constraints in the underlying system, browser, or adapter. For example:

* The underlying system might not be able to guarantee exposure of a feature in a way that is compatible with a certain browser.
* The browser vendor might not have found a secure way to implement support for that feature, or might just not have gotten round to it yet.

If you are hoping to take advantage of a specific additional feature in a WebGPU app, thorough testing is advised.

Available features
------------------

We have not listed the exact set of additional features available to be used in WebGPU, as it will vary between implementations and physical devices, and will change over time. For a list, refer to the Feature Index in the specification.

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

The following properties are available to all read-only `Set`-like objects (the links below are to the `Set` global object reference page).

`size`
Experimental

Returns the number of values in the set.

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

The following methods are available to all read-only `Set`-like objects (the below links are to the `Set` global object reference page).

`has()`
Experimental

Returns a boolean asserting whether an element is present with the given value in the set or not.

`values()`
Experimental

Returns a new iterator object that yields the **values** for each element in the set in insertion order.

`keys()`
Experimental

An alias for `values()`.

`entries()`
Experimental

Returns a new iterator object that contains **an array of `[value, value]`** for each element in the set, in insertion order.

`forEach()`
Experimental

Calls a provided callback function once for each value present in the set, in insertion order.

Examples
--------

```js
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const adapterFeatures = adapter.features;

  // Return the size of the set
  console.log(adapterFeatures.size);

  // Check whether a feature is supported by the adapter
  console.log(adapterFeatures.has("texture-compression-astc"));

  // Iterate through all the set values using values()
  const valueIterator = adapterFeatures.values();
  for (const value of valueIterator) {
    console.log(value);
  }

  // Iterate through all the set values using keys()
  const keyIterator = adapterFeatures.keys();
  for (const value of keyIterator) {
    console.log(value);
  }

  // Iterate through all the set values using entries()
  const entryIterator = adapterFeatures.entries();
  for (const entry of entryIterator) {
    console.log(entry[0]);
  }

  // Iterate through all the set values using forEach()
  adapterFeatures.forEach((value) => {
    console.log(value);
  });

  //...
}
```

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

| Specification |
| --- |
| WebGPU # gpu-supportedfeatures |

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

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

See also
--------

* The WebGPU API


Canvas API - Web APIs

Canvas API
==========

The **Canvas API** provides a means for drawing graphics via JavaScript and the HTML `<canvas>` element. Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.

The Canvas API largely focuses on 2D graphics. The WebGL API, which also uses the `<canvas>` element, draws hardware-accelerated 2D and 3D graphics.

Basic example
-------------

This simple example draws a green rectangle onto a canvas.

### HTML

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

### JavaScript

The `Document.getElementById()` method gets a reference to the HTML `<canvas>` element. Next, the `HTMLCanvasElement.getContext()` method gets that element's context—the thing onto which the drawing will be rendered.

The actual drawing is done using the `CanvasRenderingContext2D` interface. The `fillStyle` property makes the rectangle green. The `fillRect()` method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall.

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "green";
ctx.fillRect(10, 10, 150, 100);
```

### Result

Reference
---------

* `HTMLCanvasElement`
* `CanvasRenderingContext2D`
* `CanvasGradient`
* `CanvasPattern`
* `ImageBitmap`
* `ImageData`
* `TextMetrics`
* `OffscreenCanvas`
* `Path2D`
Experimental
* `ImageBitmapRenderingContext`
Experimental

**Note:** The interfaces related to the `WebGLRenderingContext` are referenced under WebGL.

**Note:** `OffscreenCanvas` is also available in web workers.

`CanvasCaptureMediaStreamTrack` is a related interface.

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

Canvas tutorial

A comprehensive tutorial covering both the basic usage of the Canvas API and its advanced features.

HTML5 Canvas Deep Dive

A hands-on, book-length introduction to the Canvas API and WebGL.

Canvas Handbook

A handy reference for the Canvas API.

Manipulating video using canvas

Combining `<video>` and `<canvas>` to manipulate video data in real time.

Libraries
---------

The Canvas API is extremely powerful, but not always simple to use. The libraries listed below can make the creation of canvas-based projects faster and easier.

* EaselJS is an open-source canvas library that makes creating games, generative art, and other highly graphical experiences easy.
* Fabric.js is an open-source canvas library with SVG parsing capabilities.
* heatmap.js is an open-source library for creating canvas-based data heat maps.
* JavaScript InfoVis Toolkit creates interactive data visualizations.
* Konva.js is a 2D canvas library for desktop and mobile applications.
* p5.js has a full set of canvas drawing functionality for artists, designers, educators, and beginners.
* Paper.js is an open-source vector graphics scripting framework that runs on top of the HTML Canvas.
* Phaser is a fast, free and fun open source framework for Canvas and WebGL powered browser games.
* Pts.js is a library for creative coding and visualization in canvas and SVG.
* Rekapi is an animation key-framing API for Canvas.
* Scrawl-canvas is an open-source JavaScript library for creating and manipulating 2D canvas elements.
* The ZIM framework provides conveniences, components, and controls for coding creativity on the canvas — includes accessibility and hundreds of colorful tutorials.
* Sprig is a beginner-friendly, open-source, tile-based game development library that uses Canvas.

**Note:** See the WebGL API for 2D and 3D libraries that use WebGL.

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

| Specification |
| --- |
| HTML Standard # the-canvas-element |

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

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

See also
--------

* WebGL


SVGFEFuncAElement - Web APIs

SVGFEFuncAElement
=================

The **`SVGFEFuncAElement`** interface corresponds to the `<feFuncA>` element.

EventTarget

Node

Element

SVGElement

SVGComponentTransferFunctionElement

SVGFEFuncAElementInstance properties
-------------------

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

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

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

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

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

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

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

See also
--------

* `<feFuncA>`


Path2D - Web APIs

Path2D
======

The **`Path2D`** interface of the Canvas 2D API is used to declare a path that can then be used on a `CanvasRenderingContext2D` object. The path methods of the `CanvasRenderingContext2D` interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired.

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

`Path2D()`

`Path2D` constructor. Creates a new `Path2D` object.

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

`Path2D.addPath()`

Adds a path to the current path.

`Path2D.closePath()`

Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.

`Path2D.moveTo()`

Moves the starting point of a new sub-path to the (`x, y`) coordinates.

`Path2D.lineTo()`

Connects the last point in the subpath to the (`x, y`) coordinates with a straight line.

`Path2D.bezierCurveTo()`

Adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using `moveTo()` before creating the Bézier curve.

`Path2D.quadraticCurveTo()`

Adds a quadratic Bézier curve to the current path.

`Path2D.arc()`

Adds an arc to the path which is centered at (`x, y`) position with radius `r` starting at `startAngle` and ending at `endAngle` going in the given direction by `counterclockwise` (defaulting to clockwise).

`Path2D.arcTo()`

Adds a circular arc to the path with the given control points and radius, connected to the previous point by a straight line.

`Path2D.ellipse()`

Adds an elliptical arc to the path which is centered at (`x, y`) position with the radii `radiusX` and `radiusY` starting at `startAngle` and ending at `endAngle` going in the given direction by `counterclockwise` (defaulting to clockwise).

`Path2D.rect()`

Creates a path for a rectangle at position (`x, y`) with a size that is determined by `width` and `height`.

`Path2D.roundRect()`

Creates a path for a rounded rectangle at position (`x, y`) with a size that is determined by `width` and `height` and the radii of the circular arc to be used for the corners of the rectangle is determined by `radii`.

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

| Specification |
| --- |
| HTML Standard # path2d-objects |

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

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

See also
--------

* `CanvasRenderingContext2D`


BackgroundFetchRegistration - Web APIs

BackgroundFetchRegistration
===========================

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

The **`BackgroundFetchRegistration`** interface of the Background Fetch API represents an individual background fetch.

A `BackgroundFetchRegistration` instance is returned by the `BackgroundFetchManager.fetch()` or `BackgroundFetchManager.get()` methods, and therefore there has no constructor.

EventTarget

BackgroundFetchRegistrationInstance properties
-------------------

The following properties are available synchronously, as convenience properties copied from those in the `BackgroundFetchRegistration` instance.

`BackgroundFetchRegistration.id` Read only
Experimental

A string containing the background fetch's ID.

`BackgroundFetchRegistration.uploadTotal` Read only
Experimental

A `number` containing the total number of bytes to be uploaded.

`BackgroundFetchRegistration.uploaded` Read only
Experimental

A `number` containing the size in bytes successfully sent, initially `0`.

`BackgroundFetchRegistration.downloadTotal` Read only
Experimental

A `number` containing the total size in bytes of this download. This is the value set when the background fetch was registered, or `0`.

`BackgroundFetchRegistration.downloaded` Read only
Experimental

A `number` containing the size in bytes that has been downloaded, initially `0`.

`BackgroundFetchRegistration.result` Read only
Experimental

Returns an empty string initially, on completion either the string `"success"` or `"failure"`.

`BackgroundFetchRegistration.failureReason` Read only
Experimental

One of the following strings:

`""`

The background fetch has not completed, or was successful.

`"aborted"`

The operation was cancelled by the user, or `abort()` was called.

`"bad-status"`

A response had a not-ok status (a status outside the range 200-299).

`"fetch-error"`

A fetch failed for other reasons, for example CORS, or a network failure.

`"quota-exceeded"`

Storage quota was reached during the operation.

`"download-total-exceeded"`

The provided `downloadTotal` was exceeded. This value was set when the background fetch was registered.

`BackgroundFetchRegistration.recordsAvailable` Read only
Experimental

A `boolean` indicating whether the `recordsAvailable` flag is set.

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

`BackgroundFetchRegistration.abort()`
Experimental

Aborts the background fetch. Returns a `Promise` that resolves with `true` if the fetch was successfully aborted.

`BackgroundFetchRegistration.match()`
Experimental

Returns a single `BackgroundFetchRecord` object which is the first match for the arguments.

`BackgroundFetchRegistration.matchAll()`
Experimental

Returns a `Promise` that resolves with an array of `BackgroundFetchRecord` objects containing requests and responses.

Events
------

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

`progress`
Experimental

 Fired when there is a change to any of the following properties:
 `uploaded`,
 `downloaded`,
 `result` or
 `failureReason`.

Examples
--------

The following code creates a `BackGroundFetchRegistration` as `bgFetch`, with an `id` of `"my-fetch"`.

```js
navigator.serviceWorker.ready.then(async (swReg) => {
  const bgFetch = await swReg.backgroundFetch.fetch(
    "my-fetch",
    ["/ep-5.mp3", "ep-5-artwork.jpg"],
    {
      title: "Episode 5: Interesting things.",
      icons: [
        {
          sizes: "300x300",
          src: "/ep-5-icon.png",
          type: "image/png",
        },
      ],
      downloadTotal: 60 \* 1024 \* 1024,
    },
  );
});
```

Logging the `id` to the console returns `"my-fetch"`.

```js
console.log(bgFetch.id); // "my-fetch"
```

The `match()` method can be used to find a particular `BackgroundFetchRecord` from those that are part of the registration.

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

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

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

| Specification |
| --- |
| Background Fetch # background-fetch-registration |

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

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


structuredClone() global function - Web APIs

structuredClone() global function
=================================

Baseline 2022
-------------

Newly availableSince March 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback

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

The global **`structuredClone()`** method creates a deep clone of a given value using the structured clone algorithm.

 The method also allows transferable objects in the original value to be *transferred* rather than cloned to the new object.
 Transferred objects are detached from the original object and attached to the new object; they are no longer accessible in the original object.

Syntax
------

```js
structuredClone(value)
structuredClone(value, options)
```

### Parameters

`value`

 The object to be cloned.
 This can be any structured-cloneable type.

`options` Optional

An object with the following properties:

`transfer`

An array of transferable objects that will be moved rather than cloned to the returned object.

### Return value

The returned value is a deep copy of the original `value`.

### Exceptions

`DataCloneError` `DOMException`

Thrown if any part of the input value is not serializable.

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

 This function can be used to deep copy JavaScript values.
 It also supports circular references, as shown below:

```js
// Create an object with a value and a circular reference to itself.
const original = { name: "MDN" };
original.itself = original;

// Clone it
const clone = structuredClone(original);

console.assert(clone !== original); // the objects are not the same (not same identity)
console.assert(clone.name === "MDN"); // they do have the same values
console.assert(clone.itself === clone); // and the circular reference is preserved
```

### Transferring values

Transferable objects (only) can be transferred rather than duplicated in the cloned object, using the `transfer` property of the `options` parameter. Transferring makes the original object unusable.

**Note:** A scenario where this might be useful is when asynchronously validating some data in a buffer before saving it.
 To avoid the buffer being modified before the data is saved, you can clone the buffer and validate that data.
 If you also *transfer* the data, any attempts to modify the original buffer will fail, preventing its accidental misuse.

 The following code shows how to clone an array and transfer its underlying resources to the new object.
 On return, the original `uInt8Array.buffer` will be cleared.

```js
// 16MB = 1024 \* 1024 \* 16
const uInt8Array = Uint8Array.from({ length: 1024 \* 1024 \* 16 }, (v, i) => i);

const transferred = structuredClone(uInt8Array, {
  transfer: [uInt8Array.buffer],
});
console.log(uInt8Array.byteLength); // 0
```

 You can clone any number of objects and transfer any subset of those objects.
 For example, the code below would transfer `arrayBuffer1` from the passed in value, but not `arrayBuffer2`.

```js
const transferred = structuredClone(
  { x: { y: { z: arrayBuffer1, w: arrayBuffer2 } } },
  { transfer: [arrayBuffer1] },
);
```

Examples
--------

### Cloning an object

In this example, we clone an object with one member, which is an array. After cloning, changes to each object do not affect the other object.

```js
const mushrooms1 = {
  amanita: ["muscaria", "virosa"],
};

const mushrooms2 = structuredClone(mushrooms1);

mushrooms2.amanita.push("pantherina");
mushrooms1.amanita.pop();

console.log(mushrooms2.amanita); // ["muscaria", "virosa", "pantherina"]
console.log(mushrooms1.amanita); // ["muscaria"]
```

### Transferring an object

In this example we create an `ArrayBuffer` and then clone the object it is a member of, transferring the buffer. We can use the buffer in the cloned object, but if we try to use the original buffer we will get an exception.

```js
// Create an ArrayBuffer with a size in bytes
const buffer1 = new ArrayBuffer(16);

const object1 = {
  buffer: buffer1,
};

// Clone the object containing the buffer, and transfer it
const object2 = structuredClone(object1, { transfer: [buffer1] });

// Create an array from the cloned buffer
const int32View2 = new Int32Array(object2.buffer);
int32View2[0] = 42;
console.log(int32View2[0]);

// Creating an array from the original buffer throws a TypeError
const int32View1 = new Int32Array(object1.buffer);
```

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

| Specification |
| --- |
| HTML Standard # dom-structuredclone |

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

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

See also
--------

* A polyfill of `structuredClone` is available in `core-js`
* Structured clone algorithm
* Structured clone polyfill


ProgressEvent - Web APIs

ProgressEvent
=============

The **`ProgressEvent`** interface represents events measuring progress of an underlying process, like an HTTP request (for an `XMLHttpRequest`, or the loading of the underlying resource of an `<img>`, `<audio>`, `<video>`, `<style>` or `<link>`).

Event

ProgressEventConstructor
-----------

`ProgressEvent()`

Creates a `ProgressEvent` event with the given parameters.

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

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

`ProgressEvent.lengthComputable` Read only

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

`ProgressEvent.loaded` Read only

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

`ProgressEvent.total` Read only

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

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

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

Examples
--------

The following example adds a `ProgressEvent` to a new `XMLHTTPRequest` and uses it to display the status of the request.

```js
const progressBar = document.getElementById("p"),
  client = new XMLHttpRequest();
client.open("GET", "magical-unicorns");
client.onprogress = (pe) => {
  if (pe.lengthComputable) {
    progressBar.max = pe.total;
    progressBar.value = pe.loaded;
  }
};
client.onloadend = (pe) => {
  progressBar.value = pe.loaded;
};
client.send();
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # interface-progressevent |

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

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

See also
--------

* The `Event` base interface.


SVGComponentTransferFunctionElement - Web APIs

SVGComponentTransferFunctionElement
===================================

The **`SVGComponentTransferFunctionElement`** interface defines a base interface used by the component transfer function interfaces.

EventTarget

Node

Element

SVGElement

SVGComponentTransferFunctionElementConstants
---------

| Name | Value | Description |
| --- | --- | --- |
| `SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN` | 0 |
 The type is not one of predefined types. It is invalid to attempt to
 define a new value of this type or to attempt to switch an existing
 value to this type.
  |
| `SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY` | 1 | Corresponds to the value `identity`. |
| `SVG_FECOMPONENTTRANSFER_TYPE_TABLE` | 2 | Corresponds to the value `table`. |
| `SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE` | 3 | Corresponds to the value `discrete`. |
| `SVG_FECOMPONENTTRANSFER_TYPE_LINEAR` | 4 | Corresponds to the value `linear`. |
| `SVG_FECOMPONENTTRANSFER_TYPE_GAMMA` | 5 | Corresponds to the value `gamma`. |

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

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

`SVGComponentTransferFunctionElement.type` Read only

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

`SVGComponentTransferFunctionElement.tableValues` Read only

An `SVGAnimatedNumberList` corresponding to the `tableValues` attribute of the given element.

`SVGComponentTransferFunctionElement.slope` Read only

An `SVGAnimatedNumber` corresponding to the `slope` attribute of the given element.

`SVGComponentTransferFunctionElement.intercept` Read only

An `SVGAnimatedNumber` corresponding to the `intercept` attribute of the given element.

`SVGComponentTransferFunctionElement.amplitude` Read only

An `SVGAnimatedNumber` corresponding to the `amplitude` attribute of the given element.

`SVGComponentTransferFunctionElement.exponent` Read only

An `SVGAnimatedNumber` corresponding to the `exponent` attribute of the given element.

`SVGComponentTransferFunctionElement.offset` Read only

An `SVGAnimatedNumber` corresponding to the `offset` attribute of the given element.

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

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

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

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

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

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

See also
--------

* `SVGFEFuncAElement`
* `SVGFEFuncBElement`
* `SVGFEFuncGElement`
* `SVGFEFuncRElement`


FetchEvent - Web APIs

FetchEvent
==========

This is the event type for `fetch` events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the `event.respondWith()` method, which allows us to provide a response to this fetch.

Event

ExtendableEvent

FetchEventConstructor
-----------

`FetchEvent()`

Creates a new `FetchEvent` object. This constructor is not typically used. The browser creates these objects and provides them to `fetch` event callbacks.

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

*Inherits properties from its ancestor, `Event`*.

`FetchEvent.clientId` Read only

The `id` of the same-origin `client` that initiated the fetch.

`FetchEvent.handled` Read only

A promise that is pending while the event has not been handled, and fulfilled once it has.

`FetchEvent.preloadResponse` Read only

A `Promise` for a `Response`, or `undefined` if this fetch is not a navigation, or navigation preload is not enabled.

`FetchEvent.replacesClientId` Read only

The `id` of the `client` that is being replaced during a page navigation.

`FetchEvent.resultingClientId` Read only

The `id` of the `client` that replaces the previous client during a page navigation.

`FetchEvent.request` Read only

The `Request` the browser intends to make.

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

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

`FetchEvent.respondWith()`

Prevent the browser's default fetch handling, and provide (a promise for) a response yourself.

`ExtendableEvent.waitUntil()`

Extends the lifetime of the event. Used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching.

Examples
--------

 This fetch event uses the browser default for non-GET requests.
 For GET requests it tries to return a match in the cache, and falls back to the network. If it finds a match in the cache, it asynchronously updates the cache for next time.

```js
self.addEventListener("fetch", (event) => {
  // Let the browser do its default thing
  // for non-GET requests.
  if (event.request.method !== "GET") return;

  // Prevent the default, and handle the request ourselves.
  event.respondWith(
    (async () => {
      // Try to get the response from a cache.
      const cache = await caches.open("dynamic-v1");
      const cachedResponse = await cache.match(event.request);

      if (cachedResponse) {
        // If we found a match in the cache, return it, but also
        // update the entry in the cache in the background.
        event.waitUntil(cache.add(event.request));
        return cachedResponse;
      }

      // If we didn't find a match in the cache, use the network.
      return fetch(event.request);
    })(),
  );
});
```

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

| Specification |
| --- |
| Service Workers # fetchevent-interface |

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

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

See also
--------

* `fetch` event
* `Promise`
* Fetch API


HTMLBodyElement - Web APIs

HTMLBodyElement
===============

The **`HTMLBodyElement`** interface provides special properties (beyond those inherited from the regular `HTMLElement` interface) for manipulating `<body>` elements.

EventTarget

Node

Element

HTMLElement

HTMLBodyElementInstance properties
-------------------

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

`HTMLBodyElement.aLink`
Deprecated

A string that represents the color of active hyperlinks.

`HTMLBodyElement.background`
Deprecated

A string that represents the description of the location of the background image resource. Note that this is not an URI, though some older version of some browsers do expect it.

`HTMLBodyElement.bgColor`
Deprecated

A string that represents the background color for the document.

`HTMLBodyElement.link`
Deprecated

A string that represents the color of unvisited links.

`HTMLBodyElement.text`
Deprecated

A string that represents the foreground color of text.

`HTMLBodyElement.vLink`
Deprecated

A string that represents the color of visited links.

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

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

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

The `HTMLElement` events are inherited.

The following `Window` `onXYZ` event handler properties are also available as aliases targeting the `window` object. However, it is advised to listen to them on the `window` object directly rather than on `HTMLBodyElement`.

**Note:** Using `addEventListener()` on `HTMLBodyElement` will not work for the `onXYZ` event handlers listed below. Listen to the events on the `window` object instead.

`HTMLBodyElement.onafterprint`

Fired after the associated document has started printing or the print preview has been closed.

`HTMLBodyElement.onbeforeprint`

Fired when the associated document is about to be printed or previewed for printing.

`HTMLBodyElement.onbeforeunload`

Fired when the window, the document and its resources are about to be unloaded.

`HTMLBodyElement.ongamepadconnected`

Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.

`HTMLBodyElement.ongamepaddisconnected`

Fired when the browser detects that a gamepad has been disconnected.

`HTMLBodyElement.onhashchange`

Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol).

`HTMLBodyElement.onlanguagechange`

Fired when the user's preferred language changes.

`HTMLBodyElement.onmessage`

Fired when the window receives a message, for example from a call to `Window.postMessage()` from another browsing context.

`HTMLBodyElement.onmessageerror`

Fired when the window receives a message that can't be deserialized.

`HTMLBodyElement.onoffline`

Fired when the browser has lost access to the network and the value of `Navigator.onLine` switches to `false`.

`HTMLBodyElement.ononline`

Fired when the browser has gained access to the network and the value of `Navigator.onLine` switches to `true`.

`HTMLBodyElement.onpagehide`

Fired when the browser hides the current page in the process of presenting a different page from the session's history.

`HTMLBodyElement.onpageshow`

Fired when the browser displays the window's document due to navigation.

`HTMLBodyElement.onpopstate`

Fired when the active history entry changes while the user navigates the session history.

`HTMLBodyElement.onrejectionhandled`

Fired whenever a JavaScript `Promise` is rejected and the rejection has been handled.

`HTMLBodyElement.onstorage`

Fired when a storage area (`localStorage`) has been modified in the context of another document.

`HTMLBodyElement.onunhandledrejection`

Fired whenever a `Promise` is rejected but the rejection was not handled.

`HTMLBodyElement.onunload`

Fired when the document is being unloaded.

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

| Specification |
| --- |
| HTML Standard # htmlbodyelement |

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

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

See also
--------

* HTML element implementing this interface: `<body>`


CustomStateSet - Web APIs

CustomStateSet
==============

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

The **`CustomStateSet`** interface of the Document Object Model stores a list of states for an autonomous custom element, and allows states to be added and removed from the set.

The interface can be used to expose the internal states of a custom element, allowing them to be used in CSS selectors by code that uses the element.

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

`CustomStateSet.size`
Experimental

Returns the number of values in the `CustomStateSet`.

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

`CustomStateSet.add()`
Experimental

Adds a value to the set, first checking that the *value* is a `<dashed-ident>`.

`CustomStateSet.clear()`
Experimental

Removes all elements from the `CustomStateSet` object.

`CustomStateSet.delete()`
Experimental

Removes one value from the `CustomStateSet` object.

`CustomStateSet.entries()`
Experimental

Returns a new iterator with the values for each element in the `CustomStateSet` in insertion order.

`CustomStateSet.forEach()`
Experimental

Executes a provided function for each value in the `CustomStateSet` object.

`CustomStateSet.has()`
Experimental

Returns a `Boolean` asserting whether an element is present with the given value.

`CustomStateSet.keys()`
Experimental

An alias for `CustomStateSet.values()`.

`CustomStateSet.values()`
Experimental

Returns a new iterator object that yields the values for each element in the `CustomStateSet` object in insertion order.

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

 Built in HTML elements can have different *states*, such as "enabled" and "disabled, "checked" and "unchecked", "initial", "loading" and "ready".
 Some of these states are public and can be set or queried using properties/attributes, while others are effectively internal, and cannot be directly set.
 Whether external or internal, element states can generally be selected and styled using CSS pseudo-classes as selectors.

 The `CustomStateSet` allows developers to add and delete states for autonomous custom elements (but not elements derived from built-in elements).
 These states can then be used as custom state pseudo-class selectors in a similar way to the pseudo-classes for built-in elements.

### Setting custom element states

 To make the `CustomStateSet` available, a custom element must first call `HTMLElement.attachInternals()` in order to attach an `ElementInternals` object.
 `CustomStateSet` is then returned by `ElementInternals.states`.
 Note that `ElementInternals` cannot be attached to a custom element based on a built-in element, so this feature only works for autonomous custom elements (see github.com/whatwg/html/issues/5166).

 The `CustomStateSet` instance is a `Set`-like object that can hold an ordered set of state values.
 Each value is a dashed identifier, with the format: `--mystatename`.
 Identifiers can be added to the set or deleted.
 If an identifier is present in the set the particular state is `true`, while if it is removed the state is `false`.

Custom elements that have states with more than two values can represent them with multiple boolean states, only one of which is `true` (present in the `CustomStateSet`) at a time.

The states can be used within the custom element but are not directly accessible outside of the custom component.

### Interaction with CSS

 Developers can select a custom element with a specific state using its state *custom state pseudo-class*.
 The format of this pseudo-class is `:--mystatename`, where `--mystatename` is the state as defined in the element.

The custom state pseudo-class matches the custom element only if the state is `true` (i.e. if `--mystatename` is present in the `CustomStateSet`).

Examples
--------

### Labeled Checkbox

 This example, which is adapted from the specification, demonstrates a custom checkbox element that has an internal "checked" state.
 This is mapped to the `--checked` custom state, allowing styling to be applied using the `:--checked` custom state pseudo class.

#### JavaScript

 First we define our class `LabeledCheckbox` which extends from `HTMLElement`.
 In the constructor we call the `super()` method, leaving most of the "work" to `connectedCallback()`, which is invoked when a custom element is added to the page.
 The content of the element is defined using a `<style>` element to be the text `[]` or `[x]` followed by a label.
 What's noteworthy here is that the custom state pseudo class is used to select the text to display: `:host(:--checked)::`.
 After the example below, we'll cover what's happening in the snippet in more detail.

```js
class LabeledCheckbox extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    // Attach an ElementInternals to get states property
    this._internals = this.attachInternals();
    this.addEventListener("click", this.\_onClick.bind(this));

    const shadowRoot = this.attachShadow({ mode: "open" });
    shadowRoot.innerHTML = `<style>
 :host {
 display: block;
 }
 :host::before {
 content: '[ ]';
 white-space: pre;
 font-family: monospace;
 }
 :host(:--checked)::before { content: '[x]'; background: grey; }
 </style>
 <slot>Label</slot>`;
  }

  get checked() {
    return this._internals.states.has("--checked");
  }

  set checked(flag) {
    if (flag) {
      this._internals.states.add("--checked");
    } else {
      this._internals.states.delete("--checked");
    }
  }

  \_onClick(event) {
    // Toggle the 'checked' property when the element is clicked
    this.checked = !this.checked;
  }
}
```

In the `LabeledCheckbox` class:

* The `connectedCallback()` method uses ``this.attachInternals()`` to attach an ``ElementInternals`` object.
* In the `get checked()` and `set checked()` we use `ElementInternals.states` to get the `CustomStateSet`.
* The `set checked(flag)` method adds the `"--checked"` dashed identifier to the `CustomStateSet` if the flag is set and delete the identifier if the flag is `false`.
* The `get checked()` method just checks whether the `--checked` property is defined in the set.
* The property value is toggled when the element is clicked.

We then call the `define()` method on the object returned by `Window.customElements` in order to register the custom element:

```js
customElements.define("labeled-checkbox", LabeledCheckbox);
```

#### HTML

After registering the custom element we can use the element in HTML as shown:

```html
<labeled-checkbox>You need to check this</labeled-checkbox>
```

#### CSS

Finally we use the `:--checked` custom state pseudo class to select CSS for when the box is checked.

```css
labeled-checkbox {
  border: dashed red;
}
labeled-checkbox:--checked {
  border: solid;
}
```

#### Result

Click the element to see a different border being applied as the checkbox `checked` state is toggled.

### Non-boolean internal states

This example shows how to handle the case where the custom element has an internal property with multiple possible value.

 The custom element in this case has a `state` property with allowed values: "loading", "interactive" and "complete".
 To make this work, we map each value to its custom state and create code to ensure that only the dashed identifier corresponding to the internal state is set.
 You can see this in the implementation of the `set state()` method: we set the internal state, add the dashed identifier for the matching custom state to `CustomStateSet`, and remove the dashed identifiers associated with all the other values.

Most of the remaining code is similar to the example that demonstrates a single boolean state (we show different text for each state as the user toggles through them).

#### JavaScript

```js
class ManyStateElement extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    // Attach an ElementInternals to get states property
    this._internals = this.attachInternals();
    this.state = "loading";
    this.addEventListener("click", this.\_onClick.bind(this));

    const shadowRoot = this.attachShadow({ mode: "open" });
    shadowRoot.innerHTML = `<style>
 :host {
 display: block;
 font-family: monospace;
 }
 :host::before { content: '[ unknown ]'; white-space: pre; }
 :host(:--loading)::before { content: '[ loading ]' }
 :host(:--interactive)::before { content: '[ interactive ]' }
 :host(:--complete)::before { content: '[ complete ]' }
 </style>
 <slot>Click me</slot>`;
  }

  get state() {
    return this._state;
  }

  set state(stateName) {
    // Set internal state to passed value
    // Add dashed identifier matching state and delete others
    if (stateName == "loading") {
      this._state = "loading";
      this._internals.states.add("--loading");
      this._internals.states.delete("--interactive");
      this._internals.states.delete("--complete");
    } else if (stateName == "interactive") {
      this._state = "interactive";
      this._internals.states.delete("--loading");
      this._internals.states.add("--interactive");
      this._internals.states.delete("--complete");
    } else if (stateName == "complete") {
      this._state = "complete";
      this._internals.states.delete("--loading");
      this._internals.states.delete("--interactive");
      this._internals.states.add("--complete");
    }
  }

  \_onClick(event) {
    // Cycle the state when element clicked
    if (this.state === "loading") {
      this.state = "interactive";
    } else if (this.state === "interactive") {
      this.state = "complete";
    } else if (this.state === "complete") {
      this.state = "loading";
    }
  }
}

customElements.define("many-state-element", ManyStateElement);
```

#### HTML

 After registering the new element we add it to the HTML.
 This is similar to the example that demonstrates a single boolean state, except we don't specify a value and use the default value from the slot (`<slot>Click me</slot>`).

```html
<many-state-element></many-state-element>
```

#### CSS

 In the CSS we use the three custom state pseudo classes to select CSS for each of the internal state values: `:--loading`, `:--interactive`, `:--complete`.
 Note that the custom element code ensures that only one of these custom states can be defined at a time.

```css
many-state-element:--loading {
  border: dotted grey;
}
many-state-element:--interactive {
  border: dashed blue;
}
many-state-element:--complete {
  border: solid green;
}
```

#### Results

Click the element to see a different border being applied as the state changes.

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

| Specification |
| --- |
| Custom State Pseudo Class # customstateset |

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

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

See also
--------

Using custom elements


Location - Web APIs

Location
========

The **`Location`** interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Both the `Document` and `Window` interface have such a linked `Location`, accessible via `Document.location` and `Window.location` respectively.

Location anatomy
----------------

Hover over the URL segments below to highlight their meaning:
```

<span id="href" title="href"
 ><span id="origin" title="origin"
 ><span id="protocol" title="protocol">https:</span>//<span
 id="host"
 title="host"
 ><span id="hostname" title="hostname">example.org</span>:<span
 id="port"
 title="port"
 >8080</span
 ></span
 ></span
 ><span id="pathname" title="pathname">/foo/bar</span
 ><span id="search" title="search">?q=baz</span
 ><span id="hash" title="hash">#bang</span></span
>
```

```
html {
  display: table;
  width: 100%;
}

body {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  font-family: Georgia;
  font-size: 175%;
  line-height: 1em;
  white-space: nowrap;
}

[title] {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  line-height: 2em;
  cursor: pointer;
  color: gray;
}

[title]::before {
  content: attr(title);
  font-family: monospace;
  position: absolute;
  top: 100%;
  width: 100%;
  left: 50%;
  margin-left: -50%;
  font-size: 60%;
  line-height: 1.5;
  background: black;
}

[title]:hover::before,
:target::before {
  background: black;
  color: yellow;
}

[title] [title]::before {
  margin-top: 1.5em;
}

[title] [title] [title]::before {
  margin-top: 3em;
}

[title] [title] [title] [title]::before {
  margin-top: 4.5em;
}

[title]:hover,
:target {
  position: relative;
  z-index: 1;
  outline: 50em solid rgb(255 255 255 / 80%);
}
```

```
document.body.addEventListener("click", (event) => {
  event.preventDefault();

  window.location.hash = event.target.hasAttribute("id")
    ? `#${event.target.getAttribute("id")}`
    : "";
});
```

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

`Location.ancestorOrigins` Read only

A static `DOMStringList` containing, in reverse order, the origins of all ancestor browsing contexts of the document associated with the given `Location` object.

`Location.href`

A stringifier that returns a string containing the entire URL. If changed, the associated document navigates to the new page. It can be set from a different origin than the associated document.

`Location.protocol`

A string containing the protocol scheme of the URL, including the final `':'`.

`Location.host`

A string containing the host, that is the *hostname*, a `':'`, and the *port* of the URL.

`Location.hostname`

A string containing the domain of the URL.

`Location.port`

A string containing the port number of the URL.

`Location.pathname`

A string containing an initial `'/'` followed by the path of the URL, not including the query string or fragment.

`Location.search`

A string containing a `'?'` followed by the parameters or "querystring" of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring.

`Location.hash`

A string containing a `'#'` followed by the fragment identifier of the URL.

`Location.origin` Read only

Returns a string containing the canonical form of the origin of the specific location.

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

`Location.assign()`

Loads the resource at the URL provided in parameter.

`Location.reload()`

Reloads the current URL, like the Refresh button.

`Location.replace()`

Replaces the current resource with the one at the provided URL (redirects to the provided URL). The difference from the `assign()` method and setting the `href` property is that after using `replace()` the current page will not be saved in session `History`, meaning the user won't be able to use the *back* button to navigate to it.

`Location.toString()`

Returns a string containing the whole URL. It is a synonym for `Location.href`, though it can't be used to modify the value.

Examples
--------

```js
// location: https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
const loc = document.location;
console.log(loc.href); // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
console.log(loc.protocol); // https:
console.log(loc.host); // developer.mozilla.org:8080
console.log(loc.hostname); // developer.mozilla.org
console.log(loc.port); // 8080
console.log(loc.pathname); // /en-US/search
console.log(loc.search); // ?q=URL
console.log(loc.hash); // #search-results-close-container
console.log(loc.origin); // https://developer.mozilla.org:8080

location.assign("http://another.site"); // load another page
```

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

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

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

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

See also
--------

* Two `Location` properties: `Window.location` and `Document.location`.
* URL manipulation interfaces: `URL` and `URLSearchParams`.


BaseAudioContext - Web APIs

BaseAudioContext
================

The `BaseAudioContext` interface of the Web Audio API 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.

A `BaseAudioContext` can be a target of events, therefore it implements the `EventTarget` interface.

EventTarget

BaseAudioContextInstance properties
-------------------

`BaseAudioContext.audioWorklet` Read only  Secure context

Returns the `AudioWorklet` object, which can be used to create and manage `AudioNode`s in which JavaScript code implementing the `AudioWorkletProcessor` interface are run in the background to process audio data.

`BaseAudioContext.currentTime` Read only

Returns a double representing an ever-increasing hardware time in seconds used for scheduling. It starts at `0`.

`BaseAudioContext.destination` Read only

Returns an `AudioDestinationNode` representing the final destination of all audio in the context. It can be thought of as the audio-rendering device.

`BaseAudioContext.listener` Read only

Returns the `AudioListener` object, used for 3D spatialization.

`BaseAudioContext.sampleRate` Read only

Returns a float representing the sample rate (in samples per second) used by all nodes in this context. The sample-rate of an `AudioContext` cannot be changed.

`BaseAudioContext.state` Read only

Returns the current state of the `AudioContext`.

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

*Also implements methods from the interface* `EventTarget`.

`BaseAudioContext.createAnalyser()`

Creates an `AnalyserNode`, which can be used to expose audio time and frequency data and for example to create data visualizations.

`BaseAudioContext.createBiquadFilter()`

Creates a `BiquadFilterNode`, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc

`BaseAudioContext.createBuffer()`

Creates a new, empty `AudioBuffer` object, which can then be populated by data and played via an `AudioBufferSourceNode`.

`BaseAudioContext.createBufferSource()`

Creates an `AudioBufferSourceNode`, which can be used to play and manipulate audio data contained within an `AudioBuffer` object. `AudioBuffer`s are created using `AudioContext.createBuffer()` or returned by `AudioContext.decodeAudioData()` when it successfully decodes an audio track.

`BaseAudioContext.createConstantSource()`

Creates a `ConstantSourceNode` object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value.

`BaseAudioContext.createChannelMerger()`

Creates a `ChannelMergerNode`, which is used to combine channels from multiple audio streams into a single audio stream.

`BaseAudioContext.createChannelSplitter()`

Creates a `ChannelSplitterNode`, which is used to access the individual channels of an audio stream and process them separately.

`BaseAudioContext.createConvolver()`

Creates a `ConvolverNode`, which can be used to apply convolution effects to your audio graph, for example a reverberation effect.

`BaseAudioContext.createDelay()`

Creates a `DelayNode`, which is used to delay the incoming audio signal by a certain amount. This node is also useful to create feedback loops in a Web Audio API graph.

`BaseAudioContext.createDynamicsCompressor()`

Creates a `DynamicsCompressorNode`, which can be used to apply acoustic compression to an audio signal.

`BaseAudioContext.createGain()`

Creates a `GainNode`, which can be used to control the overall volume of the audio graph.

`BaseAudioContext.createIIRFilter()`

Creates an `IIRFilterNode`, which represents a second order filter configurable as several different common filter types.

`BaseAudioContext.createOscillator()`

Creates an `OscillatorNode`, a source representing a periodic waveform. It basically generates a tone.

`BaseAudioContext.createPanner()`

Creates a `PannerNode`, which is used to spatialize an incoming audio stream in 3D space.

`BaseAudioContext.createPeriodicWave()`

Creates a `PeriodicWave`, used to define a periodic waveform that can be used to determine the output of an `OscillatorNode`.

`BaseAudioContext.createScriptProcessor()`
Deprecated

Creates a `ScriptProcessorNode`, which can be used for direct audio processing via JavaScript.

`BaseAudioContext.createStereoPanner()`

Creates a `StereoPannerNode`, which can be used to apply stereo panning to an audio source.

`BaseAudioContext.createWaveShaper()`

Creates a `WaveShaperNode`, which is used to implement non-linear distortion effects.

`BaseAudioContext.decodeAudioData()`

Asynchronously decodes audio file data contained in an `ArrayBuffer`. In this case, the `ArrayBuffer` is usually loaded from an `XMLHttpRequest`'s `response` attribute after setting the `responseType` to `arraybuffer`. This method only works on complete files, not fragments of audio files.

Events
------

`statechange`

Fired when the `AudioContext`'s state changes due to the calling of one of the state change methods (`AudioContext.suspend`, `AudioContext.resume`, or `AudioContext.close`).

Examples
--------

Basic audio context declaration:

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

Cross browser variant:

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

const oscillatorNode = audioContext.createOscillator();
const gainNode = audioContext.createGain();
const finish = audioContext.destination;
```

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

| Specification |
| --- |
| Web Audio API # BaseAudioContext |

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

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

See also
--------

* Using the Web Audio API
* `AudioContext`
* `OfflineAudioContext`


Scheduling - Web APIs

Scheduling
==========

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

The **`Scheduling`** object provides methods and properties to control scheduling tasks within the current document.

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

`isInputPending()`
Experimental

Returns a boolean that indicates whether there are pending input events in the event queue, meaning that the user is attempting to interact with the page.

Example
-------

See the `Scheduling.isInputPending()` page for a full example.

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

| Specification |
| --- |
| Early detection of input events # the-scheduling-interface |

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

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

See also
--------

* Faster input events with Facebook's first browser API contribution on engineering.fb.com (2019)
* Better JS scheduling with isInputPending() on developer.chrome.com (2020)
* Optimizing long tasks on web.dev (2022)