ServiceWorkerRegistration: periodicSync property - Web APIs

ServiceWorkerRegistration: periodicSync property
================================================

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

 The **`periodicSync`** read-only property of
 the `ServiceWorkerRegistration` interface returns a reference to the
 `PeriodicSyncManager` interface, which allows for registering of tasks to
 run at specific intervals.

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

Value
-----

A `PeriodicSyncManager` object.

Examples
--------

 You can access the property from either your main script or the registered service
 worker.

Here is an example from the main script:

```js
// reference registration
const registration = await navigator.serviceWorker.ready;

// feature detection
if ("periodicSync" in registration) {
  // Background Periodic Sync functionality
  const periodicSync = registration.periodicSync;
}
```

From the service worker:

```js
// service worker script

const periodicSync = self.registration.periodicSync;
```

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

| Specification |
| --- |
| Web Periodic Background Synchronization # dom-serviceworkerregistration-periodicsync |

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

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

See also
--------

* Richer offline experiences with the Periodic Background Sync API
* A Periodic Background Sync demo app


ServiceWorkerRegistration: scope property - Web APIs

ServiceWorkerRegistration: scope property
=========================================

 The **`scope`** read-only property of the
 `ServiceWorkerRegistration` interface returns a unique identifier for a
 service worker registration. The service worker must be on the same origin as the
 document that registers the `ServiceWorker`.

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

Value
-----

A unique identifier.

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

| Specification |
| --- |
| Service Workers # service-worker-registration-scope |

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

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

See also
--------

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


ServiceWorkerRegistration: updatefound event - Web APIs

ServiceWorkerRegistration: updatefound event
============================================

 The **`updatefound`** event of the
 `ServiceWorkerRegistration` interface is fired any time the `ServiceWorkerRegistration.installing` property acquires a new service worker.

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

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

```js
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
  registration.addEventListener("updatefound", () => {
    console.log("Service Worker update found!");
  });
}
```

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

| Specification |
| --- |
| Service Workers # dom-serviceworkerregistration-onupdatefound |

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

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

See also
--------

* Using Service Workers


ServiceWorkerRegistration: active property - Web APIs

ServiceWorkerRegistration: active property
==========================================

 The **`active`** property of the
 `ServiceWorkerRegistration` interface returns a service worker whose
 `ServiceWorker.state` is `activating` or `activated`.
 This property is initially set to `null`.

 An active worker controls a `Client` if the client's URL
 falls within the scope of the registration (the `scope` option set when
 `ServiceWorkerContainer.register` is first called.)

**Note:** Once an active worker is `activating`, neither a
 runtime script error nor a force termination of the active worker prevents the active
 worker from getting `activated`.

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

Value
-----

 A `ServiceWorker` object's property, if it is currently in an
 `activating` or `activated` state.

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

| Specification |
| --- |
| Service Workers # navigator-service-worker-active |

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

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

See also
--------

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


ServiceWorkerRegistration: installing property - Web APIs

ServiceWorkerRegistration: installing property
==============================================

 The **`installing`** property of the
 `ServiceWorkerRegistration` interface returns a service worker whose
 `ServiceWorker.state` is `installing`. This property is
 initially set to `null`.

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

Value
-----

 A `ServiceWorker` object, if it is currently in an `installing`
 state.

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

| Specification |
| --- |
| Service Workers # navigator-service-worker-installing |

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

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

See also
--------

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


ServiceWorkerRegistration: cookies property - Web APIs

ServiceWorkerRegistration: cookies property
===========================================

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

The **`cookies`** read-only property of the `ServiceWorkerRegistration` interface returns a reference to the `CookieStoreManager` interface, which enables a web app to subscribe to and unsubscribe from cookie change events in a service worker. This is an entry point for the Cookie Store API.

Value
-----

A `CookieStoreManager` object.

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

| Specification |
| --- |
| Cookie Store API # dom-serviceworkerregistration-cookies |

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

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


ServiceWorkerRegistration: paymentManager property - Web APIs

ServiceWorkerRegistration: paymentManager property
==================================================

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

 The **`paymentManager`** read-only property of the
 `ServiceWorkerRegistration` interface returns a payment app's `PaymentManager` instance, which is used to manage various payment app functionality.

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

Value
-----

A `PaymentManager` object instance.

Examples
--------

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

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

  // ...
});
```

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

| Specification |
| --- |
| Payment Handler API # dom-serviceworkerregistration-paymentmanager |

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

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

See also
--------

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


ServiceWorkerRegistration: navigationPreload property - Web APIs

ServiceWorkerRegistration: navigationPreload property
=====================================================

The **`navigationPreload`** read-only property of the `ServiceWorkerRegistration` interface returns the `NavigationPreloadManager` associated with the current service worker registration.

The returned object allows resources managed by a service worker to be preemptively downloaded in parallel with service worker boot up.

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

Value
-----

An instance of `NavigationPreloadManager`.

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

| Specification |
| --- |
| Service Workers # service-worker-registration-navigationpreload |

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

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


ServiceWorkerRegistration: update() method - Web APIs

ServiceWorkerRegistration: update() method
==========================================

 The **`update()`** method of the
 `ServiceWorkerRegistration` interface attempts to update the service
 worker. It fetches the worker's script URL, and if the new worker is not byte-by-byte
 identical to the current worker, it installs the new worker. The fetch of the worker
 bypasses any browser caches if the previous fetch occurred over 24 hours ago.

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

Syntax
------

```js
update()
```

### Parameters

None.

### Return value

 A `Promise` that resolves with a `ServiceWorkerRegistration`
 object.

Examples
--------

 The following simple example registers a service worker example then adds an event
 handler to a button so you can explicitly update the service worker whenever desired:

```js
if ("serviceWorker" in navigator) {
  navigator.serviceWorker
    .register("/sw.js", { scope: "/" })
    .then((registration) => {
      // registration worked
      console.log("Registration succeeded.");
      button.onclick = () => {
        registration.update();
      };
    })
    .catch((error) => {
      // registration failed
      console.error(`Registration failed with ${error}`);
    });
}
```

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

| Specification |
| --- |
| Service Workers # service-worker-registration-update |

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

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

See also
--------

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


ServiceWorkerRegistration: index property - Web APIs

ServiceWorkerRegistration: index property
=========================================

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

 The **`index`** read-only property of the
 `ServiceWorkerRegistration` interface returns a reference to the
 `ContentIndex` interface, which allows for indexing of offline content.

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

Value
-----

A `ContentIndex` object.

Examples
--------

 You can access the property from either your main script or the registered service
 worker.

Here is an example from the main script:

```js
// reference registration
const registration = await navigator.serviceWorker.ready;

// feature detection
if ("index" in registration) {
  // Content Index API functionality
  const contentIndex = registration.index;
}
```

From the service worker:

```js
// service worker script

const contentIndex = self.registration.index;
```

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

| Specification |
| --- |
| Content Index # dom-serviceworkerregistration-index |

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

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

See also
--------

* `Content Index API`
* An introductory article on the Content Index API
* An app which uses the Content Index API to list and remove 'save for later' content


ServiceWorkerRegistration: updateViaCache property - Web APIs

ServiceWorkerRegistration: updateViaCache property
==================================================

 The **`updateViaCache`** read-only property of the
 `ServiceWorkerRegistration` interface updates the cache using
 the mode specified in the call to `ServiceWorkerContainer.register`.
 Requests for `importScripts` still go via the HTTP cache. `updateViaCache` offers
 control over this behavior.

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

Value
-----

Returns one of the following values:

* `imports`, meaning the HTTP cache is not consulted for update of the service worker, but is consulted for `importScripts`.
* `all`, meaning the HTTP cache is consulted in both cases
* `none`, meaning the HTTP cache is never consulted.
Examples
--------

The following example shows the use of updateViaCache.

```js
if ("serviceWorker" in navigator) {
  navigator.serviceWorker
    .register("/service-worker.js", {
      updateViaCache: "none",
    })
    .then((registration) => {
      registration.addEventListener("updatefound", () => {
        // If updatefound is fired, it means that there's
        // a new service worker being installed.
        console.log(`Value of updateViaCache: ${registration.updateViaCache}`);
      });
    })
    .catch((error) => {
      console.error(`Service worker registration failed: ${error}`);
    });
}
```

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

| Specification |
| --- |
| Service Workers # service-worker-registration-updateviacache |

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

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

See also
--------

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


ServiceWorkerRegistration: getNotifications() method - Web APIs

ServiceWorkerRegistration: getNotifications() method
====================================================

 The **`getNotifications()`** method of
 the `ServiceWorkerRegistration` interface returns a list of the
 notifications in the order that they were created from the current origin via the
 current service worker registration. Origins can have many active but
 differently-scoped service worker registrations. Notifications created by one service
 worker on the same origin will not be available to other active service workers on
 that same origin.

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

Syntax
------

```js
getNotifications()
getNotifications(options)
```

### Parameters

`options` Optional

 An object containing options to filter the notifications returned. The available
 options are:

`tag` Optional

 A string representing a notification tag. If
 specified, only notifications that have this tag will be returned.

### Return value

A `Promise` that resolves to a list of `Notification` objects.

Examples
--------

```js
navigator.serviceWorker.register("sw.js");

const options = { tag: "user\_alerts" };

navigator.serviceWorker.ready.then((registration) => {
  registration.getNotifications(options).then((notifications) => {
    // do something with your notifications
  });
});
```

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

| Specification |
| --- |
| Notifications API Standard # dom-serviceworkerregistration-getnotifications |

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

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


ServiceWorkerRegistration: sync property - Web APIs

ServiceWorkerRegistration: sync property
========================================

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

 The **`sync`** read-only property of the
 `ServiceWorkerRegistration` interface returns a reference to the
 `SyncManager` interface, which manages background synchronization
 processes.

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

Value
-----

A `SyncManager` object.

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

| Specification |
| --- |
| Web Background Synchronization # dom-serviceworkerregistration-sync |

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

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


ServiceWorkerRegistration: unregister() method - Web APIs

ServiceWorkerRegistration: unregister() method
==============================================

 The **`unregister()`** method of the
 `ServiceWorkerRegistration` interface unregisters the service worker
 registration and returns a `Promise`. The promise will resolve to
 `false` if no registration was found, otherwise it resolves to
 `true` irrespective of whether unregistration happened or not (it may not
 unregister if someone else just called `ServiceWorkerContainer.register()`
 with the same scope.) The service worker will finish any ongoing operations before it is
 unregistered.

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

Syntax
------

```js
unregister()
```

### Parameters

None.

### Return value

`Promise` resolves with a boolean indicating whether the service worker has
 unregistered or not.

Examples
--------

 The following simple example registers a service worker example, but then immediately
 unregisters it again:

```js
if ("serviceWorker" in navigator) {
  navigator.serviceWorker
    .register("/sw.js", { scope: "/" })
    .then((registration) => {
      // registration worked
      console.log("Registration succeeded.");
      registration.unregister().then((boolean) => {
        // if boolean = true, unregister is successful
      });
    })
    .catch((error) => {
      // registration failed
      console.error(`Registration failed with ${error}`);
    });
}
```

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

| Specification |
| --- |
| Service Workers # navigator-service-worker-unregister |

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

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

See also
--------

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


ServiceWorkerRegistration: backgroundFetch property - Web APIs

ServiceWorkerRegistration: backgroundFetch property
===================================================

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

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

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

 The **`backgroundFetch`** property of the
 `ServiceWorkerRegistration` interface returns a reference to a
 `BackgroundFetchManager` object, which can be used to initiate background fetch operations.

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

Value
-----

A `BackgroundFetchManager` object.

Examples
--------

### Initiating a background fetch

The following code accesses the `backgroundFetch` property and uses it to initiate a background fetch operation.

```js
// main.js
async function requestBackgroundFetch(movieData) {
  const swRegistration = await navigator.serviceWorker.ready;
  const fetchRegistration = await swRegistration.backgroundFetch.fetch(
    "download-movie",
    ["/my-movie-part-1.webm", "/my-movie-part-2.webm"],
    {
      icons: movieIcons,
      title: "Downloading my movie",
      downloadTotal: 60 \* 1024 \* 1024,
      label: "Downloading a show",
    },
  );
  //...
}
```

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

| Specification |
| --- |
| Background Fetch # dom-serviceworkerregistration-backgroundfetch |

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

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


ServiceWorkerRegistration: waiting property - Web APIs

ServiceWorkerRegistration: waiting property
===========================================

 The **`waiting`** property of the
 `ServiceWorkerRegistration` interface returns a service worker whose
 `ServiceWorker.state` is `installed`. This property is initially
 set to `null`.

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

Value
-----

 A `ServiceWorker` object, if it is currently in an `installed`
 state.

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

| Specification |
| --- |
| Service Workers # navigator-service-worker-waiting |

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

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

See also
--------

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


ServiceWorkerRegistration: showNotification() method - Web APIs

ServiceWorkerRegistration: showNotification() method
====================================================

 The **`showNotification()`** method of the
 `ServiceWorkerRegistration` interface creates a notification on an active
 service worker.

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

Syntax
------

```js
showNotification(title)
showNotification(title, options)
```

### Parameters

`title`

The title that must be shown within the notification

`options` Optional

 An object that allows configuring the notification. It can have the following
 properties:

`actions` Optional
Experimental

An array of actions to display in the notification. Each element in the array is an object with the following members:

`action`

A string identifying a user action to be displayed on the notification.

`title`

A string containing action text to be shown to the user.

`icon`

A string containing the URL of an icon to display with the action.

 Appropriate responses are built using `event.action` within the
 `notificationclick` event.

`badge` Optional
Experimental

 a string containing the URL of an image
 to represent the notification when there is not enough space to display the
 notification itself such as for example, the Android Notification Bar. On Android
 devices, the badge should accommodate devices up to 4x resolution, about 96 by 96
 px, and the image will be automatically masked.

`body` Optional

 A string representing an extra content to display within the
 notification.

`data` Optional
Experimental

 Arbitrary data that you want to be associated with the
 notification. This can be of any data type.

`dir` Optional

The direction of the notification; it can be `auto`, `ltr` or `rtl`.

`icon` Optional

 a string containing the URL of an image to
 be used as an icon by the notification.

`image` Optional
Experimental

 a string containing the URL of an image to
 be displayed in the notification.

`lang` Optional

 Specify the lang used within the notification. This string
 must be a valid language tag according to
 RFC 5646: Tags for Identifying Languages (also known as BCP 47).

`renotify` Optional
Experimental

 A boolean that indicates whether to suppress vibrations
 and audible alerts when reusing a `tag` value.
 If *options*'s `renotify` is true
 and *options*'s `tag` is the empty string a TypeError will be
 thrown. The default is `false`.

`requireInteraction` Optional
Experimental

 Indicates that on devices with sufficiently
 large screens, a notification should remain active until the user clicks or
 dismisses it. If this value is absent or false, the desktop version of Chrome will
 auto-minimize notifications after approximately twenty seconds. The default value
 is `false`.

`silent` Optional

 When set indicates that no sounds or vibrations should be
 made. If *options*'s `silent` is true
 and *options*'s `vibrate` is present a TypeError exception
 will be thrown. The default value is `false`.

`tag` Optional

 An ID for a given notification that allows you to find,
 replace, or remove the notification using a script if necessary.

`timestamp` Optional

A timestamp, given as Unix time in milliseconds, representing the time associated with the notification. This could be in the past when a notification is used for a message that couldn't immediately be delivered because the device was offline, or in the future for a meeting that is about to start.

`vibrate` Optional
Experimental

 A vibration pattern to run with the display of the
 notification. A vibration pattern can be an array with as few as one member. The
 values are times in milliseconds where the even indices (0, 2, 4, etc.) indicate
 how long to vibrate and the odd indices indicate how long to pause. For
 example, `[300, 100, 400]` would vibrate 300ms, pause 100ms, then
 vibrate 400ms.

### Return value

A `Promise` that resolves to `undefined`.

### Exceptions

`TypeError`

Thrown if current service worker's state is not `activating` or `activated`, or if the user has explicitly denied the browser's permission request to use the API.

Examples
--------

```js
navigator.serviceWorker.register("sw.js");

function showNotification() {
  Notification.requestPermission().then((result) => {
    if (result === "granted") {
      navigator.serviceWorker.ready.then((registration) => {
        registration.showNotification("Vibration Sample", {
          body: "Buzz! Buzz!",
          icon: "../images/touch/chrome-touch-icon-192x192.png",
          vibrate: [200, 100, 200, 100, 200, 100, 200],
          tag: "vibration-sample",
        });
      });
    }
  });
}
```

 To invoke the above function at an appropriate time, you could use the
 `onnotificationclick` event handler.

 You can also retrieve details of the `Notification`s that have been fired
 from the current service worker using
 `ServiceWorkerRegistration.getNotifications()`.

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

| Specification |
| --- |
| Notifications API Standard # dom-serviceworkerregistration-shownotification |

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

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


ServiceWorkerRegistration: pushManager property - Web APIs

ServiceWorkerRegistration: pushManager property
===============================================

 The **`pushManager`** property of the
 `ServiceWorkerRegistration` interface returns a reference to the
 `PushManager` interface for managing push subscriptions; this includes
 support for subscribing, getting an active subscription, and accessing push permission
 status.

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

Value
-----

A `PushManager` object.

Examples
--------

```js
this.onpush = (event) => {
  console.log(event.data);
  // From here we can write the data to IndexedDB, send it to any open
  // windows, display a notification, etc.
};

navigator.serviceWorker
  .register("serviceworker.js")
  .then((serviceWorkerRegistration) => {
    serviceWorkerRegistration.pushManager.subscribe().then(
      (pushSubscription) => {
        console.log(pushSubscription.subscriptionId);
        console.log(pushSubscription.endpoint);
        // The push subscription details needed by the application
        // server are now available, and can be sent to it using,
        // for example, the fetch() API.
      },
      (error) => {
        // During development it often helps to log errors to the
        // console. In a production environment it might make sense to
        // also report information about errors back to the
        // application server.
        console.error(error);
      },
    );
  });
```

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

| Specification |
| --- |
| Push API # dom-serviceworkerregistration-pushmanager |

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

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

See also
--------

* Push API


NavigateEvent: intercept() method - Web APIs

NavigateEvent: intercept() method
=================================

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

 The **`intercept()`** method of the
 `NavigateEvent` interface intercepts this navigation, turning it into a same-document navigation to the `destination` URL.

Syntax
------

```js
intercept()
intercept(options)
```

### Parameters

`options` Optional

An options object containing the following properties:

`handler` Optional

A callback function that defines what the navigation handling behavior should be. This generally handles resource fetching, and returns a promise.

`focusReset` Optional

Defines the navigation's focus behavior. This may take one of the following values:

`after-transition`

Once the promise returned by your handler function resolves, the browser will focus the first element with the `autofocus` attribute, or the `<body>` element if no element has `autofocus` set. This is the default value.

`manual`

Disable the default behavior.

`scroll` Optional

Defines the navigation's scrolling behavior. This may take one of the following values:

`after-transition`

Allow the browser to handle scrolling, for example by scrolling to the relevant fragment identifier if the URL contains a fragment, or restoring the scroll position to the same place as last time if the page is reloaded or a page in the history is revisited. This is the default value.

`manual`

Disable the default behavior.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the current `Document` is not yet active, or if the navigation has been cancelled.

`SecurityError` `DOMException`

Thrown if the event was dispatched by a `dispatchEvent()` call, rather than the user agent, or if the navigation cannot be intercepted (i.e. `NavigateEvent.canIntercept` is `false`).

Examples
--------

### Handling a navigation using `intercept()`

```js
navigation.addEventListener("navigate", (event) => {
  // Exit early if this navigation shouldn't be intercepted,
  // e.g. if the navigation is cross-origin, or a download request
  if (shouldNotIntercept(event)) return;

  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        // The URL has already changed, so show a placeholder while
        // fetching the new content, such as a spinner or loading page
        renderArticlePagePlaceholder();

        // Fetch the new content and display when ready
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);
      },
    });
  }
});
```

### Using `focusReset` and `scroll`

Form submission can be detected by querying for the `NavigateEvent.formData` property. The following example turns any form submission into one which stays on the current page. In this case, you don't update the DOM, so you can cancel any default reset and scroll behavior using `focusReset` and `scroll`.

```js
navigation.addEventListener("navigate", (event) => {
  if (event.formData && event.canIntercept) {
    // User submitted a POST form to a same-domain URL
    // (If canIntercept is false, the event is just informative:
    // you can't intercept this request, although you could
    // likely still call .preventDefault() to stop it completely).

    event.intercept({
      // Since we don't update the DOM in this navigation,
      // don't allow focus or scrolling to reset:
      focusReset: "manual",
      scroll: "manual",
      async handler() {
        await fetch(event.destination.url, {
          method: "POST",
          body: event.formData,
        });
        // You could navigate again with {history: 'replace'} to change the URL here,
        // which might indicate "done"
      },
    });
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-intercept-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigateEvent: scroll() method - Web APIs

NavigateEvent: scroll() method
==============================

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

 The **`scroll()`** method of the
 `NavigateEvent` interface can be called to manually trigger the browser-driven scrolling behavior that occurs in response to the navigation, if you want it to happen before the navigation handling has completed.

Syntax
------

```js
scroll()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the current `Document` is not yet active, or if the navigation has been cancelled.

`SecurityError` `DOMException`

Thrown if the event was dispatched by a `dispatchEvent()` call, rather than the user agent.

Examples
--------

### Handling scrolling using `scroll()`

In this example of intercepting a navigation, the `handler()` function starts by fetching and rendering some article content, but then fetches and renders some secondary content afterwards. It makes sense to scroll the page to the main article content as soon as it is available so the user can interact with it, rather than waiting until the secondary content is also rendered. To achieve this, we have added a `scroll()` call between the two.

```js
navigation.addEventListener("navigate", (event) => {
  if (shouldNotIntercept(navigateEvent)) {
    return;
  }
  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);

        event.scroll();

        const secondaryContent = await getSecondaryContent(url.pathname);
        addSecondaryContent(secondaryContent);
      },
    });
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-scroll-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigateEvent: signal property - Web APIs

NavigateEvent: signal property
==============================

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

 The **`signal`** read-only property of the
 `NavigateEvent` interface returns an `AbortSignal`, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one).

Value
-----

An `AbortSignal` object.

Examples
--------

The general idea here is that the `signal` property can be passed to an associated `fetch()` operation so that if the navigation is cancelled, the `fetch()` operation can be safely aborted, avoiding wasting bandwidth on fetches that are no longer needed.

```js
navigation.addEventListener("navigate", (event) => {
  event.intercept({
    async handler() {
      // ...

      await fetch(`/img/some-image.jpg`, { signal: event.signal });

      // ...
    },
  });
});
```

**Note:** See Example: next/previous buttons for a more detailed example.

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-signal-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigateEvent: NavigateEvent() constructor - Web APIs

NavigateEvent: NavigateEvent() constructor
==========================================

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

 The **`NavigateEvent()`** constructor creates a new
 `NavigateEvent` object instance.

Syntax
------

```js
new NavigateEvent(type, init)
```

### Parameters

`type`

A string representing the type of event. In the case of `NavigateEvent` this is always `navigate`.

`init`

An object containing the following properties:

`canIntercept` Optional

A boolean defining whether the navigation can be intercepted or not (e.g. you can't intercept a cross-origin navigation). Defaults to `false`.

`destination`

A `NavigationDestination` object representing the location being navigated to.

`downloadRequest` Optional

The filename of the file requested for download, in the case of a download navigation (e.g. an `<a>` or `<area>` element with a `download` attribute). Defaults to `null`.

`formData` Optional

The `FormData` object representing the submitted data in the case of a `POST` form submission. Defaults to `null`.

`hashChange` Optional

A boolean defining if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document). Defaults to `false`.

`info` Optional

The `info` data value passed by the initiating navigation operation (e.g. `Navigation.back()`, or `Navigation.navigate()`).

`navigationType` Optional

The type of the navigation. Possible values — `push`, `reload`, `replace`, and `traverse`. Defaults to `push`.

`signal`

An `AbortSignal`, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one).

`userInitiated` Optional

A boolean defining whether the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons). Defaults to `false`.

Examples
--------

A developer would not use this constructor manually. A new `NavigateEvent` object is constructed when a handler is invoked as a result of the `navigate` event firing.

```js
navigation.addEventListener("navigate", (event) => {
  // Exit early if this navigation shouldn't be intercepted,
  // e.g. if the navigation is cross-origin, or a download request
  if (shouldNotIntercept(event)) {
    return;
  }

  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        // The URL has already changed, so show a placeholder while
        // fetching the new content, such as a spinner or loading page
        renderArticlePagePlaceholder();

        // Fetch the new content and display when ready
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);
      },
    });
  }
});
```

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

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

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigateEvent: navigationType property - Web APIs

NavigateEvent: navigationType property
======================================

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

 The **`navigationType`** read-only property of the
 `NavigateEvent` interface returns the type of the navigation — `push`, `reload`, `replace`, or `traverse`.

Value
-----

An enumerated value representing the type of navigation.

The possible values are:

* `push`: A new location is navigated to, causing a new entry to be pushed onto the history list.
* `reload`: The `Navigation.currentEntry` is reloaded.
* `replace`: The `Navigation.currentEntry` is replaced with a new history entry. This new entry will reuse the same `key`, but be assigned a different `id`.
* `traverse`: The browser navigates from one existing history entry to another existing history entry.
Examples
--------

### Async transitions with special back/forward handling

Sometimes it's desirable to handle back/forward navigations specially, e.g. reusing cached views by transitioning them onto the screen. This can be done by branching as follows:

```js
navigation.addEventListener("navigate", (event) => {
  // Some navigations, e.g. cross-origin navigations, we
  // cannot intercept. Let the browser handle those normally.
  if (!event.canIntercept) {
    return;
  }

  // Don't intercept fragment navigations or downloads.
  if (event.hashChange || event.downloadRequest !== null) {
    return;
  }

  event.intercept({
    async handler() {
      if (myFramework.currentPage) {
        await myFramework.currentPage.transitionOut();
      }

      let { key } = event.destination;

      if (
        event.navigationType === "traverse" &&
        myFramework.previousPages.has(key)
      ) {
        await myFramework.previousPages.get(key).transitionIn();
      } else {
        // This will probably result in myFramework storing
        // the rendered page in myFramework.previousPages.
        await myFramework.renderPage(event.destination);
      }
    },
  });
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-navigationtype-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigateEvent: destination property - Web APIs

NavigateEvent: destination property
===================================

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

 The **`destination`** read-only property of the
 `NavigateEvent` interface returns a `NavigationDestination` object representing the destination being navigated to.

Value
-----

A `NavigationDestination` object.

Examples
--------

```js
navigation.addEventListener("navigate", (event) => {
  // Exit early if this navigation shouldn't be intercepted,
  // e.g. if the navigation is cross-origin, or a download request
  if (shouldNotIntercept(event)) {
    return;
  }

  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        // The URL has already changed, so show a placeholder while
        // fetching the new content, such as a spinner or loading page
        renderArticlePagePlaceholder();

        // Fetch the new content and display when ready
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);
      },
    });
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-destination-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigateEvent: downloadRequest property - Web APIs

NavigateEvent: downloadRequest property
=======================================

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

 The **`downloadRequest`** read-only property of the
 `NavigateEvent` interface returns the filename of the file requested for download, in the case of a download navigation (e.g. an `<a>` or `<area>` element with a `download` attribute), or `null` otherwise.

Value
-----

A string containing the filename of the file requested for download, or `null`.

Examples
--------

```js
navigation.addEventListener("navigate", (event) => {
  // Some navigations, e.g. cross-origin navigations, we
  // cannot intercept. Let the browser handle those normally.
  if (!event.canIntercept) {
    return;
  }

  // Don't intercept fragment navigations or downloads.
  if (event.hashChange || event.downloadRequest !== null) {
    return;
  }

  event.intercept({
    handler() {
      if (event.formData) {
        processFormDataAndUpdateUI(event.formData, event.signal);
      } else {
        doSinglePageAppNav(event.destination, event.signal);
      }
    },
  });
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-downloadrequest-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigateEvent: canIntercept property - Web APIs

NavigateEvent: canIntercept property
====================================

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

 The **`canIntercept`** read-only property of the
 `NavigateEvent` interface returns `true` if the navigation can be intercepted and have its URL rewritten, or `false` otherwise

There are several rules around when a navigation can be intercepted. For example:

* You can't intercept cross-origin navigations.
* You can intercept `http` or `https` URLs if only the `path`, `query`, and `fragment` portions of the new URL differ from the current URL.
* You can intercept `file` URLs if only the `query` and `fragment` portions of the new URL differ.
* For other URL types you can intercept the navigation if only the `fragment` portion differs.

See the spec for more explanation on when a Document can have its URL rewritten, including a table of examples.

Value
-----

A boolean value—`true` if the navigation can be intercepted, `false` if not.

Examples
--------

```js
navigation.addEventListener("navigate", (event) => {
  // Some navigations, e.g. cross-origin navigations, we
  // cannot intercept. Let the browser handle those normally.
  if (!event.canIntercept) {
    return;
  }

  // Don't intercept fragment navigations or downloads.
  if (event.hashChange || event.downloadRequest !== null) {
    return;
  }

  event.intercept({
    handler() {
      if (event.formData) {
        processFormDataAndUpdateUI(event.formData, event.signal);
      } else {
        doSinglePageAppNav(event.destination, event.signal);
      }
    },
  });
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-canintercept-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigateEvent: formData property - Web APIs

NavigateEvent: formData property
================================

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

 The **`formData`** read-only property of the
 `NavigateEvent` interface returns the `FormData` object representing the submitted data in the case of a `POST` form submission, or `null` otherwise.

Value
-----

A `FormData` object, or `null`.

Examples
--------

```js
navigation.addEventListener("navigate", (event) => {
  // Some navigations, e.g. cross-origin navigations, we
  // cannot intercept. Let the browser handle those normally.
  if (!event.canIntercept) {
    return;
  }

  // Don't intercept fragment navigations or downloads.
  if (event.hashChange || event.downloadRequest !== null) {
    return;
  }

  event.intercept({
    handler() {
      if (event.formData) {
        processFormDataAndUpdateUI(event.formData, event.signal);
      } else {
        doSinglePageAppNav(event.destination, event.signal);
      }
    },
  });
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-formdata-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigateEvent: hashChange property - Web APIs

NavigateEvent: hashChange property
==================================

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

 The **`hashChange`** read-only property of the
 `NavigateEvent` interface returns `true` if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document), or `false` otherwise.

Value
-----

A boolean value—`true` if the navigation is a fragment navigation, `false` if not.

Examples
--------

```js
navigation.addEventListener("navigate", (event) => {
  // Some navigations, e.g. cross-origin navigations, we
  // cannot intercept. Let the browser handle those normally.
  if (!event.canIntercept) {
    return;
  }

  // Don't intercept fragment navigations or downloads.
  if (event.hashChange || event.downloadRequest !== null) {
    return;
  }

  event.intercept({
    handler() {
      if (event.formData) {
        processFormDataAndUpdateUI(event.formData, event.signal);
      } else {
        doSinglePageAppNav(event.destination, event.signal);
      }
    },
  });
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-hashchange-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigateEvent: info property - Web APIs

NavigateEvent: info property
============================

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

 The **`info`** read-only property of the
 `NavigateEvent` interface returns the `info` data value passed by the initiating navigation operation (e.g. `Navigation.back()`, or `Navigation.navigate()`), or `undefined` if no `info` data was passed.

Value
-----

The `info` value passed by the initiating navigation operation, or `undefined` if none was passed.

Examples
--------

One example of how `info` might be used is to trigger different single-page navigation renderings depending on how a certain route was reached. For example, consider a photo gallery app, where you can reach the same photo URL and state via various routes. You might want to use a different animation to show the photo for each route.

```js
navigation.addEventListener("navigate", (event) => {
  if (isPhotoNavigation(event)) {
    event.intercept({
      async handler() {
        switch (event.info?.via) {
          case "go-left": {
            await animateLeft();
            break;
          }
          case "go-right": {
            await animateRight();
            break;
          }
          case "gallery": {
            await animateZoomFromThumbnail(event.info.thumbnail);
            break;
          }
        }

        // TODO: actually load the photo.
      },
    });
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-info-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo
* Methods that allow info to be passed — `Navigation.back()`, `Navigation.forward()`, `Navigation.navigate()`, `Navigation.reload()`, and `Navigation.traverseTo()`


NavigateEvent: userInitiated property - Web APIs

NavigateEvent: userInitiated property
=====================================

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

 The **`userInitiated`** read-only property of the
 `NavigateEvent` interface returns `true` if the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons), or `false` otherwise.

**Note:** The table found at Appendix: types of navigations shows which navigation types are user-initiated.

Value
-----

A boolean value—`true` if the navigation is user-initiated, `false` if not.

Examples
--------

```js
navigation.addEventListener("navigate", (event) => {
  console.log(event.userInitiated);
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigateevent-userinitiated-dev |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


CustomStateSet: entries() method - Web APIs

CustomStateSet: entries() method
================================

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

The **`entries`** method of the `CustomStateSet` interface returns a new iterator object, containing an array of `[value,value]` for each element in the `CustomStateSet`.

Syntax
------

```js
entries()
```

### Parameters

None.

### Return value

A new iterator object that contains an array of `[value, value]` for each element in the `CustomStateSet`, in insertion order.

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

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

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

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


CustomStateSet: keys() method - Web APIs

CustomStateSet: keys() method
=============================

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

The **`keys()`** method of the `CustomStateSet` interface is an alias for `CustomStateSet.values`.

Syntax
------

```js
keys()
```

### Parameters

None.

### Return value

A new iterator object containing the values for each element in the given `CustomStateSet`, in insertion order.

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

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

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

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


CustomStateSet: size property - Web APIs

CustomStateSet: size property
=============================

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

The **`size`** property of the `CustomStateSet` interface returns the number of values in the `CustomStateSet`.

Value
-----

An integer indicating how many properties the `CustomStateSet` has.

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

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

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

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


CustomStateSet: values() method - Web APIs

CustomStateSet: values() method
===============================

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

The **`values()`** method of the `CustomStateSet` interface returns a new iterator object that yields the values for each element in the `CustomStateSet` object in insertion order.

Syntax
------

```js
values()
```

### Parameters

None.

### Return value

A new iterator object containing the values for each element in the given `CustomStateSet`, in insertion order.

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

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

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

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


CustomStateSet: delete() method - Web APIs

CustomStateSet: delete() method
===============================

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

The **`delete()`** method of the `CustomStateSet` interface deletes a single value from the `CustomStateSet`.

Syntax
------

```js
delete(value)
```

### Parameters

`value`

value to remove from the `CustomStateSet`.

### Return value

Returns `true` if `value` was in the `CustomStateSet`; otherwise `false`.

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

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

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

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


CustomStateSet: clear() method - Web APIs

CustomStateSet: clear() method
==============================

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

The **`clear()`** method of the `CustomStateSet` interface removes all elements from the `CustomStateSet` object.

Syntax
------

```js
clear()
```

### Parameters

None.

### Return value

Undefined.

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

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

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

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


CustomStateSet: has() method - Web APIs

CustomStateSet: has() method
============================

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

The **`has()`** method of the `CustomStateSet` interface returns a `Boolean` asserting whether an element is present with the given value.

Syntax
------

```js
has(value)
```

### Parameters

`value`

The value to test for in the `CustomStateSet` object.

### Return value

A `Boolean`, `true` if `value` exists in the `CustomStateSet`.

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

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

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

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


CustomStateSet: add() method - Web APIs

CustomStateSet: add() method
============================

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

The **`add`** method of the `CustomStateSet` interface adds an item to the `CustomStateSet`, after checking that the value is in the correct format.

Syntax
------

```js
add(value)
```

### Parameters

`value`

A string which must be a `<dashed-ident>`, with the form `--mystate`.

### Return value

Undefined.

### Exceptions

`SyntaxError` `DOMException`

Thrown if the string is not a `<dashed-ident>`.

Examples
--------

The following function adds the state `--checked` to a `CustomStateSet`.

```js
class MyCustomElement extends HTMLElement {
  set checked(flag) {
    if (flag) {
      this._internals.states.add("--checked");
    }
  }
}
```

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

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

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

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


CustomStateSet: forEach() method - Web APIs

CustomStateSet: forEach() method
================================

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

The **`forEach()`** method of the `CustomStateSet` interface executes a provided function for each value in the `CustomStateSet` object.

Syntax
------

```js
forEach(callbackFn)
forEach(callbackFn, thisArg)
```

### Parameters

`callbackFn`

Function to execute for each element, taking three arguments:

`value`, `key`

The current element being processed in the `CustomStateSet`. As there are no keys in a `CustomStateSet`, the value is passed for both arguments.

`set`

The `CustomStateSet` which `forEach()` was called upon.

`thisArg`

Value to use as `this` when executing `callbackFn`.

### Return value

Undefined.

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

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

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

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


ImageData: data property - Web APIs

ImageData: data property
========================

 The readonly **`ImageData.data`** property returns a
 `Uint8ClampedArray` that contains the `ImageData` object's
 pixel data. Data is stored as a one-dimensional array in the RGBA order, with integer
 values between `0` and `255` (inclusive).

Value
-----

A `Uint8ClampedArray`.

Examples
--------

### Getting an ImageData object's pixel data

 This example creates an `ImageData` object that is 100 pixels wide and 100
 pixels tall, making 10,000 pixels in all. The `data` array stores four values
 for each pixel, making 4 x 10,000, or 40,000 values in all.

```js
let imageData = new ImageData(100, 100);
console.log(imageData.data); // Uint8ClampedArray[40000]
console.log(imageData.data.length); // 40000
```

### Filling a blank ImageData object

 This example creates and fills a new `ImageData` object with colorful
 pixels.

#### HTML

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

#### JavaScript

 Since each pixel consists of four values within the `data` array, the
 `for` loop iterates by multiples of four. The values associated with each
 pixel are R (red), G (green), B (blue), and A (alpha), in that order.

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

// Fill the array with RGBA values
for (let i = 0; i < imageData.data.length; i += 4) {
  // Percentage in the x direction, times 255
  let x = ((i % 400) / 400) \* 255;
  // Percentage in the y direction, times 255
  let y = (Math.ceil(i / 400) / 100) \* 255;

  // Modify pixel data
  imageData.data[i + 0] = x; // R value
  imageData.data[i + 1] = y; // G value
  imageData.data[i + 2] = 255 - x; // B value
  imageData.data[i + 3] = 255; // A value
}

// Draw image data to the canvas
ctx.putImageData(imageData, 20, 20);
```

#### Result

### More examples

 For more examples using `ImageData.data`, see Pixel manipulation with canvas,
 `CanvasRenderingContext2D.createImageData()`, and
 `CanvasRenderingContext2D.putImageData()`.

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

| Specification |
| --- |
| HTML Standard # dom-imagedata-data-dev |

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

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

See also
--------

* `ImageData.height`
* `ImageData.width`
* `ImageData`
* `CanvasRenderingContext2D.createImageData()`
* `CanvasRenderingContext2D.putImageData()`
* Pixel manipulation with canvas


ImageData: colorSpace property - Web APIs

ImageData: colorSpace property
==============================

The read-only **`ImageData.colorSpace`** property is a string indicating the color space of the image data.

The color space can be set during `ImageData` initialization using either the `ImageData()` constructor or the `createImageData()` method.

Value
-----

This property can have the following values:

* `"srgb"` representing the sRGB color space.
* `"display-p3"` representing the display-p3 color space.
Examples
--------

### Getting the color space of canvas image data

 The `getImageData()` method allows you to explicitly request a color space. If it doesn't match the color space the canvas was initialized with, a conversion will be performed.
 Use the `colorSpace` property to know which color space your `ImageData` object is in.

```js
const context = canvas.getContext("2d", { colorSpace: "display-p3" });
context.fillStyle = "color(display-p3 0.5 0 0)";
context.fillRect(0, 0, 10, 10);

const p3ImageData = context.getImageData(0, 0, 1, 1);
console.log(p3ImageData.colorSpace); // "display-p3"

const srgbImageData = context.getImageData(0, 0, 1, 1, { colorSpace: "srgb" });
console.log(srgbImageData.colorSpace); // "srgb"
```

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

| Specification |
| --- |
| HTML Standard # dom-imagedata-colorspace |

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

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

See also
--------

* `CanvasRenderingContext2D.createImageData()`
* `CanvasRenderingContext2D.getImageData()`
* `colorSpace` setting in `canvas.getContext()`
* Setting WebGL color spaces:
    + `WebGLRenderingContext.drawingBufferColorSpace`
    + `WebGLRenderingContext.unpackColorSpace`


ImageData: ImageData() constructor - Web APIs

ImageData: ImageData() constructor
==================================

 The **`ImageData()`** constructor returns a newly instantiated
 `ImageData` object built from the typed array given and having the
 specified width and height.

 This constructor is the preferred way of creating such an object in a
 `Worker`.

Syntax
------

```js
new ImageData(width, height)
new ImageData(width, height, settings)

new ImageData(dataArray, width)
new ImageData(dataArray, width, height)
new ImageData(dataArray, width, height, settings)
```

### Parameters

`width`

An unsigned long representing the width of the image.

`height`

 An unsigned long representing the height of the image. This value is optional if an
 array is given: the height will be inferred from the array's size and the given width.

`settings` Optional

An object with the following properties:

* `colorSpace`: Specifies the color space of the image data. Can be set to `"srgb"` for the sRGB color space or `"display-p3"` for the display-p3 color space.

`dataArray`

A `Uint8ClampedArray` containing the underlying pixel representation of the image. If no such array is given, an image with a transparent black rectangle of the specified `width` and `height` will be created.

### Return value

A new `ImageData` object.

### Errors thrown

`IndexSizeError` `DOMException`

Thrown if `array` is specified, but its length is not a multiple of `(4 * width)` or `(4 * width * height)`.

Examples
--------

### Creating a blank ImageData object

 This example creates an `ImageData` object that is 200 pixels wide and 100
 pixels tall, containing a total of 20,000 pixels.

```js
let imageData = new ImageData(200, 100);
// ImageData { width: 200, height: 100, data: Uint8ClampedArray[80000] }
```

### ImageData using the display-p3 color space

This example creates an `ImageData` object with the display-p3 color space.

```js
let imageData = new ImageData(200, 100, { colorSpace: "display-p3" });
```

### Initializing ImageData with an array

 This example instantiates an `ImageData` object with pixel colors defined by
 an array.

#### HTML

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

#### JavaScript

 The array (`arr`) has a length of `40000`: it consists of 10,000
 pixels, each of which is defined by 4 values. The `ImageData` constructor
 specifies a `width` of `200` for the new object, so its
 `height` defaults to 10,000 divided by 200, which is `50`.

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const arr = new Uint8ClampedArray(40\_000);

// Fill the array with the same RGBA values
for (let i = 0; i < arr.length; i += 4) {
  arr[i + 0] = 0; // R value
  arr[i + 1] = 190; // G value
  arr[i + 2] = 0; // B value
  arr[i + 3] = 255; // A value
}

// Initialize a new ImageData object
let imageData = new ImageData(arr, 200);

// Draw image data to the canvas
ctx.putImageData(imageData, 20, 20);
```

#### Result

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

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

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

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

See also
--------

* `CanvasRenderingContext2D.createImageData()`, the creator method that
 can be used outside workers.


ImageData: height property - Web APIs

ImageData: height property
==========================

 The readonly **`ImageData.height`** property returns the number
 of rows in the `ImageData` object.

Value
-----

A number.

Examples
--------

 This example creates an `ImageData` object that is 200 pixels wide and 100
 pixels tall. Thus, the `height` property is `100`.

```js
let imageData = new ImageData(200, 100);
console.log(imageData.height); // 100
```

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

| Specification |
| --- |
| HTML Standard # dom-imagedata-height-dev |

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

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

See also
--------

* `ImageData.width`
* `ImageData`


ImageData: width property - Web APIs

ImageData: width property
=========================

 The readonly **`ImageData.width`** property returns the number
 of pixels per row in the `ImageData` object.

Value
-----

A number.

Examples
--------

 This example creates an `ImageData` object that is 200 pixels wide and 100
 pixels tall. Thus, the `width` property is `200`.

```js
let imageData = new ImageData(200, 100);
console.log(imageData.width); // 200
```

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

| Specification |
| --- |
| HTML Standard # dom-imagedata-width-dev |

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

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

See also
--------

* `ImageData.height`
* `ImageData`


NodeList: entries() method - Web APIs

NodeList: entries() method
==========================

 The **`NodeList.entries()`** method returns an
 `iterator` allowing to go through all key/value pairs
 contained in this object. The values are `Node` objects.

Syntax
------

```js
entries()
```

### Return value

Returns an `iterator`.

Example
-------

```js
const node = document.createElement("div");
const kid1 = document.createElement("p");
const kid2 = document.createTextNode("hey");
const kid3 = document.createElement("span");
node.appendChild(kid1);
node.appendChild(kid2);
node.appendChild(kid3);

const list = node.childNodes;

// Using for...of
for (const entry of list.entries()) {
  console.log(entry);
}
```

results in:
```

Array [ 0, <p> ]
Array [ 1, #text "hey" ]
Array [ 2, <span> ]
```

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

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

See also
--------

* Polyfill of `NodeList.prototype.entries` in `core-js`
* `Node`
* `NodeList`


NodeList: values() method - Web APIs

NodeList: values() method
=========================

 The **`NodeList.values()`** method returns an
 `iterator` allowing to go through all values contained
 in this object. The values are `Node` objects.

Syntax
------

```js
values()
```

### Return value

Returns an `iterator`.

Example
-------

```js
const node = document.createElement("div");
const kid1 = document.createElement("p");
const kid2 = document.createTextNode("hey");
const kid3 = document.createElement("span");

node.appendChild(kid1);
node.appendChild(kid2);
node.appendChild(kid3);

const list = node.childNodes;

// Using for...of
for (const value of list.values()) {
  console.log(value);
}
```

The result is:
```

<p>
#text "hey"
<span>
```

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

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

See also
--------

* Polyfill of `NodeList.prototype.values` in `core-js`
* `Node`
* `NodeList`


NodeList: length property - Web APIs

NodeList: length property
=========================

 The **`NodeList.length`** property returns the number of items
 in a `NodeList`.

Value
-----

An integer value representing the number of items in a `NodeList`.

Examples
--------

 The `length` property is often useful in DOM programming. It's often used to
 test the length of a list, to see if it exists at all. It's also commonly used as the
 iterator in a `for` loop, as in this example.

```js
// All the paragraphs in the document
const items = document.getElementsByTagName("p");

// For each item in the list,
// append the entire element as a string of HTML
let gross = "";
for (let i = 0; i < items.length; i++) {
  gross += items[i].innerHTML;
}

// gross is now all the HTML for the paragraphs
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-nodelist-length① |

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

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


NodeList: item() method - Web APIs

NodeList: item() method
=======================

 Returns a node from a `NodeList` by index. This method
 doesn't throw exceptions as long as you provide arguments. A value of `null`
 is returned if the index is out of range, and a `TypeError` is thrown if no
 argument is provided.

Syntax
------

```js
item(index)
```

 JavaScript also offers an array-like bracketed syntax for obtaining an item from a
 NodeList by index:

```js
nodeItem = nodeList[index];
```

### Parameters

* `index` is the index of the node to be fetched. The index is zero-based.
### Return value

The `index`th node in the `nodeList` returned by the `item` method.

### Exceptions

`TypeError`

Thrown if no argument is provided.

Examples
--------

```js
const tables = document.getElementsByTagName("table");
const firstTable = tables.item(1); // or tables[1] - returns the second table in the DOM
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-nodelist-item① |

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

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


NodeList: forEach() method - Web APIs

NodeList: forEach() method
==========================

 The **`forEach()`** method of the `NodeList`
 interface calls the callback given in parameter once for each value pair in the list, in
 insertion order.

Syntax
------

```js
forEach(callback)
forEach(callback, thisArg)
```

### Parameters

`callback`

 A function to execute on each element of `someNodeList`. It
 accepts 3 parameters:

`currentValue`

The current element being processed in `someNodeList`.

`currentIndex` Optional

 The index of the `currentValue` being processed in
 `someNodeList`.

`listObj` Optional

 The `someNodeList` that `forEach()` is being
 applied to.

`thisArg` Optional

 Value to use as
 `this`
 when executing `callback`.

### Return value

`undefined`.

Example
-------

```js
const node = document.createElement("div");
const kid1 = document.createElement("p");
const kid2 = document.createTextNode("hey");
const kid3 = document.createElement("span");

node.appendChild(kid1);
node.appendChild(kid2);
node.appendChild(kid3);

const list = node.childNodes;

list.forEach(function (currentValue, currentIndex, listObj) {
  console.log(`${currentValue}, ${currentIndex}, ${this}`);
}, "myThisArg");
```

The above code results in the following:
```

[object HTMLParagraphElement], 0, myThisArg
[object Text], 1, myThisArg
[object HTMLSpanElement], 2, myThisArg
```

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

| Specification |
| --- |
| DOM Standard # interface-nodelist |

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

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

See also
--------

* Polyfill of `NodeList.prototype.forEach` in `core-js`
* `Node`
* `NodeList`


NodeList: keys() method - Web APIs

NodeList: keys() method
=======================

 The **`NodeList.keys()`** method returns an
 `iterator` allowing to go through all keys contained
 in this object. The keys are `unsigned integer`.

Syntax
------

```js
keys()
```

### Return value

Returns an `iterator`.

Example
-------

```js
const node = document.createElement("div");
const kid1 = document.createElement("p");
const kid2 = document.createTextNode("hey");
const kid3 = document.createElement("span");

node.appendChild(kid1);
node.appendChild(kid2);
node.appendChild(kid3);

let list = node.childNodes;

// Using for...of
for (const key of list.keys()) {
  console.log(key);
}
```

The result is:
```

0
1
2
```

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

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

See also
--------

* Polyfill of `NodeList.prototype.keys` in `core-js`
* `Node`
* `NodeList`


ImageCapture: grabFrame() method - Web APIs

ImageCapture: grabFrame() method
================================

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

 The **`grabFrame()`** method of the
 `ImageCapture` interface takes a snapshot of the live video in a
 `MediaStreamTrack` and returns a `Promise` that resolves with
 a `ImageBitmap` containing the snapshot.

Syntax
------

```js
grabFrame()
```

### Parameters

None.

### Return value

A `Promise` that resolves to an `ImageBitmap` object.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if `readyState` property of the `MediaStreamTrack` passing in the constructor is not `live`.

`UnknownError` `DOMException`

Thrown if the operation can't complete for any reason.

Examples
--------

 This example is extracted from this Simple Image Capture demo. It shows how to use the `Promise` returned by
 `grabFrame()` to copy the returned frame to a `<canvas>`
 element. For simplicity it does not show how to instantiate the
 `ImageCapture` object.

```js
let grabFrameButton = document.querySelector("button#grabFrame");
let canvas = document.querySelector("canvas");

grabFrameButton.onclick = grabFrame;

function grabFrame() {
  imageCapture
    .grabFrame()
    .then((imageBitmap) => {
      console.log("Grabbed frame:", imageBitmap);
      canvas.width = imageBitmap.width;
      canvas.height = imageBitmap.height;
      canvas.getContext("2d").drawImage(imageBitmap, 0, 0);
      canvas.classList.remove("hidden");
    })
    .catch((error) => {
      console.error("grabFrame() error: ", error);
    });
}
```

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

| Specification |
| --- |
| MediaStream Image Capture # dom-imagecapture-grabframe |

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

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


ImageCapture: track property - Web APIs

ImageCapture: track property
============================

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

 The **`track`** read-only property of the
 `ImageCapture` interface returns a reference to the
 `MediaStreamTrack` passed to the
 `ImageCapture()` constructor.

Value
-----

A `MediaStreamTrack` object.

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

| Specification |
| --- |
| MediaStream Image Capture # dom-imagecapture-track |

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

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


ImageCapture: getPhotoCapabilities() method - Web APIs

ImageCapture: getPhotoCapabilities() method
===========================================

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

 The **`getPhotoCapabilities()`**
 method of the `ImageCapture` interface returns a `Promise`
 that resolves with an object containing the ranges of
 available configuration options.

Syntax
------

```js
getPhotoCapabilities()
```

### Parameters

None.

### Return value

A `Promise` that resolves with an object containing the following properties:

`redEyeReduction`

Returns one of `"never"`, `"always"`, or `"controllable"`. The `"controllable"` value means the device's red-eye reduction is controllable by the user.

`imageHeight`

Returns an object indicating the image height range supported by the user agent.

`imageWidth`

Returns an object indicating the image width range supported by the user agent.

`fillLightMode`

Returns an array of available fill light options. Options include `auto`, `off`, or `flash`.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if `readyState` property of the `MediaStreamTrack` passing in the constructor is not `live`.

`OperationError` `DOMException`

Thrown if the operation can't complete for any reason.

Examples
--------

 The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from
 `getPhotoCapabilities()` to modify the size of an input range. This example
 also shows how the `ImageCapture` object is created using a
 `MediaStreamTrack` retrieved from a device's `MediaStream`.

```js
const input = document.querySelector('input[type="range"]');

let imageCapture;

navigator.mediaDevices
  .getUserMedia({ video: true })
  .then((mediaStream) => {
    document.querySelector("video").srcObject = mediaStream;

    const track = mediaStream.getVideoTracks()[0];
    imageCapture = new ImageCapture(track);

    return imageCapture.getPhotoCapabilities();
  })
  .then((photoCapabilities) => {
    const settings = imageCapture.track.getSettings();

    input.min = photoCapabilities.imageWidth.min;
    input.max = photoCapabilities.imageWidth.max;
    input.step = photoCapabilities.imageWidth.step;

    return imageCapture.getPhotoSettings();
  })
  .then((photoSettings) => {
    input.value = photoSettings.imageWidth;
  })
  .catch((error) => console.error("Argh!", error.name || error));
```

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

| Specification |
| --- |
| MediaStream Image Capture # dom-imagecapture-getphotocapabilities |

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

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


ImageCapture: ImageCapture() constructor - Web APIs

ImageCapture: ImageCapture() constructor
========================================

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

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

Syntax
------

```js
new ImageCapture(videoTrack)
```

### Parameters

`videoTrack`

 A `MediaStreamTrack` from which the still images will be taken. This
 can be any source, such as an incoming stream of a video conference, a playing movie,
 or the stream from a webcam.

### Return value

 A new `ImageCapture` object which can be used to capture still frames from
 the specified video track.

### Exceptions

`NotSupportedError` `DOMException`

Thrown if the `videoTrack` parameter's `kind` property is not `video`.

Examples
--------

 The following example shows how to use a call to
 `MediaDevices.getUserMedia()` to retrieve the
 `MediaStreamTrack` needed by the `ImageCapture()` constructor.

```js
navigator.mediaDevices
  .getUserMedia({ video: true })
  .then((mediaStream) => {
    document.querySelector("video").srcObject = mediaStream;
    const track = mediaStream.getVideoTracks()[0];
    imageCapture = new ImageCapture(track);
  })
  .catch((error) => console.error(error));
```

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

| Specification |
| --- |
| MediaStream Image Capture # dom-imagecapture-imagecapture |

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

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


ImageCapture: takePhoto() method - Web APIs

ImageCapture: takePhoto() method
================================

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

 The **`takePhoto()`** method of the
 `ImageCapture` interface takes a single exposure using the video capture
 device sourcing a `MediaStreamTrack` and returns a `Promise`
 that resolves with a `Blob` containing the data.

Syntax
------

```js
takePhoto()
takePhoto(photoSettings)
```

### Parameters

`photoSettings` Optional

An object that sets options for the photo to be taken. The available options are:

`fillLightMode`

 The flash setting of the capture device, one of
 `"auto"`, `"off"`, or `"flash"`.

`imageHeight`

 The desired image height as an integer. The user agent
 selects the closest height value to this setting if it only supports discrete
 heights.

`imageWidth`

 The desired image width as an integer. The user agent
 selects the closest width value to this setting if it only supports discrete
 widths.

`redEyeReduction`

 A boolean indicating whether the red-eye reduction
 should be used if it is available.

### Return value

A `Promise` that resolves with a `Blob`.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if `readyState` property of the `MediaStreamTrack` passing in the constructor is not `live`.

`UnknownError` `DOMException`

Thrown if the operation can't complete for any reason.

Examples
--------

 This example is extracted from this Simple Image Capture demo. It shows how to use the `Promise` returned by
 `takePhoto()` to copy the returned `Blob` to an
 `<img>` element. For simplicity it does not show how to instantiate the
 `ImageCapture` object.

```js
let takePhotoButton = document.querySelector("button#takePhoto");
let canvas = document.querySelector("canvas");

takePhotoButton.onclick = takePhoto;

function takePhoto() {
  imageCapture
    .takePhoto()
    .then((blob) => {
      console.log("Took photo:", blob);
      img.classList.remove("hidden");
      img.src = URL.createObjectURL(blob);
    })
    .catch((error) => {
      console.error("takePhoto() error: ", error);
    });
}
```

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

| Specification |
| --- |
| MediaStream Image Capture # dom-imagecapture-takephoto |

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

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


ImageCapture: getPhotoSettings() method - Web APIs

ImageCapture: getPhotoSettings() method
=======================================

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

 The **`getPhotoSettings()`** method of
 the `ImageCapture` interface returns a `Promise` that
 resolves with an object containing the current photo
 configuration settings.

Syntax
------

```js
getPhotoSettings()
```

### Parameters

None.

### Return value

A `Promise` that resolves with an object containing the following properties:

`fillLightMode`

The flash setting of the capture device, one of `"auto"`, `"off"`, or `"flash"`.

`imageHeight`

The desired image height as an integer. The browser selects the closest width value to this setting if it only supports discrete heights.

`imageWidth`

The desired image width as an integer. The browser selects the closest width value to this setting if it only supports discrete widths.

`redEyeReduction`

A boolean indicating whether the red-eye reduction should be used if it is available.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if `readyState` property of the `MediaStreamTrack` passing in the constructor is not `live`.

`OperationError` `DOMException`

Thrown if the operation can't complete for any reason.

Examples
--------

 The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from
 `getPhotoSettings()` to modify the size of an input range. This example also
 shows how the `ImageCapture` object is created using a
 `MediaStreamTrack` retrieved from a device's `MediaStream`.

```js
const input = document.querySelector('input[type="range"]');

let imageCapture;

navigator.mediaDevices
  .getUserMedia({ video: true })
  .then((mediaStream) => {
    document.querySelector("video").srcObject = mediaStream;

    const track = mediaStream.getVideoTracks()[0];
    imageCapture = new ImageCapture(track);

    return imageCapture.getPhotoCapabilities();
  })
  .then((photoCapabilities) => {
    const settings = imageCapture.track.getSettings();

    input.min = photoCapabilities.imageWidth.min;
    input.max = photoCapabilities.imageWidth.max;
    input.step = photoCapabilities.imageWidth.step;

    return imageCapture.getPhotoSettings();
  })
  .then((photoSettings) => {
    input.value = photoSettings.imageWidth;
  })
  .catch((error) => console.error("Argh!", error.name || error));
```

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

| Specification |
| --- |
| MediaStream Image Capture # dom-imagecapture-getphotosettings |

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

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


WebTransportSendStream: sendOrder property - Web APIs

WebTransportSendStream: sendOrder property
==========================================

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

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

The **`sendOrder`** property of the `WebTransportSendStream` interface indicates the send priority of this stream relative to other streams for which the value has been set.

 Queued bytes are sent first for streams that have a higher value.
 If not set, the send order depends on the implementation.

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

Value
-----

A number indicating the relative priority of this stream when sending bytes.

Examples
--------

 The example below shows how you can set the initial `sendOrder` when calling `WebTransport.createUnidirectionalStream()` to create the send stream, read the value from the stream, and then change the order.
 After changing the order the priority of this stream would increase, becoming higher than any stream with a priority of less than "596996858".

```js
async function writeData() {
  const stream = await transport.createUnidirectionalStream({
    sendOrder: "400", // Set initial stream order
  });

  console.log(`Stream order: ${stream.sendOrder}`); // Stream order: 400

  // write data ...

  // Change the stream order
  stream.sendOrder = 596996858;
  console.log(`Stream order: ${stream.sendOrder}`); // Stream order: 596996858

  // write more data ...
}
```

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

| Specification |
| --- |
| WebTransport # dom-webtransportsendstream-sendorder |

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

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

See also
--------

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


WebTransportSendStream: getStats() method - Web APIs

WebTransportSendStream: getStats() method
=========================================

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

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

The **`getStats()`** method of the `WebTransportSendStream` interface asynchronously returns an object containing statistics for the current stream.

 The statistics include the total number of bytes written to the stream, the number that have been sent (ignoring packet overhead), and the number of bytes that have been set at least once, and the number that have been acknowledged (up until the first sequentially-ordered non-acknowledged byte).
 It therefore provides a measure of how quickly the application is sending bytes to the server on this particular stream.

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

Syntax
------

```js
getStats()
```

### Parameters

None.

### Return value

 A `Promise` that resolves to a object containing statistics about the current stream.
 The returned object has the following properties:

`bytesAcknowledged`

 A positive integer indicating the number of bytes written to this stream that have been sent and acknowledged as received by the server, using QUIC's ACK mechanism.
 Only sequential bytes up to, but not including, the first non-acknowledged byte, are counted.
 This number can only increase and is always less than or equal to `bytesSent`.
 When the connection is over HTTP/2, the value will match `bytesSent`.

`bytesSent`

 A positive integer indicating the number of bytes written to this stream that have been sent at least once (but not necessarily acknowledged).
 This number can only increase, and is always less than or equal to `bytesWritten`.
 Note that this count does not include bytes sent as network overhead (such as packet headers).

`bytesWritten`

 A positive integer indicating the number of bytes successfully written to this stream.
 This number can only increase.

Examples
--------

 The code snippet below uses `await` to wait on the `Promise` returned by `getStats()`.
 When the promise fulfills, the result for the number of bytes that have been sent but not acknowledged is logged to the console.

```js
const stats = await stream.getStats();
const bytesNotReceived = stats.bytesWritten - stats.bytesAcknowledged;
console.log(`Bytes still successfully sent: ${bytesNotReceived}`);
```

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

| Specification |
| --- |
| WebTransport # dom-webtransportsendstream-getstats |

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

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


PaymentManager: enableDelegations() method - Web APIs

PaymentManager: enableDelegations() method
==========================================

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

The **`enableDelegations()`** method of the `PaymentManager` interface delegates responsibility for providing various parts of the required payment information to the payment app rather than collecting it from the browser (for example, via autofill).

For example, if the `requestShipping` option is set to `true` in the options object when invoking the `PaymentRequest()` constructor, a shipping address will be returned.

* If `enableDelegations()` was used to delegate `shippingAddress`, that address will come from the payment app.
* If not, it will come from the browser autofill.
Syntax
------

```js
enableDelegations(delegations)
```

### Parameters

`delegations` Optional

An array containing one or more enumerated values that specify the payment information you want to delegate to the payment app. Possible values can be:

`payerEmail`

The payment app will provide the payer's email whenever it is needed.

`payerName`

The payment app will provide the payer's name whenever it is needed.

`payerPhone`

The payment app will provide the payer's phone number whenever it is needed.

`shippingAddress`

The payment app will provide the shipping address whenever it is needed.

### Return value

A `Promise` that resolves with a value of `undefined`.

Examples
--------

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

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

  // ...
});
```

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

| Specification |
| --- |
| Payment Handler API # dom-paymentmanager-enabledelegations |

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

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

See also
--------

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


PaymentManager: userHint property - Web APIs

PaymentManager: userHint property
=================================

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

The **`userHint`** property of the `PaymentManager` interface provides a hint for the browser to display along with the payment app's name and icon in the Payment Handler UI.

Value
-----

A string.

Examples
--------

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

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

  // ...
});
```

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

| Specification |
| --- |
| Payment Handler API # dom-paymentmanager-userhint |

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

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

See also
--------

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


PaymentRequestUpdateEvent: PaymentRequestUpdateEvent() constructor - Web APIs

PaymentRequestUpdateEvent: PaymentRequestUpdateEvent() constructor
==================================================================

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

 The **`PaymentRequestUpdateEvent()`** constructor creates a new
 `PaymentRequestUpdateEvent` object which enables a web page to update the
 details of a `PaymentRequest` in response to a user action. Actual updates
 are made by passing options to the
 `updateWith()` method.

Syntax
------

```js
new PaymentRequestUpdateEvent()
```

### Parameters

None.

### Return value

A new `PaymentRequestUpdateEvent`.

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

| Specification |
| --- |
| Payment Request API 1.1 # constructor-0 |

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

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