Touch - Web APIs

Touch
=====

The **`Touch`** interface represents a single contact point on a touch-sensitive device. The contact point is commonly a finger or stylus and the device may be a touchscreen or trackpad.

The `Touch.radiusX`, `Touch.radiusY`, and `Touch.rotationAngle` describe the area of contact between the user and the screen, the *touch area*. This can be helpful when dealing with imprecise pointing devices such as fingers. These values are set to describe an ellipse that as closely as possible matches the entire area of contact (such as the user's fingertip).

**Note:** Many of the properties' values are hardware-dependent; for example, if the device doesn't have a way to detect the amount of pressure placed on the surface, the `force` value will always be 0. This may also be the case for `radiusX` and `radiusY`; if the hardware reports only a single point, these values will be 1.

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

`Touch()`

Creates a Touch object.

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

*This interface has no parent, and doesn't inherit or implement other properties.*

### Basic properties

`Touch.identifier` Read only

Returns a unique identifier for this `Touch` object. A given touch point (say, by a finger) will have the same identifier for the duration of its movement around the surface. This lets you ensure that you're tracking the same touch all the time.

`Touch.screenX` Read only

Returns the X coordinate of the touch point relative to the left edge of the screen.

`Touch.screenY` Read only

Returns the Y coordinate of the touch point relative to the top edge of the screen.

`Touch.clientX` Read only

Returns the X coordinate of the touch point relative to the left edge of the browser viewport, not including any scroll offset.

`Touch.clientY` Read only

Returns the Y coordinate of the touch point relative to the top edge of the browser viewport, not including any scroll offset.

`Touch.pageX` Read only

Returns the X coordinate of the touch point relative to the left edge of the document. Unlike `clientX`, this value includes the horizontal scroll offset, if any.

`Touch.pageY` Read only

Returns the Y coordinate of the touch point relative to the top of the document. Unlike `clientY,` this value includes the vertical scroll offset, if any.

`Touch.target` Read only

Returns the `Element` on which the touch point started when it was first placed on the surface, even if the touch point has since moved outside the interactive area of that element or even been removed from the document.

### Touch area

`Touch.radiusX` Read only

Returns the X radius of the ellipse that most closely circumscribes the area of contact with the screen. The value is in pixels of the same scale as `screenX`.

`Touch.radiusY` Read only

Returns the Y radius of the ellipse that most closely circumscribes the area of contact with the screen. The value is in pixels of the same scale as `screenY`.

`Touch.rotationAngle` Read only

Returns the angle (in degrees) that the ellipse described by radiusX and radiusY must be rotated, clockwise, to most accurately cover the area of contact between the user and the surface.

`Touch.force` Read only

Returns the amount of pressure being applied to the surface by the user, as a `float` between `0.0` (no pressure) and `1.0` (maximum pressure).

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

*This interface has no methods and no parent, and doesn't inherit or implement any methods.*

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

| Specification |
| --- |
| Touch Events # touch-interface |

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

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

See also
--------

* Touch events
* `Document.createTouch()`


BluetoothDevice - Web APIs

BluetoothDevice
===============

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

 The BluetoothDevice interface of the Web Bluetooth API represents a Bluetooth device inside a particular script execution
 environment.

EventTarget

BluetoothDeviceInstance properties
-------------------

`BluetoothDevice.id`
Experimental
 Read only

A string that uniquely identifies a device.

`BluetoothDevice.name`
Experimental
 Read only

A string that provides a human-readable name for the device.

`BluetoothDevice.gatt`
Experimental
 Read only

A reference to the device's `BluetoothRemoteGATTServer`.

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

`BluetoothDevice.watchAdvertisements()`
Experimental

 A `Promise` that resolves to `undefined` or is rejected with
 an error if advertisements can't be shown for any reason.

`BluetoothDevice.forget()`
Experimental

Provides a way for the page to revoke access to a device the user has granted access to.

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

| Specification |
| --- |
| Web Bluetooth # bluetoothdevice-interface |

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

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


MediaTrackConstraints - Web APIs

MediaTrackConstraints
=====================

The **`MediaTrackConstraints`** dictionary is used to describe a set of capabilities and the value or values each can take on. A constraints dictionary is passed into `applyConstraints()` to allow a script to establish a set of exact (required) values or ranges and/or preferred values or ranges of values for the track, and the most recently-requested set of custom constraints can be retrieved by calling `getConstraints()`.

Constraints
-----------

The following types are used to specify a constraint for a property. They allow you to specify one or more `exact` values from which one must be the parameter's value, or a set of `ideal` values which should be used if possible. You can also specify a single value (or an array of values) which the user agent will do its best to match once all more stringent constraints have been applied.

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

**Note:** `min` and `exact` values are not permitted in constraints used in `MediaDevices.getDisplayMedia()` calls — they produce a `TypeError` — but they are allowed in constraints used in `MediaStreamTrack.applyConstraints()` calls.

### ConstrainBoolean

The `ConstrainBoolean` constraint type is used to specify a constraint for a property whose value is a Boolean value. Its value may either be set to a Boolean (`true` or `false`) or an object containing the following properties:

`exact`

A Boolean which must be the value of the property. If the property can't be set to this value, matching will fail.

`ideal`

A Boolean specifying an ideal value for the property. If possible, this value will be used, but if it's not possible, the user agent will use the closest possible match.

### ConstrainDouble

The `ConstrainDouble` constraint type is used to specify a constraint for a property whose value is a double-precision floating-point number. Its value may either be set to a number or an object containing the following properties:

`max`

A decimal number specifying the largest permissible value of the property it describes. If the value cannot remain equal to or less than this value, matching will fail.

`min`

A decimal number specifying the smallest permissible value of the property it describes. If the value cannot remain equal to or greater than this value, matching will fail.

`exact`

A decimal number specifying a specific, required, value the property must have to be considered acceptable.

`ideal`

A decimal number specifying an ideal value for the property. If possible, this value will be used, but if it's not possible, the user agent will use the closest possible match.

### ConstrainDOMString

The `ConstrainDOMString` constraint type is used to specify a constraint for a property whose value is a string. Its value may either be set to a string, an array of strings, or an object containing the following properties:

`exact`

A string or an array of strings, one of which must be the value of the property. If the property can't be set to one of the listed values, matching will fail.

`ideal`

A string or an array of strings, specifying ideal values for the property. If possible, one of the listed values will be used, but if it's not possible, the user agent will use the closest possible match.

### ConstrainULong

The `ConstrainULong` constraint type is used to specify a constraint for a property whose value is an integer. Its value may either be set to a number or an object containing the following properties:

`max`

An integer specifying the largest permissible value of the property it describes. If the value cannot remain equal to or less than this value, matching will fail.

`min`

An integer specifying the smallest permissible value of the property it describes. If the value cannot remain equal to or greater than this value, matching will fail.

`exact`

An integer specifying a specific, required, value the property must have to be considered acceptable.

`ideal`

An integer specifying an ideal value for the property. If possible, this value will be used, but if it's not possible, the user agent will use the closest possible match.

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

Some combination—but not necessarily all—of the following properties will exist on the object. This may be because a given browser doesn't support the property, or because it doesn't apply. For example, because RTP doesn't provide some of these values during negotiation of a WebRTC connection, a track associated with a `RTCPeerConnection` will not include certain values, such as `facingMode` or `groupId`.

### Instance properties of all media tracks

`deviceId`

A `ConstrainDOMString` object specifying a device ID or an array of device IDs which are acceptable and/or required.

`groupId`

A `ConstrainDOMString` object specifying a group ID or an array of group IDs which are acceptable and/or required.

### Instance properties of audio tracks

`autoGainControl`

A `ConstrainBoolean` object which specifies whether automatic gain control is preferred and/or required.

`channelCount`

A `ConstrainULong` specifying the channel count or range of channel counts which are acceptable and/or required.

`echoCancellation`

A `ConstrainBoolean` object specifying whether or not echo cancellation is preferred and/or required.

`latency`

A `ConstrainDouble` specifying the latency or range of latencies which are acceptable and/or required.

`noiseSuppression`

A `ConstrainBoolean` which specifies whether noise suppression is preferred and/or required.

`sampleRate`

A `ConstrainULong` specifying the sample rate or range of sample rates which are acceptable and/or required.

`sampleSize`

A `ConstrainULong` specifying the sample size or range of sample sizes which are acceptable and/or required.

`volume`
Deprecated

Non-standard

A `ConstrainDouble` specifying the volume or range of volumes which are acceptable and/or required.

### Instance properties of image tracks

whiteBalanceMode

A `String` specifying one of `"none"`, `"manual"`, `"single-shot"`, or `"continuous"`.

exposureMode

A `String` specifying one of `"none"`, `"manual"`, `"single-shot"`, or `"continuous"`.

focusMode

A `String` specifying one of `"none"`, `"manual"`, `"single-shot"`, or `"continuous"`.

pointsOfInterest

The pixel coordinates on the sensor of one or more points of interest. This is either an object in the form { x:*value*, y:*value* } or an array of such objects, where *value* is a double-precision integer.

exposureCompensation

A `ConstrainDouble` (a double-precision integer) specifying f-stop adjustment by up to ±3.

colorTemperature

A `ConstrainDouble` (a double-precision integer) specifying a desired color temperature in degrees kelvin.

iso

A `ConstrainDouble` (a double-precision integer) specifying a desired iso setting.

brightness

A `ConstrainDouble` (a double-precision integer) specifying a desired brightness setting.

contrast

A `ConstrainDouble` (a double-precision integer) specifying the degree of difference between light and dark.

saturation

A `ConstrainDouble` (a double-precision integer) specifying the degree of color intensity.

sharpness

A `ConstrainDouble` (a double-precision integer) specifying the intensity of edges.

focusDistance

A `ConstrainDouble` (a double-precision integer) specifying distance to a focused object.

zoom

A `ConstrainDouble` (a double-precision integer) specifying the desired focal length.

torch

A boolean value defining whether the fill light is continuously connected, meaning it stays on as long as the track is active.

### Instance properties of video tracks

`aspectRatio`

A `ConstrainDouble` specifying the video aspect ratio or range of aspect ratios which are acceptable and/or required.

`facingMode`

A `ConstrainDOMString` object specifying a facing or an array of facings which are acceptable and/or required.

`frameRate`

A `ConstrainDouble` specifying the frame rate or range of frame rates which are acceptable and/or required.

`height`

A `ConstrainULong` specifying the video height or range of heights which are acceptable and/or required.

`width`

A `ConstrainULong` specifying the video width or range of widths which are acceptable and/or required.

resizeMode

A `ConstrainDOMString` object specifying a mode or an array of modes the UA can use to derive the resolution of a video track. Allowed values are `none` and `crop-and-scale`. `none` means that the user agent uses the resolution provided by the camera, its driver or the OS. `crop-and-scale` means that the user agent can use cropping and downscaling on the camera output in order to satisfy other constraints that affect the resolution.

### Instance properties of shared screen tracks

These constraints apply to the `video` property of the object passed into `getDisplayMedia()` to obtain a stream for screen sharing.

`displaySurface`

A `ConstrainDOMString` which specifies the types of display surface that may be selected by the user. This may be a single one of the following strings, or a list of them to allow multiple source surfaces:

`browser`

The stream contains the contents of a single browser tab selected by the user.

`monitor`

The stream's video track contains the entire contents of one or more of the user's screens.

`window`

The stream contains a single window selected by the user for sharing.

`logicalSurface`

A `ConstrainBoolean` value which may contain a single Boolean value or a set of them, indicating whether or not to allow the user to choose source surfaces which do not directly correspond to display areas. These may include backing buffers for windows to allow capture of window contents that are hidden by other windows in front of them, or buffers containing larger documents that need to be scrolled through to see the entire contents in their windows.

`suppressLocalAudioPlayback`
Experimental

A `ConstrainBoolean` value describing the requested or mandatory constraints placed upon the value of the `suppressLocalAudioPlayback` constrainable property. This property controls whether the audio playing in a tab will continue to be played out of a user's local speakers when the tab is captured.

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

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

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

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

See also
--------

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


Speculation Rules API - Web APIs

Speculation Rules API
=====================

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

The **Speculation Rules API** is designed to improve performance for future navigations. It targets document URLs rather than specific resource files, and so makes sense for multi-page applications (MPAs) rather than single-page applications (SPAs).

The Speculation Rules API provides an alternative to the widely-available `<link rel="prefetch">` feature and is designed to supersede the Chrome-only deprecated `<link rel="prerender">` feature. It provides many improvements over these technologies, along with a more expressive, configurable syntax for specifying which documents should be prefetched or prerendered.

**Note:** The Speculation Rules API doesn't handle subresource prefetches; for that you'll need to use `<link rel="prefetch">`.

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

Speculation rules are specified inside `<script type="speculationrules"> ... </script>`. The rules are specified as a JSON structure.

For example:

```html
<script type="speculationrules">
 {
 "prerender": [
 {
 "source": "list",
 "urls": ["extra.html", "extra2.html"]
 }
 ],
 "prefetch": [
 {
 "source": "list",
 "urls": ["next.html", "next2.html"],
 "requires": ["anonymous-client-ip-when-cross-origin"],
 "referrer\_policy": "no-referrer"
 }
 ]
 }
</script>
```

You specify a different array to contain the rules for each speculative loading type (for example `"prerender"` or `"prefetch"`). Each rule is contained in an object that specifies for example a list of resources to be fetched, plus options such as an explicit `Referrer-Policy` setting for each rule. Note that prerendered URLs are also prefetched.

See `<script type="speculationrules">` for a full explanation of the available syntax.

**Note:** As speculation rules use a `<script>` element, they need to be explicitly allowed in the `Content-Security-Policy` `script-src` directive if the site includes it. This is done by adding the `'inline-speculation-rules'` source along with a hash- or nonce-source.

### Using prefetching

Including `prefetch` rules inside `<script type=speculationrules> ... </script>` will cause supporting browsers to download the response body of the referenced pages, but none of the subresources referenced by the page. When a prefetched page is navigated to, it will render much more quickly than if it were not prefetched.

The results are kept in a per-document in-memory cache. Any cached prefetches are discarded when you navigate away from the current page, except of course a prefetched document that you then navigate to.

This means that if you prefetch something the user doesn't navigate to, it is generally a waste of resources, although the result may populate the HTTP cache if headers allow. That said, the upfront cost of a prefetch is much smaller than the upfront cost of a prerender, so you are encouraged to adopt prefetching broadly, for example prefetching all of the significant pages on your site, provided they are safe to prefetch (see Unsafe speculative loading conditions for more details).

Same-site and cross-site prefetches will work, but cross-site prefetches are limited (see "same-site" and "cross-site" for an explanation of the difference between the two). For privacy reasons cross-site prefetches will currently only work if the user has no cookies set for the destination site — we don't want sites to be able to track user activity via prefetched pages (which they may never even actually visit) based on previously-set cookies.

**Note:** In the future an opt-in will be provided via the `Supports-Loading-Mode` header, but this was not implemented at the time of writing.

For browsers that support it, speculation rules prefetch should be preferred over older prefetch mechanisms, namely `<link rel="prefetch">` and `fetch()` with a `priority: "low"` option set on it. Because we know that speculation rules prefetch is for navigations, not general resource prefetching:

* It can be used for cross-site navigations, whereas `<link rel="prefetch">` cannot.
* It doesn't get blocked by `Cache-Control` headers, whereas `<link rel="prefetch">` often does.

In addition, speculation rules prefetch:

* Automatically lowers the priority when needed (`fetch()` doesn't).
* Is respectful of the user's configuration. For example, prefetching doesn't happen when the user's device is in Battery Saver or Data Saver mode.
* Stores the prefetched resources in a per-document in-memory cache as opposed to the HTTP cache, which may result in slightly faster prefetching.
### Using prerendering

Including `prerender` rules inside `<script type=speculationrules> ... </script>` will cause supporting browsers to fetch, render, and load the content into an invisible tab, stored in a per-document in-memory cache. This includes loading all subresources, running all JavaScript, and even loading subresources and performing data fetches started by JavaScript. Any cached prerenders and their subresources are discarded when you navigate away from the current page, except of course a prerendered document that you then navigate to.

Future navigations to a prerendered page will be near-instant. The browser activates the invisible tab instead of carrying out the usual navigation process, replacing the old foreground page with the prerendered page. If a page is activated before it has fully prerendered, it is activated in its current state and then continues to load, which means you will still see a significant performance improvement.

Prerendering uses memory and network bandwidth. If you prerender something the user doesn't navigate to, these are wasted (although the result may populate the HTTP cache if headers allow, allowing later use). The upfront cost of a prerender is much larger than the upfront cost of a prefetch, and there are more conditions that could make content unsafe to prerender (see Unsafe speculative loading conditions for more details). As a result, you are encouraged to adopt prerendering more sparingly, carefully considering cases where there is a high likelihood of the page being navigated to, and you think the user experience benefit is worth the extra cost.

**Note:** To put the amount of potential resource wastage in perspective, a prerender uses about the same amount of resources as rendering an `<iframe>`.

**Note:** Many APIs will be automatically deferred when prerendering/until activation. See Platform features deferred or restricted during prerender for more details.

Prerendering is restricted to same-origin documents by default. Cross-origin, same-site prerendering is possible — it requires the navigation target to opt-in using the `Supports-Loading-Mode` header with a value of `credentialed-prerender`. Cross-site prerendering is not possible at this time.

For browsers that support it, speculation rules prerender should be preferred over older prerender mechanisms, namely `<link rel="prerender">`:

* `<link rel="prerender">` is Chrome-specific and was never standardized, and the Chrome engineering team are in the process of sunsetting it.
Experimental
* It loads subresources loaded via JavaScript, whereas `<link rel="prerender">` doesn't.
* It doesn't get blocked by `Cache-Control` settings, whereas `<link rel="prerender">` often does.
* Speculation rules prerender should be treated as a hint and a progressive enhancement. Unlike `<link rel="prerender">`, it is a speculative hint and the browser may choose not to act upon the hint based on user settings, current memory usage, or other heuristics.
### Speculation rules API feature detection

You can check if the Speculation Rules API is supported using the following code:

```js
if (
  HTMLScriptElement.supports &&
  HTMLScriptElement.supports("speculationrules")
) {
  console.log("Your browser supports the Speculation Rules API.");
}
```

For example, you might want to insert speculation rules for prefetching in supporting browsers, but use an older technology such as `<link rel="prefetch">` in others:

```js
if (
  HTMLScriptElement.supports &&
  HTMLScriptElement.supports("speculationrules")
) {
  const specScript = document.createElement("script");
  specScript.type = "speculationrules";
  const specRules = {
    prefetch: [
      {
        source: "list",
        urls: ["/next.html"],
      },
    ],
  };
  specScript.textContent = JSON.stringify(specRules);
  document.body.append(specScript);
} else {
  const linkElem = document.createElement("link");
  linkElem.rel = "prefetch";
  linkElem.href = "/next.html";
  document.head.append(linkElem);
}
```

Detecting prefetched and prerendered pages
------------------------------------------

This section looks at different ways to detect whether a requested page has been prefetched or prerendered.

### Server-side detection

Prefetched and prerendered page requests are sent with the `Sec-Purpose` request header:

For prefetch:

```http
Sec-Purpose: prefetch
```

For prerender:

```http
Sec-Purpose: prefetch;prerender
```

Servers can respond based on this header, for example to log speculative load requests, return different content, or even prevent the speculative loading from happening. If a non-success response code is returned (not 200 or 304), then the page will not be prefetched/prerendered. This is the easiest way to prevent speculative loading, although it is usually a better approach to allow the prefetch/prerender, but delay any actions that should only happen then the page is actually viewed, using JavaScript.

### JavaScript prefetch detection

When a page is prefetched, its `PerformanceResourceTiming.deliveryType` entry will return a value of `"navigational-prefetch"`. You could use the following to run a function when a performance entry of type `"navigational-prefetch"` is received:

```js
if (
  performance.getEntriesByType("navigation")[0].deliveryType ===
  "navigational-prefetch"
) {
  respondToPrefetch(); // Author-defined function
}
```

This technique is useful when measuring performance, or when you want to defer actions that might cause problems if they occur during prefetching (see Unsafe prefetching).

### JavaScript prerender detection

To run an activity while the page is prerendering, you can check for the `Document.prerendering` property. You could for example run some analytics:

```js
if (document.prerendering) {
  analytics.sendInfo("got this far during prerendering!");
}
```

When a prerendered document is activated, `PerformanceNavigationTiming.activationStart` is set to a `DOMHighResTimeStamp` representing the time between when the prerender was started and the document was actually activated. The following function can check for prerendering *and* prerendered pages:

```js
function pagePrerendered() {
  return (
    document.prerendering ||
    self.performance?.getEntriesByType?.("navigation")[0]?.activationStart > 0
  );
}
```

When the prerendered page is activated by the user viewing the page, the `prerenderingchange` event will fire. This can be used to enable activities that previously would be started by default on page load but which you wish to delay until the page is actually viewed by the user. The following code sets up an event listener to run a function once prerendering has finished, on a prerendered page, or runs it immediately on a non-prerendered page:

```js
if (document.prerendering) {
  document.addEventListener("prerenderingchange", initAnalytics, {
    once: true,
  });
} else {
  initAnalytics();
}
```

Unsafe speculative loading conditions
-------------------------------------

This section covers conditions to look out for, under which prefetching and/or prerendering are **unsafe**. This means that prefetching/prerendering pages that exhibit these conditions may require mitigations in your code, or need to be avoided altogether.

### Unsafe prefetching

As mentioned earlier, we recommend adopting prefetching broadly, as the risk to reward ratio is fairly low — the potential for resource wastage is minimal, and the performance improvements can be significant. However, you need to make sure prefetched pages do not cause problems with the flow of your application.

When a prefetch is done, the browser downloads the response body of the referenced page via a single GET request, which the user may navigate to at a future time. Problems can arise specifically when the URL of the request performs a server-initiated side effect that you don't want to happen until the URL is actually navigated to.

For example:

* Sign-out URLs.
* Language switching URLs.
* "Add to cart" URLs.
* Sign-in flow URLs where the server causes an SMS to be sent, for example as a one-time password (OTP).
* URLs that increment a user's usage allowance numbers, such as consuming their monthly free article allowance or starting the timer on their monthly minutes.
* URLs that initiate server-side ad conversion tracking.

Such issues can be mitigated on the server by watching for the `Sec-Purpose: prefetch` header as the requests come in, and then running specific code to defer problematic functionality. Later on, when the page is actually navigated to, you can initiate the deferred functionality via JavaScript if needed.

**Note:** You can find more details about the detection code in the Detecting prefetched and prerendered pages section.

If the functionality only occurs under normal circumstances when JavaScript runs, then prefetching is safe, since the JavaScript will not run until activation.

It is also potentially risky to prefetch a document whose server-rendered contents will change due to actions the user can take on the current page. This could include, for example, flash sale pages or movie theater seat maps. Test such cases carefully, and mitigate such issues by updating content once the page is loaded. See Server-rendered varying state for more details about these cases.

**Note:** Browsers will cache prefetched pages for a short time (Chrome for example caches them for 5 minutes) before discarding them, so in any case, your users might see content that is up to 5 minutes out of date.

One final tip is to audit the URLs listed as disallowed in your robots.txt file — normally these URLs point to pages that can only be accessed by authenticated users, and therefore should not be included in search engine results. Many of these will be fine, but it can be a good place to find URLs unsafe for prefetching (i.e. they exhibit the conditions described above).

### Unsafe prerendering

Prerendering is more risky to adopt than prefetching and should therefore be done more sparingly, in cases where it is worth it. There are more unsafe conditions to watch out for with prerendering so, while the reward is higher, the risk is too.

When a prerender is done, the browser GETs the URL and renders and loads the content into an invisible tab. This includes running the content's JavaScript and loading all subresources, including those fetched by JavaScript. Content can be potentially unsafe to prerender if any of the following conditions are observed:

* The URL is unsafe to prefetch. Read the previous section first if you haven't already, and understand that these conditions also equally apply to unsafe prerendering.
* The page's JavaScript modifies client-side storage (for example Web Storage or IndexedDB) on load in a way that may cause confusing effects in other, non-prerendered pages that the user is currently looking at.
* The page runs JavaScript or loads images that cause side effects such as sending analytics, recording ad impressions, or otherwise modifying the state of the application as if the user had already interacted with it. Again, this can affect the flow of the application, or cause incorrect performance or usage reporting. See Server-rendered varying state for more details about such use cases.

To mitigate such problems, you can use the following techniques:

* Watch for the `Sec-Purpose: prefetch` header on the server as the requests come in, and then run specific code to defer problematic functionality.
* Use the `prerenderingchange` event to detect when the prerendered page is actually activated and run code as a result. This is useful in two cases:
    + Deferring code that may cause problems if it is run before the page is viewed. For example, you may want to wait until after activation to update client-side storage or modify server-side state using JavaScript. This can avoid situations when the UI and the application state become out of sync with one another, for example a shopping cart showing no items even though the user has added some.
    + If the above is not possible, then you could still rerun code after the page is activated to bring the app up-to-date again. For example, a highly-dynamic flash sale page might rely on content updates coming in from a third-party library. If you can't delay the updates, you can always get fresh updates once the user views the page. Prerendered pages can be updated in real time using the Broadcast Channel API, or another mechanism such as `fetch()` or a `WebSocket`. This guarantees that the user will see up-to-date content after prerendering activation.
* Manage your third-party analytics scripts carefully — if possible, use scripts that are prerendering-aware (for example use the `Document.prerendering` property to defer running on prerendering pages) such as Google Analytics or NewRelic.
    + Note that cross-origin `<iframe>` loads are delayed while prerendering, therefore most other third-party widgets such as adtech are actually safe to use while prerendering.
    + For third-party scripts that are not prerendering-aware, avoid loading them until after activation using the `prerenderingchange` event, as mentioned earlier.
### Server-rendered varying state

There are two main types of server-rendered state to be concerned with: **outdated state**, and **user-specific state**. This can cause both unsafe prefetching and prerendering.

* Outdated state: Consider the example of a server-rendered list of blog comments, which may become out of date between the blog post being prerendered, and it being viewed. This might be particularly problematic if the current page is an admin panel where the user is deleting spam comments. If the user then navigates to the blog post, they might be confused as to why they can see the spam comments they just deleted.
* User-specific state: Consider the example of tracking sign-in state via a cookie. Problems can arise like the following:
    + The user visits `https://site.example/a` in tab 1 and `https://site.example/b` in tab 2, while logged out.
    + `https://site.example/b` prerenders `https://site.example/c`. It will be prerendered in a logged-out state.
    + The user signs in to `https://site.example` in tab 1.
    + The user switches to tab 2 and clicks the link to `https://site.example/c`, which activates the prerendered page.
    + Tab 2 displays a signed-out view of `https://site.example/c`, which confuses the user since they thought they were logged in.

User-specific state problems can occur for other user settings, for example language settings, dark-mode preferences, or adding items to a cart. They can also occur when only a single tab is involved:

* Let's say the user visits `https://site.example/product`.
* `https://site.example.com/product` prerenders `https://site.example.com/cart`. It prerenders with 0 items in the cart.
* The user clicks on the "Add to cart" buttons, which initiates a fetch request to add the item to the user's cart (with no page reload).
* The user clicks on the link to `https://site.example.com/cart`, which activates the prerendered page.
* The user sees an empty cart, even though they just added something to it.

The best mitigation for these cases, and indeed any time when content can get out of sync with the server, is for pages to refresh themselves as needed. For example, a server might use the Broadcast Channel API, or another mechanism such as `fetch()` or a `WebSocket`. Pages can then update themselves appropriately, including speculatively loaded pages that have not yet activated.

Session history behavior for prerendered documents
--------------------------------------------------

Activating a prerendering/prerendered document behaves like any conventional navigation, from the end-user perspective. The activated document is displayed in the tab and appended to session history, and any existing forward history entries are pruned. Any navigations taking place within the prerendering browsing context *before* activation do not affect the session history.

From the developer's perspective, a prerendering document can be thought of as having a **trivial session history** where only one entry — the current entry — exists. All navigations within the prerendering context are effectively replaced.

While API features that operate on session history (for example `History` and `Navigation`) can be called within prerendering documents, they only operate on the context's trivial session history. Consequently, prerendering documents do not take part in their referring page's joint session history. For example, they cannot navigate their referrer via `History.back()`.

This design ensures that users get the expected experience when using the back button — i.e. that they are taken back to the last thing they saw. Once a prerendering document is activated, only a single session history entry gets appended to the joint session history, ignoring any previous navigations that happened within the prerendering browsing context. Going back one step in the joint session history — for example by pressing the back button — takes the user back to the referrer page.

Platform features deferred or restricted during prerender
---------------------------------------------------------

Because a prerendered page is opened in a hidden state, a number of APIs and other web platform features that cause potentially intrusive behaviors are not activated in this state, and are instead deferred until the page is activated or restricted altogether. In the small number of cases where this is not yet possible, the prerender is canceled.

### Asynchronous API deferral

The following asynchronous features' results are deferred in prerendered documents until they are activated:

* Audio Output Devices API: `MediaDevices.selectAudioOutput()`
* Background Fetch API: `BackgroundFetchManager.fetch()`
* Broadcast Channel API: `BroadcastChannel.postMessage()`
* Credential Management API: `CredentialsContainer.create()`, `CredentialsContainer.get()`, `CredentialsContainer.store()`
* Encrypted Media Extensions API: `Navigator.requestMediaKeySystemAccess()`
* Gamepad API: `Navigator.getGamepads()`, `gamepadconnected` event, `gamepaddisconnected` event
* Geolocation API: `Geolocation.getCurrentPosition()`, `Geolocation.watchPosition()`, `Geolocation.clearWatch()`
* `HTMLMediaElement` API: The playback position will not advance while the containing document is prerendering
* Idle Detection API: `IdleDetector.start()`
* Media Capture and Streams API: `MediaDevices.getUserMedia()` (and the legacy `Navigator.getUserMedia()` version), `MediaDevices.enumerateDevices()`
* Notifications API: `Notification()` constructor, `Notification.requestPermission()`
* Push API: `PushManager.subscribe()`
* Screen Orientation API: `ScreenOrientation.lock()`, `ScreenOrientation.unlock()`
* Sensor APIs: `Sensor.start()`
* Service Worker API: `ServiceWorker.postMessage()`, `ServiceWorkerContainer.register()`, `ServiceWorkerRegistration.update()`, `ServiceWorkerRegistration.unregister()`
* Storage API: `StorageManager.persist()`
* Web Audio API: `AudioContext`s are not allowed to start while the containing document is prerendering
* Web Bluetooth API: `Bluetooth.getDevices()`, `Bluetooth.requestDevice()`
* WebHID API: `HID.getDevices()`, `HID.requestDevice()`
* Web Locks API: `LockManager.query()`, `LockManager.request()`
* Web MIDI API: `Navigator.requestMIDIAccess()`
* Web NFC API: `NDefReader.write()`, `NDefReader.scan()`
* Web Serial API: `Serial.getPorts()`, `Serial.requestPort()`
* Web Speech API: `SpeechRecognition.abort()`, `SpeechRecognition.start()`, `SpeechRecognition.stop()`, `SpeechSynthesis.cancel()`, `SpeechSynthesis.pause()`, `SpeechSynthesis.resume()`, `SpeechSynthesis.speak()`
* WebUSB API: `USB.getDevices()`, `USB.requestDevice()`
* WebXR Device API: `XRSystem.requestSession()`
### Implicitly restricted APIs

The following features will automatically fail or no-op in documents that are not activated.

APIs that require transient activation or sticky activation:

* Confirmation dialogs generated by the `beforeunload` event
* The firing of any events in the Clipboard API.
* File System API: `Window.showDirectoryPicker()`, `Window.showOpenFilePicker()`, `Window.showSaveFilePicker()`
* Fullscreen API: `Element.requestFullscreen()`
* Idle Detection API: `IdleDetector.requestPermission()`
* Keyboard API: `Keyboard.lock()` (which requires fullscreen)
* Payment Request API: `PaymentRequest.show()`
* Presentation API: `PresentationRequest.start()`
* Pointer Lock API: `Element.requestPointerLock()`
* Screen Capture API: `MediaDevices.getDisplayMedia()`
* Web Share API: `Navigator.share()`
* `Window.open()`

APIs that require the containing document to be focused:

* Clipboard API: `Clipboard.read()`, `Clipboard.readText()`, `Clipboard.write()`, `Clipboard.writeText()`

APIs that require the containing document's `Document.visibilityState` to be `"visible"`:

* Picture-in-Picture API: `HTMLVideoElement.requestPictureInPicture()` (requires the containing document's visibility state to be `"visible", *or* transient activation)
* Screen Wake Lock API: `WakeLock.request()`
### Other restricted features

* Download links, i.e. `<a>` and `<area>` elements with the `download` attribute, will have their downloads delayed until prerendering has finished.
* No cross-site navigations: Any prerendering document that navigates to a different site will be immediately discarded before a request to that other site is sent.
* Restricted URLs: Prerendering documents cannot host non-HTTP(S) top-level URLs. Including the following URL types will cause the prerender to be immediately discarded:
    + `javascript:` URLs
    + `data:` URLs
    + `blob:` URLs
    + `about:` URLs, including `about:blank` and `about:srcdoc`
* Session storage: `Window.sessionStorage` can be used, but the behavior is very specific, to avoid breaking sites that expect only one page to access the tab's session storage at a time. A prerendered page therefore starts out with a clone of the tab's session storage state from when it was created. Upon activation, the prerendered page's storage clone is discarded, and the tab's main storage state is used instead. Pages that use session storage can use the `prerenderingchange` event to detect when this storage swap occurs.
* `Window.print()`: Any calls to this method are ignored.
* "Simple dialog methods" are restricted as follows:
    + `Window.alert()` immediately returns without showing a dialog.
    + `Window.confirm()` immediately returns `false` without showing a dialog.
    + `Window.prompt()` immediately returns an empty string (`""`) without showing a dialog.
* Dedicated/shared worker scripts are loaded, but their execution is deferred until the prerendered document is activated.
* Cross-origin `<iframe>` loads are delayed while prerendering until after the page is activated.
Interfaces
----------

The Speculation Rules API does not define any interfaces of its own.

### Extensions to other interfaces

`Document.prerendering`
Experimental

A boolean property that returns `true` if the document is currently in the process of prerendering.

`prerenderingchange` event
Experimental

Fired on a prerendered document when it is activated (i.e. the user views the page).

`PerformanceNavigationTiming.activationStart`
Experimental

A number representing the time between when a document starts prerendering and when it is activated.

`PerformanceResourceTiming.deliveryType` `"navigational-prefetch"` value
Experimental

Signals that the type of a performance entry is a prefetch.

HTTP headers
------------

`Content-Security-Policy` `'inline-speculation-rules'` value
Experimental

Used to opt-in to allowing usage of `<script type="speculationrules">` to define speculation rules on the document being fetched.

`Supports-Loading-Mode`
Experimental

Set by a navigation target to opt-in to using various higher-risk loading modes. For example, cross-origin, same-site prerendering requires a `Supports-Loading-Mode` value of `credentialed-prerender`.

HTML features
-------------

`<script type="speculationrules"> ... </script>`
Experimental

Used to define a set of prefetch and/or prerender speculation rules on the current document.

Examples
--------

You can find a complete prerender demo here.

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

| Specification |
| --- |
| Speculation Rules  |
| Prerendering Revamped  |

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

### api.Document.prerendering

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

### api.Document.prerenderingchange\_event

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

### html.elements.script.type.speculationrules

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

See also
--------

* Prerender pages in Chrome for instant page navigations on developer.chrome.com (2023)
* Speculative loading for a comparison of speculation rules and other similar performance improvement features.


RTCCertificateStats - Web APIs

RTCCertificateStats
===================

The **`RTCCertificateStats`** dictionary of the WebRTC API is used to report information about a certificate used by an `RTCDtlsTransport` and its underlying `RTCIceTransport`.

The report can be obtained by iterating the `RTCStatsReport` returned by `RTCPeerConnection.getStats()` until you find an entry with the `type` of `certificate`.

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

`fingerprint`

A string containing the certificate fingerprint, which is calculated using the hash function specified in `fingerprintAlgorithm`.

`fingerprintAlgorithm`

A string containing the hash function used to compute the certificate `fingerprint`, such as "sha-256".

`base64Certificate`

A string containing the base-64 representation of the DER-encoded certificate.

### Common instance properties

The following properties are common to all WebRTC statistics objects (See `RTCStatsReport` for more information).

`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 `"certificate"`, indicating the type of statistics that the object contains.

Examples
--------

 Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code below uses `await` to wait for the statistics report, and then iterates it using `RTCStatsReport.forEach()`.
 It then filters the dictionaries for just those reports that have the type of `certificate` and logs the result.

```js
const stats = await myPeerConnection.getStats();

stats.forEach((report) => {
  if (report.type === "certificate") {
    // Log the certificate information
    console.log(report);
  }
});
```

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

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

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

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

See also
--------

* `RTCStatsReport`
* `RTCCertificate`


SVGAngle - Web APIs

SVGAngle
========

The `SVGAngle` interface is used to represent a value that can be an `<angle>` or `<number>` value. An `SVGAngle` reflected through the `animVal` attribute is always read only.

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

An `SVGAngle` object can be associated with a particular element. The associated element is used to determine which element's content attribute to update if the object reflects an attribute. Unless otherwise described, an `SVGAngle` object is not associated with any element.

Every `SVGAngle` object operates in one of two modes:

1. ***Reflect the base value*** of a reflected animatable attribute (being exposed through the `baseVal` member of an `SVGAnimatedAngle`),
2. ***Be detached*,** which is the case for `SVGAngle` objects created with `SVGSVGElement.createSVGAngle()`.
Constants
---------

`SVG_ANGLETYPE_UNKNOWN`

Some unknown type of value.

`SVG_ANGLETYPE_UNSPECIFIED`

A unitless `<number>` interpreted as a value in degrees.

`SVG_ANGLETYPE_DEG`

An `<angle>` with a `deg` unit.

`SVG_ANGLETYPE_RAD`

An `<angle>` with a `rad` unit.

`SVG_ANGLETYPE_GRAD`

An `<angle>` with a `grad` unit.

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

`unitType`

The type of the value as specified by one of the `SVG_ANGLETYPE_*` constants defined on this interface.

`value`

The value as a floating point value, in user units. Setting this attribute will cause `valueInSpecifiedUnits` and `valueAsString` to be updated automatically to reflect this setting.

**Exceptions on setting:** A `DOMException` with code `NO_MODIFICATION_ALLOWED_ERR` is raised when the length corresponds to a read-only attribute, or when the object itself is read-only.

`valueInSpecifiedUnits`

The value as a floating point value, in the units expressed by `unitType`. Setting this attribute will cause `value` and `valueAsString` to be updated automatically to reflect this setting.

**Exceptions on setting:** A `DOMException` with code `NO_MODIFICATION_ALLOWED_ERR` is raised when the length corresponds to a read-only attribute, or when the object itself is read-only.

`valueAsString`

The value as a string value, in the units expressed by `unitType`. Setting this attribute will cause `value`, `valueInSpecifiedUnits`, and `unitType` to be updated automatically to reflect this setting.

**Exceptions on setting:**

A `DOMException` with code `SYNTAX_ERR` is raised if the assigned string cannot be parsed as a valid `<angle>`.

A `DOMException` with code `NO_MODIFICATION_ALLOWED_ERR` is raised when the length corresponds to a read-only attribute, or when the object itself is read-only.

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

`newValueSpecifiedUnits`

Reset the value as a number with an associated unitType, thereby replacing the values for all of the attributes on the object.

**Exceptions:**

* A `DOMException` with code `NOT_SUPPORTED_ERR` is raised if `unitType` is `SVG_ANGLETYPE_UNKNOWN` or not a valid unit type constant (one of the other `SVG_ANGLETYPE_*` constants defined on this interface).
* A `DOMException` with code `NO_MODIFICATION_ALLOWED_ERR` is raised when the length corresponds to a read only attribute or when the object itself is read only.

`convertToSpecifiedUnits`

Preserve the same underlying stored value, but reset the stored unit identifier to the given `unitType`. Object attributes `unitType`, `valueInSpecifiedUnits`, and `valueAsString` might be modified as a result of this method.

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

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

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

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


SVGFontFaceSrcElement - Web APIs

SVGFontFaceSrcElement
=====================

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

The **`SVGFontFaceSrcElement`** interface corresponds to the `<font-face-src>` elements.

Object-oriented access to the attributes of the `<font-face-src>` element via the SVG DOM is not possible.

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

*This interface has no properties but inherits properties from its parent, `SVGElement`.*

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

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

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

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 1.1 (Second Edition) # InterfaceSVGFontFaceSrcElement |

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

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

See also
--------

* `<font-face-src>`


TaskPriorityChangeEvent - Web APIs

TaskPriorityChangeEvent
=======================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`TaskPriorityChangeEvent`** is the interface for the `prioritychange` event.

Event

TaskPriorityChangeEventConstructor
-----------

`TaskPriorityChangeEvent()`

Creates a new `TaskPriorityChangeEvent` object, setting an event name and previous priority.

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

*This interface also inherits the properties of its parent, `Event`.*

`TaskPriorityChangeEvent.previousPriority` Read only

Returns the priority of the corresponding `TaskSignal` *before* this `prioritychange` event.

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

*This interface has no methods of its own, but inherits the methods of its parent, `Event`.*

Examples
--------

 An object of this type is returned in the handler for a `prioritychange` event.
 The code below shows a handler in which the `newPriority` and `previousPriority` are logged.

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

A more complete live example can be found in `prioritychange` event > Examples.

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

| Specification |
| --- |
| Prioritized Task Scheduling # sec-task-priority-change-event |

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

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

See also
--------

* `prioritychange` event


AudioParamDescriptor - Web APIs

AudioParamDescriptor
====================

The **`AudioParamDescriptor`** dictionary of the Web Audio API specifies properties for `AudioParam` objects.

It is used to create custom `AudioParam`s on an `AudioWorkletNode`. If the underlying `AudioWorkletProcessor` has a `parameterDescriptors` static getter, then the returned array of objects based on this dictionary is used internally by `AudioWorkletNode` constructor to populate its `parameters` property accordingly.

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

`name`

The string which represents the name of the `AudioParam`. Under this name the `AudioParam` will be available in the `parameters` property of the node, and under this name the `AudioWorkletProcessor.process` method will acquire the calculated values of this `AudioParam`.

`automationRate` Optional

Either `"a-rate"`, or `"k-rate"` string which represents an automation rate of this `AudioParam`. Defaults to `"a-rate"`.

`minValue` Optional

A `float` which represents minimum value of the `AudioParam`. Defaults to `-3.4028235e38`.

`maxValue` Optional

A `float` which represents maximum value of the `AudioParam`. Defaults to `3.4028235e38`.

`defaultValue` Optional

A `float` which represents initial value of the `AudioParam`. Defaults to `0`.

Examples
--------

The code fragment below shows a descriptor of this type being returned by a static `parameterDescriptors` method defined in a custom `AudioWorkletProcessor` (this is part of the more complete example in AudioWorkletNode.parameters).

```js
// white-noise-processor.js
class WhiteNoiseProcessor extends AudioWorkletProcessor {
  static get parameterDescriptors() {
    return [
      {
        name: "customGain",
        defaultValue: 1,
        minValue: 0,
        maxValue: 1,
        automationRate: "a-rate",
      },
    ];
  }

  // …
}
```

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

#### No specification found

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

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

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

See also
--------

* Web Audio API
* Using the Web Audio API


SVGTransformList - Web APIs

SVGTransformList
================

SVG transform list interface
----------------------------

The `SVGTransformList` defines a list of `SVGTransform` objects.

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

An `SVGTransformList` is indexable and can be accessed like an array.

### Interface overview

|  |  |
| --- | --- |
| Also implement | *None* |
| Methods | * `void clear()`
* `SVGTransform`
`initialize(in `SVGTransform`
*newItem*)`
* `SVGTransform`
`getItem(in unsigned long *index*)`
* `SVGTransform`
`insertItemBefore(in `SVGTransform`
*newItem*, in unsigned long *index*)`
* `SVGTransform`
`replaceItem(in `SVGTransform`
*newItem*, in unsigned long *index*)`
* `SVGTransform`
`removeItem(in unsigned long *index*)`
* `SVGTransform`
`appendItem(in `SVGTransform`
*newItem*)`
* `SVGTransform`
`createSVGTransformFromMatrix(in
`DOMMatrix`)`
* `SVGTransform` `consolidate()`
 |
| Properties | * readonly unsigned long `numberOfItems`
* readonly unsigned long
 `length`
Non-standard
 |
| Normative document | SVG 1.1 (2nd Edition) |

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

| Name | Type | Description |
| --- | --- | --- |
| `numberOfItems` | unsigned long | The number of items in the list. |
| `length`
Non-standard
 | unsigned long | The number of items in the list. |

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

| Name & Arguments | Return | Description |
| --- | --- | --- |
| `**clear**()` | `void` |
 Clears all existing current items from the list, with the result being
 an empty list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**initialize**(in
`SVGTransform` *newItem*)` | `SVGTransform` |
 Clears all existing current items from the list and re-initializes the
 list to hold the single item specified by the parameter. If the
 inserted item is already in a list, it is removed from its previous
 list before it is inserted into this list. The inserted item is the
 item itself and not a copy. The return value is the item inserted into
 the list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**getItem**(in unsigned long *index*)` | `SVGTransform` |
 Returns the specified item from the list. The returned item is the
 item itself and not a copy. Any changes made to the item are
 immediately reflected in the list. The first item is number 0.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**insertItemBefore**(in
`SVGTransform` *newItem*, in unsigned
long *index*)` | `SVGTransform` |
 Inserts a new item into the list at the specified position. The first
 item is number 0. If `newItem` is already in a list, it is
 removed from its previous list before it is inserted into this list.
 The inserted item is the item itself and not a copy. If the item is
 already in this list, note that the index of the item to insert before
 is before the removal of the item. If the `index` is equal
 to 0, then the new item is inserted at the front of the list. If the
 index is greater than or equal to `numberOfItems`, then the
 new item is appended to the end of the list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**replaceItem**(in
`SVGTransform` *newItem*, in unsigned
long *index*)` | `SVGTransform` |
 Replaces an existing item in the list with a new item. If
 `newItem` is already in a list, it is removed from its
 previous list before it is inserted into this list. The inserted item
 is the item itself and not a copy. If the item is already in this
 list, note that the index of the item to replace is before the removal
 of the item.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
* a `DOMException` with code
 `INDEX_SIZE_ERR` is raised if the index number is greater
 than or equal to `numberOfItems`.
 |
| `**removeItem**(in unsigned long *index*)` | `SVGTransform` | Removes an existing item from the list.
**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
* a `DOMException` with code
 `INDEX_SIZE_ERR` is raised if the index number is greater
 than or equal to `numberOfItems`.
 |
| `**appendItem**(in
`SVGTransform` *newItem*)` | `SVGTransform` |
 Inserts a new item at the end of the list. If `newItem` is
 already in a list, it is removed from its previous list before it is
 inserted into this list. The inserted item is the item itself and not
 a copy.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**createSVGTransformFromMatrix**(in
`DOMMatrix`)` | `SVGTransform` |
 Creates an `SVGTransform` object which is initialized to
 transform of type `SVG_TRANSFORM_MATRIX` and whose values are
 the given matrix. The values from the parameter matrix are copied, the
 matrix parameter is not adopted as `SVGTransform::matrix`.
  |
| `**consolidate**()` | `SVGTransform` |
 Consolidates the list of separate `SVGTransform` objects by
 multiplying the equivalent transformation matrices together to result
 in a list consisting of a single `SVGTransform` object of
 type `SVG_TRANSFORM_MATRIX`. The consolidation operation
 creates new `SVGTransform` object as the first and only
 item in the list. The returned item is the item itself and not a copy.
 Any changes made to the item are immediately reflected in the list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |

Examples
--------

### Using multiple SVGTransform objects

In this example we create a function that will apply three different transformations to the SVG element that has been clicked on. In order to do this we create a separate `SVGTransform` object for each transformation — such as `translate`, `rotate`, and `scale`. We apply multiple transformation by appending the transform object to the `SVGTransformList` associated with an SVG element.

```html
<svg
 id="my-svg"
 viewBox="0 0 300 280"
 xmlns="http://www.w3.org/2000/svg"
 version="1.1">
  <desc>
    Example showing how to transform svg elements that using SVGTransform
    objects
  </desc>
  <script type="application/ecmascript">
 <![CDATA[
 function transformMe(evt) {
 // svg root element to access the createSVGTransform() function
 const svgroot = evt.target.parentNode;
 // SVGTransformList of the element that has been clicked on
 const tfmList = evt.target.transform.baseVal;

 // Create a separate transform object for each transform
 const translate = svgroot.createSVGTransform();
 translate.setTranslate(50,5);
 const rotate = svgroot.createSVGTransform();
 rotate.setRotate(10,0,0);
 const scale = svgroot.createSVGTransform();
 scale.setScale(0.8,0.8);

 // apply the transformations by appending the SVGTransform objects to the SVGTransformList associated with the element
 tfmList.appendItem(translate);
 tfmList.appendItem(rotate);
 tfmList.appendItem(scale);
 }
 ]]>
 </script>

  <polygon
 fill="orange"
 stroke="black"
 stroke-width="5"
 points="100,225 100,115 130,115 70,15 70,15 10,115 40,115 40,225"
 onclick="transformMe(evt)" />
  <rect
 x="200"
 y="100"
 width="100"
 height="100"
 fill="yellow"
 stroke="black"
 stroke-width="5"
 onclick="transformMe(evt)" />
  <text x="40" y="250" font-family="Verdana" font-size="16" fill="green">
    Click on a shape to transform it
  </text>
</svg>
```

Live preview:

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

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

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

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


Remote Playback API - Web APIs

Remote Playback API
===================

The Remote Playback API extends the `HTMLMediaElement` to enable the control of media played on a remote device.

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

Remote playback devices are connected devices such as TVs, projectors, or speakers. The API takes into account wired devices connected via HDMI or DVI, and wireless devices, for example Chromecast or AirPlay.

The API enables a page, which has an media element such as a video or audio file, to initiate and control playback of that media on a connected remote device. For example, playing a video on a connected TV.

**Note:** Safari for iOS has some APIs which enable remote playback on AirPlay. Details of these can be found in the Safari 9.0 release notes.

Android versions of Firefox and Chrome also contain some remote playback features. These devices will show a Cast button if there is a Cast device available in the local network.

Interfaces
----------

`RemotePlayback`

Allows the page to detect availability of remote playback devices, then connect to and control playing on these devices.

### Extensions to other interfaces

`HTMLMediaElement.disableRemotePlayback`

A boolean that sets or returns the remote playback state, indicating whether the media element is allowed to have a remote playback UI.

`HTMLMediaElement.remote` Read only

Return a `RemotePlayback` object instance associated with the media element.

Examples
--------

The following example demonstrates a player with custom controls that supports remote playback. Initially the button used to select a device is hidden.

```html
<video id="videoElement" src="https://example.org/media.ext">
  <button id="deviceBtn" style="display: none;">Pick device</button>
</video>
```

The `RemotePlayback.watchAvailability()` method watches for available remote playback devices. If a device is available, use the callback to show the button.

```js
const deviceBtn = document.getElementById("deviceBtn");
const videoElem = document.getElementById("videoElement");

function availabilityCallback(available) {
  // Show or hide the device picker button depending on device availability.
  deviceBtn.style.display = available ? "inline" : "none";
}

videoElem.remote.watchAvailability(availabilityCallback).catch(() => {
  /\* If the device cannot continuously watch available,
 show the button to allow the user to try to prompt for a connection.\*/
  deviceBtn.style.display = "inline";
});
```

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

| Specification |
| --- |
| Remote Playback API  |

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

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


SpeechRecognitionEvent - Web APIs

SpeechRecognitionEvent
======================

The **`SpeechRecognitionEvent`** interface of the Web Speech API represents the event object for the `result` and `nomatch` events, and contains all the data associated with an interim or final speech recognition result.

Event

SpeechRecognitionEventInstance properties
-------------------

*`SpeechRecognitionEvent` also inherits properties from its parent interface, `Event`.*

`SpeechRecognitionEvent.emma` Read only
Deprecated

Non-standard

Returns an Extensible MultiModal Annotation markup language (EMMA) — XML — representation of the result.

`SpeechRecognitionEvent.interpretation` Read only
Deprecated

Non-standard

Returns the semantic meaning of what the user said.

`SpeechRecognitionEvent.resultIndex` Read only

Returns the lowest index value result in the `SpeechRecognitionResultList` "array" that has actually changed.

`SpeechRecognitionEvent.results` Read only

Returns a `SpeechRecognitionResultList` object representing all the speech recognition results for the current session.

Examples
--------

This code is excerpted from our Speech color changer example.

```js
recognition.onresult = (event) => {
  // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
  // The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
  // It has a getter so it can be accessed like an array
  // The first [0] returns the SpeechRecognitionResult at position 0.
  // Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects that contain
  // individual results.
  // These also have getters so they can be accessed like arrays.
  // The second [0] returns the SpeechRecognitionAlternative at position 0.
  // We then return the transcript property of the SpeechRecognitionAlternative object
  const color = event.results[0][0].transcript;
  diagnostic.textContent = `Result received: ${color}.`;
  bg.style.backgroundColor = color;
};
```

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

| Specification |
| --- |
| Web Speech API # speechreco-event |

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

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

See also
--------

* Web Speech API


CountQueuingStrategy - Web APIs

CountQueuingStrategy
====================

The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams.

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

`CountQueuingStrategy()`

Creates a new `CountQueuingStrategy` object instance.

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

`CountQueuingStrategy.highWaterMark` Read only

The total number of chunks that can be contained in the internal queue before backpressure is applied.

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

`CountQueuingStrategy.size()`

Always returns `1`.

Examples
--------

```js
const queueingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });

const writableStream = new WritableStream(
  {
    // Implement the sink
    write(chunk) {
      // …
    },
    close() {
      // …
    },
    abort(err) {
      console.log("Sink error:", err);
    },
  },
  queueingStrategy,
);

const size = queueingStrategy.size();
```

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

| Specification |
| --- |
| Streams Standard # cqs-class |

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

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

See also
--------

* Streams API
* `CountQueuingStrategy()` constructor
* Internal queues and queuing strategies


DOMMatrixReadOnly - Web APIs

DOMMatrixReadOnly
=================

The **`DOMMatrixReadOnly`** interface represents a read-only 4×4 matrix, suitable for 2D and 3D operations. The `DOMMatrix` interface — which is based upon `DOMMatrixReadOnly`—adds mutability, allowing you to alter the matrix after creating it.

This interface should be available inside web workers, though some implementations doesn't allow it yet.

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

`DOMMatrixReadOnly()`

Creates a new `DOMMatrixReadOnly` object.

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

*This interface doesn't inherit any properties.*

`is2D` Read only

A Boolean flag whose value is `true` if the matrix was initialized as a 2D matrix. If `false`, the matrix is 3D.

`isIdentity` Read only

A Boolean whose value is `true` if the matrix is the identity matrix. The identity matrix is one in which every value is `0` *except* those on the main diagonal from top-left to bottom-right corner (in other words, where the offsets in each direction are equal).

`m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44`

Double-precision floating-point values representing each component of a 4×4 matrix, where `m11` through `m14` are the first column, `m21` through `m24` are the second column, and so forth.

`a`, `b`, `c`, `d`, `e`, `f`

Double-precision floating-point values representing the components of a 4×4 matrix which are required in order to perform 2D rotations and translations. These are aliases for specific components of a 4×4 matrix, as shown below.

| 2D | 3D equivalent |
| --- | --- |
| `a` | `m11` |
| `b` | `m12` |
| `c` | `m21` |
| `d` | `m22` |
| `e` | `m41` |
| `f` | `m42` |

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

*This interface doesn't inherit any methods. None of the following methods alter the original matrix.*

`DOMMatrixReadOnly.flipX()`

Returns a new `DOMMatrix` created by flipping the source matrix around its X-axis. This is equivalent to multiplying the matrix by `DOMMatrix(-1, 0, 0, 1, 0, 0)`. The original matrix is not modified.

`DOMMatrixReadOnly.flipY()`

Returns a new `DOMMatrix` created by flipping the source matrix around its Y-axis. This is equivalent to multiplying the matrix by `DOMMatrix(1, 0, 0, -1, 0, 0)`. The original matrix is not modified.

`DOMMatrixReadOnly.inverse()`

Returns a new `DOMMatrix` created by inverting the source matrix. If the matrix cannot be inverted, the new matrix's components are all set to `NaN` and its `is2D` property is set to `false`. The original matrix is not altered.

`DOMMatrixReadOnly.multiply()`

Returns a new `DOMMatrix` created by computing the dot product of the source matrix and the specified matrix: `A⋅B`. If no matrix is specified as the multiplier, the matrix is multiplied by a matrix in which every element is `0` *except* the bottom-right corner and the element immediately above and to its left: `m33` and `m34`. These have the default value of `1`. The original matrix is not modified.

`DOMMatrixReadOnly.rotateAxisAngle()`

Returns a new `DOMMatrix` created by rotating the source matrix by the given angle around the specified vector. The original matrix is not modified.

`DOMMatrixReadOnly.rotate()`

Returns a new `DOMMatrix` created by rotating the source matrix around each of its axes by the specified number of degrees. The original matrix is not altered.

`DOMMatrixReadOnly.rotateFromVector()`

Returns a new `DOMMatrix` created by rotating the source matrix by the angle between the specified vector and `(1, 0)`. The original matrix is not modified.

`DOMMatrixReadOnly.scale()`

Returns a new `DOMMatrix` created by scaling the source matrix by the amount specified for each axis, centered on the given origin. By default, the X and Z axes are scaled by `1` and the Y axis has no default scaling value. The default origin is `(0, 0, 0)`. The original matrix is not modified.

`DOMMatrixReadOnly.scale3d()`

Returns a new `DOMMatrix` created by scaling the source 3D matrix by the given factor along all its axes, centered on the specified origin point. The default origin is `(0, 0, 0)`. The original matrix is not modified.

`DOMMatrixReadOnly.scaleNonUniform()`
Deprecated

Returns a new `DOMMatrix` created by applying the specified scaling on the X, Y, and Z axes, centered at the given origin. By default, the Y and Z axes' scaling factors are both `1`, but the scaling factor for X must be specified. The default origin is `(0, 0, 0)`. The original matrix is not changed.

`DOMMatrixReadOnly.skewX()`

Returns a new `DOMMatrix` created by applying the specified skew transformation to the source matrix along its X-axis. The original matrix is not modified.

`DOMMatrixReadOnly.skewY()`

Returns a new `DOMMatrix` created by applying the specified skew transformation to the source matrix along its Y-axis. The original matrix is not modified.

`DOMMatrixReadOnly.toFloat32Array()`

Returns a new `Float32Array` containing all 16 elements (`m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44`) which comprise the matrix. The elements are stored into the array as single-precision floating-point numbers in column-major (colexographical access, or "colex") order. (In other words, down the first column from top to bottom, then the second column, and so forth.)

`DOMMatrixReadOnly.toFloat64Array()`

Returns a new `Float64Array` containing all 16 elements (`m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44`) which comprise the matrix. The elements are stored into the array as double-precision floating-point numbers in column-major (colexographical access, or "colex") order. (In other words, down the first column from top to bottom, then the second column, and so forth.)

`DOMMatrixReadOnly.toJSON()`

Returns a JSON representation of the `DOMMatrixReadOnly` object.

`DOMMatrixReadOnly.toString()`

Creates and returns a string object which contains a string representation of the matrix in CSS matrix syntax, using the appropriate CSS matrix notation. See the `matrix()` CSS function for details on this syntax.

For a 2D matrix, the elements `a` through `f` are listed, for a total of six values and the form `matrix(a, b, c, d, e, f)`.

For a 3D matrix, the returned string contains all 16 elements and takes the form `matrix3d(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44)`. See the CSS `matrix3d()` function for details on the 3D notation's syntax.

Throws an `InvalidStateError` exception if any of the elements in the matrix are non-finite (even if, in the case of a 2D matrix, the non-finite values are in elements not used by the 2D matrix representation).

`DOMMatrixReadOnly.transformPoint()`

Transforms the specified point using the matrix, returning a new `DOMPoint` object containing the transformed point. Neither the matrix nor the original point are altered.

`DOMMatrixReadOnly.translate()`

Returns a new `DOMMatrix` containing a matrix calculated by translating the source matrix using the specified vector. By default, the vector is `(0, 0, 0)`. The original matrix is not changed.

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

`fromFloat32Array()`

Creates a new mutable `DOMMatrix` object given an array of single-precision (32-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix. Otherwise, a `TypeError` exception is thrown.

`fromFloat64Array()`

Creates a new mutable `DOMMatrix` object given an array of double-precision (64-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix. Otherwise, a `TypeError` exception is thrown.

`fromMatrix()`

Creates a new mutable `DOMMatrix` object given an existing matrix or a `DOMMatrixInit` dictionary which provides the values for its properties. If no matrix is specified, the matrix is initialized with every element set to `0` *except* the bottom-right corner and the element immediately above and to its left: `m33` and `m34`. These have the default value of `1`.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # DOMMatrix |

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

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

See also
--------

* The mutable matrix type, `DOMMatrix`, which is based on this one.
* The CSS `matrix()` and `matrix3d()` functional notation that can be generated from this interface to be used in a CSS `transform`.


SVGTextElement - Web APIs

SVGTextElement
==============

The **`SVGTextElement`** interface corresponds to the `<text>` elements.

EventTarget

Node

Element

SVGElement

SVGGraphicsElement

SVGTextContentElement

SVGTextPositioningElement

SVGTextElementInstance properties
-------------------

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

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

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

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

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

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

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

See also
--------

* `<text>`


RTCRtpTransceiver - Web APIs

RTCRtpTransceiver
=================

The WebRTC interface **`RTCRtpTransceiver`** describes a permanent pairing of an `RTCRtpSender` and an `RTCRtpReceiver`, along with some shared state.

 Each SDP media section describes one bidirectional SRTP ("Secure Real Time Protocol") stream (excepting the media section for `RTCDataChannel`, if present).
 This pairing of send and receive SRTP streams is significant for some applications, so `RTCRtpTransceiver` is used to represent this pairing, along with other important state from the media section.
 Each non-disabled SRTP media section is always represented by exactly one transceiver.

A transceiver is uniquely identified using its `mid` property, which is the same as the media ID (`mid`) of its corresponding m-line. An `RTCRtpTransceiver` is **associated** with an m-line if its `mid` is non-null; otherwise it's considered disassociated.

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

`currentDirection` Read only

 A read-only string which indicates the transceiver's current negotiated directionality, or `null` if the transceiver has never participated in an exchange of offers and answers.
 To change the transceiver's directionality, set the value of the `direction` property.

`direction`

A string which is used to set the transceiver's desired direction.

`mid` Read only

The media ID of the m-line associated with this transceiver. This association is established, when possible, whenever either a local or remote description is applied. This field is `null` if neither a local or remote description has been applied, or if its associated m-line is rejected by either a remote offer or any answer.

`receiver` Read only

The `RTCRtpReceiver` object that handles receiving and decoding incoming media.

`sender` Read only

The `RTCRtpSender` object responsible for encoding and sending data to the remote peer.

`stopped`
Deprecated

Indicates whether or not sending and receiving using the paired `RTCRtpSender` and `RTCRtpReceiver` has been permanently disabled, either due to SDP offer/answer, or due to a call to `stop()`.

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

`setCodecPreferences()`

A list of `RTCRtpCodecParameters` objects which override the default preferences used by the user agent for the transceiver's codecs.

`stop()`

 Permanently stops the `RTCRtpTransceiver`.
 The associated sender stops sending data, and the associated receiver likewise stops receiving and decoding incoming data.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # rtcrtptransceiver-interface |

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

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

See also
--------

* WebRTC API
* Introduction to the Real-time Transport Protocol (RTP)
* `RTCPeerConnection.addTrack()` and `RTCPeerConnection.addTransceiver()` both create transceivers
* `RTCRtpReceiver` and `RTCRtpSender`


AbsoluteOrientationSensor - Web APIs

AbsoluteOrientationSensor
=========================

The **`AbsoluteOrientationSensor`** interface of the Sensor APIs describes the device's physical orientation in relation to the Earth's reference coordinate system.

To use this sensor, the user must grant permission to the `'accelerometer'`, `'gyroscope'`, and `'magnetometer'` device sensors through the Permissions API.

This feature may be blocked by a Permissions Policy set on your server.

EventTarget

Sensor

OrientationSensor

AbsoluteOrientationSensorConstructor
-----------

`AbsoluteOrientationSensor()`

Creates a new `AbsoluteOrientationSensor` object.

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

*No specific properties; inherits properties from its ancestors `OrientationSensor` and `Sensor`.*

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

*No specific methods; inherits methods from its ancestors `OrientationSensor` and `Sensor`.*

Events
------

*No specific events; inherits methods from its ancestor, `Sensor`.*

Examples
--------

### Basic Example

The following example, which is loosely based on Intel's Orientation Phone demo, instantiates an `AbsoluteOrientationSensor` with a frequency of 60 times a second. On each reading it uses `OrientationSensor.quaternion` to rotate a visual model of a phone.

```js
const options = { frequency: 60, referenceFrame: "device" };
const sensor = new AbsoluteOrientationSensor(options);

sensor.addEventListener("reading", () => {
  // model is a Three.js object instantiated elsewhere.
  model.quaternion.fromArray(sensor.quaternion).inverse();
});
sensor.addEventListener("error", (error) => {
  if (event.error.name === "NotReadableError") {
    console.log("Sensor is not available.");
  }
});
sensor.start();
```

### Permissions Example

Using orientation sensors requires requesting permissions for multiple device sensors. Because the `Permissions` interface uses promises, a good way to request permissions is to use `Promise.all`.

```js
const sensor = new AbsoluteOrientationSensor();
Promise.all([
  navigator.permissions.query({ name: "accelerometer" }),
  navigator.permissions.query({ name: "magnetometer" }),
  navigator.permissions.query({ name: "gyroscope" }),
]).then((results) => {
  if (results.every((result) => result.state === "granted")) {
    sensor.start();
    // …
  } else {
    console.log("No permissions to use AbsoluteOrientationSensor.");
  }
});
```

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

| Specification |
| --- |
| Orientation Sensor # absoluteorientationsensor-interface |

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

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


AnimationTimeline - Web APIs

AnimationTimeline
=================

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

Newly availableSince September 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
The `AnimationTimeline` interface of the Web Animations API represents the timeline of an animation. This interface exists to define timeline features, inherited by other timeline types:

* `DocumentTimeline`
* `ScrollTimeline`
* `ViewTimeline`
Instance properties
-------------------

`currentTime` Read only

Returns the time value in milliseconds for this timeline or `null` if this timeline is inactive.

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

| Specification |
| --- |
| Web Animations # the-animationtimeline-interface |

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

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

See also
--------

* `DocumentTimeline`, `ScrollTimeline`, `ViewTimeline`
* `Document.timeline`
* Web Animations API
* CSS scroll-driven animations


GeolocationPosition - Web APIs

GeolocationPosition
===================

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

The **`GeolocationPosition`** interface represents the position of the concerned device at a given time. The position, represented by a `GeolocationCoordinates` object, comprehends the 2D position of the device, on a spheroid representing the Earth, but also its altitude and its speed.

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

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

`GeolocationPosition.coords` Read only

Returns a `GeolocationCoordinates` object defining the current location.

`GeolocationPosition.timestamp` Read only

Returns a timestamp, given as Unix time in milliseconds, representing the time at which the location was retrieved.

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

*The `GeolocationPosition` interface neither implements, nor inherits any methods.*

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

| Specification |
| --- |
| Geolocation API # position\_interface |

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

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

See also
--------

* Using the Geolocation API
* `Geolocation`


AudioData - Web APIs

AudioData
=========

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

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

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

The **`AudioData`** interface of the WebCodecs API represents an audio sample.

`AudioData` is a transferable object.

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

An audio track consists of a stream of audio samples, each sample representing a captured moment of sound. An `AudioData` object is a representation of such a sample. Working alongside the interfaces of the Insertable Streams API, you can break a stream into individual `AudioData` objects with `MediaStreamTrackProcessor`, or construct an audio track from a stream of frames with `MediaStreamTrackGenerator`.

**Note:** Find out more about audio on the web in Digital audio concepts.

### The media resource

An `AudioData` object contains a reference to an attached **media resource**. This media resource contains the actual audio sample data described by the object. A media resource is maintained by the user agent until it is no longer referenced by an `AudioData` object, for example when `AudioData.close()` is called.

### Planes and audio format

To return the sample format of an `AudioData` use the `AudioData.format` property. The format may be described as **interleaved** or **planar**. In interleaved formats, the audio samples from the different channels are laid out in a single buffer, described as a **plane**. This plane contains a number of elements equal to `AudioData.numberOfFrames` \* `AudioData.numberOfChannels`.

In planar format, the number of planes is equal to `AudioData.numberOfChannels`, and each plane is a buffer containing a number of elements equal to `AudioData.numberOfFrames`.

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

`AudioData()`
Experimental

Creates a new `AudioData` object.

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

`AudioData.format` Read only
Experimental

Returns the sample format of the audio.

`AudioData.sampleRate` Read only
Experimental

Returns the sample rate of the audio in Hz.

`AudioData.numberOfFrames` Read only
Experimental

Returns the number of frames.

`AudioData.numberOfChannels` Read only
Experimental

Returns the number of audio channels.

`AudioData.duration` Read only
Experimental

Returns the duration of the audio in microseconds.

`AudioData.timestamp` Read only
Experimental

Returns the timestamp of the audio in microseconds.

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

`AudioData.allocationSize()`
Experimental

Returns the number of bytes required to hold the sample as filtered by options passed into the method.

`AudioData.copyTo()`
Experimental

Copies the samples from the specified plane of the `AudioData` object to the destination.

`AudioData.clone()`
Experimental

Creates a new `AudioData` object with reference to the same media resource as the original.

`AudioData.close()`
Experimental

Clears all states and releases the reference to the media resource.

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

| Specification |
| --- |
| WebCodecs # audiodata-interface |

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

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


Resize Observer API - Web APIs

Resize Observer API
===================

The Resize Observer API provides a performant mechanism by which code can monitor an element for changes to its size, with notifications being delivered to the observer each time the size changes.

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

There are a whole raft of use cases for responsive design techniques (and others besides) that respond to changes in an element's size, but previously their implementations have often been hacky and/or brittle.

For example, media queries / `window.matchMedia` are great for updating layouts at specific points when the viewport changes sizes, but what if you want to change layout in response to a specific element's size changing, which isn't the outer container?

To achieve this, a limited solution would be to listen to changes to a suitable event that hints at the element you are interested in changing size (e.g. the window resize event), then figure out what the new dimensions or other features of the element after a resize using `Element.getBoundingClientRect` or `Window.getComputedStyle`, for example.

Such a solution tends to only work for limited use cases, be bad for performance (continually calling the above methods would result in a big performance hit), and often won't work when the browser window size is not changed.

The Resize Observer API provides a solution to exactly these kinds of problems, and more besides, allowing you to easily observe and respond to changes in the size of an element's content or border box in a performant way. It provides a JavaScript solution to the often-discussed lack of element queries in the web platform.

Usage is simple, and pretty much the same as other observers, such as Performance Observer or Intersection Observer — you create a new `ResizeObserver` object using the `ResizeObserver()` constructor, then use `ResizeObserver.observe()` to make it look for changes to a specific element's size. A callback function set up inside the constructor then runs every time the size changes, providing access to the new dimensions and allowing you to do anything you like in response to those changes.

Interfaces
----------

`ResizeObserver`

Provides the ability to register new observers and to start and stop observing elements.

`ResizeObserverEntry`

Describes a single element which has been resized, identifying the element and its new size.

Examples
--------

You find a couple of simple examples on our GitHub repo:

* resize-observer-border-radius.html (see source): A simple example with a green box, sized as a percentage of the viewport size. When the viewport size is changed, the box's rounded corners change in proportion to the size of the box. We could just implement this using `border-radius` with a percentage, but that quickly leads to ugly-looking elliptical corners, whereas the above solution gives you nice round corners that scale with the box size.
* resize-observer-text.html (see source): Here we use the resize observer to change the `font-size` of a header and paragraph as a slider's value is changed causing the containing `<div>` to change width. This shows that you can respond to changes in an element's size, even if they have nothing to do with the viewport.

The code will usually follow this kind of pattern (taken from resize-observer-border-radius.html):

```js
const resizeObserver = new ResizeObserver((entries) => {
  const calcBorderRadius = (size1, size2) =>
    `${Math.min(100, size1 / 10 + size2 / 10)}px`;

  for (const entry of entries) {
    if (entry.borderBoxSize) {
      entry.target.style.borderRadius = calcBorderRadius(
        entry.borderBoxSize[0].inlineSize,
        entry.borderBoxSize[0].blockSize,
      );
    } else {
      entry.target.style.borderRadius = calcBorderRadius(
        entry.contentRect.width,
        entry.contentRect.height,
      );
    }
  }
});

resizeObserver.observe(document.querySelector("div"));
```

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

| Specification |
| --- |
| Resize Observer # resize-observer-interface |

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

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

See also
--------

* ResizeObserver: It's Like document.onresize for Elements


DOMRect - Web APIs

DOMRect
=======

A **`DOMRect`** describes the size and position of a rectangle.

The type of box represented by the `DOMRect` is specified by the method or property that returned it. For example, `Range.getBoundingClientRect()` specifies the rectangle that bounds the content of the range using such objects.

It inherits from its parent, `DOMRectReadOnly`.

DOMRectReadOnly

DOMRectConstructor
-----------

`DOMRect()`

Creates a new `DOMRect` object.

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

*`DOMRect` inherits properties from its parent, `DOMRectReadOnly`. The difference is that they are not read-only anymore.*

`DOMRectReadOnly.x`

The x coordinate of the `DOMRect`'s origin (typically the top-left corner of the rectangle).

`DOMRectReadOnly.y`

The y coordinate of the `DOMRect`'s origin (typically the top-left corner of the rectangle).

`DOMRectReadOnly.width`

The width of the `DOMRect`.

`DOMRectReadOnly.height`

The height of the `DOMRect`.

`DOMRectReadOnly.top`

Returns the top coordinate value of the `DOMRect` (has the same value as `y`, or `y + height` if `height` is negative).

`DOMRectReadOnly.right`

Returns the right coordinate value of the `DOMRect` (has the same value as `x + width`, or `x` if `width` is negative).

`DOMRectReadOnly.bottom`

Returns the bottom coordinate value of the `DOMRect` (has the same value as `y + height`, or `y` if `height` is negative).

`DOMRectReadOnly.left`

Returns the left coordinate value of the `DOMRect` (has the same value as `x`, or `x + width` if `width` is negative).

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

*`DOMRect` may also inherit static methods from its parent, `DOMRectReadOnly`.*

`DOMRect.fromRect()`

Creates a new `DOMRect` object with a given location and dimensions.

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

*`DOMRect` may inherit methods from its parent, `DOMRectReadOnly`.*

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # DOMRect |

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

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

See also
--------

* `DOMPoint`