XRLightProbe - Web APIs

XRLightProbe
============

**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 **`XRLightProbe`** interface of the WebXR Device API contains lighting information at a given point in the user's environment. You can get an `XRLighting` object using the `XRSession.requestLightProbe()` method.

This object doesn't itself contain lighting values, but it is used to collect lighting states for each `XRFrame`. See `XRLightEstimate` for the estimated lighting values for an `XRLightProbe`.

EventTarget

XRLightProbeInstance properties
-------------------

`XRLightProbe.onreflectionchange`

Event handler property for the `reflectionchange` event.

`XRLightProbe.probeSpace` Read only
Experimental

An `XRSpace` tracking the position and orientation the lighting estimations are relative to.

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

None.

Events
------

`reflectionchange`
Experimental

Fired each time the estimated reflection cube map changes. (This happens when the user moves around and the environment's lighting changes.)

Examples
--------

### Getting an `XRLightProbe` object for a session

Use the `XRSession.requestLightProbe()` method to get a light probe.

```js
const lightProbe = await xrSession.requestLightProbe();
```

### Getting a probe pose within an `XRFrame`

Pass the light probe's `probeSpace` to `XRFrame.getPose()` to get a light probe for a pose.

```js
const probePose = xrFrame.getPose(lightProbe.probeSpace, xrReferenceSpace);
```

### Using the `reflectionchange` event

Pass `XRLightProbe` to get a reflection cube map whenever the `reflectionchange` event fires. See also `XRWebGLBinding.getReflectionCubeMap()`.

```js
const glBinding = new XRWebGLBinding(xrSession, gl);
const lightProbe = await xrSession.requestLightProbe();
let glCubeMap = glBinding.getReflectionCubeMap(lightProbe);

lightProbe.addEventListener("reflectionchange", () => {
  glCubeMap = glBinding.getReflectionCubeMap(lightProbe);
});
```

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

| Specification |
| --- |
| WebXR Lighting Estimation API Level 1 # xrlightprobe-interface |

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

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

See also
--------

* `XRSession.requestLightProbe()`


WEBGL_draw_buffers extension - Web APIs

WEBGL\_draw\_buffers extension
==============================

The **`WEBGL_draw_buffers`** extension is part of the WebGL API and enables a fragment shader to write to several textures, which is useful for deferred shading, for example.

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

**Note:** This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. In WebGL 2, the constants are available without the "WEBGL" suffix and the new GLSL built-ins require GLSL `#version 300 es`.

Constants
---------

This extension exposes new constants, which can be used in the `gl.framebufferRenderbuffer()`, `gl.framebufferTexture2D()`, `gl.getFramebufferAttachmentParameter()` `ext.drawBuffersWEBGL()`, and `gl.getParameter()` methods.

`ext.COLOR_ATTACHMENT0_WEBGL ext.COLOR_ATTACHMENT1_WEBGL ext.COLOR_ATTACHMENT2_WEBGL ext.COLOR_ATTACHMENT3_WEBGL ext.COLOR_ATTACHMENT4_WEBGL ext.COLOR_ATTACHMENT5_WEBGL ext.COLOR_ATTACHMENT6_WEBGL ext.COLOR_ATTACHMENT7_WEBGL ext.COLOR_ATTACHMENT8_WEBGL ext.COLOR_ATTACHMENT9_WEBGL ext.COLOR_ATTACHMENT10_WEBGL ext.COLOR_ATTACHMENT11_WEBGL ext.COLOR_ATTACHMENT12_WEBGL ext.COLOR_ATTACHMENT13_WEBGL ext.COLOR_ATTACHMENT14_WEBGL ext.COLOR_ATTACHMENT15_WEBGL`

A `GLenum` specifying a color buffer.

`ext.DRAW_BUFFER0_WEBGL ext.DRAW_BUFFER1_WEBGL ext.DRAW_BUFFER2_WEBGL ext.DRAW_BUFFER3_WEBGL ext.DRAW_BUFFER4_WEBGL ext.DRAW_BUFFER5_WEBGL ext.DRAW_BUFFER6_WEBGL ext.DRAW_BUFFER7_WEBGL ext.DRAW_BUFFER8_WEBGL ext.DRAW_BUFFER9_WEBGL ext.DRAW_BUFFER10_WEBGL ext.DRAW_BUFFER11_WEBGL ext.DRAW_BUFFER12_WEBGL ext.DRAW_BUFFER13_WEBGL ext.DRAW_BUFFER14_WEBGL ext.DRAW_BUFFER15_WEBGL`

A `GLenum` returning a draw buffer.

`ext.MAX_COLOR_ATTACHMENTS_WEBGL`

A `GLint` indicating the maximum number of framebuffer color attachment points.

`ext.MAX_DRAW_BUFFERS_WEBGL`

A `GLint` indicating the maximum number of draw buffers.

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

This extension exposes one new method.

`ext.drawBuffersWEBGL()`

Defines the draw buffers to which all fragment colors are written. (When using `WebGL2`, this method is available as `gl.drawBuffers()` by default).

Examples
--------

Enabling the extension:

```js
const ext = gl.getExtension("WEBGL\_draw\_buffers");
```

Binding multiple textures (to a `tx[]` array) to different framebuffer color attachments:

```js
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(
  gl.FRAMEBUFFER,
  ext.COLOR\_ATTACHMENT0\_WEBGL,
  gl.TEXTURE\_2D,
  tx[0],
  0,
);
gl.framebufferTexture2D(
  gl.FRAMEBUFFER,
  ext.COLOR\_ATTACHMENT1\_WEBGL,
  gl.TEXTURE\_2D,
  tx[1],
  0,
);
gl.framebufferTexture2D(
  gl.FRAMEBUFFER,
  ext.COLOR\_ATTACHMENT2\_WEBGL,
  gl.TEXTURE\_2D,
  tx[2],
  0,
);
gl.framebufferTexture2D(
  gl.FRAMEBUFFER,
  ext.COLOR\_ATTACHMENT3\_WEBGL,
  gl.TEXTURE\_2D,
  tx[3],
  0,
);
```

Mapping the color attachments to draw buffer slots that the fragment shader will write to using `gl_FragData`:

```js
ext.drawBuffersWEBGL([
  ext.COLOR\_ATTACHMENT0\_WEBGL, // gl\_FragData[0]
  ext.COLOR\_ATTACHMENT1\_WEBGL, // gl\_FragData[1]
  ext.COLOR\_ATTACHMENT2\_WEBGL, // gl\_FragData[2]
  ext.COLOR\_ATTACHMENT3\_WEBGL, // gl\_FragData[3]
]);
```

Shader code that writes to multiple textures:

```html
<script type="x-shader/x-fragment">
 #extension GL\_EXT\_draw\_buffers : require

 precision highp float;

 void main(void) {
 gl\_FragData[0] = vec4(0.25);
 gl\_FragData[1] = vec4(0.5);
 gl\_FragData[2] = vec4(0.75);
 gl\_FragData[3] = vec4(1.0);
 }
</script>
```

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

| Specification |
| --- |
| WebGL WEBGL\_draw\_buffers Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGL2RenderingContext.drawBuffers()`
* WebGL deferred shading - Mozilla Hacks blog


ImageBitmapRenderingContext - Web APIs

ImageBitmapRenderingContext
===========================

The **`ImageBitmapRenderingContext`** interface is a canvas rendering context that provides the functionality to replace the canvas's contents with the given `ImageBitmap`. Its context id (the first argument to `HTMLCanvasElement.getContext()` or `OffscreenCanvas.getContext()`) is `"bitmaprenderer"`.

This interface is available in both the window and the worker context.

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

`ImageBitmapRenderingContext.transferFromImageBitmap()`

Displays the given `ImageBitmap` in the canvas associated with this rendering context. Ownership of the `ImageBitmap` is transferred to the canvas. This was previously named `transferImageBitmap()`, but was renamed in a spec change. The old name is being kept as an alias to avoid code breakage.

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

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

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

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

See also
--------

* `OffscreenCanvas`


HTMLProgressElement - Web APIs

HTMLProgressElement
===================

The **`HTMLProgressElement`** interface provides special properties and methods (beyond the regular `HTMLElement` interface it also has available to it by inheritance) for manipulating the layout and presentation of `<progress>` elements.

EventTarget

Node

Element

HTMLElement

HTMLProgressElementInstance properties
-------------------

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

`HTMLProgressElement.max`

A `double` value reflecting the content attribute of the same name, limited to numbers greater than zero. Its default value is `1.0`.

`HTMLProgressElement.position` Read only

Returns a `double` value returning the result of dividing the current value (`value`) by the maximum value (`max`); if the progress bar is an indeterminate progress bar, it returns `-1`.

`HTMLProgressElement.value`

A `double` value that reflects the current value; if the progress bar is an indeterminate progress bar, it returns `0`.

`HTMLProgressElement.labels` Read only

Returns `NodeList` containing the list of `<label>` elements that are labels for this element.

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

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

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

| Specification |
| --- |
| HTML Standard # htmlprogresselement |

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: `<progress>`


RTCRtpScriptTransformer - Web APIs

RTCRtpScriptTransformer
=======================

The **`RTCRtpScriptTransformer`** interface of the WebRTC API provides a worker-side Stream API interface that a WebRTC Encoded Transform can use to modify encoded media frames in the incoming and outgoing WebRTC pipelines.

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

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

`RTCRtpScriptTransformer.readable` Read only

A `ReadableStream` on which encoded frames from the WebRTC sender or receiver pipelines may be enqueued.

`RTCRtpScriptTransformer.writable` Read only

A `WritableStream` that encoded frames should be piped to.

`RTCRtpScriptTransformer.options` Read only

Options passed from the `RTCRtpScriptTransform` constructor, which are used to configure transform code based on whether incoming or outgoing frames are being processed.

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

`RTCRtpScriptTransformer.generateKeyFrame()`

Requests a video encoder generate a key frame. May be called by a transformer in the sender pipeline when processing outgoing frames.

`RTCRtpScriptTransformer.sendKeyFrameRequest()`

Requests the sender send a key frame. May be called by a transformer in the receiver pipeline when processing incoming encoded video frames.

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

A `RTCRtpScriptTransformer` instance is created as part of construction of an associated `RTCRtpScriptTransform`, which specifies the worker in which the transformer is created and options that will be passed to it.

 The transformer is made available to a worker through the `rtctransform` event `transformer` property.
 This event is fired on construction of the associated `RTCRtpScriptTransform` and when an encoded frame is enqueued on the `RTCRtpScriptTransformer.readable` from a codec (outgoing) or from the packetizer (incoming).

 The transformer exposes a `readable` and `writable` stream into the worker, along with an `options` object provided to the `RTCRtpScriptTransform` on construction.
 When the associated `RTCRtpScriptTransform` is assigned to a `RTCRtpSender` or `RTCRtpReceiver`, encoded media frames from the WebRTC sender or receiver pipelines are enqueued on the `readable` stream.

 A WebRTC Encoded Transform must read encoded frames from `transformer.readable`, modify them as needed, and write them to `transformer.writable` in the same order, and without any duplication.
 The `transformer.options` allow an appropriate transform function to be used, based on whether the encoded media frames are incoming or outgoing.
 The transform is usually implemented by piping frames from the `readable` through one or more `TransformStream` instances to the `writable`, transforming them as needed.

The interface also provides methods for a sender to generate get a video encoder to generate a new keyframe, or for a receiver to request a new key frame from the sender's encoder (video encoders commonly send a key frame containing the full information needed to construct an image, and subsequently send delta frames containing just the information that has changed since the previous frame).

 These methods are required in cases where a recipient would be unable to decode incoming frames until they receive a new key frame.
 For example, a new recipient joining a conference call will not be able see video until they have received a new key frame, since delta frames can only be decoded if you have the last key frame and all subsequent delta frames.
 Similarly, if frames are encrypted for a recipient, they will only be able to decode frames once they have received their first encrypted key frame.

Examples
--------

This example shows the code for a WebRTC Encoded Transform running in a worker.

The code uses `addEventListener()` to register a handler function for the `rtctransform` event, which makes the **`RTCRtpScriptTransformer`** available as `event.transformer`.

 The handler creates a `TransformStream` and pipes frames from the `event.transformer.readable` through it to `event.transformer.writable`.
 The transform stream `transform()` implementation is called for each encoded frame queued on the stream: it can read the data from the frame and in this case negates the bytes and then enqueues the modifiable frame on the stream.

```js
addEventListener("rtctransform", (event) => {
  const transform = new TransformStream({
    start() {}, // Called on startup.
    flush() {}, // Called when the stream is about to be closed.
    async transform(encodedFrame, controller) {
      // Reconstruct the original frame.
      const view = new DataView(encodedFrame.data);

      // Construct a new buffer
      const newData = new ArrayBuffer(encodedFrame.data.byteLength);
      const newView = new DataView(newData);

      // Negate all bits in the incoming frame
      for (let i = 0; i < encodedFrame.data.byteLength; ++i) {
        newView.setInt8(i, ~view.getInt8(i));
      }

      encodedFrame.data = newData;
      controller.enqueue(encodedFrame);
    },
  });
  event.transformer.readable
    .pipeThrough(transform)
    .pipeTo(event.transformer.writable);
});
```

The only special things to note about the `TransformStream` above are that it queues encoded media frames (`RTCEncodedVideoFrame` or `RTCEncodedAudioFrame`) rather than arbitrary "chunks", and that `writableStrategy` and `readableStrategy` properties are not defined (because the queuing strategy is entirely managed by the user agent).

 A transform can run in either the incoming or outgoing WebRTC pipelines.
 This doesn't matter in the code above, because the same algorithm might be used in the sender to negate the frames, and in the receiver to revert them.
 If the sender and receiver pipelines need to apply a different transform algorithm then information about the current pipeline must be passed from the main thread.
 This is done by setting an `options` argument in the corresponding `RTCRtpScriptTransform` constructor, which is then made available to the worker in `RTCRtpScriptTransformer.options`.

 Below we use the `transformer.options` to choose either a sender transform or a receiver transform.
 Note that the properties of the object are arbitrary (provided the values can be serialized) and it is also possible to transfer a `MessageChannel` and use it to communicate with a transform at runtime in order to, for example, share encryption keys.

```js
// Code to instantiate transform and attach them to sender/receiver pipelines.
onrtctransform = (event) => {
  let transform;
  if (event.transformer.options.name == "senderTransform")
    transform = createSenderTransform();
  // returns a TransformStream (not shown)
  else if (event.transformer.options.name == "receiverTransform")
    transform = createReceiverTransform();
  // returns a TransformStream (not shown)
  else return;
  event.transformer.readable
    .pipeThrough(transform)
    .pipeTo(event.transformer.writable);
};
```

Note that the above code is part of more complete examples provided in Using WebRTC Encoded Transforms.

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

| Specification |
| --- |
| WebRTC Encoded Transform # rtcrtpscripttransformer |

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

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

See also
--------

* Using WebRTC Encoded Transforms
* `TransformStream`


TrustedScript - Web APIs

TrustedScript
=============

The **`TrustedScript`** interface of the `Trusted Types API` represents a string with an uncompiled script body that a developer can insert into an injection sink that might execute the script. These objects are created via `TrustedTypePolicy.createScript()` and therefore have no constructor.

The value of a **TrustedScript** object is set when the object is created and cannot be changed by JavaScript as there is no setter exposed.

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

`TrustedScript.toJSON()`

Returns a JSON representation of the stored data.

`TrustedScript.toString()`

A string containing the sanitized script.

Examples
--------

The constant `sanitized` is an object created via a Trusted Types policy.

```js
const sanitized = scriptPolicy.createScript("eval('2 + 2')");
console.log(sanitized); /\* a TrustedScript object \*/
```

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

| Specification |
| --- |
| Trusted Types # trusted-script |

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

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

See also
--------

* Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types


SVGFEFuncRElement - Web APIs

SVGFEFuncRElement
=================

The **`SVGFEFuncRElement`** interface corresponds to the `<feFuncR>` element.

EventTarget

Node

Element

SVGElement

SVGComponentTransferFunctionElement

SVGFEFuncRElementInstance properties
-------------------

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

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

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

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

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

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

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

See also
--------

* `<feFuncR>`


HTMLDetailsElement - Web APIs

HTMLDetailsElement
==================

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

EventTarget

Node

Element

HTMLElement

HTMLDetailsElementInstance properties
-------------------

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

`HTMLDetailsElement.open`

A boolean value reflecting the `open` HTML attribute, indicating whether or not the element's contents (not counting the `<summary>`) is to be shown to the user.

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

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

Events
------

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

`toggle`

Fired when the `open`/`closed` state of a `<details>` element is toggled.

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

| Specification |
| --- |
| HTML Standard # htmldetailselement |

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: `<details>`


btoa() global function - Web APIs

btoa() global function
======================

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

 The **`btoa()`** method creates a
 Base64-encoded ASCII string from a *binary string* (i.e., a
 string in which each character in the string is treated as a byte
 of binary data).

 You can use this method to encode data which may otherwise cause communication
 problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control
 characters such as ASCII values 0 through 31.

Syntax
------

```js
btoa(stringToEncode)
```

### Parameters

`stringToEncode`

The *binary string* to encode.

### Return value

 An ASCII string containing the Base64 representation of
 `stringToEncode`.

### Exceptions

`InvalidCharacterError` `DOMException`

 The string contained a character that did not fit in a single byte. See "Unicode
 strings" below for more detail.

Examples
--------

```js
const encodedData = btoa("Hello, world"); // encode a string
const decodedData = atob(encodedData); // decode the string
```

Unicode strings
---------------

 Base64, by design, expects binary data as its input. In terms of JavaScript strings,
 this means strings in which the code point of each character occupies only one byte. So if you pass a
 string into `btoa()` containing characters that occupy more than one byte,
 you will get an error, because this is not considered binary data:

```js
const ok = "a";
console.log(ok.codePointAt(0).toString(16)); // 61: occupies < 1 byte

const notOK = "✓";
console.log(notOK.codePointAt(0).toString(16)); // 2713: occupies > 1 byte

console.log(btoa(ok)); // YQ==
console.log(btoa(notOK)); // error
```

For how to work around this limitation when dealing with arbitrary Unicode text, see The "Unicode Problem" section of the Base64 glossary entry.

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

| Specification |
| --- |
| HTML Standard # dom-btoa-dev |

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

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

See also
--------

* A polyfill of `btoa` is available in `core-js`
* `data` URLs
* `atob()`
* Base64


DedicatedWorkerGlobalScope - Web APIs

DedicatedWorkerGlobalScope
==========================

The **`DedicatedWorkerGlobalScope`** object (the `Worker` global scope) is accessible through the `self` keyword. Some additional global functions, namespaces objects, and constructors, not typically associated with the worker global scope, but available on it, are listed in the JavaScript Reference. See also: Functions available to workers.

EventTarget

WorkerGlobalScope

DedicatedWorkerGlobalScopeInstance properties
-------------------

*This interface inherits properties from the `WorkerGlobalScope` interface, and its parent `EventTarget`.*

`DedicatedWorkerGlobalScope.name` Read only

The name that the `Worker` was (optionally) given when it was created using the `Worker()` constructor. This is mainly useful for debugging purposes.

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

*This interface inherits methods from the `WorkerGlobalScope` interface, and its parent `EventTarget`.*

`DedicatedWorkerGlobalScope.close()`

Discards any tasks queued in the `WorkerGlobalScope`'s event loop, effectively closing this particular scope.

`DedicatedWorkerGlobalScope.postMessage()`

Sends a message — which can consist of `any` JavaScript object — to the parent document that first spawned the worker.

`DedicatedWorkerGlobalScope.cancelAnimationFrame()`

Cancels an animation frame request previously scheduled through a call to `requestAnimationFrame()`.

`DedicatedWorkerGlobalScope.requestAnimationFrame()`

Perform an animation frame request and call a user-supplied callback function before the next repaint.

Events
------

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

`message`

Fired when the worker receives a message from its parent.

`messageerror`

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

`rtctransform`

Fired when an encoded video or audio frame has been queued for processing by a WebRTC Encoded Transform.

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

| Specification |
| --- |
| HTML Standard # dedicated-workers-and-the-dedicatedworkerglobalscope-interface |

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

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

See also
--------

* `Worker`
* `WorkerGlobalScope`
* Using web workers
* Functions available to workers


SVGFEDiffuseLightingElement - Web APIs

SVGFEDiffuseLightingElement
===========================

The **`SVGFEDiffuseLightingElement`** interface corresponds to the `<feDiffuseLighting>` element.

EventTarget

Node

Element

SVGElement

SVGFEDiffuseLightingElementInstance properties
-------------------

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

`SVGFEDiffuseLightingElement.diffuseConstant` Read only

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

`SVGFEDiffuseLightingElement.height` Read only

An `SVGAnimatedLength` corresponding to the `height` attribute of the given element.

`SVGFEDiffuseLightingElement.in1` Read only

An `SVGAnimatedString` corresponding to the `in` attribute of the given element.

`SVGFEDiffuseLightingElement.kernelUnitLengthX` Read only

An `SVGAnimatedNumber` corresponding to the X component of the `kernelUnitLength` attribute of the given element.

`SVGFEDiffuseLightingElement.kernelUnitLengthY` Read only

An `SVGAnimatedNumber` corresponding to the Y component of the `kernelUnitLength` attribute of the given element.

`SVGFEDiffuseLightingElement.result` Read only

An `SVGAnimatedString` corresponding to the `result` attribute of the given element.

`SVGFEDiffuseLightingElement.surfaceScale` Read only

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

`SVGFEDiffuseLightingElement.width` Read only

An `SVGAnimatedLength` corresponding to the `width` attribute of the given element.

`SVGFEDiffuseLightingElement.x` Read only

An `SVGAnimatedLength` corresponding to the `x` attribute of the given element.

`SVGFEDiffuseLightingElement.y` Read only

An `SVGAnimatedLength` corresponding to the `y` attribute of the given element.

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

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

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

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

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

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

See also
--------

* `<feDiffuseLighting>`


Request - Web APIs

Request
=======

The **`Request`** interface of the Fetch API represents a resource request.

You can create a new `Request` object using the `Request()` constructor, but you are more likely to encounter a `Request` object being returned as the result of another API operation, such as a service worker `FetchEvent.request`.

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

`Request()`

Creates a new `Request` object.

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

`Request.body` Read only

A `ReadableStream` of the body contents.

`Request.bodyUsed` Read only

Stores `true` or `false` to indicate whether or not the body has been used in a request yet.

`Request.cache` Read only

Contains the cache mode of the request (e.g., `default`, `reload`, `no-cache`).

`Request.credentials` Read only

Contains the credentials of the request (e.g., `omit`, `same-origin`, `include`). The default is `same-origin`.

`Request.destination` Read only

A string describing the type of content being requested.

`Request.headers` Read only

Contains the associated `Headers` object of the request.

`Request.integrity` Read only

Contains the subresource integrity value of the request (e.g., `sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=`).

`Request.method` Read only

Contains the request's method (`GET`, `POST`, etc.)

`Request.mode` Read only

Contains the mode of the request (e.g., `cors`, `no-cors`, `same-origin`, `navigate`.)

`Request.redirect` Read only

Contains the mode for how redirects are handled. It may be one of `follow`, `error`, or `manual`.

`Request.referrer` Read only

Contains the referrer of the request (e.g., `client`).

`Request.referrerPolicy` Read only

Contains the referrer policy of the request (e.g., `no-referrer`).

`Request.signal` Read only

Returns the `AbortSignal` associated with the request

`Request.url` Read only

Contains the URL of the request.

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

`Request.arrayBuffer()`

Returns a promise that resolves with an `ArrayBuffer` representation of the request body.

`Request.blob()`

Returns a promise that resolves with a `Blob` representation of the request body.

`Request.clone()`

Creates a copy of the current `Request` object.

`Request.formData()`

Returns a promise that resolves with a `FormData` representation of the request body.

`Request.json()`

Returns a promise that resolves with the result of parsing the request body as `JSON`.

`Request.text()`

Returns a promise that resolves with a text representation of the request body.

**Note:** The request body functions can be run only once; subsequent calls will reject with TypeError showing that the body stream has already used.

Examples
--------

In the following snippet, we create a new request using the `Request()` constructor (for an image file in the same directory as the script), then return some property values of the request:

```js
const request = new Request("https://www.mozilla.org/favicon.ico");

const url = request.url;
const method = request.method;
const credentials = request.credentials;
```

You could then fetch this request by passing the `Request` object in as a parameter to a `fetch()` call, for example:

```js
fetch(request)
  .then((response) => response.blob())
  .then((blob) => {
    image.src = URL.createObjectURL(blob);
  });
```

In the following snippet, we create a new request using the `Request()` constructor with some initial data and body content for an API request which need a body payload:

```js
const request = new Request("https://example.com", {
  method: "POST",
  body: '{"foo": "bar"}',
});

const url = request.url;
const method = request.method;
const credentials = request.credentials;
const bodyUsed = request.bodyUsed;
```

**Note:** The body can only be a `Blob`, an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `FormData`, a `URLSearchParams`, a `ReadableStream`, or a `String` object, as well as a string literal, so for adding a JSON object to the payload you need to stringify that object.

You could then fetch this API request by passing the `Request` object in as a parameter to a `fetch()` call, for example and get the response:

```js
fetch(request)
  .then((response) => {
    if (response.status === 200) {
      return response.json();
    } else {
      throw new Error("Something went wrong on API server!");
    }
  })
  .then((response) => {
    console.debug(response);
    // …
  })
  .catch((error) => {
    console.error(error);
  });
```

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

| Specification |
| --- |
| Fetch Standard # request-class |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


WindowClient - Web APIs

WindowClient
============

The `WindowClient` interface of the ServiceWorker API represents the scope of a service worker client that is a document in a browsing context, controlled by an active worker. The service worker client independently selects and uses a service worker for its own loading and sub-resources.

Client

WindowClientInstance methods
----------------

*`WindowClient` inherits methods from its parent interface, `Client`.*

`WindowClient.focus()`

Gives user input focus to the current client.

`WindowClient.navigate()`

Loads a specified URL into a controlled client page.

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

*`WindowClient` inherits properties from its parent interface, `Client`.*

`WindowClient.ancestorOrigins` Read only
Experimental

An array of strings that indicates the ancestor origins of the browsing context represented by this `WindowClient` in reverse order.

`WindowClient.focused` Read only

A boolean that indicates whether the current client has focus.

`WindowClient.visibilityState` Read only

Indicates the visibility of the current client. This value can be one of `"hidden"`, `"visible"`, or `"prerender"`.

Example
-------

```js
self.addEventListener("notificationclick", (event) => {
  console.log("On notification click: ", event.notification.tag);
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(
    clients
      .matchAll({
        type: "window",
      })
      .then((clientList) => {
        for (const client of clientList) {
          if (client.url === "/" && "focus" in client) {
            client.focus();
            break;
          }
        }
        if (clients.openWindow) return clients.openWindow("/");
      }),
  );
});
```

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

| Specification |
| --- |
| Service Workers # windowclient |

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
* Channel Messaging API


Worklet - Web APIs

Worklet
=======

The **`Worklet`** interface is a lightweight version of `Web Workers` and gives developers access to low-level parts of the rendering pipeline.

With Worklets, you can run JavaScript and WebAssembly code to do graphics rendering or audio processing where high performance is required.

 Worklets allow static import of ECMAScript modules, if supported, using `import`.
 Dynamic import is disallowed by the specification — calling `import()` will throw.

Worklet types
-------------

Worklets are restricted to specific use cases; they cannot be used for arbitrary computations like Web Workers. The `Worklet` interface abstracts properties and methods common to all kind of worklets, and cannot be created directly. Instead, you can use one of the following classes:

| Name | Description | Location | Specification |
| --- | --- | --- | --- |
| `AudioWorklet` | For audio processing with custom AudioNodes. | Web Audio render thread | Web Audio API |
| `AnimationWorklet` |
 For creating scroll-linked and other high performance procedural
 animations.
  | Compositor thread | CSS Animation Worklet API |
| `LayoutWorklet` | For defining the positioning and dimensions of custom elements. |  | CSS Layout API |
| `SharedStorageWorklet` | For running private operations on cross-site data, without risk of data leakage. | Main thread | Shared Storage API |

**Note:** Paint worklets, defined by the CSS Painting API, don't subclass `Worklet`. They are accessed through a regular `Worklet` object obtained using `CSS.paintWorklet`.

For 3D rendering with WebGL, you don't use worklets. Instead, you write vertex shaders and fragment shaders using GLSL code, and those shaders will then run on the graphics card.

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

*The Worklet interface does not define any properties.*

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

`Worklet.addModule()`

Adds the script module at the given URL to the current worklet.

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

| Specification |
| --- |
| HTML Standard # worklets-worklet |

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

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

See also
--------

* Houdini: Demystifying CSS on Google Developers (2016)
* AudioWorklet :: What, Why, and How on YouTube (2017)
* Enter AudioWorklet on Google Developers (2017)
* Animation Worklet - HTTP203 Advent on YouTube (2017)


GPUCommandBuffer - Web APIs

GPUCommandBuffer
================

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

The **`GPUCommandBuffer`** interface of the WebGPU API represents a pre-recorded list of GPU commands that can be submitted to a `GPUQueue` for execution.

A `GPUCommandBuffer` is created via the `GPUCommandEncoder.finish()` method; the GPU commands recorded within are submitted for execution by passing the `GPUCommandBuffer` into the parameter of a `GPUQueue.submit()` call.

**Note:** Once a `GPUCommandBuffer` object has been submitted, it cannot be used again.

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.

Examples
--------

```js
// ...

const commandBuffer = commandEncoder.finish();
device.queue.submit([commandBuffer]);
```

**Note:** Study the WebGPU samples to find complete examples.

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

| Specification |
| --- |
| WebGPU # gpucommandbuffer |

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

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

See also
--------

* The WebGPU API


SharedStorageOperation - Web APIs

SharedStorageOperation
======================

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

The **`SharedStorageOperation`** interface of the Shared Storage API represents the base class for all output gate operation types.

The output gate types are detailed below:

| Name | Description | Defined by | Invoked by |
| --- | --- | --- | --- |
| URL Selection | Used to select a URL to display to the user based on shared storage data. | `SharedStorageSelectURLOperation` | `selectURL()` |
| Run | A generic way to process some shared storage data. Used, for example, by the Private Aggregation API to process shared storage data and generate aggregated reports. | `SharedStorageRunOperation` | `run()` |

Examples
--------

### Defining individual operations

Many shared storage worklet module scripts only define and register a single operation; you can see examples on the `SharedStorageSelectURLOperation` and `SharedStorageRunOperation` pages.

### Defining multiple operations

In more advanced cases, it is possible to define and register multiple operations in the same shared storage worklet module script with different names. In the following worklet module script, we define a URL Selection operation called `SelectURLOperation` that selects a URL for A/B testing, and a Run operation called `ExperimentGroupReportingOperation`, which runs a histogram report based on the user's A/B testing group:

```js
// ab-testing-worklet.js

class SelectURLOperation {
  async run(urls, data) {
    // Read the user's group from shared storage
    const experimentGroup = await sharedStorage.get("ab-testing-group");

    // Log to console for the demo
    console.log(`urls = ${JSON.stringify(urls)}`);
    console.log(`data = ${JSON.stringify(data)}`);
    console.log(`ab-testing-group in shared storage is ${experimentGroup}`);

    // Return the index of the group
    return data.indexOf(experimentGroup);
  }
}

function getBucketForTestingGroup(testingGroup) {
  switch (testingGroup) {
    case "control":
      return 0;
    case "experiment-a":
      return 1;
    case "experiment-b":
      return 2;
  }
}

class ExperimentGroupReportingOperation {
  async run() {
    const experimentGroup = await sharedStorage.get("ab-testing-group");

    const bucket = BigInt(getBucketForTestingGroup(experimentGroup));
    privateAggregation.contributeToHistogram({ bucket, value: 1 });
  }
}

// Register the operations
register("ab-testing", SelectURLOperation);
register("experiment-group-reporting", ExperimentGroupReportingOperation);
```

In the main browsing context, these operations are invoked by `selectURL()` and `run()`, respectively. The operations to invoke via these methods are selected using the names they were registered with, and they are also required to conform to the structures defined by the `SharedStorageSelectURLOperation` and `SharedStorageRunOperation` classes and their `run()` methods.

```js
// For demo purposes. The hostname is used to determine the usage of
// development localhost URL vs production URL
const contentProducerUrl = window.location.host;

// Map the experiment groups to the URLs
const EXPERIMENT\_MAP = [
  {
    group: "control",
    url: `https://${contentProducerUrl}/ads/default-ad.html`,
  },
  {
    group: "experiment-a",
    url: `https://${contentProducerUrl}/ads/experiment-ad-a.html`,
  },
  {
    group: "experiment-b",
    url: `https://${contentProducerUrl}/ads/experiment-ad-b.html`,
  },
];

// Choose a random group for the initial experiment
function getRandomExperiment() {
  const randomIndex = Math.floor(Math.random() \* EXPERIMENT\_MAP.length);
  return EXPERIMENT\_MAP[randomIndex].group;
}

async function injectAd() {
  // Load the worklet module
  await window.sharedStorage.worklet.addModule("ab-testing-worklet.js");

  // Set the initial value in the storage to a random experiment group
  window.sharedStorage.set("ab-testing-group", getRandomExperiment(), {
    ignoreIfPresent: true,
  });

  const urls = EXPERIMENT\_MAP.map(({ url }) => ({ url }));
  const groups = EXPERIMENT\_MAP.map(({ group }) => group);

  // Resolve the selectURL call to a fenced frame config only when it exists on the page
  const resolveToConfig = typeof window.FencedFrameConfig !== "undefined";

  // Run the URL selection operation to select an ad based on the experiment group in shared storage
  const selectedUrl = await window.sharedStorage.selectURL("ab-testing", urls, {
    data: groups,
    resolveToConfig,
    keepAlive: true,
  });

  const adSlot = document.getElementById("ad-slot");

  if (resolveToConfig && selectedUrl instanceof FencedFrameConfig) {
    adSlot.config = selectedUrl;
  } else {
    adSlot.src = selectedUrl;
  }

  // Run the reporting operation
  await window.sharedStorage.run("experiment-group-reporting");
}

injectAd();
```

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

| Specification |
| --- |
| Shared Storage API # sharedstorageoperation |

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

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

See also
--------

* Shared Storage API


SVGStyleElement - Web APIs

SVGStyleElement
===============

The **`SVGStyleElement`** interface corresponds to the SVG `<style>` element.

EventTarget

Node

Element

SVGElement

SVGStyleElementInstance properties
-------------------

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

`SVGStyleElement.type`
Deprecated

A string corresponding to the `type` attribute of the given element.

`SVGStyleElement.media`

A string corresponding to the `media` attribute of the given element.

`SVGStyleElement.title`

A string corresponding to the `title` attribute of the given element.

`SVGStyleElement.sheet` Read only

Returns the `CSSStyleSheet` object associated with the given element, or `null` if there is none.

`SVGStyleElement.disabled`

A boolean value indicating whether or not the associated stylesheet is disabled.

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

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

Examples
--------

### Dynamically adding an SVG style element

To dynamically create an SVG style element (`SVGStyleElement`), you need to use `Document.createElementNS()`, specifying a `style` element in the SVG namespace.

**Note:** `Document.createElement()` can't be used to create SVG style elements (it returns an `HTMLStyleElement`).

Given the following SVG element:

```html
<svg
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink">
  <circle cx="50" cy="50" r="25" />
</svg>
```

You can create an SVG style element as shown:

```js
// Get the SVG element object by tag name
const svg = document.querySelector("svg");

// Create the `style` element in the SVG namespace
const style = document.createElementNS("http://www.w3.org/2000/svg", "style");
const node = document.createTextNode("circle { fill: red; }");
style.appendChild(node);

// Append the style element to the SVG element
svg.appendChild(style);
```

### Accessing an existing SVG style

 You can access an SVG style element that was defined in HTML (or an SVG file) using the normal HTML methods for getting tags, ids, and so on.
 These include: `Document.getElementsByTagName()`, `Document.getElementById()`, `Document.querySelector()`, `Document.querySelectorAll()`, and so on.

For example, consider the HTML below that defines an SVG file with a style element.

```html
<svg
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink">
  <style id="circle\_style\_id">
 circle {
 fill: gold;
 stroke: green;
 stroke-width: 3px;
 }
 </style>
  <circle cx="50" cy="50" r="25" />
</svg>
```

To fetch the first `style` element in the first `svg` element, you might use `Document.querySelector()` as shown below.

```js
const svg = document.querySelector("svg");
const style = svg.querySelector("style");
```

Alternatively, you can could use `Document.getElementById()`, specifying the tag id:

```js
const svg = document.querySelector("svg");
const style = svg.getElementById("circle\_style\_id");
```

Or just get the element from document by id (in this case using `document.querySelector()`):

```js
const style = document.querySelector("#circle\_style\_id");
```

Getting and setting properties
------------------------------

This example demonstrates how to get and set the properties of a style element, which in this case was specified in an SVG definition.

### HTML

The HTML contains an SVG definition for a `<circle>` with a `<style>` element, along with an HTML `<button>` element that will be used to enable and disable the style, and an HTML `<textarea>` element for logging the property values.

```html
<button>Disable</button>
<textarea id="log" rows="6" cols="90"></textarea>
<svg
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink">
  <style id="circle\_style\_id" media="all and (min-width: 600px)">
 circle {
 fill: gold;
 stroke: green;
 stroke-width: 3px;
 }
 </style>
  <circle cx="60" cy="60" r="50" />
</svg>
```

 Note that above we have set the `media` attribute on the `style` tag.
 We have not set `type` as it is deprecated, or `disabled` because there is no such attribute (only the property on the element).

### JavaScript

The code below gets the `style` element (an `SVGStyleElement`) using its id.

```js
const svg = document.querySelector("svg");
const style = svg.getElementById("circle\_style\_id");
```

 We then add a function to log the style properties.
 This is called after initialization, whenever the frame resizes, and if the button is pressed.

```js
// Get logging text area
const log = document.getElementById("log");

function setLogText() {
  //Log current values of properties
  log.value = `style.media: ${style.media} (frame width: ${window.innerWidth})\n`; // 'all' by default
  log.value += `style.title: ${style.title}\n`; // no default value
  log.value += `style.disabled: ${style.disabled}\n`; // 'false' by default
  log.value += `style.type: ${style.type}\n`; // deprecated (do not use)
  log.value += `style.sheet.rules[0].cssText: ${style.sheet.rules[0].cssText}\n`;
}

// Log initial property values
setLogText();

// Log when the frame resizes
addEventListener("resize", () => {
  setLogText();
});
```

 Last of all we set an event handler for the button.
 When the button is clicked the `disabled` property is toggled.
 This also updates the log and the button text.

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

button.addEventListener("click", () => {
  style.disabled = !style.disabled;
  button.textContent = style.disabled ? "Enable" : "Disable";

  // Log after button presses
  setLogText();
});
```

### Result

 The result is shown below.
 Toggle the button to enable and disable the SVG style element.
 If the SVG style is not disabled, you can also resize the window width to see the effect of the `media` property on the style when the frame holding the live example is 600px wide.

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

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

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

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

See also
--------

* `HTMLStyleElement`


RTCIceCandidateStats - Web APIs

RTCIceCandidateStats
====================

The **`RTCIceCandidateStats`** dictionary of the WebRTC API is used to report statistics related to an `RTCIceCandidate`.

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

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

`address` Optional

A string containing the address of the candidate. This value may be an IPv4 address, an IPv6 address, or a fully-qualified domain name. This property was previously named `ip` and only accepted IP addresses.

`candidateType`

A string matching one of the values in `RTCIceCandidate.type`, indicating what kind of candidate the object provides statistics for.

`deleted` Optional

A Boolean value indicating whether or not the candidate has been released or deleted; the default value is `false`. For local candidates, its value is `true` if the candidate has been deleted or released. For host candidates, `true` means that any network resources (usually a network socket) associated with the candidate have already been released. For TURN candidates, the TURN allocation is no longer active for deleted candidates. This property is not present for remote candidates.

`port` Optional

The network port number used by the candidate.

`priority` Optional

The candidate's priority, corresponding to `RTCIceCandidate.priority`.

`protocol` Optional

A string specifying the protocol (`tcp` or `udp`) used to transmit data on the `port`.

`relayProtocol` Optional

 A string identifying the protocol used by the endpoint for communicating with the TURN server; valid values are `tcp`, `udp`, and `tls`.
 Only present for local candidates.

`transportId`

A string uniquely identifying the transport object that was inspected in order to obtain the `RTCTransportStats` associated with the candidate corresponding to these statistics.

`url` Optional

 For local candidates, the `url` property is the URL of the ICE server from which the candidate was received.
 This URL matches the one included in the `RTCPeerConnectionIceEvent` object representing the `icecandidate` event that delivered the candidate to the local peer.

### Common instance properties

The following properties are common to all WebRTC statistics objects.

`id`

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

`timestamp`

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

`type`

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

Examples
--------

TBD

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

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

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

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


RTCRtpStreamStats - Web APIs

RTCRtpStreamStats
=================

The `RTCRtpStreamStats` dictionary is returned by the `RTCPeerConnection.getStats()`, `RTCRtpSender.getStats()`, and `RTCRtpReceiver.getStats()` methods to provide detailed statistics about WebRTC connectivity.

While the dictionary has a base set of properties that are present in each of these cases, there are also additional properties added depending on which interface the method is called on.

`RTCRtpStreamStats` is the base class for all RTP-related statistics reports.

**Note:** This interface was called `RTCRTPStreamStats` until a specification update in the spring of 2017.
 Check the Browser compatibility table to know if and when the name change was implemented in specific browsers.

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

### Standard fields included for all media types

`codecId`

A string which uniquely identifies the object which was inspected to produce the `RTCCodecStats` object associated with this RTP stream.

`kind`

A string whose value is `"audio"` if the associated `MediaStreamTrack` is audio-only or `"video"` if the track contains video. This value will match that of the media type indicated by `RTCCodecStats.codec`, as well as the track's `kind` property. Previously called `mediaType`.

`ssrc`

The 32-bit integer which identifies the source of the RTP packets this `RTCRtpStreamStats` object covers. This value is generated per the RFC 3550 specification.

`trackId`

A string which uniquely identifies the `RTCMediaStreamTrackStats` object representing the associated `MediaStreamTrack`. This is *not* the same as the value of `MediaStreamTrack.id`.

`transportId`

A string uniquely identifying the object which was inspected to produce the `RTCTransportStats` object associated with this RTP stream.

### Common instance properties

The following properties are common to all WebRTC statistics objects.

`id

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

`timestamp`

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

`type`

A string that indicates the type of statistics that the object contains.

### Local-only measurements

These properties are computed locally, and are only available to the device receiving the media stream. Their primary purpose is to examine the error resiliency of the connection, as they provide information about lost packets, lost frames, and how heavily compressed the data is.

`firCount`

A count of the total number of Full Intra Request (FIR) packets received by the sender. This statistic is only available to the device which is receiving the stream and is only available for video tracks. A FIR packet is sent by the receiving end of the stream when it falls behind or has lost packets and is unable to continue decoding the stream; the sending end of the stream receives the FIR packet and responds by sending a full frame instead of a delta frame, thereby letting the receiver "catch up." The higher this number is, the more often a problem of this nature arose, which can be a sign of network congestion or an overburdened receiving device.

`nackCount`

The number of times the receiver notified the sender that one or more RTP packets has been lost by sending a Negative ACKnowledgement (NACK, also called "Generic NACK") packet to the sender. This value is only available to the receiver.

`pliCount`

The number of times the receiving end of the stream sent a Picture Loss Indication (PLI) packet to the sender, indicating that it has lost some amount of encoded video data for one or more frames. Only the receiver has this value, and it's only valid for video tracks.

`qpSum`

The sum of the Quantization Parameter (QP) values associated with every frame received to date on the video track described by this `RTCRtpStreamStats` object. In general, the higher this number is, the more heavily compressed the video track was. Combined with `RTCReceivedRtpStreamStats.framesDecoded` or `RTCSentRtpStreamStats.framesEncoded`, you can approximate the average QP over those frames, keeping in mind that codecs often vary the quantizer values even within frames. Also keep in mind that the values of QP can vary from codec to codec, so this value is only potentially useful when compared against the same codec.

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

#### No specification found

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


Clients - Web APIs

Clients
=======

The `Clients` interface provides access to `Client` objects. Access it via ``self`.clients` within a service worker.

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

`Clients.get()`

Returns a `Promise` for a `Client` matching a given `id`.

`Clients.matchAll()`

Returns a `Promise` for an array of `Client` objects. An options argument allows you to control the types of clients returned.

`Clients.openWindow()`

Opens a new browser window for a given URL and returns a `Promise` for the new `WindowClient`.

`Clients.claim()`

Allows an active service worker to set itself as the `controller` for all clients within its `scope`.

Examples
--------

The following example shows an existing chat window or creates a new one when the user clicks a notification.

```js
addEventListener("notificationclick", (event) => {
  event.waitUntil(
    (async () => {
      const allClients = await clients.matchAll({
        includeUncontrolled: true,
      });

      let chatClient;

      // Let's see if we already have a chat window open:
      for (const client of allClients) {
        const url = new URL(client.url);

        if (url.pathname === "/chat/") {
          // Excellent, let's use it!
          client.focus();
          chatClient = client;
          break;
        }
      }

      // If we didn't find an existing chat window,
      // open a new one:
      if (!chatClient) {
        chatClient = await clients.openWindow("/chat/");
      }

      // Message the client:
      chatClient.postMessage("New chat messages!");
    })(),
  );
});
```

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

| Specification |
| --- |
| Service Workers # clients-interface |

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

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

See also
--------

* Using Service Workers


Media Capabilities API - Web APIs

Media Capabilities API
======================

The **Media Capabilities API** allows developers to determine decoding and encoding abilities of the device, exposing information such as whether media is supported and whether playback should be smooth and power efficient, with real time feedback about playback to better enable adaptive streaming, and access to display property information.

Examples
--------

### Detect audio file support and expected performance

This example defines an audio configuration then checks to see if the user agent supports decoding that media configuration, and whether it will perform well in terms of smoothness and power efficiency.

```js
if ("mediaCapabilities" in navigator) {
  const audioFileConfiguration = {
    type: "file",
    audio: {
      contentType: "audio/mp3",
      channels: 2,
      bitrate: 132700,
      samplerate: 5200,
    },
  };

  navigator.mediaCapabilities
    .decodingInfo(audioFileConfiguration)
    .then((result) => {
      console.log(
        `This configuration is ${result.supported ? "" : "not "}supported,`,
      );
      console.log(`${result.smooth ? "" : "not "}smooth, and`);
      console.log(`${result.powerEfficient ? "" : "not "}power efficient.`);
    })
    .catch(() => {
      console.log(`decodingInfo error: ${contentType}`);
    });
}
```

Media Capabilities API concepts and usage
-----------------------------------------

There are a myriad of video and audio codecs. Different browsers support different media types and new media types are always being developed. With the Media Capabilities API, developers can ensure each user is getting the best bitrate and storage savings for their browser, device, and OS capabilities.

Whether a device uses hardware or software decoding impacts how smooth and power efficient the video decoding is and how efficient the playback will be. The Media Capabilities API enables determining which codecs are supported and how performant a media file will be both in terms of smoothness and power efficiency.

The Media Capabilities API provide more powerful features than say `MediaRecorder.isTypeSupported()` or `HTMLMediaElement.canPlayType()`, which only address general browser support, not performance. The API also provides abilities to access display property information such as supported color gamut, dynamic range abilities, and real-time feedback about the playback.

To test support, smoothness, and power efficiency of a video or audio file, you use the `MediaCapabilities` interface's `encodingInfo()` and `decodingInfo()` methods.

Media capabilities information enables websites to enable adaptive streaming to alter the quality of content based on actual user-perceived quality, and react to a pick of CPU/GPU usage in real time.

Media Capabilities Interfaces
-----------------------------

`MediaCapabilities`

Provides information about the decoding abilities of the device, system and browser based on codecs, profile, resolution, and bitrates. The information can be used to serve optimal media streams to the user and determine if playback should be smooth and power efficient .

ScreenColorGamut

Will describe the color gamut, or the range of color, the screen can display (not currently supported anywhere).

ScreenLuminance

Will describe the known luminance characteristics of the screen (not currently supported anywhere).

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

| Specification |
| --- |
| Media Capabilities # media-capabilities-interface |

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

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

See also
--------

* HTMLMediaElement's method canPlayType()
* MediaSource's method isTypeSupported()
* `Navigator` interface
* Using the Media Capabilities API


HTMLTableCellElement - Web APIs

HTMLTableCellElement
====================

The **`HTMLTableCellElement`** interface provides special properties and methods (beyond the regular `HTMLElement` interface it also has available to it by inheritance) for manipulating the layout and presentation of table cells, either header cells (`<th>`)) or data cells (`<td>`), in an HTML document.

EventTarget

Node

Element

HTMLElement

HTMLTableCellElementInstance properties
-------------------

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

`HTMLTableCellElement.abbr`

A string which can be used on `<th>` elements (not on `<td>`), specifying an alternative label for the header cell. This alternate label can be used in other contexts, such as when describing the headers that apply to a data cell. This is used to offer a shorter term for use by screen readers in particular, and is a valuable accessibility tool. Usually the value of `abbr` is an abbreviation or acronym, but can be any text that's appropriate contextually.

`HTMLTableCellElement.cellIndex` Read only

A long integer representing the cell's position in the `cells` collection of the `<tr>` the cell is contained within. If the cell doesn't belong to a `<tr>`, it returns `-1`.

`HTMLTableCellElement.colSpan`

An unsigned long integer indicating the number of columns this cell must span; this lets the cell occupy space across multiple columns of the table. It reflects the `colspan` attribute.

`HTMLTableCellElement.headers` Read only

A `DOMTokenList` describing a list of `id` of `<th>` elements that represents headers associated with the cell. It reflects the `headers` attribute.

`HTMLTableCellElement.rowSpan`

An unsigned long integer indicating the number of rows this cell must span; this lets a cell occupy space across multiple rows of the table. It reflects the `rowspan` attribute.

`HTMLTableCellElement.scope`

A string indicating the scope of a `<th>` cell. Header cells can be configured, using the `scope` property, the apply to a specified row or column, or to the not-yet-scoped cells within the current row group (that is, the same ancestor `<thead>`, `<tbody>`, or `<tfoot>` element). If no value is specified for `scope`, the header is not associated directly with cells in this way. Permitted values for `scope` are:

`col`

The header cell applies to the following cells in the same column (or columns, if `colspan` is used as well), until either the end of the column or another `<th>` in the column establishes a new scope.

`colgroup`

The header cell applies to all cells in the current column group that do not already have a scope applied to them. This value is only allowed if the cell is in a column group.

`row`

The header cell applies to the following cells in the same row (or rows, if `rowspan` is used as well), until either the end of the row or another `<th>` in the same row establishes a new scope.

`rowgroup`

The header cell applies to all cells in the current row group that do not already have a scope applied to them. This value is only allowed if the cell is in a row group.

The empty string (`""`)

The header cell has no predefined scope; the user agent will establish the scope based on contextual clues.

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

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

Deprecated properties
---------------------

**Warning:** These properties have been deprecated and should no longer be used. They are documented primarily to help understand older code bases.

`HTMLTableCellElement.align`
Deprecated

A string containing an enumerated value reflecting the `align` attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, and `"center"`.

`HTMLTableCellElement.axis`
Deprecated

A string containing a name grouping cells in virtual. It reflects the obsolete `axis` attribute.

`HTMLTableCellElement.bgColor`
Deprecated

A string containing the background color of the cells. It reflects the obsolete `bgColor` attribute.

`HTMLTableCellElement.ch`
Deprecated

A string containing one single character. This character is the one to align all the cell of a column on. It reflects the `char` and default to the decimal points associated with the language, e.g. `'.'` for English, or `','` for French. This property was optional and was not very well supported.

`HTMLTableCellElement.chOff`
Deprecated

A string containing an integer indicating how many characters must be left at the right (for left-to-right scripts; or at the left for right-to-left scripts) of the character defined by `HTMLTableCellElement.ch`. This property was optional and was not very well supported.

`HTMLTableCellElement.height`
Deprecated

A string containing a length of pixel of the hinted height of the cell. It reflects the obsolete `height` attribute.

`HTMLTableCellElement.noWrap`
Deprecated

A boolean value reflecting the `nowrap` attribute and indicating if cell content can be broken in several lines.

`HTMLTableCellElement.vAlign`
Deprecated

A string representing an enumerated value indicating how the content of the cell must be vertically aligned. It reflects the `valign` attribute and can have one of the following values: `"top"`, `"middle"`, `"bottom"`, or `"baseline"`. Use the CSS `vertical-align` property instead.

`HTMLTableCellElement.width`
Deprecated

A string specifying the number of pixels wide the cell should be drawn, if possible. This property reflects the also obsolete `width` attribute. Use the CSS `width` property instead.

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

| Specification |
| --- |
| HTML Standard # htmltablecellelement |

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

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

See also
--------

* The HTML elements implementing this interface: `<th>` and `<td>`.


SVGFontFaceNameElement - Web APIs

SVGFontFaceNameElement
======================

**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 **`SVGFontFaceNameElement`** interface corresponds to the `<font-face-name>` elements.

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

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

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

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

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

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

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

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

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

See also
--------

* `<font-face-name>`


TrustedHTML - Web APIs

TrustedHTML
===========

The **`TrustedHTML`** interface of the `Trusted Types API` represents a string that a developer can insert into an injection sink that will render it as HTML. These objects are created via `TrustedTypePolicy.createHTML()` and therefore have no constructor.

The value of a **TrustedHTML** object is set when the object is created and cannot be changed by JavaScript as there is no setter exposed.

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

`TrustedHTML.toJSON()`

Returns a JSON representation of the stored data.

`TrustedHTML.toString()`

A string containing the sanitized HTML.

Examples
--------

In the below example we create a policy that will create `TrustedHTML` objects using `TrustedTypePolicyFactory.createPolicy()`. We can then use `TrustedTypePolicy.createHTML` to create a sanitized HTML string to be inserted into the document.

The sanitized value can then be used with `Element.innerHTML` to ensure that no new HTML elements can be injected.

```html
<div id="myDiv"></div>
```

```js
const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {
  createHTML: (string) => string.replace(/</g, "<"),
});

let el = document.getElementById("myDiv");
const escaped = escapeHTMLPolicy.createHTML("<img src=x onerror=alert(1)>");
console.log(escaped instanceof TrustedHTML); // true
el.innerHTML = escaped;
```

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

| Specification |
| --- |
| Trusted Types # trusted-html |

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

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

See also
--------

* Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types


XRCubeLayer - Web APIs

XRCubeLayer
===========

**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 **`XRCubeLayer`** interface of the WebXR Device API is a layer that renders directly from a cubemap and projects it onto the inside faces of a cube.

`XRCubeLayer` requires the `layers` feature to be enabled for the `XRSession`. You can request it in `XRSystem.requestSession()`.

To create a new `XRCubeLayer`, call `XRWebGLBinding.createCubeLayer()`.

To present layers to the XR device, add them to the `layers` render state using `XRSession.updateRenderState()`.

EventTarget

XRLayer

XRCompositionLayer

XRCubeLayerInstance properties
-------------------

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

`XRCubeLayer.space`
Experimental

An `XRSpace` representing the layer's spatial relationship with the user's physical environment.

`XRCubeLayer.orientation`
Experimental

A `DOMPointReadOnly` representing the orientation relative to the `space` property.

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

*Inherits methods from its parents, `XRCompositionLayer` and `EventTarget`*.

Events
------

`redraw`
Experimental

Sent to the `XRCubeLayer` object when the underlying resources of the layer are lost or when the XR Compositor can no longer reproject the layer. If this event is sent, authors should redraw the content of the layer in the next XR animation frame.

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

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

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

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

See also
--------

* `XRLayer`
* `EventTarget`
* `XRCompositionLayer`
* `XREquirectLayer`
* `XRQuadLayer`
* `XRCylinderLayer`
* `XRProjectionLayer`


AudioDecoder - Web APIs

AudioDecoder
============

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

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

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

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

The **`AudioDecoder`** interface of the WebCodecs API decodes chunks of audio.

EventTarget

AudioDecoderConstructor
-----------

`AudioDecoder()`
Experimental

Creates a new `AudioDecoder` object.

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

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

`AudioDecoder.decodeQueueSize` Read only
Experimental

An integer representing the number of decode queue requests.

`AudioDecoder.state` Read only
Experimental

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

### Events

`dequeue`
Experimental

Fires to signal a decrease in `AudioDecoder.decodeQueueSize`.

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

`AudioDecoder.isConfigSupported()`
Experimental

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

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

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

`AudioDecoder.configure()`
Experimental

Enqueues a control message to configure the audio decoder for decoding chunks.

`AudioDecoder.decode()`
Experimental

Enqueues a control message to decode a given chunk of audio.

`AudioDecoder.flush()`
Experimental

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

`AudioDecoder.reset()`
Experimental

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

`AudioDecoder.close()`
Experimental

Ends all pending work and releases system resources.

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

| Specification |
| --- |
| WebCodecs # audiodecoder-interface |

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

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


PaymentRequestUpdateEvent - Web APIs

PaymentRequestUpdateEvent
=========================

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

The **`PaymentRequestUpdateEvent`** interface is used for events sent to a `PaymentRequest` instance when changes are made to shipping-related information for a pending `PaymentRequest`. Those events are:

`shippingaddresschange`

Dispatched whenever the user changes their shipping address.

`shippingoptionchange`

Dispatched whenever the user changes a shipping option.

Event

PaymentRequestUpdateEventConstructor
-----------

`PaymentRequestUpdateEvent()`

Creates a new `PaymentRequestUpdateEvent` object.

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

*Provides only the properties inherited from its parent interface, `Event`.*

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

*In addition to methods inherited from the parent interface, `Event`, `PaymentRequestUpdateEvent` offers the following methods:*

`PaymentRequestUpdateEvent.updateWith()`

If the event handler determines that information included in the payment request needs to be changed, or that new information needs to be added, it calls `updateWith()` with the information that needs to be replaced or added.

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

| Specification |
| --- |
| Payment Request API 1.1 # paymentrequestupdateevent-interface |

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

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

See also
--------

* Using the Payment Request API


Compression Streams API - Web APIs

Compression Streams API
=======================

The **Compression Streams API** provides a JavaScript API for compressing and decompressing streams of data using the gzip or deflate formats.

Built in compression means that JavaScript applications will not need to include a compression library, which makes the download size of the application smaller.

Interfaces
----------

`CompressionStream`

Compresses a stream of data.

`DecompressionStream`

Decompresses a stream of data.

Examples
--------

In this example a stream is compressed using gzip compression.

```js
const compressedReadableStream = inputReadableStream.pipeThrough(
  new CompressionStream("gzip"),
);
```

In the following example a function decompresses a blob using gzip.

```js
async function DecompressBlob(blob) {
  const ds = new DecompressionStream("gzip");
  const decompressedStream = blob.stream().pipeThrough(ds);
  return await new Response(decompressedStream).blob();
}
```

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

| Specification |
| --- |
| Compression Streams # compression-stream |

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

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


CSS Font Loading API - Web APIs

CSS Font Loading API
====================

The CSS Font Loading API provides events and interfaces for dynamically loading font resources.

**Note:** This feature is available in Web Workers (`self.fonts` provides access to `FontFaceSet`).

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

 CSS stylesheets allow authors to use custom fonts; specifying fonts to download using the `@font-face` rule, and applying them to elements with the `font-family` property.
 The point at which a font is downloaded is controlled by the user agent.
 Most agents only fetch and load fonts when they are first needed, which can result in a perceptible delay.

 The CSS Font Loading API overcomes this problem by letting authors control and track when a font face is fetched and loaded, and when it is added to the font face set owned by the document or worker.
 Adding a font face to the document or worker font face set allows the user agent to fetch and load the associated font resource automatically if needed.
 A font face can be loaded either before or after it is added to a font face set, but it *must* be added to the set before it can be used for drawing.

 Font faces are defined in `FontFace` objects, which specify a binary or URL font source and other properties of font in much the same way as the CSS `@font-face` rule.
 `FontFace` objects are added to the document or worker `FontFaceSet` using `Document.fonts` and `WorkerGlobalScope.fonts`, respectively.
 Authors can trigger download of fonts using either `FontFace` or `FontFaceSet`, and monitor loading completion.
 `FontFaceSet` can additionally be used to determine when all fonts required by a page have loaded and the document layout is complete.

 The `FontFace.status` property indicates the font face loading status: `unloaded`, `loading`, `loaded` or `failed`.
 This status is initially `unloaded`.
 It is set to `loading` when the file is being downloaded or the font data is being processed, and to `failed` if the font definition is invalid or the font data cannot be loaded.
 The status is set to `loaded` when the font face data has been successfully fetched (if needed) and loaded.

### Defining a font face

 Font faces are created using the `FontFace` constructor, which takes as parameters: the font family, the font source, and optional descriptors.
 The format and grammar of these arguments is the same as the equivalent `@font-face` definition.

 The font source can either be binary data in an `ArrayBuffer` or a font resource at an URL.
 A typical font face definition using a URL source might be as shown below.
 Note that the `url()` function is required for URL font sources.

```js
const font = new FontFace("myfont", "url(myfont.woff)", {
  style: "italic",
  weight: "400",
  stretch: "condensed",
});
```

**Note:** As with `@font-face`, some descriptors represent the expected data in the font data and are used for font matching, while others actually set/define properties of the generated font face.
 For example, setting the `style` to "italic" indicates that the file contains italic fonts; it is up to the author to specify a file for which this is true.

 Font faces with a *binary source* are automatically loaded if the font definition is valid and the font data can be loaded — `FontFace.status` is set to `loaded` on success and `failed` otherwise.
 Font faces with a URL source are validated but not automatically loaded — `FontFace.status` is set `unloaded` if the font face definition is valid and `failed` otherwise.

### Adding a font to a document or worker

Font faces are usually added to the document or worker `FontFaceSet` to allow the user agent to automatically load the font when needed, and *must* be added in order for the font to be used for rendering text.

The code below shows a font face being added to the document.

```js
// Define a FontFace
const font = new FontFace("myfont", "url(myfont.woff)", {
  style: "italic",
  weight: "400",
  stretch: "condensed",
});

// Add to the document.fonts (FontFaceSet)
document.fonts.add(font);
```

### Loading a font

 A font face can be loaded manually by calling `FontFace.load()`, or by calling `FontFaceSet.load()` if the font face has been added to the `FontFaceSet`.
 Note that attempting to load an already-loaded font has no effect.

The code below shows how to define a font face, add it to the document fonts, and then initiate a font load.

```js
// Define a FontFace
const font = new FontFace("myfont", "url(myfont.woff)");

// Add to the document.fonts (FontFaceSet)
document.fonts.add(font);

// Load the font
font.load();

// Wait until the fonts are all loaded
document.fonts.ready.then(() => {
  // Use the font to render text (for example, in a canvas)
});
```

 Note that the `font.load()` returns a promise, so we could have handled the completion of font loading by chaining `then` afterwards.
 Using `document.fonts.ready` can be better in some circumstances, as it is only called when all fonts in the document have been resolved and layout is complete.

Interfaces
----------

`FontFace`

Represents a single usable font face.

`FontFaceSet`

An interface loading font faces and checking their download statuses.

`FontFaceSetLoadEvent`

Fired whenever a `FontFaceSet` loads.

Examples
--------

### Basic font loading

 This is a very simple example that shows a font being loaded from Google Fonts and used to draw text to a canvas.
 The example also logs the `status` immediately after creation and after loading.

#### HTML

This code defines a canvas for drawing to and a textarea for logging.

```html
<canvas id="js-canvas"></canvas>
<textarea id="log" rows="3" cols="100"></textarea>
```

#### JavaScript

First we get the element to which we will log, and the canvas that will be used to render text in the downloaded font.

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

const canvas = document.getElementById("js-canvas");
canvas.width = 650;
canvas.height = 75;
```

 Next we define a `FontFace` that has a URL source that is a Google Font and add it to `document.fonts`.
 We then log the font status, which should be `unloaded`.

```js
const bitterFontFace = new FontFace(
  "FontFamily Bitter",
  "url(https://fonts.gstatic.com/s/bitter/v7/HEpP8tJXlWaYHimsnXgfCOvvDin1pK8aKteLpeZ5c0A.woff2)",
);
document.fonts.add(bitterFontFace);
log.textContent += `Bitter font: ${bitterFontFace.status}\n`; // > Bitter font: unloaded
```

 Then we call the `FontFace.load()` method to load the font face, and wait on the returned promise.
 Once the promise resolves we log the loaded status (which should be `loaded`) and draw text in the loaded font to the canvas.

```js
bitterFontFace.load().then(
  () => {
    log.textContent += `Bitter font: ${bitterFontFace.status}\n`; // > Bitter font: loaded

    const ctx = canvas.getContext("2d");
    ctx.font = '36px "FontFamily Bitter"';
    ctx.fillText("Bitter font loaded", 20, 50);
  },
  (err) => {
    console.error(err);
  },
);
```

Note that we could also have waited on the promise returned by the `FontFace.loaded` property, or on `FontFaceSet.ready`.

#### Result

 The result is shown below.
 It should show the name of the font drawn on the canvas in the downloaded font, and a log showing the load status before and after loading.

### Font loading with events

 This example is similar to the previous one, except that it uses `FontFaceSet.load()` to load the font.
 It also demonstrates how to listen for font loading events.

#### HTML

```html
<canvas id="js-canvas"></canvas>
<textarea id="log" rows="25" cols="100"></textarea>
```

#### JavaScript

The code below defines a canvas context for drawing text, defines a font face, and adds it to the document font face set.

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

const canvas = document.getElementById("js-canvas");
canvas.width = 650;
canvas.height = 75;
const ctx = canvas.getContext("2d");

const oxygenFontFace = new FontFace(
  "FontFamily Oxygen",
  "url(https://fonts.gstatic.com/s/oxygen/v5/qBSyz106i5ud7wkBU-FrPevvDin1pK8aKteLpeZ5c0A.woff2)",
);
document.fonts.add(oxygenFontFace);
log.textContent += `Oxygen status: ${oxygenFontFace.status}\n`;
```

 Next we use `load()` on the font face set to load the font, specifying which of the fonts to load.
 The method returns a `Promise`.
 If the promise is resolved we use the font to draw some text.
 If it is rejected the error is logged.

```js
document.fonts.load("36px FontFamily Oxygen").then(
  (fonts) => {
    log.textContent += `Bitter font: ${fonts}\n`; // > Oxygen font: loaded
    log.textContent += `Bitter font: ${oxygenFontFace.status}\n`; // > Oxygen font: loaded
    ctx.font = '36px "FontFamily Oxygen"';
    ctx.fillText("Oxygen font loaded", 20, 50);
  },
  (err) => {
    console.error(err);
  },
);
```

 Instead of waiting on a promise we might instead use events to track the font loading operation.
 The code below listens for the `loading` and `loadingerror` events and logs the number of font faces for each case.
 In the `loadingdone` event listener we additionally iterate through the font faces and log the family names.

```js
document.fonts.addEventListener("loading", (event) => {
  log.textContent += `loading\_event: ${event.fontfaces.length}\n`;
});
document.fonts.addEventListener("loadingerror", (event) => {
  log.textContent += `loadingerror\_event: ${event.fontfaces.length}\n`;
});
document.fonts.addEventListener("loadingdone", (event) => {
  log.textContent += `loadingdone\_event: ${event.fontfaces.length}\n`;
  event.fontfaces.forEach((value) => {
    log.textContent += ` fontface: ${value.family}\n`;
  });
});
```

 The last bit of code demonstrates how you can monitor the completion of font loading using the promise returned by `FontFaceSet.ready`.
 Unlike the other mechanisms this returns when all fonts defined in the document have been downloaded and layout is complete.

When the promise resolves we iterate the values in the document's font faces.

```js
document.fonts.ready.then(function () {
  log.textContent += `\nFontFaces in document: ${document.fonts.size}.\n`;

  for (const fontFace of document.fonts.values()) {
    log.textContent += "FontFace:\n";
    for (const property in fontFace) {
      log.textContent += ` ${property}: ${fontFace[property]}\n`;
    }
  }
});
```

#### Result

 The output below shows the text drawn in "Oxygen" font.
 This also shows logging from the events and when the promise returned by `document.fonts.ready` resolves.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # fontface-interface |

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

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


Keyboard API - Web APIs

Keyboard API
============

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

The Keyboard API provides methods for working with a physical keyboard that is attached to a device running a browser.

It provides several capabilities. *Keyboard mapping* provides an interface for retrieving the string generated by particular physical key on a keyboard to correctly identify that key to a user. *Keyboard locking* enables a web page to capture keys that are normally reserved by the user agent or the underlying operating system. The intended use of the Keyboard API is by web applications such as games or remote access apps that provide a fullscreen immersive experience.

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

### Keyboard mapping

On physical keyboards, the `code` attribute contains the physical location of the key that was pressed, and the `key` attribute contains the string generated by pressing the key at that physical location on the keyboard. The `key` value takes into account the keyboard's locale (for example, 'en-US'), layout (for example, 'QWERTY'), and modifier-key state (`Shift`, `Control`, etc.). Historically there has been no way to retrieve that information.

The Keyboard Map API provides a way to retrieve the string generated by a particular key press, through the `Keyboard` interface and the `KeyboardLayoutMap` interface. The `Keyboard` interface is accessed through `navigator.keyboard`. `Keyboard` provides the `Keyboard.getLayoutMap` method, which returns a promise that resolves with a `KeyboardLayoutMap` object that contains members for converting codes to keys. A list of valid code values is found in the Writing System Keys section of the UI Events KeyboardEvent code Values spec.

The following example demonstrates how to get the location-specific or layout-specific string associated with the key labeled `W` on an English QWERTY keyboard.

```js
if (navigator.keyboard) {
  const keyboard = navigator.keyboard;
  keyboard.getLayoutMap().then((keyboardLayoutMap) => {
    const upKey = keyboardLayoutMap.get("KeyW");
    window.alert(`Press ${upKey} to move up.`);
  });
} else {
  // Do something else.
}
```

### Keyboard locking

Richly interactive web pages, games, and remote-streaming experiences often require access to special keys and keyboard shortcuts while in fullscreen mode. Examples of such key/key combinations include `Escape`, `Alt+Tab`, and `Ctrl+N`. Those keys and key combinations are typically captured by the user agent or the underlying operating system, as illustrated in the following example.

To capture the `W`, `A`, `S`, and `D` keys, call `lock()` with a list that contains the key code attribute value for each of these keys:

```js
navigator.keyboard.lock(["KeyW", "KeyA", "KeyS", "KeyD"]);
```

This captures these keys regardless of which modifiers are used with the key press. Assuming a standard United States QWERTY layout, registering `KeyW` ensures that `W`, `Shift+W`, `Control+W`, `Control+Shift+W`, and all other key modifier combinations with `W` are sent to the app. The same applies to for `KeyA`, `KeyS`, and `KeyD`.

### Writing system keys

The codes passed `Keyboard.lock` and the various methods of the `KeyboardLayoutMap` interface are called "writing system keys".

"Writing system keys" are defined in the Writing System Keys section of the UI Events KeyboardEvent code Values spec, since the physical keys change meaning based on the current locale and keyboard layout. These keys are shown below. Blue keys are present on all standard keyboards while green keys are only available on some keyboards.

![Writing system keys as defined by the UI Events KeyboardEvent code Values spec.](/en-US/docs/Web/API/Keyboard_API/writing-system-keys.png)

Interfaces
----------

`Keyboard`
Experimental

Provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

`KeyboardLayoutMap`
Experimental

A map-like object with functions for retrieving the string associated with specific physical keys.

### Extensions to other interfaces

`navigator.keyboard` Read only
Experimental

Returns a `Keyboard` object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

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

| Specification |
| --- |
| Keyboard Lock  |
| Keyboard Map  |

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

### api.Keyboard

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

### api.KeyboardLayoutMap

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


DocumentPictureInPictureEvent - Web APIs

DocumentPictureInPictureEvent
=============================

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

The **`DocumentPictureInPictureEvent`** interface of the Document Picture-in-Picture API is the event object for the `enter` event, which fires when the Picture-in-Picture window is opened.

Event

DocumentPictureInPictureEventConstructor
-----------

`DocumentPictureInPictureEvent()`
Experimental

Creates a new `DocumentPictureInPictureEvent` object instance.

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

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

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

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

`window` Read only
Experimental

Returns a `Window` instance representing the browsing context inside the `DocumentPictureInPicture` window the event was fired on.

Examples
--------

```js
documentPictureInPicture.addEventListener("enter", (event) => {
  const pipWindow = event.window;
  console.log("Video player has entered the pip window");

  const pipMuteButton = pipWindow.document.createElement("button");
  pipMuteButton.textContent = "Mute";
  pipMuteButton.addEventListener("click", () => {
    const pipVideo = pipWindow.document.querySelector("#video");
    if (!pipVideo.muted) {
      pipVideo.muted = true;
      pipMuteButton.textContent = "Unmute";
    } else {
      pipVideo.muted = false;
      pipMuteButton.textContent = "Mute";
    }
  });

  pipWindow.document.body.append(pipMuteButton);
});
```

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

| Specification |
| --- |
| Document Picture-in-Picture Specification # documentpictureinpictureevent |

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

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

See also
--------

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