XPathException - Web APIs

XPathException
==============

**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.

In the DOM XPath API the **`XPathException`** interface represents exception conditions that can be encountered while performing XPath operations.

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

`XPathException.code` Read only

Returns a `short` that contains one of the error code constants.

Constants
---------

| Constant | Value | Description |
| --- | --- | --- |
| `INVALID_EXPRESSION_ERR` | `51` |
 If the expression has a syntax error or otherwise is not a legal
 expression according to the rules of the specific
 `XPathEvaluator` or contains specialized
 extension functions or variables not supported by this implementation.
  |
| `TYPE_ERR` | `52` | If the expression cannot be converted to return the specified type. |

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

#### No specification found

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

* `Document.createExpression()`
* `XPathExpression`


GeolocationPositionError - Web APIs

GeolocationPositionError
========================

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

The **`GeolocationPositionError`** interface represents the reason of an error occurring when using the geolocating device.

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

*The `GeolocationPositionError` interface doesn't inherit any property.*

`GeolocationPositionError.code` Read only

Returns an `unsigned short` representing the error code. The following values are possible:

| Value | Associated constant | Description |
| --- | --- | --- |
| `1` | `PERMISSION_DENIED` | The acquisition of the geolocation information failed because the page didn't have the necessary permissions, for example because it is blocked by a Permissions Policy |
| `2` | `POSITION_UNAVAILABLE` | The acquisition of the geolocation failed because at least one internal source of position returned an internal error. |
| `3` | `TIMEOUT` | The time allowed to acquire the geolocation was reached before the information was obtained. |

`GeolocationPositionError.message` Read only

Returns a human-readable string describing the details of the error. Specifications note that this is primarily intended for debugging use and not to be shown directly in a user interface.

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

*The `GeolocationPositionError` interface neither implements nor inherits any method.*

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

| Specification |
| --- |
| Geolocation API # position\_error\_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`


DeprecationReportBody - Web APIs

DeprecationReportBody
=====================

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

The `DeprecationReportBody` interface of the Reporting API represents the body of a deprecation report.

A deprecation report is generated when a deprecated feature (for example a deprecated API method) is used on a document being observed by a `ReportingObserver`. In addition to the support of this API, receiving useful deprecation warnings relies on browser vendors adding these warnings for deprecated features.

ReportBody

DeprecationReportBodyConstructor
-----------

An instance of `DeprecationReportBody` is returned as the value of `Report.body` when `Report.Type` is `deprecation`. The interface has no constructor.

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

This interface also inherits properties from `ReportBody`.

`DeprecationReportBody.id`
Experimental

A string representing the feature or API that is deprecated, for example `NavigatorGetUserMedia`. This can be used to group reports by deprecated feature.

`DeprecationReportBody.anticipatedRemoval`
Experimental

A `Date` object (rendered as a string) representing the date when the feature is expected to be removed from the current browser. If the date is not known, this property will return `null`.

`DeprecationReportBody.message`
Experimental

A string containing a human-readable description of the deprecation, including information such as what newer feature has superseded it, if any. This typically matches the message a browser will display in its DevTools console when a deprecated feature is used, if one is available.

`DeprecationReportBody.sourceFile`
Experimental

A string containing the path to the source file where the deprecated feature was used, if known, or `null` otherwise.

`DeprecationReportBody.lineNumber`
Experimental

A number representing the line in the source file in which the deprecated feature was used, if known, or `null` otherwise.

`DeprecationReportBody.columnNumber`
Experimental

A number representing the column in the source file in which the deprecated feature was used, if known, or `null` otherwise.

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

This interface also inherits methods from `ReportBody`.

`DeprecationReportBody.toJSON()`
Experimental

A *serializer* which returns a JSON representation of the `InterventionReportBody` object.

Examples
--------

In our deprecation\_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page:

```js
const options = {
  types: ["deprecation"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  reportBtn.onclick = () => displayReports(reports);
}, options);
```

We then tell it to start observing reports using `ReportingObserver.observe()`; this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor:

```js
observer.observe();
```

Because of the event handler we set up inside the `ReportingObserver()` constructor, we can now click the button to display the report details.

![image of a jolly bearded man with various stats displayed below it about a deprecated feature](/en-US/docs/Web/API/DeprecationReportBody/reporting_api_example.png)

The report details are displayed via the `displayReports()` function, which takes the observer callback's `reports` parameter as its parameter:

```js
function displayReports(reports) {
  const outputElem = document.querySelector(".output");
  const list = document.createElement("ul");
  outputElem.appendChild(list);

  reports.forEach((report, i) => {
    const listItem = document.createElement("li");
    const textNode = document.createTextNode(
      `Report ${i + 1}, type: ${report.type}`,
    );
    listItem.appendChild(textNode);
    const innerList = document.createElement("ul");
    listItem.appendChild(innerList);
    list.appendChild(listItem);

    for (const [key, value] of Object.entries(report.body)) {
      const innerListItem = document.createElement("li");
      innerListItem.textContent = `${key}: ${value}`;
      innerList.appendChild(innerListItem);
    }
  });
}
```

The `reports` parameter contains an array of all the reports in the observer's report queue. We loop over each report using a basic `for` loop, then iterate over each entry of in the report's body (a `DeprecationReportBody` instance) using a `for...in` structure, displaying each key/value pair inside a list item.

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

| Specification |
| --- |
| Deprecation Reporting # deprecationreportbody |

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

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

See also
--------

* Reporting API
* The Reporting API


SVGAnimateTransformElement - Web APIs

SVGAnimateTransformElement
==========================

The `SVGAnimateTransformElement` interface corresponds to the `<animateTransform>` element.

EventTarget

Node

Element

SVGElement

SVGAnimationElement

SVGAnimateTransformElementInstance properties
-------------------

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

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

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

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

| Specification |
| --- |
| SVG Animations Level 2 # InterfaceSVGAnimateTransformElement |

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

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


Bluetooth - Web APIs

Bluetooth
=========

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

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

 The **`Bluetooth`** interface of the Web Bluetooth API returns a
 `Promise` to a `BluetoothDevice` object with the specified
 options.

EventTarget

BluetoothInstance properties
-------------------

*Inherits properties from its parent `EventTarget`.*

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

`Bluetooth.getAvailability()`
Experimental

 Returns a `Promise` that resolved to a boolean value indicating
 whether the user-agent has the ability to support Bluetooth. Some user-agents let the
 user configure an option that affects what is returned by this value. If this option
 is set, that is the value returned by this method.

`Bluetooth.getDevices()`
Experimental

 Returns a `Promise` that resolved to an array of
 `BluetoothDevice`s which the origin already obtained permission for via a
 call to `Bluetooth.requestDevice()`.

`Bluetooth.requestDevice()`
Experimental

 Returns a `Promise` to a `BluetoothDevice` object with the
 specified options.

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

| Specification |
| --- |
| Web Bluetooth # bluetooth |

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

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


HTMLSourceElement - Web APIs

HTMLSourceElement
=================

The **`HTMLSourceElement`** interface provides special properties (beyond the regular `HTMLElement` object interface it also has available to it by inheritance) for manipulating `<source>` elements.

EventTarget

Node

Element

HTMLElement

HTMLSourceElementInstance properties
-------------------

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

`HTMLSourceElement.media`

A string reflecting the `media` HTML attribute, containing the intended type of the media resource.

`HTMLSourceElement.sizes`

A string representing image sizes between breakpoints

`HTMLSourceElement.src`

A string reflecting the `src` HTML attribute, containing the URL for the media resource. The `HTMLSourceElement.src` property has a meaning only when the associated `<source>` element is nested in a media element that is a `<video>` or an `<audio>` element. It has no meaning and is ignored when it is nested in a `<picture>` element.

**Note:** If the `src` property is updated (along with any siblings), the parent `HTMLMediaElement`'s `load` method should be called when done, since `<source>` elements are not re-scanned automatically.

`HTMLSourceElement.srcset`

A string reflecting the `srcset` HTML attribute, containing a list of candidate images, separated by a comma (`',', U+002C COMMA`). A candidate image is a URL followed by a `'w'` with the width of the images, or an `'x'` followed by the pixel density.

`HTMLSourceElement.type`

A string reflecting the `type` HTML attribute, containing the type of the media resource.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlsourceelement |

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

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

See also
--------

* The HTML element implementing this interface: `<source>`.
* The HTML DOM APIs of the elements that can contain a `<source>` element: `HTMLVideoElement`, `HTMLAudioElement`, `HTMLPictureElement`.


PaymentAddress - Web APIs

PaymentAddress
==============

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

**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.

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

The **`PaymentAddress`** interface of the Payment Request API is used to store shipping or payment address information.

It may be useful to refer to the Universal Postal Union website's Addressing S42 standard materials, which provide information about international standards for postal addresses.

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

`PaymentAddress.addressLine` Read only
Deprecated

Non-standard

An array of strings providing each line of the address not included among the other properties. The exact size and content varies by country or location and can include, for example, a street name, house number, apartment number, rural delivery route, descriptive instructions, or post office box number.

`PaymentAddress.country` Read only
Deprecated

Non-standard

A string specifying the country in which the address is located, using the ISO-3166-1 alpha-2 standard. The string is always given in its canonical upper-case form. Some examples of valid `country` values: `"US"`, `"GB"`, `"CN"`, or `"JP"`.

`PaymentAddress.city` Read only
Deprecated

Non-standard

A string which contains the city or town portion of the address.

`PaymentAddress.dependentLocality` Read only
Deprecated

Non-standard

A string giving the dependent locality or sublocality within a city, for example, a neighborhood, borough, district, or UK dependent locality.

`PaymentAddress.organization` Read only
Deprecated

Non-standard

A string specifying the name of the organization, firm, company, or institution at the payment address.

`PaymentAddress.phone` Read only
Deprecated

Non-standard

A string specifying the telephone number of the recipient or contact person.

`PaymentAddress.postalCode` Read only
Deprecated

Non-standard

A string specifying a code used by a jurisdiction for mail routing, for example, the ZIP code in the United States or the PIN code in India.

`PaymentAddress.recipient` Read only
Deprecated

Non-standard

A string giving the name of the recipient, purchaser, or contact person at the payment address.

`PaymentAddress.region` Read only
Deprecated

Non-standard

A string containing the top level administrative subdivision of the country, for example a state, province, oblast, or prefecture.

`PaymentAddress.sortingCode` Read only
Deprecated

Non-standard

A string providing a postal sorting code such as is used in France.

**Note:** Properties for which values were not specified contain empty strings.

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

`PaymentAddress.toJSON()`
Deprecated

Non-standard

A standard serializer that returns a JSON representation of the `PaymentAddress` object's properties.

Examples
--------

In the following example, the `PaymentRequest()` constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options.

The first of these three (`supportedInstruments` in the example below) contains a `data` property that has to conform to the structure defined by the payment method.

```js
const supportedInstruments = [
  {
    supportedMethods: "https://example.com/pay",
  },
];

const details = {
  total: { label: "Donation", amount: { currency: "USD", value: "65.00" } },
  displayItems: [
    {
      label: "Original donation amount",
      amount: { currency: "USD", value: "65.00" },
    },
  ],
  shippingOptions: [
    {
      id: "standard",
      label: "Standard shipping",
      amount: { currency: "USD", value: "0.00" },
      selected: true,
    },
  ],
};

const options = { requestShipping: true };

async function doPaymentRequest() {
  const request = new PaymentRequest(supportedInstruments, details, options);
  // Add event listeners here.
  // Call show() to trigger the browser's payment flow.
  const response = await request.show();
  // Process payment.
  const json = response.toJSON();
  const httpResponse = await fetch("/pay/", { method: "POST", body: json });
  const result = httpResponse.ok ? "success" : "failure";

  await response.complete(result);
}
doPaymentRequest();
```

Once the payment flow has been triggered using `PaymentRequest.show()` and the promise resolves successfully, the `PaymentResponse` object available from the fulfilled promise (`instrumentResponse` above) will have a `PaymentResponse.details` property containing response details. This has to conform to the structure defined by the payment method provider.

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

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


GPUCommandEncoder - Web APIs

GPUCommandEncoder
=================

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

The **`GPUCommandEncoder`** interface of the WebGPU API represents a command encoder, used to encode commands to be issued to the GPU.

A `GPUCommandEncoder` object instance is created via the `GPUDevice.createCommandEncoder()` property.

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

`label`
Experimental

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

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

`beginComputePass()`
Experimental

Starts encoding a compute pass, returning a `GPUComputePassEncoder` that can be used to control computation.

`beginRenderPass()`
Experimental

Starts encoding a render pass, returning a `GPURenderPassEncoder` that can be used to control rendering.

`clearBuffer()`
Experimental

Encodes a command that fills a region of a `GPUBuffer` with zeroes.

`copyBufferToBuffer()`
Experimental

Encodes a command that copies data from one `GPUBuffer` to another.

`copyBufferToTexture()`
Experimental

Encodes a command that copies data from a `GPUBuffer` to a `GPUTexture`.

`copyTextureToBuffer()`
Experimental

Encodes a command that copies data from a `GPUTexture` to a `GPUBuffer`.

`copyTextureToTexture()`
Experimental

Encodes a command that copies data from one `GPUTexture` to another.

`finish()`
Experimental

Completes recording of the command sequence encoded on this `GPUCommandEncoder`, returning a corresponding `GPUCommandBuffer`.

`insertDebugMarker()`
Experimental

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

`popDebugGroup()`
Experimental

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

`pushDebugGroup()`
Experimental

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

`resolveQuerySet()`
Experimental

Encodes a command that resolves a `GPUQuerySet`, copying the results into a specified `GPUBuffer`.

`writeTimestamp()`
Experimental

Encodes a command that writes a timestamp into a `GPUQuerySet` once the previous commands recorded into the same queued `GPUCommandBuffer` have been executed by the GPU.

Examples
--------

In our basic render demo, several commands are recorded via a `GPUCommandEncoder`:

```js
// ...

// Create GPUCommandEncoder
const commandEncoder = device.createCommandEncoder();

// Create GPURenderPassDescriptor to tell WebGPU which texture to draw into, then initiate render pass

const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear",
      storeOp: "store",
      view: context.getCurrentTexture().createView(),
    },
  ],
};

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

// Draw a triangle

passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

// End the render pass

passEncoder.end();

// ...
```

The commands encoded by the `GPUCommandEncoder` are recoded into a `GPUCommandBuffer` using the `GPUCommandEncoder.finish()` method. The command buffer is then passed into the queue via a `submit()` call, ready to be processed by the GPU.

```js
device.queue.submit([commandEncoder.finish()]);
```

**Note:** Study the WebGPU samples to find more command encoding examples.

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

| Specification |
| --- |
| WebGPU # gpucommandencoder |

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

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

See also
--------

* The WebGPU API


Animation - Web APIs

Animation
=========

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 **`Animation`** interface of the Web Animations API represents a single animation player and provides playback controls and a timeline for an animation node or source.

EventTarget

AnimationConstructor
-----------

`Animation()`

Creates a new `Animation` object instance.

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

`Animation.currentTime`

The current time value of the animation in milliseconds, whether running or paused. If the animation lacks a `timeline`, is inactive or hasn't been played yet, its value is `null`.

`Animation.effect`

Gets and sets the `AnimationEffect` associated with this animation. This will usually be a `KeyframeEffect` object.

`Animation.finished` Read only

Returns the current finished Promise for this animation.

`Animation.id`

Gets and sets the `String` used to identify the animation.

`Animation.pending` Read only

Indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation.

`Animation.playState` Read only

Returns an enumerated value describing the playback state of an animation.

`Animation.playbackRate`

Gets or sets the playback rate of the animation.

`Animation.ready` Read only

Returns the current ready Promise for this animation.

`Animation.replaceState` Read only

Indicates whether the animation is active, has been automatically removed after being replaced by another animation, or has been explicitly persisted by a call to `Animation.persist()`.

`Animation.startTime`

Gets or sets the scheduled time when an animation's playback should begin.

`Animation.timeline`

Gets or sets the `timeline` associated with this animation.

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

`Animation.cancel()`

Clears all `keyframeEffects` caused by this animation and aborts its playback.

`Animation.commitStyles()`

Commits the current styling state of an animation to the element being animated, even after that animation has been removed. It will cause the current styling state to be written to the element being animated, in the form of properties inside a `style` attribute.

`Animation.finish()`

Seeks either end of an animation, depending on whether the animation is playing or reversing.

`Animation.pause()`

Suspends playing of an animation.

`Animation.persist()`

Explicitly persists an animation, preventing it from being automatically removed when another animation replaces it.

`Animation.play()`

Starts or resumes playing of an animation, or begins the animation again if it previously finished.

`Animation.reverse()`

Reverses playback direction, stopping at the start of the animation. If the animation is finished or unplayed, it will play from end to beginning.

`Animation.updatePlaybackRate()`

Sets the speed of an animation after first synchronizing its playback position.

Events
------

`cancel`

Fires when the `Animation.cancel()` method is called or when the animation enters the `"idle"` play state from another state.

`finish`

Fires when the animation finishes playing.

`remove`

Fires when the animation is automatically removed by the browser.

Accessibility concerns
----------------------

Blinking and flashing animation can be problematic for people with cognitive concerns such as Attention Deficit Hyperactivity Disorder (ADHD). Additionally, certain kinds of motion can be a trigger for Vestibular disorders, epilepsy, and migraine, and Scotopic sensitivity.

Consider providing a mechanism for pausing or disabling animation, as well as using the Reduced Motion Media Query (or equivalent user agent client hint `Sec-CH-Prefers-Reduced-Motion`) to create a complimentary experience for users who have expressed a preference for no animated experiences.

* Designing Safer Web Animation For Motion Sensitivity · An A List Apart Article
* An Introduction to the Reduced Motion Media Query | CSS-Tricks
* Responsive Design for Motion | WebKit
* MDN Understanding WCAG, Guideline 2.2 explanations
* Understanding Success Criterion 2.2.2 | W3C Understanding WCAG 2.0
Specifications
--------------

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

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

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

See also
--------

* Web Animations API


MessagePort - Web APIs

MessagePort
===========

The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a `MessageChannel`, allowing messages to be sent from one port and listening out for them arriving at the other.

`MessagePort` is a transferable object.

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

EventTarget

MessagePortInstance methods
----------------

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

`postMessage()`

Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.

`start()`

Starts the sending of messages queued on the port (only needed when using `EventTarget.addEventListener`; it is implied when using `onmessage`).

`close()`

Disconnects the port, so it is no longer active.

Events
------

*Inherits events from its parent, `EventTarget`*.

`message`

Fired when a `MessagePort` object receives a message.

`messageerror`

Fired when a `MessagePort` object receives a message that can't be deserialized.

Example
-------

In the following example, you can see a new channel being created using the `MessageChannel()` constructor.

When the IFrame has loaded, we register an `onmessage` handler for `MessageChannel.port1` and transfer `MessageChannel.port2` to the IFrame using the `window.postMessage` method along with a message.

When a message is received back from the IFrame, the `onMessage` function outputs the message to a paragraph.

```js
const channel = new MessageChannel();
const output = document.querySelector(".output");
const iframe = document.querySelector("iframe");

// Wait for the iframe to load
iframe.addEventListener("load", onLoad);

function onLoad() {
  // Listen for messages on port1
  channel.port1.onmessage = onMessage;

  // Transfer port2 to the iframe
  iframe.contentWindow.postMessage("Hello from the main page!", "\*", [
    channel.port2,
  ]);
}

// Handle messages received on port1
function onMessage(e) {
  output.innerHTML = e.data;
}
```

For a full working example, see our channel messaging basic demo on GitHub (run it live too).

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

| Specification |
| --- |
| HTML Standard # message-ports |

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

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

See also
--------

* Using channel messaging


WebTransportError - Web APIs

WebTransportError
=================

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

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

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

The **`WebTransportError`** interface of the WebTransport API represents an error related to the API, which can arise from server errors, network connection problems, or client-initiated abort operations (for example, arising from a `WritableStream.abort()` call).

DOMException

WebTransportError

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

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

`WebTransportError()`

Creates a new `WebTransportError` object instance.

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

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

`source` Read only

Returns an enumerated value indicating the source of the error—can be either `stream` or `session`.

`streamErrorCode` Read only

Returns a number in the range 0-255 indicating the application protocol error code for this error, or `null` if one is not available.

Examples
--------

```js
const url = "notaurl";

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

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

    // ...
  } catch (error) {
    const msg = `Transport initialization failed.
 Reason: ${error.message}.
 Source: ${error.source}.
 Error code: ${error.streamErrorCode}.`;
    console.log(msg);
  }
}
```

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

| Specification |
| --- |
| WebTransport # webtransporterror |

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

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

See also
--------

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


FeaturePolicy - Web APIs

FeaturePolicy
=============

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

The `FeaturePolicy` interface represents the set of Permissions Policies applied to the current execution context.

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

`FeaturePolicy.allowsFeature`
Experimental

Returns a Boolean that indicates whether or not a particular feature is enabled in the specified context.

`FeaturePolicy.features`
Experimental

Returns a list of names of all features supported by the User Agent. Features whose names appear on the list might not be allowed by the Permissions Policy of the current execution context and/or might be restricted by user-granted permissions.

`FeaturePolicy.allowedFeatures`
Experimental

Returns a list of names of all features supported by the User Agent and allowed by the Permissions Policy. Note that features appearing on this list might still be behind a user permission.

`FeaturePolicy.getAllowlistForFeature`
Experimental

Returns the allow for the specified feature.

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

#### No specification found

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

* `Permissions-Policy`
* Privacy, permissions, and information security


GPUOutOfMemoryError - Web APIs

GPUOutOfMemoryError
===================

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

The **`GPUOutOfMemoryError`** interface of the WebGPU API describes an out-of-memory (oom) error indicating that there was not enough free memory to complete the requested operation.

It represents one of the types of errors surfaced by `GPUDevice.popErrorScope` and the `uncapturederror` event.

Out-of-memory errors should be relatively rare in a well-behaved app but are less predictable than `GPUValidationError`s. This is because they are dependent on the device your app is running on as well as other apps that are using GPU resources at the time.

GPUError

GPUOutOfMemoryErrorConstructor
-----------

`GPUOutOfMemoryError()`
Experimental

Creates a new `GPUOutOfMemoryError` object instance.

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

The `message` property is inherited from its parent, `GPUError`:

`message`
Experimental
 Read only

A string providing a human-readable message that explains why the error occurred.

Examples
--------

The following example uses an error scope to capture an out-of-memory error, logging it to the console.

```js
device.pushErrorScope("out-of-memory");

let buffer = device.createBuffer({
  size: 100\_000\_000\_000, // 100GB; far too big
  usage: GPUBufferUsage.COPY\_SRC | GPUBufferUsage.MAP\_WRITE,
});

device.popErrorScope().then((error) => {
  if (error) {
    // error is a GPUOutOfMemoryError object instance
    buffer = null;
    console.error(`Out of memory, buffer too large. Error: ${error.message}`);
  }
});
```

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

| Specification |
| --- |
| WebGPU # gpuoutofmemoryerror |

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

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

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices


SVGClipPathElement - Web APIs

SVGClipPathElement
==================

The **`SVGClipPathElement`** interface provides access to the properties of `<clipPath>` elements, as well as methods to manipulate them.

EventTarget

Node

Element

SVGElement

SVGClipPathElementInstance properties
-------------------

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

`SVGClipPathElement.clipPathUnits` Read only

Returns an `SVGAnimatedEnumeration` corresponding to the `clipPathUnits` attribute of the associated `<clipPath>` element. Takes one of the constants defined in `SVGUnitTypes`.

`SVGClipPathElement.transform` Read only

Returns an `SVGAnimatedTransformList` corresponding to the `transform` attribute of the associated `<clipPath>` element.

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

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

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

| Specification |
| --- |
| CSS Masking Module Level 1 # InterfaceSVGClipPathElement |

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

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

See also
--------

* `<clipPath>`


SVGTRefElement - Web APIs

SVGTRefElement
==============

**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 **`SVGTRefElement`** interface corresponds to the `<tref>` elements.

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

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

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

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

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

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

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

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

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

See also
--------

* `<tref>`


HTMLEmbedElement - Web APIs

HTMLEmbedElement
================

The **`HTMLEmbedElement`** interface provides special properties (beyond the regular `HTMLElement` interface it also has available to it by inheritance) for manipulating `<embed>` elements.

**Note:** This topic describes the `HTMLEmbedElement` interface as defined in the standard. It does not address earlier, non-standardized version of the interface.

EventTarget

Node

Element

HTMLElement

HTMLEmbedElementInstance properties
-------------------

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

`HTMLEmbedElement.align`
Deprecated

A string representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"center"`, and `"justify"`.

`HTMLEmbedElement.height`

A string reflecting the `height` HTML attribute, containing the displayed height of the resource.

`HTMLEmbedElement.name`
Deprecated

A string representing the name of the embedded object.

`HTMLEmbedElement.src`

A string that reflects the `src` HTML attribute, containing the address of the resource.

`HTMLEmbedElement.type`

A string that reflects the `type` HTML attribute, containing the type of the resource.

`HTMLEmbedElement.width`

A string that reflects the `width` HTML attribute, containing the displayed width of the resource.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlembedelement |

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

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

See also
--------

* The HTML element implementing this interface: `<embed>`


queueMicrotask() global function - Web APIs

queueMicrotask() global function
================================

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

 The **`queueMicrotask()`** method,
 which is exposed on the `Window` or `Worker` interface,
 queues a microtask to be executed at a safe time prior to control returning to the
 browser's event loop.

 The microtask is a short function which will run after
 the current task has completed its work and when there is no other code waiting to be
 run before control of the execution context is returned to the browser's event loop.

 This lets your code run without interfering with any other, potentially higher
 priority, code that is pending, but before the browser regains control over the
 execution context, potentially depending on work you need to complete. You can learn
 more about how to use microtasks and why you might choose to do so in our microtask guide.

 The importance of microtasks comes in its ability to perform tasks asynchronously but
 in a specific order. See Using microtasks in JavaScript with queueMicrotask() for more details.

 Microtasks are especially useful for libraries and frameworks that need to perform
 final cleanup or other just-before-rendering tasks.

Syntax
------

```js
queueMicrotask(() => {/\* ... \*/})
```

### Parameters

`function`

 A `function` to be executed when the browser engine determines it is
 safe to call your code. Enqueued microtasks are executed after all pending tasks have
 completed but before yielding control to the browser's event loop.

### Return value

None (`undefined`).

Examples
--------

```js
queueMicrotask(() => {
  // function contents here
});
```

Taken from the queueMicrotask spec:

```js
MyElement.prototype.loadData = function (url) {
  if (this._cache[url]) {
    queueMicrotask(() => {
      this.\_setData(this._cache[url]);
      this.dispatchEvent(new Event("load"));
    });
  } else {
    fetch(url)
      .then((res) => res.arrayBuffer())
      .then((data) => {
        this._cache[url] = data;
        this.\_setData(data);
        this.dispatchEvent(new Event("load"));
      });
  }
};
```

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

| Specification |
| --- |
| HTML Standard # microtask-queuing |

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

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

See also
--------

* Polyfill of `queueMicrotask()` in `core-js`
* Using microtasks in JavaScript with queueMicrotask()
* Asynchronous JavaScript
* queueMicrotask explainer
* Tasks, microtasks, queues and schedules by Jake Archibald


ServiceWorkerRegistration - Web APIs

ServiceWorkerRegistration
=========================

The **`ServiceWorkerRegistration`** interface of the Service Worker API represents the service worker registration. You register a service worker to control one or more pages that share the same origin.

The lifetime of a service worker registration is beyond that of the `ServiceWorkerRegistration` objects that represent them within the lifetime of their corresponding service worker clients. The browser maintains a persistent list of active `ServiceWorkerRegistration` objects.

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

EventTarget

ServiceWorkerRegistrationInstance properties
-------------------

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

`ServiceWorkerRegistration.active` Read only

Returns a service worker whose state is `activating` or `activated`. This is initially set to `null`. An active worker will control a `Client` if the client's URL falls within the scope of the registration (the `scope` option set when `ServiceWorkerContainer.register` is first called.)

`ServiceWorkerRegistration.backgroundFetch` Read only
Experimental

Returns a reference to a `BackgroundFetchManager` object, which manages background fetch operations.

`ServiceWorkerRegistration.cookies` Read only
Experimental

Returns a reference to the `CookieStoreManager` interface, which allows subscribe and unsubscribe to cookie change events.

`ServiceWorkerRegistration.index` Read only
Experimental

Returns a reference to the `ContentIndex` interface, for managing indexed content for offline viewing.

`ServiceWorkerRegistration.installing` Read only

Returns a service worker whose state is `installing`. This is initially set to `null`.

`ServiceWorkerRegistration.navigationPreload` Read only

Returns the instance of `NavigationPreloadManager` associated with the current service worker registration.

`ServiceWorkerRegistration.paymentManager` Read only
Experimental

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

`ServiceWorkerRegistration.periodicSync` Read only
Experimental

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

`ServiceWorkerRegistration.pushManager` Read only

Returns a reference to the `PushManager` interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status.

`ServiceWorkerRegistration.scope` Read only

Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the `ServiceWorker`.

`ServiceWorkerRegistration.sync` Read only
Experimental

Returns a reference to the `SyncManager` interface, which manages background synchronization processes.

`ServiceWorkerRegistration.updateViaCache` Read only

Returns a string indicating what is the cache strategy to use when updating the service worker scripts. It can be one of the following: `imports`, `all`, or `none`.

`ServiceWorkerRegistration.waiting` Read only

Returns a service worker whose state is `installed`. This is initially set to `null`.

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

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

`ServiceWorkerRegistration.getNotifications()`

Returns a list of the notifications in the order that they were created from the current origin via the current service worker registration.

`ServiceWorkerRegistration.showNotification()`

Displays the notification with the requested title.

`ServiceWorkerRegistration.unregister()`

Unregisters the service worker registration and returns a `Promise`. The service worker will finish any ongoing operations before it is unregistered.

`ServiceWorkerRegistration.update()`

Checks the server for an updated version of the service worker without consulting caches.

Events
------

`updatefound`

Fired any time the `ServiceWorkerRegistration.installing` property acquires a new service worker.

Examples
--------

In this example, the code first checks whether the browser supports service workers and if so registers one. Next, it adds an `updatefound` listener in which it uses the service worker registration to listen for further changes to the service worker's state. If the service worker hasn't changed since the last time it was registered, then the `updatefound` event will not be fired.

```js
if ("serviceWorker" in navigator) {
  navigator.serviceWorker
    .register("/sw.js")
    .then((registration) => {
      registration.addEventListener("updatefound", () => {
        // If updatefound is fired, it means that there's
        // a new service worker being installed.
        const installingWorker = registration.installing;
        console.log(
          "A new service worker is being installed:",
          installingWorker,
        );

        // You can listen for changes to the installing service worker's
        // state via installingWorker.onstatechange
      });
    })
    .catch((error) => {
      console.error(`Service worker registration failed: ${error}`);
    });
} else {
  console.error("Service workers are not supported.");
}
```

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

| Specification |
| --- |
| Service Workers # serviceworkerregistration-interface |
| Push API # extensions-to-the-serviceworkerregistration-interface |

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

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

See also
--------

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


HTMLTrackElement - Web APIs

HTMLTrackElement
================

The **`HTMLTrackElement`** interface represents an HTML `<track>` element within the DOM. This element can be used as a child of either `<audio>` or `<video>` to specify a text track containing information such as closed captions or subtitles.

EventTarget

Node

Element

HTMLElement

HTMLTrackElementInstance properties
-------------------

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

`HTMLTrackElement.kind`

A string that reflects the `kind` HTML attribute, indicating how the text track is meant to be used. Possible values are: `subtitles`, `captions`, `descriptions`, `chapters`, or `metadata`.

`HTMLTrackElement.src`

A string that reflects the `src` HTML attribute, indicating the address of the text track data.

`HTMLTrackElement.srclang`

A string that reflects the `srclang` HTML attribute, indicating the language of the text track data.

`HTMLTrackElement.label`

A string that reflects the `label` HTML attribute, indicating a user-readable title for the track.

`HTMLTrackElement.default`

A boolean value reflecting the `default` attribute, indicating that the track is to be enabled if the user's preferences do not indicate that another track would be more appropriate.

`HTMLTrackElement.readyState` Read only

Returns an `unsigned short` that show the readiness state of the track:

| Constant | Value | Description |
| --- | --- | --- |
| `NONE` | 0 | Indicates that the text track's cues have not been obtained. |
| `LOADING` | 1 | Indicates that the text track is loading and there have been no fatal errors encountered so far. Further cues might still be added to the track by the parser. |
| `LOADED` | 2 | Indicates that the text track has been loaded with no fatal errors. |
| `ERROR` | 3 | Indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way. Some or all of the cues are likely missing and will not be obtained. |

`HTMLTrackElement.track` Read only

Returns `TextTrack` is the track element's text track data.

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

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

Events
------

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

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

`cuechange`

 Sent when the underlying `TextTrack` has changed the currently-presented cues. This event is always sent to the `TextTrack` but is *also* sent to the `HTMLTrackElement` if one is associated with the track.
 You may also use the `oncuechange` event handler to establish a handler for this event.

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

### Loading of the track's text resource

The WebVTT or TTML data describing the actual cues for the text track isn't loaded if the track's `mode` is initially in the `disabled` state. If you need to be able to perform any processing on the track after the `<track>` is set up, you should instead ensure that the track's `mode` is either `hidden` (if you don't want it to start out being presented to the user) or `showing` (to initially display the track). You can then change the mode as desired later.

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

| Specification |
| --- |
| HTML Standard # htmltrackelement |

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

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

See also
--------

* The HTML element implementing this interface: `<track>`.


TextUpdateEvent - Web APIs

TextUpdateEvent
===============

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

The **`TextUpdateEvent`** interface is a `DOM event` that represents a text or selection update in an editable text region that's attached to an `EditContext` instance.

This interface inherits properties from `Event`.

Event

TextUpdateEventConstructor
-----------

`TextUpdateEvent()`
Experimental

Creates a new `TextUpdateEvent` object.

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

`TextUpdateEvent.updateRangeStart` Read only
Experimental

Returns the index of the first character in the range of text that was updated.

`TextUpdateEvent.updateRangeEnd` Read only
Experimental

Returns the index of the last character in the range of text that was updated.

`TextUpdateEvent.text` Read only
Experimental

Returns the text that was inserted in the updated range.

`TextUpdateEvent.selectionStart` Read only
Experimental

Returns the index of the first character in the new selection range, after the update.

`TextUpdateEvent.selectionEnd` Read only
Experimental

Returns the index of the last character in the new selection range, after the update.

Examples
--------

### Rendering the updated text in an editable canvas

In the following example, the EditContext API is used to render editable text in a `<canvas>` element, and the `textupdate` event is used to render the text when the user is typing.

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

```js
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
const editContext = new EditContext();
canvas.editContext = editContext;

function render() {
  // Clear the canvas.
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Render the text.
  ctx.fillText(editContext.text, 10, 10);
}

editContext.addEventListener("textupdate", (e) => {
  // Re-render the editor view when the user is entering text.
  render();

  console.log(
    `The user entered ${e.text}. Rendering the entire text: ${editContext.text}`,
  );
});
```

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

| Specification |
| --- |
| EditContext API # dom-textupdateevent |

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

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


EXT_color_buffer_float extension - Web APIs

EXT\_color\_buffer\_float extension
===================================

The **`EXT_color_buffer_float`** extension is part of WebGL and adds the ability to render a variety of floating point formats.

WebGL extensions are available using the `WebGLRenderingContext.getExtension()` method. For more information, see also Using Extensions in the WebGL tutorial.

**Note:** This extension is available to WebGL 2 contexts only.

For WebGL 1, see the `EXT_color_buffer_half_float` and `WEBGL_color_buffer_float` extensions.

Extended methods
----------------

The following sized formats become **color-renderable**:

* `gl.R16F`,
* `gl.RG16F`,
* `gl.RGBA16F`,
* `gl.R32F`,
* `gl.RG32F`,
* `gl.RGBA32F`,
* `gl.R11F_G11F_B10F`.

**Color-renderable** means:

* The `WebGLRenderingContext.renderbufferStorage()` method now accepts these formats.
* Framebuffers with attached textures of these formats may now be **FRAMEBUFFER\_COMPLETE**.
Examples
--------

`gl` must be a `WebGL2RenderingContext`. This extension does not work in WebGL 1 contexts.

```js
const ext = gl.getExtension("EXT\_color\_buffer\_float");

gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA16F, 256, 256);
```

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

| Specification |
| --- |
| WebGL EXT\_color\_buffer\_float Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.renderbufferStorage()`
* `EXT_color_buffer_half_float`
* `WEBGL_color_buffer_float`


OscillatorNode - Web APIs

OscillatorNode
==============

The **`OscillatorNode`** interface represents a periodic waveform, such as a sine wave. It is an `AudioScheduledSourceNode` audio-processing module that causes a specified frequency of a given wave to be created—in effect, a constant tone.

EventTarget

AudioNode

AudioScheduledSourceNode

OscillatorNode

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |
| Channel count mode | `max` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `speakers` |

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

`OscillatorNode()`

Creates a new instance of an `OscillatorNode` object, optionally providing an object specifying default values for the node's properties. As an alternative, you can use the `BaseAudioContext.createOscillator()` factory method; see Creating an AudioNode.

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

*Inherits properties from its parent, `AudioScheduledSourceNode`, and adds the following properties:*

`OscillatorNode.frequency`

An a-rate `AudioParam` representing the frequency of oscillation in hertz (though the `AudioParam` returned is read-only, the value it represents is not). The default value is 440 Hz (a standard middle-A note).

`OscillatorNode.detune`

An a-rate `AudioParam` representing detuning of oscillation in cents (though the `AudioParam` returned is read-only, the value it represents is not). The default value is 0.

`OscillatorNode.type`

A string which specifies the shape of waveform to play; this can be one of a number of standard values, or `custom` to use a `PeriodicWave` to describe a custom waveform. Different waves will produce different tones. Standard values are `"sine"`, `"square"`, `"sawtooth"`, `"triangle"` and `"custom"`. The default is `"sine"`.

### Event handlers

`AudioScheduledSourceNode.ended_event`

Sets the event handler for the `ended` event, which fires when the tone has stopped playing.

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

*Inherits methods from its parent, `AudioScheduledSourceNode`, and adds the following:*

`OscillatorNode.setPeriodicWave()`

Sets a `PeriodicWave` which describes a periodic waveform to be used instead of one of the standard waveforms; calling this sets the `type` to `custom`.

`AudioScheduledSourceNode.start()`

Specifies the exact time to start playing the tone.

`AudioScheduledSourceNode.stop()`

Specifies the time to stop playing the tone.

Examples
--------

The following example shows basic usage of an `AudioContext` to create an oscillator node and to start playing a tone on it. For an applied example, check out our Violent Theremin demo (see app.js for relevant code).

```js
// create web audio api context
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// create Oscillator node
const oscillator = audioCtx.createOscillator();

oscillator.type = "square";
oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz
oscillator.connect(audioCtx.destination);
oscillator.start();
```

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

| Specification |
| --- |
| Web Audio API # OscillatorNode |

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

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

See also
--------

* Using the Web Audio API


XRWebGLSubImage - Web APIs

XRWebGLSubImage
===============

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

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

The **`XRWebGLSubImage`** interface is used during rendering of WebGL layers.

XRSubImage

XRWebGLSubImageInstance properties
-------------------

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

`XRWebGLSubImage.colorTexture` Read only
Experimental

A color `WebGLTexture` object for the `XRCompositionLayer` to render.

`XRWebGLSubImage.depthStencilTexture` Read only
Experimental

A depth/stencil `WebGLTexture` object for the `XRCompositionLayer` to render.

`XRWebGLSubImage.imageIndex` Read only
Experimental

A number representing the offset into the texture array if the layer was requested with `texture-array`; `null` otherwise.

`XRWebGLSubImage.colorTextureWidth` Read only
Experimental

A number representing the width in pixels of the GL attachment.

`XRWebGLSubImage.colorTextureHeight` Read only
Experimental

A number representing the height in pixels of the GL attachment.

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

| Specification |
| --- |
| WebXR Layers API Level 1 # xrwebglsubimagetype |

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

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

See also
--------

* `XRLayer`
* `XRWebGLBinding.getSubImage()`
* `XRWebGLBinding.getViewSubImage()`


RTCStatsReport - Web APIs

RTCStatsReport
==============

The **`RTCStatsReport`** interface of the WebRTC API provides a statistics report for a `RTCPeerConnection`, `RTCRtpSender`, or `RTCRtpReceiver`.

An `RTCStatsReport` instance is a read-only `Map`-like object, in which each key is an identifier for an object for which statistics are being reported, and the corresponding value is a dictionary object providing the statistics.

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

`RTCStatsReport.size`

Returns the number of items in the `RTCStatsReport` object.

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

`RTCStatsReport.entries()`

Returns a new Iterator object that contains a two-member array of `[id, statistic-dictionary]` for each element in the `RTCStatsReport` object, in insertion order.

`RTCStatsReport.forEach()`

 Calls `callbackFn` once for each key-value pair present in the `RTCStatsReport` object, in insertion order.
 If a `thisArg` parameter is provided to `forEach`, it will be used as the `this` value for each callback.

`RTCStatsReport.get()`

Returns the statistics dictionary associated with the passed `id`, or `undefined` if there is none.

`RTCStatsReport.has()`

Returns a boolean indicating whether the `RTCStatsReport` contains a statistics dictionary associated with the specified `id`.

`RTCStatsReport.keys()`

Returns a new Iterator object that contains the keys (IDs) for each element in the `RTCStatsReport` object, in insertion order.

`RTCStatsReport.values()`

Returns a new Iterator object that contains the values (statistics object) for each element in the `RTCStatsReport` object, in insertion order.

`RTCStatsReport.[@@iterator]()`

Returns a new Iterator object that contains a two-member array of `[id, statistic-dictionary]` for each element in the `RTCStatsReport` object, in insertion order.

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

 A `Promise` that resolves to an `RTCStatsReport` is returned from the `RTCRtpReceiver.getStats()`, `RTCRtpSender.getStats()` and `RTCPeerConnection.getStats()` methods.
 Calling `getStats()` on an `RTCPeerConnection` lets you specify whether you wish to obtain outbound statistics, inbound statistics, or statistics for the whole connection.
 The `RTCRtpReceiver` and `RTCRtpSender` versions of `getStats()` only return inbound and outbound statistics, respectively.

 The statistics report is a read-only `Map`-like object: an ordered dictionary, where the properties are `id` strings that uniquely identify the WebRTC object that was inspected to produce a particular set of statistics, and the value is a dictionary object containing those statistics.
 A `RTCStatsReport` can be iterated and used the same ways as a read-only `Map`.

 The report may contain many different categories of statistics, including inbound and outbound statistics for both the current and remote ends of the peer connection, information about codecs, certificates and media used, and so on.
 Each category of statistic is provided in a different type of statistics dictionary object, which can be identified from its `type` property.

### Common instance properties

All the dictionary types have the following properties:

`id`

 A string that uniquely identifies the object was monitored to produce the set of statistics.
 This value persists across reports for (at least) the lifetime of the connection.
 Note however that for some statistics the ID may vary between browsers and for subsequent connections, even to the same peer.

`timestamp`

 A high resolution timestamp object (`DOMHighResTimeStamp`) object indicating the time at which the sample was taken.
 Many reported statistics are cumulative values; the timestamp allows rates and averages to be calculated between any two reports, at any desired reporting rate.

`type`

 A string with a value that indicates the type of statistics that the object contains, such as `candidate-pair`, `inbound-rtp`, `certificate`, and so on.
 The types of statistics and their corresponding objects are listed below.

 Users typically iterate a `RTCStatsReport`, using a `forEach()` or `for...of` loop, selecting the statistics of interest using the `type` property.
 Once a particular statistic object has been identified using its `type`, the `id` property can subsequently be used with `get()` to obtain the same statistic report at a different time.

The timestamp can be used to calculate average values for statistics that accumulate over the lifetime of a connection.

### The statistic types

The statistics `type` values and their corresponding dictionaries are listed below.

| type | Dictionary | Description |
| --- | --- | --- |
| `candidate-pair` | `RTCIceCandidatePairStats` | Statistics describing the change from one `RTCIceTransport` to another, such as during an ICE restart. |
| `certificate` | `RTCCertificateStats` | Statistics about a certificate being used by an `RTCIceTransport`. |
| `codec` | `RTCCodecStats` | Statistics about a specific codec being used by streams being sent or received by this connection. |
| `data-channel` | `RTCDataChannelStats` | Statistics related to one `RTCDataChannel` on the connection. |
| `inbound-rtp` | `RTCInboundRtpStreamStats` | Statistics describing the state of one of the connection's inbound data streams. |
| `local-candidate` | `RTCIceCandidateStats` | Statistics about a local ICE candidate associated with the connection's `RTCIceTransport`s. |
| `media-source` | `RTCAudioSourceStats` or `RTCVideoSourceStats` | Statistics about the media produced by the `MediaStreamTrack` attached to an RTP sender. The dictionary this key maps to depends on the track's `kind`. |
| `outbound-rtp` | `RTCOutboundRtpStreamStats` | Statistics describing the state of one of the outbound data streams on this connection. |
| `peer-connection` | `RTCPeerConnectionStats` | Statistics describing the state of the `RTCPeerConnection`. |
| `remote-candidate` | `RTCIceCandidateStats` | Statistics about a remote ICE candidate associated with the connection's `RTCIceTransport`s. |
| `remote-inbound-rtp` | `RTCRemoteInboundRtpStreamStats` | Statistics describing the state of the inbound data stream from the perspective of the remote peer. |
| `remote-outbound-rtp` | `RTCRemoteOutboundRtpStreamStats` | Statistics describing the state of the outbound data stream from the perspective of the remote peer. |
| `transport` | `RTCTransportStats` | Statistics about a transport used by the connection. |

Examples
--------

### Iterate report from an RTCPeerConnection using forEach loop

This example logs shows how you might log video-related statistics for the local `RTCRtpReceiver` responsible for receiving streamed media.

 Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code 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 `inbound-rtp` and `kind` of `video`.

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

stats.forEach((report) => {
  if (report.type === "inbound-rtp" && report.kind === "video") {
    // Log the frame rate
    console.log(report.framesPerSecond);
  }
});
```

### Iterate report from an RTCRtpSender using a for...of loop

This example shows how you might iterate the outbound statistics from an `RTCRtpSender`.

 The code follows a similar pattern to the previous example, but iterates using a `for...of`-loop on the `RTCStatsReport.values()`, and filters on the `type` of `outbound-rtp`.
 It assumes you already have an `RTCRtpSender` object named "sender".

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

for (const stat of stats.values()) {
  if (stat.type != "outbound-rtp") continue;
  Object.keys(stat).forEach((statName) => {
    console.log(`${statName}: ${report[statName]}`);
  });
}
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # rtcstatsreport-object |

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

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

See also
--------

* WebRTC API
* `RTCPeerConnection`
* `RTCPeerConnection.getStats()`, `RTCRtpReceiver.getStats()`, and `RTCRtpSender.getStats()`


Notifications API - Web APIs

Notifications API
=================

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

The Notifications API allows web pages to control the display of system notifications to the end user. These are outside the top-level browsing context viewport, so therefore can be displayed even when the user has switched tabs or moved to a different app. The API is designed to be compatible with existing notification systems, across different platforms.

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

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

On supported platforms, showing a system notification generally involves two things. First, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initializes, using the `Notification.requestPermission()` method. This should be done in response to a user gesture, such as clicking a button, for example:

```js
btn.addEventListener("click", () => {
  let promise = Notification.requestPermission();
  // wait for permission
});
```

This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example.

This will spawn a request dialog, along the following lines:

![A dialog box asking the user to allow notifications from that origin. There are options to never allow or allow notifications.](/en-US/docs/Web/API/Notifications_API/screen_shot_2019-12-11_at_9.59.14_am.png)

From here the user can choose to allow notifications from this origin, or block them. Once a choice has been made, the setting will generally persist for the current session.

**Note:** As of Firefox 44, the permissions for Notifications and Push have been merged. If permission is granted for notifications, push will also be enabled.

Next, a new notification is created using the `Notification()` constructor. This must be passed a title argument, and can optionally be passed an options object to specify options, such as text direction, body text, icon to display, notification sound to play, and more.

In addition, the Notifications API spec specifies a number of additions to the ServiceWorker API, to allow service workers to fire notifications.

**Note:** To find out more about using notifications in your own app, read Using the Notifications API.

Interfaces
----------

`Notification`

Defines a notification object.

`NotificationEvent`

Represents a notification event dispatched on the `ServiceWorkerGlobalScope` of a `ServiceWorker`.

### Extensions to other interfaces

`notificationclick` event

Occurs when a user clicks on a displayed notification.

`notificationclose` event

Occurs when a user closes a displayed notification.

`ServiceWorkerRegistration.getNotifications()`

Returns a list of the notifications in the order that they were created from the current origin via the current service worker registration.

`ServiceWorkerRegistration.showNotification()`

Displays the notification with the requested title.

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

| Specification |
| --- |
| Notifications API Standard  |

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

### api.Notification

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

### api.ServiceWorkerRegistration.showNotification

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

### api.ServiceWorkerRegistration.getNotifications

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

See also
--------

* Using the Notifications API


SVGAnimateColorElement - Web APIs

SVGAnimateColorElement
======================

**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 **`SVGAnimateColorElement`** interface corresponds to the `<animateColor>` element.

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

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

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

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

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

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

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

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


RTCDtlsTransport - Web APIs

RTCDtlsTransport
================

The **`RTCDtlsTransport`** interface provides access to information about the Datagram Transport Layer Security (**DTLS**) transport over which a `RTCPeerConnection`'s RTP and RTCP packets are sent and received by its `RTCRtpSender` and `RTCRtpReceiver` objects.

A `RTCDtlsTransport` object is also used to provide information about SCTP packets transmitted and received by a connection's data channels.

Features of the DTLS transport include the addition of security to the underlying transport; the `RTCDtlsTransport` interface can be used to obtain information about the underlying transport and the security added to it by the DTLS layer.

EventTarget

RTCDtlsTransportInstance properties
-------------------

*Also inherits properties from `EventTarget`.*

`iceTransport` Read only

Returns a reference to the underlying `RTCIceTransport` object.

`state` Read only

 Returns a string
 which describes the underlying Datagram Transport Layer Security (**DTLS**) transport state.
 It can be one of the following values:
 `new`, `connecting`, `connected`, `closed`, or `failed`.

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

*Also inherits methods from `EventTarget`.*

`getRemoteCertificates()`

Returns an array of `ArrayBuffer` containing the certificates of the remote peer of the connection.

Events
------

`error`

Sent when a transport-level error occurs on the `RTCPeerConnection`.

`statechange`

Sent when the `state` of the DTLS transport changes.

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

### Allocation of DTLS transports

`RTCDtlsTransport` objects are created when an app calls either `setLocalDescription()` or `setRemoteDescription()`. The number of DTLS transports created and how they're used depends on the bundling mode used when creating the `RTCPeerConnection`.

Whether bundling is used depends on what the other endpoint is able to negotiate. All browsers support bundling, so when both endpoints are browsers, you can rest assured that bundling will be used.

Some non-browser legacy endpoints, however, may not support bundle. To be able to negotiate with such endpoints (or to exclude them entirely), the `bundlePolicy` property may be provided when creating the connection. The `bundlePolicy` lets you control how to negotiate with these legacy endpoints. The default policy is `"balanced"`, which provides a balance between performance and compatibility.

For example, to create the connection using the highest level of bundling:

```js
const rtcConfig = {
  bundlePolicy: "max-bundle",
};

const pc = new RTCPeerConnection(rtcConfig);
```

Bundling lets you use one `RTCDtlsTransport` to carry the data for multiple higher-level transports, such as multiple `RTCRtpTransceiver`s.

#### When not using BUNDLE

When the connection is created without using BUNDLE, each RTP or RTCP component of each `RTCRtpTransceiver` has its own `RTCDtlsTransport`; that is, every `RTCRtpSender` and `RTCRtpReceiver`, has its own transport, and all `RTCDataChannel` objects share a transport dedicated to SCTP.

#### When using BUNDLE

When the connection is using BUNDLE, each `RTCDtlsTransport` object represents a group of `RTCRtpTransceiver` objects. If the connection was created using `max-compat` mode, each transport is responsible for handling all communication for a given type of media (audio, video, or data channel). Thus, a connection with any number of audio and video channels will always have exactly one DTLS transport for audio and one for video communications.

Because transports are established early in the negotiation process, it's likely that it won't be known until after they're created whether or not the remote peer supports bundling. For this reason, you'll sometimes see separate transports created at first, one for each track, then see them get bundled up once it's known that bundling is possible. If your code accesses `RTCRtpSender`s and/or `RTCRtpReceiver`s directly, you may encounter situations where they're initially separate, then half or more of them get closed and the senders and receivers updated to refer to the appropriate remaining `RTCDtlsTransport` objects.

### Data channels

`RTCDataChannel`s use SCTP to communicate. All of a peer connection's data channels share a single `RTCSctpTransport`, found in the connection's `sctp` property.

You can, in turn, identify the `RTCDtlsTransport` used to securely encapsulate the data channels' SCTP communications by looking at the `RTCSctpTransport` object's `transport` property.

Examples
--------

This example presents a function, `tallySenders()`, which iterates over an `RTCPeerConnection`'s `RTCRtpSender`s, tallying up how many of them are in various states. The function returns an object containing properties whose values indicate how many senders are in each state.

```js
let pc = new RTCPeerConnection({ bundlePolicy: "max-bundle" });

// …

function tallySenders(pc) {
  let results = {
    transportMissing: 0,
    connectionPending: 0,
    connected: 0,
    closed: 0,
    failed: 0,
    unknown: 0,
  };

  let senderList = pc.getSenders();
  senderList.forEach((sender) => {
    let transport = sender.transport;

    if (!transport) {
      results.transportMissing++;
    } else {
      switch (transport.state) {
        case "new":
        case "connecting":
          results.connectionPending++;
          break;
        case "connected":
          results.connected++;
          break;
        case "closed":
          results.closed++;
          break;
        case "failed":
          results.failed++;
          break;
        default:
          results.unknown++;
          break;
      }
    }
  });
  return results;
}
```

Note that in this code, the `new` and `connecting` states are being treated as a single `connectionPending` status in the returned object.

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

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

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

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

See also
--------

* `RTCRtpSender.transport` and `RTCRtpReceiver.transport`
* `RTCSctpTransport.transport`


CSS Object Model (CSSOM) - Web APIs

CSS Object Model (CSSOM)
========================

The **CSS Object Model** is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify CSS style dynamically.

The values of CSS are represented untyped, that is using `String` objects.

Reference
---------

* `AnimationEvent`
* `CaretPosition`
* `CSS`
* `CSSConditionRule`
* `CSSCounterStyleRule`
* `CSSFontFaceRule`
* `CSSFontFeatureValuesMap`
* `CSSFontFeatureValuesRule`
* `CSSGroupingRule`
* `CSSImportRule`
* `CSSKeyframeRule`
* `CSSKeyframesRule`
* `CSSMarginRule`
* `CSSMediaRule`
* `CSSNamespaceRule`
* `CSSPageRule`
* `CSSRule`
* `CSSRuleList`
* `CSSStyleDeclaration`
* `CSSStyleSheet`
* `CSSStyleRule`
* `CSSSupportsRule`
* `FontFace`
* `FontFaceSet`
* `FontFaceSetLoadEvent`
* `MediaList`
* `MediaQueryList`
* `MediaQueryListEvent`
* `Screen`
* `StyleSheet`
* `StyleSheetList`
* `TransitionEvent`

Several other interfaces are also extended by the CSSOM-related specifications: `Document`, `Window`, `Element`, `HTMLElement`, `HTMLImageElement`, `Range`, `MouseEvent`, and `SVGElement`.

### CSS Typed Object Model
Experimental

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

* `CSSImageValue`
Experimental
* `CSSKeywordValue`
Experimental
* `CSSMathInvert`
Experimental
* `CSSMathMax`
Experimental
* `CSSMathMin`
Experimental
* `CSSMathNegate`
Experimental
* `CSSMathProduct`
Experimental
* `CSSMathSum`
Experimental
* `CSSMathValue`
Experimental
* `CSSMatrixComponent`
Experimental
* `CSSNumericArray`
Experimental
* `CSSNumericValue`
Experimental
* `CSSPerspective`
Experimental
* `CSSPositionValue`
Experimental
* `CSSRotate`
Experimental
* `CSSScale`
Experimental
* `CSSSkew`
Experimental
* `CSSSkewX`
Experimental
* `CSSSkewY`
Experimental
* `CSSStyleValue`
Experimental
* `CSSTransformComponent`
Experimental
* `CSSTransformValue`
Experimental
* `CSSTranslate`
Experimental
* `CSSUnitValue`
Experimental
* `CSSUnparsedValue`
Experimental
* `CSSVariableReferenceValue`
Experimental
* `StylePropertyMap`
Experimental
* `StylePropertyMapReadOnly`
Experimental
### Obsolete CSSOM interfaces
Deprecated

**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.

* `CSSPrimitiveValue`
Deprecated
* `CSSValue`
Deprecated
* `CSSValueList`
Deprecated
Tutorials
---------

* Determining the dimensions of elements
* Managing screen orientation
Specifications
--------------

| Specification |
| --- |
| CSS Object Model (CSSOM)  |
| CSSOM View Module  |
| CSS Typed OM Level 1  |

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

All these features have been added little by little over the years to the different browsers: it was a quite complex process that can't be summarized in a simple table. Please refer to the specific interfaces for its availability.

See also
--------

* Document Object Model (DOM)
* Houdini APIs


AudioEncoder - Web APIs

AudioEncoder
============

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 **`AudioEncoder`** interface of the WebCodecs API encodes `AudioData` objects.

EventTarget

AudioEncoderConstructor
-----------

`AudioEncoder()`
Experimental

Creates a new `AudioEncoder` object.

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

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

`AudioEncoder.encodeQueueSize` Read only
Experimental

An integer representing the number of encode queue requests.

`AudioEncoder.state` Read only
Experimental

Represents the state of the underlying codec and whether it is configured for encoding.

### Events

`dequeue`
Experimental

Fires to signal a decrease in `AudioEncoder.encodeQueueSize`.

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

`AudioEncoder.isConfigSupported()`
Experimental

Returns a promise indicating whether the provided `AudioEncoderConfig` is supported.

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

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

`AudioEncoder.configure()`
Experimental

Enqueues a control message to configure the audio encoder for encoding chunks.

`AudioEncoder.encode()`
Experimental

Enqueues a control message to encode a given `AudioData` objects.

`AudioEncoder.flush()`
Experimental

Returns a promise that resolves once all pending messages in the queue have been completed.

`AudioEncoder.reset()`
Experimental

Resets all states including configuration, control messages in the control message queue, and all pending callbacks.

`AudioEncoder.close()`
Experimental

Ends all pending work and releases system resources.

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

| Specification |
| --- |
| WebCodecs # audioencoder-interface |

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

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


CSPViolationReportBody - Web APIs

CSPViolationReportBody
======================

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

The `CSPViolationReportBody` interface contains the report data for a Content Security Policy (CSP) violation. CSP violations are thrown when the webpage attempts to load a resource that violates the CSP set by the `Content-Security-Policy` HTTP header.

**Note:** this interface is similar, but not identical to, the JSON objects sent back to the `report-uri` or `report-to` policy directive of the `Content-Security-Policy` header.

ReportBody

CSPViolationReportBodyInstance properties
-------------------

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

`CSPViolationReportBody.blockedURL` Read only

A string representing the URL of the resource that was blocked because it violates the CSP.

`CSPViolationReportBody.columnNumber` Read only

The column number in the script at which the violation occurred.

`CSPViolationReportBody.disposition` Read only

Indicates how the violated policy is configured to be treated by the user agent. This will be `"enforce"` or `"report"`.

`CSPViolationReportBody.documentURL` Read only

A string representing the URL of the document or worker in which the violation was found.

`CSPViolationReportBody.effectiveDirective` Read only

A string representing the directive whose enforcement uncovered the violation.

`CSPViolationReportBody.lineNumber` Read only

The line number in the script at which the violation occurred.

`CSPViolationReportBody.originalPolicy` Read only

A string containing the policy whose enforcement uncovered the violation.

`CSPViolationReportBody.referrer` Read only

A string representing the URL for the referrer of the resources whose policy was violated, or `null`.

`CSPViolationReportBody.sample` Read only

A string representing a sample of the resource that caused the violation, usually the first 40 characters. This will only be populated if the resource is an inline script, event handler, or style — external resources causing a violation will not generate a sample.

`CSPViolationReportBody.sourceFile` Read only

If the violation occurred as a result of a script, this will be the URL of the script; otherwise, it will be `null`. Both `columnNumber` and `lineNumber` should have non-null values if this property is not `null`.

`CSPViolationReportBody.statusCode` Read only

A number representing the HTTP status code of the document or worker in which the violation occurred.

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

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

`CSPViolationReportBody.toJSON()`

A *serializer* which returns a JSON representation of the `CSPViolationReportBody` object.

Examples
--------

### Obtaining a `CSPViolationReportBody` object

To obtain a `CSPViolationReportBody` object, you must configure your page so that a CSP violation will occur. In this example, we will set our CSP to only allow content from the site's own origin, and then attempt to load a script from `apis.google.com`, which is an external origin.

First, we will set our `Content-Security-Policy` header:

```http
Content-Security-Policy: default-src 'self';
```

Then, we will attempt to load an external script:

```html
<!-- This should generate a CSP violation -->
<script src="https://apis.google.com/js/platform.js"></script>
```

Finally, we will create a new `ReportingObserver` object to listen for CSP violations.

```js
const observer = new ReportingObserver(
  (reports, observer) => {
    const cspViolation = reports[0].body;
  },
  {
    types: ["csp-violation"],
    buffered: true,
  },
);

observer.observe();
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # cspviolationreportbody |

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

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

See also
--------

* `ReportBody`
* `ReportingObserver`
* `Content-Security-Policy`
* `SecurityPolicyViolationEvent`


WEBGL_compressed_texture_etc extension - Web APIs

WEBGL\_compressed\_texture\_etc extension
=========================================

The **`WEBGL_compressed_texture_etc`** extension is part of the WebGL API and exposes 10 ETC/EAC compressed texture formats.

Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures.

WebGL extensions are available using the `WebGLRenderingContext.getExtension()` method. For more information, see also Using Extensions in the WebGL tutorial.

**Note:** This extension is available to both, WebGL1 and WebGL2 contexts.

Constants
---------

The compressed texture formats are exposed by 10 constants and can be used in two functions: `compressedTexImage2D()` and `compressedTexSubImage2D()`.

`ext.COMPRESSED_R11_EAC`

One-channel (red) unsigned format compression.

`ext.COMPRESSED_SIGNED_R11_EAC`

One-channel (red) signed format compression.

`ext.COMPRESSED_RG11_EAC`

Two-channel (red and green) unsigned format compression.

`ext.COMPRESSED_SIGNED_RG11_EAC`

Two-channel (red and green) signed format compression.

`ext.COMPRESSED_RGB8_ETC2`

Compresses RGB8 data with no alpha channel.

`ext.COMPRESSED_RGBA8_ETC2_EAC`

Compresses RGBA8 data. The RGB part is encoded the same as `RGB_ETC2`, but the alpha part is encoded separately.

`ext.COMPRESSED_SRGB8_ETC2`

Compresses sRGB8 data with no alpha channel.

`ext.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC`

Compresses sRGBA8 data. The sRGB part is encoded the same as `SRGB_ETC2`, but the alpha part is encoded separately.

`ext.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2`

Similar to `RGB8_ETC`, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.

`ext.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2`

Similar to `SRGB8_ETC`, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.

Examples
--------

```js
const ext = gl.getExtension("WEBGL\_compressed\_texture\_etc");

const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE\_2D, texture);

gl.compressedTexImage2D(
  gl.TEXTURE\_2D,
  0,
  ext.COMPRESSED\_RGBA8\_ETC2\_EAC,
  512,
  512,
  0,
  textureData,
);
```

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

| Specification |
| --- |
| WebGL WEBGL\_compressed\_texture\_etc Extension Specification  |

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

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

### Compatibility notes

* This extension was named `WEBGL_compressed_texture_es3` from Firefox 46 to Firefox 51 and used to be available on the WebGL 2 context by default – this is not the case anymore. You have to enable it on both, WebGL 1 and WebGL 2 contexts, in order to use it.
See also
--------

* Ericsson Texture Compression – Wikipedia
* `WEBGL_compressed_texture_etc1` (ETC1)
* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.compressedTexImage2D()`
* `WebGLRenderingContext.compressedTexSubImage2D()`
* `WebGLRenderingContext.getParameter()`


IDBKeyRange - Web APIs

IDBKeyRange
===========

The **`IDBKeyRange`** interface of the IndexedDB API represents a continuous interval over some data type that is used for keys. Records can be retrieved from `IDBObjectStore` and `IDBIndex` objects using keys or a range of keys. You can limit the range using lower and upper bounds. For example, you can iterate over all values of a key in the value range A–Z.

A key range can be a single value or a range with upper and lower bounds or endpoints. If the key range has both upper and lower bounds, then it is *bounded*; if it has no bounds, it is *unbounded*. A bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). To retrieve all keys within a certain range, you can use the following code constructs:

| Range | Code |
| --- | --- |
| All keys ≥ **x** | `IDBKeyRange.lowerBound(x)` |
| All keys > **x** | `IDBKeyRange.lowerBound(x, true)` |
| All keys ≤ **y** | `IDBKeyRange.upperBound(y)` |
| All keys < **y** | `IDBKeyRange.upperBound(y, true)` |
| All keys ≥ **x** && ≤ **y** | `IDBKeyRange.bound(x, y)` |
| All keys > **x** &&< **y** | `IDBKeyRange.bound(x, y, true, true)` |
| All keys > **x** && ≤ **y** | `IDBKeyRange.bound(x, y, true, false)` |
| All keys ≥ **x** &&< **y** | `IDBKeyRange.bound(x, y, false, true)` |
| The key = **z** | `IDBKeyRange.only(z)` |

A key is in a key range if the following conditions are true:

* The lower value of the key range is one of the following:
    + `undefined`
    + Less than key value
    + Equal to key value if `lowerOpen` is `false`.
* The upper value of the key range is one of the following:
    + `undefined`
    + Greater than key value
    + Equal to key value if `upperOpen` is `false`.

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

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

`IDBKeyRange.lower` Read only

Lower bound of the key range.

`IDBKeyRange.upper` Read only

Upper bound of the key range.

`IDBKeyRange.lowerOpen` Read only

Returns false if the lower-bound value is included in the key range.

`IDBKeyRange.upperOpen` Read only

Returns false if the upper-bound value is included in the key range.

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

`IDBKeyRange.bound()`

Creates a new key range with upper and lower bounds.

`IDBKeyRange.only()`

Creates a new key range containing a single value.

`IDBKeyRange.lowerBound()`

Creates a new key range with only a lower bound.

`IDBKeyRange.upperBound()`

Creates a new upper-bound key range.

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

`IDBKeyRange.includes()`

Returns a boolean indicating whether a specified key is inside the key range.

Examples
--------

 The following example illustrates how you'd use a key range. Here we declare a `keyRangeValue` as a range between values of `"A"` and `"F"`. We open a transaction (using `IDBTransaction`) and an object store, and open a cursor with `IDBObjectStore.openCursor`, declaring `keyRangeValue` as its optional key range value. This means that the cursor will only retrieve records with keys inside that range. This range includes the values `"A"` and `"F"`, as we haven't declared that they should be open bounds.
 If we used `IDBKeyRange.bound("A", "F", true, true);`, then the range would not include `"A"` and `"F"`, only the values between them.

**Note:** For a more complete example allowing you to experiment with key range, have a look at our IDBKeyRange-example repo (view the example live too.)

```js
function displayData() {
  const keyRangeValue = IDBKeyRange.bound("A", "F");

  const transaction = db.transaction(["fThings"], "readonly");
  const objectStore = transaction.objectStore("fThings");

  objectStore.openCursor(keyRangeValue).onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.fThing}, ${cursor.value.fRating}`;
      list.appendChild(listItem);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # keyrange |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


GPUPipelineError - Web APIs

GPUPipelineError
================

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

The **`GPUPipelineError`** interface of the WebGPU API describes a pipeline failure. This is the value received when a `Promise` returned by a `GPUDevice.createComputePipelineAsync()` or `GPUDevice.createRenderPipelineAsync()` call rejects.

DOMException

GPUPipelineErrorConstructor
-----------

`GPUPipelineError()`
Experimental

Creates a new `GPUPipelineError` object instance.

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

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

`reason`
Experimental
 Read only

An enumerated value that defines the reason the pipeline creation failed in a machine-readable way.

Examples
--------

In the following snippet we are attempting to create a `GPUComputePipeline` using `GPUDevice.createComputePipelineAsync()`. However, we have misspelt our compute pipeline `entryPoint` as `"maijn"` (it should be `"main"`), therefore pipeline creation fails, and our `catch` block prints the resulting reason and error message to the console.

```js
// ...

let computePipeline;

try {
  computePipeline = await device.createComputePipelineAsync({
    layout: device.createPipelineLayout({
      bindGroupLayouts: [bindGroupLayout],
    }),
    compute: {
      module: shaderModule,
      entryPoint: "maijn",
    },
  });
} catch (error) {
  // error is a GPUPipelineError object instance
  console.error(error.reason);
  console.error(`Pipeline creation failed: ${error.message}`);
}

// ...
```

In this case, the given `reason` is `"Validation"`, and the `message` is `"Entry point "maijn" doesn't exist in the shader module [ShaderModule]."`

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

| Specification |
| --- |
| WebGPU # gpupipelineerror |

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

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

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices