XRLayerEvent: XRLayerEvent() constructor - Web APIs

XRLayerEvent: XRLayerEvent() constructor
========================================

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

The **`XRLayerEvent`** constructor creates and returns a new `XRLayerEvent` object. These events relate to a change of state of an `XRLayer` object.

Syntax
------

```js
new XRLayerEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `redraw`.

`options`

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`layer`

The `XRLayer` to which the event is to be delivered.

### Return value

 A new `XRLayer` object representing an object of the
 specified type and configured as described by the `eventInitDict` parameter.

Examples
--------

### Creating a new `XRLayerEvent`

In this example, a new `redraw` event is created for an `XRQuadLayer`.

```js
const redrawEvent = new XRLayerEvent("redraw", {
  layer: quadLayer,
});

quadLayer.dispatchEvent();
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrlayerevent-xrlayerevent |

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

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

See also
--------

* `XRLayer`
* `EventTarget.dispatchEvent()`


ExtendableCookieChangeEvent: ExtendableCookieChangeEvent() constructor - Web APIs

ExtendableCookieChangeEvent: ExtendableCookieChangeEvent() constructor
======================================================================

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

 The **`ExtendableCookieChangeEvent()`** constructor creates a new `ExtendableCookieChangeEvent` object
 which is the event type passed to `cookiechange` event fired at the `ServiceWorkerGlobalScope` when any cookie changes occur which match the service worker's cookie change subscription list.
 This constructor is called by the browser when a change event occurs.

**Note:** This event constructor is generally not needed for production websites. It's primary use is for tests that require an instance of this event.

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

Syntax
------

```js
new ExtendableCookieChangeEvent(type)
new ExtendableCookieChangeEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `cookiechange`.

`options` Optional

An object that, *in addition of the properties defined in `ExtendableEvent()`*, can have the following properties:

`changed` Optional

An array containing a changed cookie.

`deleted` Optional

An array containing a deleted cookie.

### Return value

A new `ExtendableCookieChangeEvent` object.

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

| Specification |
| --- |
| Cookie Store API # dom-extendablecookiechangeevent-extendablecookiechangeevent |

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

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


ExtendableCookieChangeEvent: changed property - Web APIs

ExtendableCookieChangeEvent: changed property
=============================================

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

The **`changed`** read-only property of the `ExtendableCookieChangeEvent` interface returns any cookies that have been changed by the given `ExtendableCookieChangeEvent` instance.

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

Value
-----

An array of objects containing the changed cookie(s). Each object contains the following properties:

`name`

A string containing the name of the cookie.

`value`

A string containing the value of the cookie.

`domain`

A string containing the domain of the cookie.

`path`

A string containing the path of the cookie.

`expires`

A timestamp, given as Unix time in milliseconds, containing the expiration date of the cookie.

`secure`

A `boolean` indicating whether the cookie is from a site with a secure context (HTTPS rather than HTTP).

`sameSite`

One of the following `SameSite` values:

`"strict"`

Cookies will only be sent in a first-party context and not be sent with requests initiated by third party websites.

`"lax"`

Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating within the origin site (i.e. when following a link).

`"none"`

Cookies will be sent in all contexts.

`partitioned`

A boolean indicating whether the cookie is a partitioned cookie (`true`) or not (`false`). See Cookies Having Independent Partitioned State (CHIPS) for more information.

Examples
--------

In this example when the cookie is set, the event listener logs the `changed` property to the console. The first item in that array contains an object representing the cookie that has just been set.

```js
self.addEventListener("cookiechange", (event) => {
  console.log(event.changed[0]);
});

const one_day = 24 \* 60 \* 60 \* 1000;
cookieStore.set({
  name: "cookie1",
  value: "cookie1-value",
  expires: Date.now() + one_day,
  domain: "example.com",
});
```

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

| Specification |
| --- |
| Cookie Store API # dom-extendablecookiechangeevent-changed |

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

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


ExtendableCookieChangeEvent: deleted property - Web APIs

ExtendableCookieChangeEvent: deleted property
=============================================

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

The **`deleted`** read-only property of the `ExtendableCookieChangeEvent` interface returns any cookies that have been deleted by the given `ExtendableCookieChangeEvent` instance.

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

Value
-----

An array of objects containing the deleted cookie(s). Each object contains the following properties:

`name`

A string containing the name of the cookie.

`value`

A string containing the value of the cookie.

`domain`

A string containing the domain of the cookie.

`path`

A string containing the path of the cookie.

`expires`

A timestamp, given as Unix time in milliseconds, containing the expiration date of the cookie.

`secure`

A `boolean` indicating whether the cookie is from a site with a secure context (HTTPS rather than HTTP).

`sameSite`

One of the following `SameSite` values:

`"strict"`

Cookies will only be sent in a first-party context and not be sent with requests initiated by third party websites.

`"lax"`

Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating within the origin site (i.e. when following a link).

`"none"`

Cookies will be sent in all contexts.

`partitioned`

A boolean indicating whether the cookie is a partitioned cookie (`true`) or not (`false`). See Cookies Having Independent Partitioned State (CHIPS) for more information.

Examples
--------

In this example when the cookie is deleted the event listener logs the first item in the `deleted` property to the console. It contains an object representing the cookie that has just been deleted.

```js
self.addEventListener("cookiechange", (event) => {
  console.log(event.deleted[0]);
});
```

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

| Specification |
| --- |
| Cookie Store API # dom-extendablecookiechangeevent-deleted |

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

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


MediaRecorderErrorEvent: MediaRecorderErrorEvent() constructor - Web APIs

MediaRecorderErrorEvent: MediaRecorderErrorEvent() constructor
==============================================================

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

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

 The
 **`MediaRecorderErrorEvent()`** constructor creates a new `MediaRecorderErrorEvent` object
 that represents an error that occurred during the recording of media
 by the MediaStream Recording API.

**Note:** In general, you won't create these yourself; they are delivered to your
 implementation of `onerror` when errors occur while
 recording media.

Syntax
------

```js
new MediaRecorderErrorEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `error`.

`options`

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`error`

 A `DOMException` that describes the error that occurred. This
 object's `name` property should indicate the
 name of the error that occurred. The other fields may or may not be present.

**Note:** Some user agents add to the `error` object
 other properties that provide information such as stack dumps, the name of the
 JavaScript file and the line number where the error occurred, and other debugging
 aids, but you should not rely on this information in a production environment.

### Return value

A new `MediaRecorderErrorEvent` object.

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

This feature is no longer part of any specification, and longer on track to become standard.

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

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


MediaRecorderErrorEvent: error property - Web APIs

MediaRecorderErrorEvent: error property
=======================================

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

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

 The **`error`** read-only property of the
 `MediaRecorderErrorEvent` interface is a
 `DOMException` object providing details about the exception that was thrown
 by a `MediaRecorder` instance.

 When a `MediaRecorderErrorEvent` occurs, you can determine to some extent
 what went wrong by examining the `error` property within the
 `MediaRecorderErrorEvent` received by the `MediaRecorder`'s
 `error` event handler, `onerror`.

Value
-----

 A `DOMException` describing the error represented by the event. The
 error's `name` property's value may be any exception
 that makes sense during the handling of media recording, including these specifically
 identified by the specification. The descriptions here are generic ones; you'll find
 more specific ones to various scenarios in which they may occur in the corresponding
 method references.

`InvalidStateError`

 An operation was attempted in a context in which it isn't allowed, or a request has
 been made on an object that's deleted or removed.

`NotSupportedError`

 A `MediaRecorder` couldn't be created because the specified options
 weren't valid. The `message` attribute should provide additional
 information, if it exists.

`SecurityError`

 The `MediaStream` is configured to disallow recording. This may be the
 case, for example, with sources obtained using `getUserMedia()` when the user denies permission to use an input device.

`InvalidModificationError`

 The number of tracks on the stream being recorded has changed. You can't add or
 remove tracks while recording media.

`UnknownError`

 A non-security related error occurred that cannot otherwise be categorized.
 Recording stops, the `MediaRecorder`'s `state` becomes `inactive`, one last `dataavailable` event is
 sent to the `MediaRecorder` with the remaining received data, and finally a
 `stop` event is sent.

Examples
--------

### Basic error-handling example

 This function creates and returns a `MediaRecorder` for a given
 `MediaStream`, configured to buffer data into an array and to watch for
 errors.

```js
function recordStream(stream) {
  let recorder = null;
  let bufferList = [];

  try {
    recorder = new MediaRecorder(stream);
  } catch (err) {
    /\* exception while trying to create the recorder; handle that \*/
  }

  recorder.ondataavailable = (event) => {
    bufferList.push(event.data);
  };

  recorder.onerror = (event) => {
    console.error(`Error: ${event.error}`);
  };

  recorder.start(100); /\* 100ms time slices per buffer \*/
  return recorder;
}
```

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

This feature is no longer part of any specification, and longer on track to become standard.

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

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

See also
--------

* MediaStream Recording API
* Using the MediaStream Recording API


WebGLContextEvent: WebGLContextEvent() constructor - Web APIs

WebGLContextEvent: WebGLContextEvent() constructor
==================================================

The **`WebGLContextEvent()`** constructor creates a new `WebGLContextEvent` object.

**Note:** You typically don't need to call this constructor; the browser creates these objects automatically when WebGL context events get fired. To manually trigger a `webglcontextlost` event, use `WEBGL_lose_context.loseContext()`.

Syntax
------

```js
new WebGLContextEvent(type, options)
```

### Parameters

`type`

 A string indicating the type of the event.
 It is case-sensitive and should be one of `webglcontextcreationerror`, `webglcontextlost`, or `webglcontextrestored`.

`options` Optional

An object that, *in addition to the properties defined in `Event()`*, has the following properties:

`statusMessage` Optional

A string with additional status information. It defaults to the empty string (`""`).

### Return value

A new `WebGLContextEvent` object.

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

| Specification |
| --- |
| WebGL Specification # 5.15 |

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

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

See also
--------

* `webglcontextlost`
* `webglcontextrestored`
* `webglcontextcreationerror`


WebGLContextEvent: statusMessage property - Web APIs

WebGLContextEvent: statusMessage property
=========================================

The read-only **`WebGLContextEvent.statusMessage`** property contains additional event status information, or is an empty string if no additional information is available.

Examples
--------

The `statusMessage` property can contain a platform dependent string with details of an event. This can occur, for example, if the `webglcontextcreationerror` event is fired.

```js
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");

canvas.addEventListener(
  "webglcontextcreationerror",
  (e) => {
    console.log(
      `WebGL context creation failed: ${e.statusMessage || "Unknown error"}`,
    );
  },
  false,
);
```

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

| Specification |
| --- |
| WebGL Specification # 5.15.1 |

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

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

See also
--------

* webglcontextcreationerror


CSSTransformComponent: toMatrix() method - Web APIs

CSSTransformComponent: toMatrix() method
========================================

 The **`toMatrix()`** method of the
 `CSSTransformComponent` interface returns a `DOMMatrix`
 object.

All transform functions can be represented mathematically as a 4x4 transformation matrix. This is explained in detail in Understanding the CSS Transforms matrix.

**Note:** The `is2D` property affects what transform, and therefore type of matrix that will be returned. CSS 2D and 3D transforms are different for legacy reasons. A brief explanation of 2D vs. 3D transforms can be found in Using CSS transforms.

Syntax
------

```js
toMatrix()
```

### Parameters

None.

### Return value

A `DOMMatrix` object

### Exceptions

`TypeError`

 Raised if any lengths involved in generating the matrix are not compatible units
 with px (such as relative lengths or percentages).

Examples
--------

To Do

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-csstransformcomponent-tomatrix |

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

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


CSSTransformComponent: toString() method - Web APIs

CSSTransformComponent: toString() method
========================================

The **`toString()`** method of the `CSSTransformComponent` interface is a stringifier returning a CSS Transforms function.

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string in the form of a CSS `Transforms function`.

This will use the value of `is2D` to return either a 2D or 3D transform. For example if the component represents `CSSRotate` and `is2D` is false then the string returned will be in the form of the CSS transformation `rotate3D()` function. If true the string returned will be in the form of the 2-dimensional `rotate3D()` function.

Examples
--------

To Do

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

| Specification |
| --- |
| CSS Typed OM Level 1 # CSSTransformComponent-stringification-behavior |

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

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


CSSTransformComponent: is2D property - Web APIs

CSSTransformComponent: is2D property
====================================

The **`is2D`** read-only property of the `CSSTransformComponent` interface indicates where the transform is 2D or 3D.

Value
-----

 A boolean. True indicating the transform is a 2D transform, false if it is a 3D
 transform.

Examples
--------

To Do

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-csstransformcomponent-is2d |

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

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


ReadableByteStreamController: desiredSize property - Web APIs

ReadableByteStreamController: desiredSize property
==================================================

The **`desiredSize`** read-only property of the `ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size".

 The value is used by the stream to indicate a preferred flow rate to the underlying source.
 Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible.

The `desiredSize` is used to apply backpressure from downstream consumers.

Value
-----

An integer. Note that this can be negative if the queue is over-full.

The value will be `null` if the stream has errored and `0` if it is closed.

Examples
--------

The A readable stream with an underlying push source and backpressure support example in the spec provides a good example of using `desiredSize` to manually detect when the stream is full and apply backpressure.

While the example uses a default source, the concepts are exactly the same as for readable byte sources.

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

| Specification |
| --- |
| Streams Standard # ref-for-rbs-controller-desired-size② |

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

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

See also
--------

* Using readable byte streams
* `ReadableByteStreamController`


ReadableByteStreamController: byobRequest property - Web APIs

ReadableByteStreamController: byobRequest property
==================================================

The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests.

 An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`).
 This will result in an efficient zero-byte transfer of the data to the consumer.

Value
-----

A `ReadableStreamBYOBRequest` object instance, or `null`.

Examples
--------

The example in Using readable byte streams > Creating a readable socket push byte stream shows how you use a `byobRequest` to transfer data (if it exists), or otherwise copy the data to the stream's internal queues using `ReadableByteStreamController.enqueue()`.

 The relevant code is reproduced below.
 If the `byobRequest` exists, data is read into `controller.byobRequest.view`, and then `ReadableStreamBYOBRequest.respond()` is called to signal the amount of data that is ready to transfer.

```js
if (controller.byobRequest) {
  const v = controller.byobRequest.view;
  bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength);
  if (bytesRead === 0) {
    controller.close();
  }
  controller.byobRequest.respond(bytesRead);
} else {
  // Write to data using enqueue().
}
```

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

| Specification |
| --- |
| Streams Standard # ref-for-rbs-controller-byob-request② |

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

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

See also
--------

* Using readable byte streams
* `ReadableByteStreamController`


ReadableByteStreamController: error() method - Web APIs

ReadableByteStreamController: error() method
============================================

The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason.

 This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error).
 It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails.

Syntax
------

```js
error(errorObject)
```

### Parameters

`errorObject`

Any object that you want future interactions to fail with.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason.

Examples
--------

The example in Using readable byte streams > Creating a readable socket push byte stream shows how you might use `error()` to manually trigger a stream error if another part of the system it relies on fails.

 Specifically, the underlying source `start()` method calls `readRepeatedly()` to perform all setup operations and to make a request for data.
 This returns a promise.
 If there are any errors thrown when reading the data they will be caught by the chained `catch()` function.
 In `catch()` we then call `error()` on the controller, passing the reason from the underlying source.

```js
function start(controller) {
  readRepeatedly().catch((e) => controller.error(e));
}

function readRepeatedly() {
  return socket.select2().then(() => {
    // …
  });
}
```

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

| Specification |
| --- |
| Streams Standard # ref-for-rbs-controller-error① |

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

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

See also
--------

* Using readable byte streams


ReadableByteStreamController: close() method - Web APIs

ReadableByteStreamController: close() method
============================================

The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream.

This might be called by the underlying source when its data source has been exhausted/completed.

**Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed.
 However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored.

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason.

Examples
--------

The example in Using readable byte streams > Creating a readable socket push byte stream how we might close the stream when there is no more data.

 The relevant code is reproduced below.
 This relies on the hypothetical `readInto()` method returning 0 bytes only when there is no more data.

```js
bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength);
if (bytesRead === 0) {
  controller.close();
}
```

 After calling close, the stream will be closed, and any consumers signalled.
 For example if using a `ReadableStreamBYOBReader` any `read()` requests would resolve with `done: true` and the promise from `ReadableStreamBYOBReader.closed` would also be resolved.

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

| Specification |
| --- |
| Streams Standard # ref-for-rbs-controller-close① |

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

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

See also
--------

* Using readable byte streams
* `ReadableByteStreamController`


ReadableByteStreamController: enqueue() method - Web APIs

ReadableByteStreamController: enqueue() method
==============================================

The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues).

This should only be used to transfer data to the queue when `byobRequest` is `null`.

Syntax
------

```js
enqueue(chunk)
```

### Parameters

`chunk`

The chunk to enqueue.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

 Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached.
 It is also thrown if the stream has been closed.

Examples
--------

 The example in Using readable byte streams > Creating a readable socket push byte stream shows how you can use `enqueue()` to copy data to the stream if there is no outstanding `byobRequest`.
 If there is a `byobRequest` then it should be used!

The code below shows data being read into an `ArrayBuffer` using a "hypothetical" `socket.readInto()` method and then enqueued (but only if data was actually copied):

```js
const buffer = new ArrayBuffer(DEFAULT\_CHUNK\_SIZE);
bytesRead = socket.readInto(buffer, 0, DEFAULT\_CHUNK\_SIZE);
if (bytesRead === 0) {
  controller.close();
} else {
  controller.enqueue(new Uint8Array(buffer, 0, bytesRead));
}
```

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

| Specification |
| --- |
| Streams Standard # ref-for-rbs-controller-enqueue① |

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

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

See also
--------

* Using readable byte streams
* `ReadableByteStreamController`


CanvasCaptureMediaStreamTrack: canvas property - Web APIs

CanvasCaptureMediaStreamTrack: canvas property
==============================================

The **`canvas`** read-only property of the `CanvasCaptureMediaStreamTrack` interface returns the `HTMLCanvasElement` from which frames are being captured.

Value
-----

An `HTMLCanvasElement` indicating the canvas, which is the source of the frames being captured.

Example
-------

```js
// Find the canvas element to capture
const canvasElt = document.querySelector("canvas");

// Get the stream
const stream = canvasElt.captureStream(25); // 25 FPS

// Do things to the stream
// …

// Obtain the canvas associated with the stream
const canvas = stream.canvas;
```

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

| Specification |
| --- |
| Media Capture from DOM Elements # dom-canvascapturemediastreamtrack-canvas |

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

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

See also
--------

* `HTMLCanvasElement.captureStream()` to create a stream to capture a
 given canvas element.
* `<canvas>`


CanvasCaptureMediaStreamTrack: requestFrame() method - Web APIs

CanvasCaptureMediaStreamTrack: requestFrame() method
====================================================

The **`requestFrame()`** method of the `CanvasCaptureMediaStreamTrack` interface requests that a frame be captured from the canvas and sent to the stream.

 Applications that need to carefully control
 the timing of rendering and frame capture can use `requestFrame()` to
 directly specify when it's time to capture a frame.

 To prevent automatic capture of frames, so that frames are only captured when
 `requestFrame()` is called, specify a value of 0 for the
 `captureStream()` method when creating
 the stream.

Syntax
------

```js
requestFrame()
```

### Return value

None (`undefined`).

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

 There is currently an issue flagged in the specification pointing out that at this
 time, no exceptions are being thrown if the canvas isn't origin-clean. This may change
 in the future, so it would be wise to plan ahead and watch for exceptions such as
 `SecurityError` (although the specific error that might be thrown is not
 mentioned in the spec, this is a likely candidate).

Example
-------

```js
// Find the canvas element to capture
const canvasElt = document.querySelector("canvas");

// Get the stream
const stream = canvasElt.captureStream(25); // 25 FPS

// Send the current state of the canvas as a frame to the stream
stream.getVideoTracks()[0].requestFrame();
```

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

| Specification |
| --- |
| Media Capture from DOM Elements # dom-canvascapturemediastreamtrack-requestframe |

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

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

See also
--------

* `CanvasCaptureMediaStreamTrack`, the interface it belongs to.
* `<canvas>`


How to create a DOM tree - Web APIs

How to create a DOM tree
========================

This page describes how to use the DOM API in JavaScript to create XML documents.

Consider the following XML document:

```xml
<?xml version="1.0"?>
<people>
  <person first-name="eric" middle-initial="H" last-name="jung">
    <address street="321 south st" city="denver" state="co" country="usa"/>
    <address street="123 main st" city="arlington" state="ma" country="usa"/>
  </person>

  <person first-name="jed" last-name="brown">
    <address street="321 north st" city="atlanta" state="ga" country="usa"/>
    <address street="123 west st" city="seattle" state="wa" country="usa"/>
    <address street="321 south avenue" city="denver" state="co" country="usa"/>
  </person>
</people>
```

You can use the DOM API to create an in-memory representation of this document:

```js
const doc = document.implementation.createDocument("", "", null);
const peopleElem = doc.createElement("people");

const personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");

const addressElem1 = doc.createElement("address");
addressElem1.setAttribute("street", "321 south st");
addressElem1.setAttribute("city", "denver");
addressElem1.setAttribute("state", "co");
addressElem1.setAttribute("country", "usa");
personElem1.appendChild(addressElem1);

const addressElem2 = doc.createElement("address");
addressElem2.setAttribute("street", "123 main st");
addressElem2.setAttribute("city", "arlington");
addressElem2.setAttribute("state", "ma");
addressElem2.setAttribute("country", "usa");
personElem1.appendChild(addressElem2);

const personElem2 = doc.createElement("person");
personElem2.setAttribute("first-name", "jed");
personElem2.setAttribute("last-name", "brown");

const addressElem3 = doc.createElement("address");
addressElem3.setAttribute("street", "321 north st");
addressElem3.setAttribute("city", "atlanta");
addressElem3.setAttribute("state", "ga");
addressElem3.setAttribute("country", "usa");
personElem2.appendChild(addressElem3);

const addressElem4 = doc.createElement("address");
addressElem4.setAttribute("street", "123 west st");
addressElem4.setAttribute("city", "seattle");
addressElem4.setAttribute("state", "wa");
addressElem4.setAttribute("country", "usa");
personElem2.appendChild(addressElem4);

const addressElem5 = doc.createElement("address");
addressElem5.setAttribute("street", "321 south avenue");
addressElem5.setAttribute("city", "denver");
addressElem5.setAttribute("state", "co");
addressElem5.setAttribute("country", "usa");
personElem2.appendChild(addressElem5);

peopleElem.appendChild(personElem1);
peopleElem.appendChild(personElem2);
doc.appendChild(peopleElem);
```

DOM trees can be:

* Queried using XPath expressions.
* Converted to strings using XMLSerializer.
* Posted to a web server using the Fetch API.
* Transformed using XSLT or XLink.
See also
--------

* XML
* XPath
* Parsing and serializing XML
* Fetch API


Using the Document Object Model - Web APIs

Using the Document Object Model
===============================

The *Document Object Model* (DOM) is an API for manipulating DOM trees of HTML and XML documents (among other tree-like documents). This API is at the root of the description of a page and serves as a base for scripting on the web.

What is a DOM tree?
-------------------

A **DOM tree** is a tree structure whose nodes represent an HTML or XML document's contents. Each HTML or XML document has a DOM tree representation. For example, consider the following document:

```html
<html lang="en">
  <head>
    <title>My Document</title>
  </head>
  <body>
    <h1>Header</h1>
    <p>Paragraph</p>
  </body>
</html>
```

It has a DOM tree that looks like this:

![The DOM as a tree-like representation of a document that has a root and node elements containing content](/en-US/docs/Web/API/Document_object_model/Using_the_Document_Object_Model/using_the_w3c_dom_level_1_core-doctree.jpg)

Although the above tree is similar to the above document's DOM tree, it's not identical, as the actual DOM tree preserves whitespace.

When a web browser parses an HTML document, it builds a DOM tree and then uses it to display the document.

What does the Document API do?
------------------------------

The Document API, also sometimes called the DOM API, allows you to modify a DOM tree in *any way you want*. It enables you to create any HTML or XML document from scratch or to change any contents of a given HTML or XML document. Web page authors can edit the DOM of a document using JavaScript to access the `document` property of the global object. This `document` object implements the `Document` interface.

A simple example
----------------

Suppose the author wants to change the header of the above document and write two paragraphs instead of one. The following script would do the job:

### HTML

```html
<html lang="en">
  <head>
    <title>My Document</title>
  </head>
  <body>
    <input type="button" value="Change this document." onclick="change()" />
    <h2>Header</h2>
    <p>Paragraph</p>
  </body>
</html>
```

### JavaScript

```js
function change() {
  // document.getElementsByTagName("h2") returns a NodeList of the <h2>
  // elements in the document, and the first is number 0:
  const header = document.getElementsByTagName("h2").item(0);

  // The firstChild of the header is a Text node:
  header.firstChild.data = "A dynamic document";

  // Now header is "A dynamic document".

  // Access the first paragraph
  const para = document.getElementsByTagName("p").item(0);
  para.firstChild.data = "This is the first paragraph.";

  // Create a new Text node for the second paragraph
  const newText = document.createTextNode("This is the second paragraph.");

  // Create a new Element to be the second paragraph
  const newElement = document.createElement("p");

  // Put the text in the paragraph
  newElement.appendChild(newText);

  // Put the paragraph on the end of the document by appending it to
  // the body (which is the parent of para)
  para.parentNode.appendChild(newElement);
}
```

How can I learn more?
---------------------

Now that you are familiar with the basic concepts of the DOM, you may want to learn about the more about fundamental features of the Document API by reading how to traverse an HTML table with JavaScript and DOM interfaces.

See also
--------

* The Document Object Model (DOM).


Locating DOM elements using selectors - Web APIs

Locating DOM elements using selectors
=====================================

The Selectors API provides methods that make it quick and easy to retrieve `Element` nodes from the DOM by matching against a set of selectors. This is much faster than past techniques, wherein it was necessary to, for example, use a loop in JavaScript code to locate the specific items you needed to find.

The NodeSelector interface
--------------------------

This specification adds two new methods to any objects implementing the `Document`, `DocumentFragment`, or `Element` interfaces:

`querySelector()`

Returns the first matching `Element` node within the node's subtree. If no matching node is found, `null` is returned.

`querySelectorAll()`

Returns a `NodeList` containing all matching `Element` nodes within the node's subtree, or an empty `NodeList` if no matches are found.

**Note:** The `NodeList` returned by `querySelectorAll()` is not live, which means that changes in the DOM are not reflected in the collection. This is different from other DOM querying methods that return live node lists.

You may find examples and details by reading the documentation for the `Element.querySelector()` and `Element.querySelectorAll()` methods.

Selectors
---------

The selector methods accept selectors to determine what element or elements should be returned. This includes selector lists so you can group multiple selectors in a single query.

To protect the user's privacy, some pseudo-classes are not supported or behave differently. For example `:visited` will return no matches and `:link` is treated as `:any-link`.

Only elements can be selected, so pseudo-classes are not supported.

Examples
--------

To select all paragraph (`p`) elements in a document whose classes include `warning` or `note`, you can do the following:

```js
const special = document.querySelectorAll("p.warning, p.note");
```

You can also query by ID. For example:

```js
const el = document.querySelector("#main, #basic, #exclamation");
```

After executing the above code, `el` contains the first element in the document whose ID is one of `main`, `basic`, or `exclamation`.

See also
--------

* Selectors specification
* CSS Selectors
* `Element.querySelector()`
* `Element.querySelectorAll()`
* `Document.querySelector()`
* `Document.querySelectorAll()`


Example - Web APIs

Example
=======

```html
<html>
  <head>
    <title>My Document</title>
    <script>
 function change() {
 // document.getElementsByTagName("H1") returns a NodeList of the h1
 // elements in the document, and the first is number 0:
 const header = document.getElementsByTagName("H1").item(0);
 // the firstChild of the header is a Text node:
 header.firstChild.data = "A dynamic document";
 // now the header is "A dynamic document".
 const para = document.getElementsByTagName("P").item(0);
 para.firstChild.data = "This is the first paragraph.";
 // create a new Text node for the second paragraph
 const newText = document.createTextNode(
 "This is the second paragraph.",
 );
 // create a new Element to be the second paragraph
 const newElement = document.createElement("P");
 // put the text in the paragraph
 newElement.appendChild(newText);
 // and put the paragraph on the end of the document by appending it to
 // the BODY (which is the parent of para)
 para.parentNode.appendChild(newElement);
 }
 </script>
  </head>
  <body>
    <input type="button" value="Change this document." onclick="change()" />
    <h1>Header</h1>
    <p>Paragraph</p>
  </body>
</html>
```


XRSessionEvent: XRSessionEvent() constructor - Web APIs

XRSessionEvent: XRSessionEvent() constructor
============================================

 The WebXR Device API's
 **`XRSessionEvent()`** constructor creates and returns a new
 `XRSessionEvent` object. These objects represent events announcing
 state changes in an `XRSession` representing an augmented or virtual
 reality session.

Syntax
------

```js
new XRSessionEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers set it to `end` or `visibilitychange`.

`options`

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`session`

The `XRSession` to which the event is to be delivered.

### Return value

 A new `XRSessionEvent` object representing an object of the
 specified type and configured as described by the `options` parameter.

Examples
--------

See `XRSessionEvent` for example code.

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

| Specification |
| --- |
| WebXR Device API # dom-xrsessionevent-xrsessionevent |

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

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


XRSessionEvent: session property - Web APIs

XRSessionEvent: session property
================================

 The read-only `XRSessionEvent` interface's
 **`session`** property indicates which
 `XRSession` the event is about.

Value
-----

An `XRSession` object indicating which WebXR session the event refers to.

Examples
--------

 In this example, the `session` property is used to obtain the session object
 to manage when an event is received.

```js
xrSession.addEventListener("visibilitychange", (e) => {
  switch (e.session.visibilityState) {
    case "hidden":
      myEnableRendering(true);
      break;
    case "visible":
    case "visible-blurred":
      myEnableRendering(false);
      break;
  }
});
```

This calls a function that reacts to the session's visibility state change.

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

| Specification |
| --- |
| WebXR Device API # dom-xrsessionevent-session |

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

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


VisualViewport: resize event - Web APIs

VisualViewport: resize event
============================

The **`resize`** event of the `VisualViewport` interface is fired when the visual viewport is resized.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("resize", (event) => {});

onresize = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

You can use the `resize` event in an `addEventListener()` method:

```js
visualViewport.addEventListener("resize", () => {
  // …
});
```

Or use the `onresize` event handler property:

```js
visualViewport.onresize = () => {
  // …
};
```

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

| Specification |
| --- |
| CSSOM View Module # eventdef-window-resize |

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

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


VisualViewport: pageLeft property - Web APIs

VisualViewport: pageLeft property
=================================

The **`pageLeft`** read-only property of the `VisualViewport` interface returns the x coordinate of the left edge of the visual viewport relative to the initial containing block origin, in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-pageleft |

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

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


VisualViewport: pageTop property - Web APIs

VisualViewport: pageTop property
================================

The **`pageTop`** read-only property of the `VisualViewport` interface returns the y coordinate of the top edge of the visual viewport relative to the initial containing block origin, in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-pagetop |

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

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


VisualViewport: width property - Web APIs

VisualViewport: width property
==============================

The **`width`** read-only property of the `VisualViewport` interface returns the width of the visual viewport, in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-width |

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

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


VisualViewport: offsetLeft property - Web APIs

VisualViewport: offsetLeft property
===================================

The **`offsetLeft`** read-only property of the `VisualViewport` interface returns the offset of the left edge of the visual viewport from the left edge of the layout viewport in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-offsetleft |

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

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


VisualViewport: height property - Web APIs

VisualViewport: height property
===============================

The **`height`** read-only property of the `VisualViewport` interface returns the height of the visual viewport, in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-height |

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

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


VisualViewport: scale property - Web APIs

VisualViewport: scale property
==============================

The **`scale`** read-only property of the `VisualViewport` interface returns the pinch-zoom scaling factor applied to the visual viewport, or `0` if current document is not fully active, or `1` if there is no output device.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-scale |

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

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


VisualViewport: scroll event - Web APIs

VisualViewport: scroll event
============================

The **`scroll`** event of the `VisualViewport` interface is fired when the visual viewport is scrolled.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("scroll", (event) => {});

onscroll = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

You can use the `scroll` event in an `addEventListener()` method:

```js
visualViewport.addEventListener("scroll", () => {
  // …
});
```

Or use the `onscroll` event handler property:

```js
visualViewport.onscroll = () => {
  // …
};
```

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

| Specification |
| --- |
| CSSOM View Module # eventdef-document-scroll |

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

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


VisualViewport: offsetTop property - Web APIs

VisualViewport: offsetTop property
==================================

The **`offsetTop`** read-only property of the `VisualViewport` interface returns the offset of the top edge of the visual viewport from the top edge of the layout viewport in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-offsettop |

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

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


OTPCredential: code property - Web APIs

OTPCredential: code property
============================

**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 **`code`** property of the `OTPCredential` interface contains the one-time password (OTP).

Value
-----

A string containing the OTP.

Examples
--------

The below code triggers the browser's permission flow when an SMS message arrives. If permission is granted, then the promise resolves with an `OTPCredential` object. The contained `code` value is then set as the value of an `<input>` form element, which is then submitted.

```js
navigator.credentials
  .get({
    otp: { transport: ["sms"] },
    signal: ac.signal,
  })
  .then((otp) => {
    input.value = otp.code;
    if (form) form.submit();
  })
  .catch((err) => {
    console.error(err);
  });
```

**Note:** For a full explanation of the code, see the WebOTP API landing page. You can also see this code as part of a full working demo.

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

| Specification |
| --- |
| WebOTP API # dom-otpcredential-code |

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

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


Determining the dimensions of elements - Web APIs

Determining the dimensions of elements
======================================

There are several properties you can look at in order to determine the width and height of elements, and it can be tricky to determine which is the right one for your needs. This article is designed to help you make that decision. Note that all these properties are read-only. If you want to set the width and height of an element, use `width` and `height` or the overriding `min-width` and `max-width`, and `min-height` and `max-height` properties.

How much room does it use up?
-----------------------------

If you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the `HTMLElement.offsetWidth` and `HTMLElement.offsetHeight` properties. Most of the time these are the same as width and height of `Element.getBoundingClientRect()`, when there aren't any transforms applied to the element. In case of transforms, the `offsetWidth` and `offsetHeight` returns the element's layout width and height, while `getBoundingClientRect()` returns the rendering width and height. As an example, if the element has `width: 100px;` and `transform: scale(0.5);` the `getBoundingClientRect()` will return 50 as the width, while `offsetWidth` will return 100.

![How the offsetWidth and offsetHeight properties are determined, considering padding, borders, and margin sizes](/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements/dimensions-offset.png)

What's the size of the displayed content?
-----------------------------------------

If you need to know how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars, you want to use the `Element.clientWidth` and `Element.clientHeight` properties:

![How the clientWidth and clientHeight properties are determined, considering padding, borders, and margin sizes](/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements/dimensions-client.png)

How big is the content?
-----------------------

If you need to know the actual size of the content, regardless of how much of it is currently visible, you need to use the `Element.scrollWidth` and `Element.scrollHeight` properties. These return the width and height of the entire content of an element, even if only part of it is presently visible due to the use of scroll bars.

For example, if a 600x400 pixel element is being displayed inside a 300x300 pixel scrollbox, `scrollWidth` will return 600 while `scrollHeight` will return 400.

See also
--------

* https://www.w3.org/TR/cssom-view-1/
* MSDN: Measuring Element Dimension and Location


Managing screen orientation - Web APIs

Managing screen orientation
===========================

The term *screen orientation* refers to whether a browser viewport is in landscape mode (that is, the width of the viewport is greater than its height), or else in portrait mode (the height of the viewport is greater than its width)

CSS provides the `orientation` media feature to allow adjusting layout based on screen orientation.

The Screen Orientation API provides a programmatic JavaScript API for working with screen orientation — including the ability to lock the viewport to a specific orientation.

Adjusting layout based on the orientation
-----------------------------------------

One of the most common cases for orientation changes is when you want to revise the layout of your content based on the orientation of the device. For example, perhaps you want a button bar to stretch along the longest dimension of the device's display. By using a media query, you can do this easily and automatically.

Let's have an example with the following HTML code

```html
<ul id="toolbar">
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>

<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis lacinia nisi nec
  sem viverra vitae fringilla nulla ultricies. In ac est dolor, quis tincidunt
  leo. Cras commodo quam non tortor consectetur eget rutrum dolor ultricies. Ut
  interdum tristique dapibus. Nullam quis malesuada est.
</p>
```

CSS relies on the orientation media query to handle specific styles based on the screen orientation

```css
/\* First let's define some common styles \*/

html,
body {
  width: 100%;
  height: 100%;
}

body {
  border: 1px solid black;

  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

p {
  font: 1em sans-serif;
  margin: 0;
  padding: 0.5em;
}

ul {
  list-style: none;

  font: 1em monospace;
  margin: 0;
  padding: 0.5em;

  -moz-box-sizing: border-box;
  box-sizing: border-box;

  background: black;
}

li {
  display: inline-block;
  margin: 0;
  padding: 0.5em;
  background: white;
}
```

Once we have some common styles we can start defining a special case for the orientation

```css
/\* For portrait, we want the toolbar on top \*/

@media screen and (orientation: portrait) {
  #toolbar {
    width: 100%;
  }
}

/\* For landscape, we want the toolbar stick on the left \*/

@media screen and (orientation: landscape) {
  #toolbar {
    position: fixed;
    width: 2.65em;
    height: 100%;
  }

  p {
    margin-left: 2em;
  }

  li + li {
    margin-top: 0.5em;
  }
}
```

And here's the result

| Portrait | Landscape |
| --- | --- |
|  |  |

**Note:** The orientation media query actually applies based on the orientation of the browser window (or iframe) not the orientation of the device.

Locking the screen orientation
------------------------------

Some devices (mainly mobile devices) can dynamically change the orientation of the screen based on their own orientation, ensuring that the user will always be able to read what's on the screen. While this behavior is perfectly suited for text content, there is some content that can be negatively affected by such a change. For example, games based on the orientation of the device could be messed up by such a change of the orientation.

The Screen Orientation API is made to prevent or handle such a change.

### Listening to orientation changes

The `orientationchange` event is triggered each time the device change the orientation of the screen and the orientation itself can be read with the `Screen.orientation` property.

```js
screen.addEventListener("orientationchange", () => {
  console.log(`The orientation of the screen is: ${screen.orientation}`);
});
```

### Preventing orientation change

Any web application can lock the screen to suits its own needs. The screen is locked using the `screen.orientation.lock()` method and unlocked using the `screen.orientation.unlock()` method.

The `screen.orientation.lock()` method accepts one of the following values to define the kind of lock to apply: `any`, `natural`. `portrait-primary`, `portrait-secondary`, `landscape-primary`, `landscape-secondary`, `portrait`, and `landscape`:

```js
screen.orientation.lock();
```

It returns a promise that resolves after the lock succeeds.

**Note:** A screen lock is web application dependent. If application A is locked to `landscape` and application B is locked to `portrait`, switching from application A to B or B to A will not fire an `orientationchange` event because both applications will keep the orientation they had.

However, locking the orientation can fire an `orientationchange` event if the orientation had to be changed to satisfy the lock requirements.

See also
--------

* `screen.orientation`
* `ScreenOrientation`
* `orientationchange` event
* The orientation media query


Using dynamic styling information - Web APIs

Using dynamic styling information
=================================

The CSS Object Model (CSSOM), part of the DOM, exposes specific interfaces allowing manipulation of a wide amount of information regarding CSS. Initially defined in the *DOM Level 2 Style* recommendation, these interfaces forms now a specification, *CSS Object Model (CSSOM)* which aims at superseding it.

In many cases, and where possible, it is best practice to dynamically manipulate classes via the `className` property since the ultimate appearance of all of the styling hooks can be controlled in a single stylesheet. One's JavaScript code also becomes cleaner since instead of being dedicated to styling details, it can focus on the overall semantics of each section it is creating or manipulating, leaving the precise style details to the stylesheet. However, there are cases where actually obtaining or manipulating the rules can be useful (whether for whole stylesheets or individual elements), and that is described in further detail below. Note also that, as with individual element's DOM styles, when speaking of manipulating the stylesheets, this is not actually manipulating the physical document(s), but merely the internal representation of the document.

The basic `style` object exposes the `Stylesheet` and the `CSSStylesheet` interfaces. Those interfaces contain members like `insertRule`, `selectorText`, and `parentStyleSheet` for accessing and manipulating the individual style rules that make up a CSS stylesheet.

To get to the `style` objects from the `document`, you can use the `Document.styleSheets` property and access the individual objects by index (e.g., `document.styleSheets[0]` is the first stylesheet defined for the document, etc.).

Modify a stylesheet rule with CSSOM
-----------------------------------

In this example the background of the page is set to red using CSS. The JavaScript then accesses the property using the CSSOM and changes the background to blue.

```html
<html lang="en">
  <head>
    <title>Modifying a stylesheet rule with CSSOM</title>
    <style>
 body {
 background-color: red;
 }
 </style>
    <script>
 const stylesheet = document.styleSheets[0];
 stylesheet.cssRules[0].style.backgroundColor = "aqua";
 </script>
  </head>
  <body>
    The stylesheet declaration for the body's background color is modified via
    JavaScript.
  </body>
</html>
```

### Result

The list of properties available in the DOM from the `style` property is given on the DOM CSS Properties List page.

To modify styles to a document using CSS syntax, one can insert rules or insert `<style>` tags whose `innerHTML` property is set to the desired CSS.

Modify an element's style
-------------------------

The element `style` property (see also the section "DOM Style Object" below) can also be used to get and set the styles on an element. However, this property only returns style attributes that have been set *in-line* (e.g., `<td style="background-color: lightblue">` returns the string "`background-color:lightblue`", or directly for that element using `element.style.propertyName`, even though there may be other styles on the element from a stylesheet).

Also, when you set this property on an element, you override any styles that have been set elsewhere for that element's particular property you are setting. Setting the `border` property, for example, will override settings made elsewhere for that element's `border` property in the head section, or external style sheets. However, this will not affect any other property declarations for that element's styles, such as padding or margin or font, for example.

To change a particular element's style, you can adapt the following example for the element(s) you want to style.

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>simple style example</title>

    <script>
 function alterStyle(elem) {
 elem.style.background = "green";
 }

 function resetStyle(elemId) {
 const elem = document.getElementById(elemId);
 elem.style.background = "white";
 }
 </script>
    <style>
 #p1 {
 border: solid blue 2px;
 }
 </style>
  </head>

  <body>
    <!-- passes a reference to the element's object as parameter 'this'. -->
    <p id="p1" onclick="alterStyle(this);">
      Click here to change background color.
    </p>

    <!-- passes the 'p1' id of another element's style to modify. -->
    <button onclick="resetStyle('p1');">Reset background color</button>
  </body>
</html>
```

The `getComputedStyle()` method on the `document.defaultView` object returns all styles that have actually been computed for an element.

DOM Style Object
----------------

The `style` object represents an individual style statement. The style object is accessed from the `document` or from the elements to which that style is applied. It represents the *in-line* styles on a particular element.

### Setting style properties

More important than the two properties noted here is the use of the `style` object to set individual style properties on an element:

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
 function setStyle() {
 document.getElementById("d").style.color = "orange";
 }
 function resetStyle() {
 document.getElementById("d").style.color = "black";
 }
 </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>
```

The **media** and **type** of the style may or may not be given.

### Using the setAttribute method

Note that you can also change style of an element by getting a reference to it and then use its `setAttribute` method to specify the CSS property and its value.

```js
const el = document.getElementById("some-element");
el.setAttribute("style", "background-color:darkblue;");
```

Be aware, however, that `setAttribute` removes all other `style` properties that may already have been defined in the element's `style` object. If the `some-element` element above had an in–line `style` attribute of say `style="font-size: 18px"`, that value would be removed by the use of `setAttribute`.


CSS Declaration - Web APIs

CSS Declaration
===============

A **CSS declaration** is an abstract concept not exposed as an object in the DOM. It represents a CSS property and value pairing.

A CSS declaration has the following associated properties:

property name

The property name of the declaration, for example `background-color`.

value

The value of the declaration as a list of component values.

important flag

Either set or unset.

case-sensitive flag

Set if the property name is defined to be case-sensitive according to the specification, otherwise unset.

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

The following example shows a CSS rule with a CSS declaration block for the <h1> element. The CSS declaration block is the lines between the curly braces, it contains two CSS declarations. One for `font-style` and another for `color`.

```css
h1 {
  font-style: italic;
  color: rebeccapurple;
}
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # css-declarations |


CSS Declaration Block - Web APIs

CSS Declaration Block
=====================

A **CSS declaration block** is an ordered collection of CSS properties and values. It is represented in the DOM as a `CSSStyleDeclaration`.

Each property and value pairing is known as a CSS declaration. The CSS declaration block has the following associated properties:

computed flag

Set if the `CSSStyleDeclaration` object is a computed rather than specified style. Unset by default.

declarations

The CSS declarations associated with this object.

parent CSS rule

The `CSSRule` that the CSS declaration block is associated with, otherwise null.

owner node

The `element` that the CSS declaration block is associated with, otherwise null.

updating flag

Set when the CSS declaration block is updating the owner node's `style` attribute.

When a `CSSStyleDeclaration` is returned by a CSS Object Model (CSSOM) interface these properties are set to appropriate values as defined by the specification.

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

The following example shows a CSS rule with a declaration block for the h1 element. The CSS declaration block is the lines between the curly braces.

```css
h1 {
  margin: 0 auto;
  font-family: "Helvetica Neue", "Arial", sans-serif;
  font-style: italic;
  color: rebeccapurple;
}
```

We can return a `CSSStyleDeclaration` representing this CSS declaration block using `CSSStyleRule.style`.

```js
let myRules = document.styleSheets[0].cssRules;
let rule = myRules[0]; // a CSSStyleRule
console.log(rule.style); // a CSSStyleDeclaration object
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # css-declaration-blocks |


SharedWorkerGlobalScope: connect event - Web APIs

SharedWorkerGlobalScope: connect event
======================================

The **`connect`** event is fired in shared workers at their `SharedWorkerGlobalScope` when a new client connects.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("connect", (event) => {});

onconnect = (event) => {};
```

Event type
----------

A `MessageEvent`. Inherits from `Event`.

Event

MessageEventEvent properties
----------------

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

`MessageEvent.data` Read only

The data sent by the message emitter.

`MessageEvent.origin` Read only

A string representing the origin of the message emitter.

`MessageEvent.lastEventId` Read only

A string representing a unique ID for the event.

`MessageEvent.source` Read only

A `MessageEventSource` (which can be a WindowProxy, `MessagePort`, or `ServiceWorker` object) representing the message emitter.

`MessageEvent.ports` Read only

An array of `MessagePort` objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).

Examples
--------

This example shows a shared worker file — when a connection to the worker occurs from a main thread via a `MessagePort`, the `onconnect` event handler fires. The event object is a `MessageEvent`.

The connecting port can be referenced through the event object's `ports` parameter; this reference can have an `onmessage` handler attached to it to handle messages coming in through the port, and its `postMessage()` method can be used to send messages back to the main thread using the worker.

```js
self.onconnect = (e) => {
  const port = e.ports[0];

  port.onmessage = (e) => {
    const workerResult = `Result: ${e.data[0] \* e.data[1]}`;
    port.postMessage(workerResult);
  };

  port.start();
};
```

For a complete running example, see our Basic shared worker example (run shared worker.)

### addEventListener equivalent

You could also set up an event handler using the `addEventListener()` method:

```js
self.addEventListener("connect", (e) => {
  const port = e.ports[0];

  port.onmessage = (e) => {
    const workerResult = `Result: ${e.data[0] \* e.data[1]}`;
    port.postMessage(workerResult);
  };
});
```

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

| Specification |
| --- |
| HTML Standard # event-workerglobalscope-connect |
| HTML Standard # handler-sharedworkerglobalscope-onconnect |

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

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

See also
--------

* Using web workers
* `SharedWorkerGlobalScope`


SharedWorkerGlobalScope: close() method - Web APIs

SharedWorkerGlobalScope: close() method
=======================================

The **`close()`** method of the `SharedWorkerGlobalScope` interface discards any tasks queued in the `SharedWorkerGlobalScope`'s event loop, effectively closing this particular scope.

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

If you want to close your worker instance from inside the worker itself, you can call the following:

```js
close();
```

`close()` and `self.close()` are effectively equivalent — both represent `close()` being called from inside the worker's inner scope.

**Note:** There is also a way to stop the worker from the main thread: the `Worker.terminate` method.

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

| Specification |
| --- |
| HTML Standard # dom-sharedworkerglobalscope-close-dev |

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

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

See also
--------

`DedicatedWorkerGlobalScope`


SharedWorkerGlobalScope: name property - Web APIs

SharedWorkerGlobalScope: name property
======================================

 The **`name`** read-only property of the
 `SharedWorkerGlobalScope` interface returns the name that the
 `SharedWorker` was (optionally) given when it was created. This is the name
 that the `SharedWorker()` constructor can pass
 to get a reference to the `SharedWorkerGlobalScope`.

Value
-----

A string.

Examples
--------

If a shared worker is created using a constructor with a `name` option:

```js
const myWorker = new SharedWorker("worker.js", { name: "mySharedWorker" });
```

 the `SharedWorkerGlobalScope` will now have a name of "mySharedWorker",
 returnable by running

```js
self.name;
```

from inside the shared worker.

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

| Specification |
| --- |
| HTML Standard # dom-sharedworkerglobalscope-name-dev |

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

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

See also
--------

* `SharedWorkerGlobalScope`


PerformanceElementTiming: loadTime property - Web APIs

PerformanceElementTiming: loadTime property
===========================================

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

The **`loadTime`** read-only property of the `PerformanceElementTiming` interface always returns `0` for text. For images it returns the time which is the latest between the time the image resource is loaded and the time it is attached to the element.

Value
-----

A `DOMHighResTimeStamp` with the `loadTime` of the element. Always `0` for text.

Examples
--------

### Logging `loadTime`

In this example an `<img>` element is being observed by adding the `elementtiming` attribute. A `PerformanceObserver` is registered to get all performance entries of type `"element"`. The `buffered` flag is used to access data from before the observer was created. Calling `entry.loadTime` returns the loadTime of the image element.

```html
<img
 src="image.jpg"
 alt="a nice image"
 elementtiming="big-image"
 id="myImage" />
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.loadTime);
    }
  });
});
observer.observe({ type: "element", buffered: true });
```

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

| Specification |
| --- |
| Element Timing API # ref-for-dom-performanceelementtiming-loadtime① |

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

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


PerformanceElementTiming: element property - Web APIs

PerformanceElementTiming: element property
==========================================

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

The **`element`** read-only property of the `PerformanceElementTiming` interface returns an `Element` which is a pointer to the observed element.

Value
-----

An `Element`, or `null` if the element is a shadow DOM element.

Examples
--------

### Logging the observed element

In this example an `<img>` element is being observed by adding the `elementtiming` attribute. A `PerformanceObserver` is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. The DOM element that is observed is logged to the console.

```html
<img src="image.jpg" alt="a nice image" elementtiming="big-image" />
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.element);
    }
  });
});
observer.observe({ type: "element", buffered: true });
```

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

| Specification |
| --- |
| Element Timing API # ref-for-dom-performanceelementtiming-element |

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

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


PerformanceElementTiming: naturalHeight property - Web APIs

PerformanceElementTiming: naturalHeight property
================================================

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

The **`naturalHeight`** read-only property of the `PerformanceElementTiming` interface returns the intrinsic height of the image element.

Value
-----

An unsigned 32-bit integer (unsigned long) which is the intrinsic height of the image if this is applied to an image, `0` for text.

Examples
--------

### Logging `naturalHeight`

In this example an `<image>` element is being observed by adding the `elementtiming` attribute. A `PerformanceObserver` is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. The image file has a width of 1000px and a height of 750px. Calling `entry.naturalHeight` returns `750`, that being the intrinsic height in pixels.

```html
<img
 src="image.jpg"
 alt="a nice image"
 elementtiming="big-image"
 id="myImage" />
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.naturalHeight);
    }
  });
});
observer.observe({ type: "element", buffered: true });
```

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

| Specification |
| --- |
| Element Timing API # ref-for-dom-performanceelementtiming-naturalheight |

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

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


PerformanceElementTiming: url property - Web APIs

PerformanceElementTiming: url property
======================================

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

The **`url`** read-only property of the `PerformanceElementTiming` interface returns the initial URL of the resource request when the element is an image.

Value
-----

A string which is the initial URL of the resources request for images or `0` for text.

Examples
--------

### Logging `url`

In this example an `<img>` element is being observed by adding the `elementtiming` attribute. A `PerformanceObserver` is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. Calling `entry.url` returns `https://example.com/image.jpg`.

```html
<img
 src="https://example.com/image.jpg"
 alt="a nice image"
 elementtiming="big-image"
 id="myImage" />
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.url);
    }
  });
});
observer.observe({ type: "element", buffered: true });
```

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

| Specification |
| --- |
| Element Timing API # ref-for-dom-performanceelementtiming-url |

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

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


PerformanceElementTiming: identifier property - Web APIs

PerformanceElementTiming: identifier property
=============================================

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

The **`identifier`** read-only property of the `PerformanceElementTiming` interface returns the value of the `elementtiming` attribute on the element.

Value
-----

A string.

Examples
--------

### Using `identifier`

In this example an `<img>` element is being observed by adding the `elementtiming` attribute. A `PerformanceObserver` is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. The value of `elementtiming` is `big-image`. Calling `entry.identifier` therefore returns the string `big-image`.

```html
<img
 src="image.jpg"
 alt="a nice image"
 elementtiming="big-image"
 id="myImage" />
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.naturalWidth);
    }
  });
});
observer.observe({ type: "element", buffered: true });
```

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

| Specification |
| --- |
| Element Timing API # ref-for-dom-performanceelementtiming-identifier |

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

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


PerformanceElementTiming: renderTime property - Web APIs

PerformanceElementTiming: renderTime property
=============================================

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

The **`renderTime`** read-only property of the `PerformanceElementTiming` interface returns the render time of the associated element.

Value
-----

A `DOMHighResTimeStamp` with the render time of the element.

For images this will be the **image rendering timestamp**. This is defined as the next paint that occurs after the image becomes fully loaded. If the timing allow check fails (as defined by the Timing-allow-origin header) this will return `0`.

For text nodes this will be the **text rendering timestamp**. This is defined as when the element becomes text painted.

Examples
--------

### Logging `renderTime`

In this example an `<image>` element is being observed by adding the `elementtiming` attribute. A `PerformanceObserver` is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. Calling `entry.renderTime` returns the render time of the image element.

```html
<img
 src="image.jpg"
 alt="a nice image"
 elementtiming="big-image"
 id="myImage" />
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.renderTime);
    }
  });
});
observer.observe({ type: "element", buffered: true });
```

### Cross-origin image render time

For security reasons, the value of the `renderTime` property is `0` if the resource is a cross-origin request. To expose cross-origin render time information, the `Timing-Allow-Origin` HTTP response header needs to be set.

For example, to allow `https://developer.mozilla.org` to see `renderTime`, the cross-origin resource should send:

```http
Timing-Allow-Origin: https://developer.mozilla.org
```

Alternatively, you can use `startTime` which returns the value of the entry's `renderTime` if it is not `0`, and otherwise the value of this entry's `loadTime`. However, it is recommended to set the `Timing-Allow-Origin` header so that the metrics will be more accurate.

If you use `startTime`, you can flag any inaccuracies by checking if `renderTime` was used:

```js
const isRenderTime = entry.renderTime ? true : false;
```

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

| Specification |
| --- |
| Element Timing API # ref-for-dom-performanceelementtiming-rendertime① |

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

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


PerformanceElementTiming: id property - Web APIs

PerformanceElementTiming: id property
=====================================

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

The **`id`** read-only property of the `PerformanceElementTiming` interface returns the `id` of the associated element.

Value
-----

A string.

Examples
--------

### Using `id`

In this example an `<img>` element is being observed by adding the `elementtiming` attribute. A `PerformanceObserver` is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. It will log `myImage` to the console, this being the `id` of the image element.

```html
<img
 src="image.jpg"
 alt="a nice image"
 elementtiming="big-image"
 id="myImage" />
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.id);
    }
  });
});
observer.observe({ type: "element", buffered: true });
```

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

| Specification |
| --- |
| Element Timing API # ref-for-dom-performanceelementtiming-id |

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

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


PerformanceElementTiming: intersectionRect property - Web APIs

PerformanceElementTiming: intersectionRect property
===================================================

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

The **`intersectionRect`** read-only property of the `PerformanceElementTiming` interface returns the rectangle of the element within the viewport.

Value
-----

A `DOMRectReadOnly` which is the rectangle of the element within the viewport.

For display images this is the display rectangle of the image within the viewport. For text this is the display rectangle of the node in the viewport. This being the smallest rectangle that contains the union of all text nodes that belong to the element.

Examples
--------

### Logging `intersectionRect`

In this example an `<img>` element is being observed by adding the `elementtiming` attribute. A `PerformanceObserver` is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. Calling `entry.intersectionRect` returns a `DOMRectReadOnly` object with the display rectangle of the image.

```html
<img
 src="image.jpg"
 alt="a nice image"
 elementtiming="big-image"
 id="myImage" />
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.intersectionRect);
    }
  });
});
observer.observe({ type: "element", buffered: true });
```

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

| Specification |
| --- |
| Element Timing API # ref-for-dom-performanceelementtiming-intersectionrect |

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

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


PerformanceElementTiming: toJSON() method - Web APIs

PerformanceElementTiming: toJSON() method
=========================================

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

The **`toJSON()`** method of the `PerformanceElementTiming` interface is a serializer; it returns a JSON representation of the `PerformanceElementTiming` object.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A `JSON` object that is the serialization of the `PerformanceElementTiming` object.

The JSON doesn't contain the `element` property because it is of type `Element`, which doesn't provide a `toJSON()` operation. The `id` of the element is provided, though.

Examples
--------

### Using the toJSON method

In this example, calling `entry.toJSON()` returns a JSON representation of the `PerformanceElementTiming` object, with the information about the image element.

```html
<img
 src="image.jpg"
 alt="a nice image"
 elementtiming="big-image"
 id="myImage" />
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.toJSON());
    }
  });
});
observer.observe({ type: "element", buffered: true });
```

This would log a JSON object like so:

```json
{
  "name": "image-paint",
  "entryType": "element",
  "startTime": 670894.1000000238,
  "duration": 0,
  "renderTime": 0,
  "loadTime": 670894.1000000238,
  "intersectionRect": {
    "x": 299,
    "y": 76,
    "width": 135,
    "height": 155,
    "top": 76,
    "right": 434,
    "bottom": 231,
    "left": 299
  },
  "identifier": "big-image",
  "naturalWidth": 135,
  "naturalHeight": 155,
  "id": "myImage",
  "url": "https://en.wikipedia.org/static/images/project-logos/enwiki.png"
}
```

To get a JSON string, you can use `JSON.stringify(entry)` directly; it will call `toJSON()` automatically.

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

| Specification |
| --- |
| Element Timing API # dom-performanceelementtiming-tojson |

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

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

See also
--------

* `JSON`


PerformanceElementTiming: naturalWidth property - Web APIs

PerformanceElementTiming: naturalWidth property
===============================================

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

The **`naturalWidth`** read-only property of the `PerformanceElementTiming` interface returns the intrinsic width of the image element.

Value
-----

An unsigned 32-bit integer (unsigned long) which is the intrinsic width of the image if this is applied to an image, `0` for text.

Examples
--------

### Logging `naturalWidth`

In this example an `<image>` element is being observed by adding the `elementtiming` attribute. A `PerformanceObserver` is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. The image file has a width of 1000px and a height of 750px. Calling `entry.naturalWidth` returns `1000`, that being the intrinsic width in pixels.

```html
<img
 src="image.jpg"
 alt="a nice image"
 elementtiming="big-image"
 id="myImage" />
```

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.identifier === "big-image") {
      console.log(entry.naturalWidth);
    }
  });
});
observer.observe({ type: "element", buffered: true });
```

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

| Specification |
| --- |
| Element Timing API # ref-for-dom-performanceelementtiming-naturalwidth |

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

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


AuthenticatorAttestationResponse: getPublicKeyAlgorithm() method - Web APIs

AuthenticatorAttestationResponse: getPublicKeyAlgorithm() method
================================================================

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

The **`getPublicKeyAlgorithm()`** method of the `AuthenticatorAttestationResponse` interface returns a number that is equal to a COSE Algorithm Identifier, representing the cryptographic algorithm used for the new credential.

This is a convenience function created to allow easy access to the algorithm type. This information will need to be stored in order to verify future authentication operations (i.e., using `navigator.credentials.get()`).

Syntax
------

```js
getPublicKeyAlgorithm()
```

### Parameters

None.

### Return value

A number that is equal to a COSE Algorithm Identifier, representing the cryptographic algorithm used for the new credential.

Examples
--------

See Creating a public key credential using the WebAuthn API for a detailed example.

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

| Specification |
| --- |
| Web Authentication: An API for accessing Public Key Credentials - Level 3 # dom-authenticatorattestationresponse-getpublickeyalgorithm |

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

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


AuthenticatorAttestationResponse: getAuthenticatorData() method - Web APIs

AuthenticatorAttestationResponse: getAuthenticatorData() method
===============================================================

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

The **`getAuthenticatorData()`** method of the `AuthenticatorAttestationResponse` interface returns an `ArrayBuffer` containing the authenticator data contained within the `AuthenticatorAttestationResponse.attestationObject` property.

This is a convenience function, created to allow easy access to the authenticator data without having to write extra parsing code to extract it from the `attestationObject`.

Syntax
------

```js
getAuthenticatorData()
```

### Parameters

None.

### Return value

An `ArrayBuffer` with a `ArrayBuffer.byteLength` of at least 37 bytes, which contains the data structure explained in Authenticator data.

This will be equivalent to the authenticator data contained within the `AuthenticatorAttestationResponse.attestationObject` property.

Examples
--------

See Creating a public key credential using the WebAuthn API for a detailed example.

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

| Specification |
| --- |
| Web Authentication: An API for accessing Public Key Credentials - Level 3 # dom-authenticatorattestationresponse-getauthenticatordata |

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

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


AuthenticatorAttestationResponse: getTransports() method - Web APIs

AuthenticatorAttestationResponse: getTransports() method
========================================================

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

The **`getTransports()`** method of the `AuthenticatorAttestationResponse` interface returns an array of strings describing the different transports which may be used by the authenticator.

Such transports may be USB, NFC, BLE, internal (applicable when the authenticator is not removable from the device), or a hybrid approach. Sites should not interpret this array but instead store it along with the rest of the credential information. In a subsequent `navigator.credentials.get()` call, the `transports` value(s) specified inside `publicKey.allowCredentials` should be set to the stored array value. This provides a hint to the browser as to which types of authenticators to try when making an assertion for this credential.

Syntax
------

```js
getTransports()
```

### Parameters

None.

### Return value

An `Array` of strings representing the different transports supported by the authenticator, in lexicographical order. Values may include:

* `"ble"`: The authenticator may be used over BLE (Bluetooth Low Energy).
* `"hybrid"`: The authenticator can be used over a combination of (often separate) data transport and proximity mechanisms. This supports, for example, authentication on a desktop computer using a smartphone.
* `"internal"`: The authenticator is specifically bound to the client device (cannot be removed).
* `"nfc"`: The authenticator may be used over NFC (Near Field Communication).
* `"usb"`: The authenticator can be contacted over USB.
Examples
--------

See Creating a public key credential using the WebAuthn API for a detailed example.

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

| Specification |
| --- |
| Web Authentication: An API for accessing Public Key Credentials - Level 3 # dom-authenticatorattestationresponse-gettransports |

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

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


AuthenticatorAttestationResponse: attestationObject property - Web APIs

AuthenticatorAttestationResponse: attestationObject property
============================================================

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

 The **`attestationObject`** property of the
 `AuthenticatorAttestationResponse` interface returns an
 `ArrayBuffer` containing the new public key, as well as signature over the
 entire `attestationObject` with a private key that is stored in the
 authenticator when it is manufactured.

 As part of the `CredentialsContainer.create()` call, an authenticator will
 create a new keypair as well as an `attestationObject` for that keypair. The public key
 that corresponds to the private key that has created the attestation signature is well
 known; however, there are various well known attestation public key chains for different
 ecosystems (for example, Android or TPM attestations).

Value
-----

 After decoding the CBOR encoded
 `ArrayBuffer`, the resulting JavaScript object will contain the following
 properties:

`authData`

The Authenticator data for the operation. Note that in `AuthenticatorAssertionResponse`, the `authenticatorData` is exposed as a property in a JavaScript object (see `AuthenticatorAssertionResponse.authenticatorData`) while in `AuthenticatorAttestationResponse`, the `authenticatorData` is a property in a CBOR map.

The same `AuthenticatorAssertionResponse.authenticatorData` field is used by both `AuthenticatorAttestationResponse` and by `AuthenticatorAssertionResponse`. When used in attestation, it contains an optional field, `attestedCredentialData`. This field is not included when used in the `AuthenticatorAssertionResponse`. The attestedCredentialData field contains the `credentialId` and `credentialPublicKey`.

`fmt`

 A text string that indicates the format of the attStmt. The WebAuthn specification defines a number of formats; however, formats may also be defined
 in other specifications and registered in an IANA registry. Formats
 defined by WebAuthn are:

* `"packed"`
* `"tpm"`
* `"android-key"`
* `"android-safetynet"`
* `"fido-u2f"`
* `"none"`

`attStmt`

 An attestation statement that is of the format defined by `"fmt"`. For
 now, see the WebAuthn specification for details on each format.

Examples
--------

See Creating a public key credential using the WebAuthn API for a detailed example.

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

| Specification |
| --- |
| Web Authentication: An API for accessing Public Key Credentials - Level 3 # dom-authenticatorattestationresponse-attestationobject |

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

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

See also
--------

* `CredentialsContainer.create()`: the method used to create a statement with
 a cryptographic `challenge` which signature by the authenticator is contained in `attStmt`,
 with the specified `attestation` transport option.