IDBTransaction: mode property - Web APIs

IDBTransaction: mode property
=============================

 The **`mode`** read-only property of the
 `IDBTransaction` interface returns the current mode for accessing the
 data in the object stores in the scope of the transaction (i.e. is the mode to be
 read-only, or do you want to write to the object stores?) The default value is
 `readonly`.

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

Value
-----

 An object defining the mode for isolating access to
 data in the current object stores:
 A string defining the mode for isolating access to data in the current object stores.
 The following values are available:

`readonly`

Allows data to be read but not changed.

`readwrite`

Allows reading and writing of data in existing data stores to be changed.

`versionchange`

 Allows any operation, including ones that delete and
 create object stores and indexes.
 This mode is for updating the version number of transactions if the need is detected when calling `IDBFactory.open()`.
 Transactions of this mode cannot run concurrently with other transactions.
 Transactions in this mode are known as *upgrade transactions*.

Examples
--------

 In the following code snippet, we open a read/write transaction on our database and add
 some data to an object store. Note also the functions attached to transaction event
 handlers to report on the outcome of the transaction opening in the event of success or
 failure. At the end, we log the mode of the current transaction using `mode`.
 For a full working example, see our To-do Notifications app (view example live).

```js
const note = document.getElementById("notifications");

// an instance of a db object for us to store the IDB data in
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready for being inserted into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = (event) => {
    note.innerHTML +=
      "<li>Transaction completed: database modification finished.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");

  // add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of the request (this does not mean the item
    // has been stored successfully in the DB - for that you need transaction.onsuccess)
    note.innerHTML += "<li>Request successful.</li>";
  };

  // Return the mode this transaction has been opened in (should be "readwrite" in this case)
  transaction.mode;
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbtransaction-mode① |

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

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

See also
--------

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


IDBTransaction: objectStoreNames property - Web APIs

IDBTransaction: objectStoreNames property
=========================================

 The **`objectStoreNames`** read-only property of the
 `IDBTransaction` interface returns a `DOMStringList` of names
 of `IDBObjectStore` objects.

Value
-----

A `DOMStringList` of names of `IDBObjectStore` objects.

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbtransaction-objectstorenames① |

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

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

See also
--------

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


IDBTransaction: durability property - Web APIs

IDBTransaction: durability property
===================================

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

 The **`durability`** read-only property of the
 `IDBTransaction` interface returns the durability hint the transaction was
 created with. This is a hint to the user agent of whether to prioritize performance or
 durability when committing the transaction.

The value of this property is defined in the `options` parameter when creating a transaction using `IDBDatabase.transaction()`.

Value
-----

Any of the following literal `strings`:

`"strict"`

 The user agent may consider that the transaction has
 successfully committed only after verifying that all outstanding changes have been
 successfully written to a persistent storage medium.

`"relaxed"`

 The user agent may consider that the transaction has
 successfully committed as soon as all outstanding changes have been written to the
 operating system, without subsequent verification.

`"default"`

 The user agent should use its default durability behavior
 for the storage bucket. This is the default for transactions if not otherwise
 specified.

Examples
--------

For a full working example, see our To-do Notifications app (view example live).

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

| Specification |
| --- |
| Indexed Database API 3.0 # dom-idbtransaction-durability |

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

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


IDBTransaction: db property - Web APIs

IDBTransaction: db property
===========================

 The **`db`** read-only property of the `IDBTransaction` interface returns the database connection
 with which this transaction is associated.

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

Value
-----

An `IDBDatabase` object.

Examples
--------

 In the following code snippet, we open a read/write transaction on our database and add
 some data to an object store. Note also the functions attached to transaction event
 handlers to report on the outcome of the transaction opening in the event of success or
 failure. At the end, we return the associated database connection using `db`.
 For a full working example, see our To-do Notifications app (view example live).

```js
const note = document.getElementById("notifications");

// an instance of a db object for us to store the IDB data in
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready for being inserted into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = (event) => {
    note.innerHTML +=
      "<li>Transaction completed: database modification finished.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");

  // add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of the request (this does not mean the item
    // has been stored successfully in the DB - for that you need transaction.onsuccess)
    note.innerHTML += "<li>Request successful.</li>";
  };

  // Return the database (IDBDatabase) connection with which this transaction is associated
  transaction.db;
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbtransaction-db① |

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

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

See also
--------

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


FileSystemHandle: requestPermission() method - Web APIs

FileSystemHandle: requestPermission() method
============================================

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

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

 The **`requestPermission()`** method of the
 `FileSystemHandle` interface requests read or readwrite permissions for the
 file handle.

Syntax
------

```js
requestPermission(fileSystemHandlePermissionDescriptor)
```

### Parameters

FileSystemHandlePermissionDescriptor Optional

An object which specifies the permission mode to query for. Options are as follows:

* `'mode'`: Can be either `'read'` or
 `'readwrite'`.

### Return value

A `Promise` that resolves to a `PermissionStatus` object.

### Exceptions

`TypeError`

 Thrown if no parameter is specified or the `mode` is not that of
 `'read'` or `'readwrite'`

Examples
--------

The following asynchronous function requests permissions if they have not been granted.

```js
// fileHandle is a FileSystemFileHandle
// withWrite is a boolean set to true if write

async function verifyPermission(fileHandle, withWrite) {
  const opts = {};
  if (withWrite) {
    opts.mode = "readwrite";
  }

  // Check if we already have permission, if so, return true.
  if ((await fileHandle.queryPermission(opts)) === "granted") {
    return true;
  }

  // Request permission to the file, if the user grants permission, return true.
  if ((await fileHandle.requestPermission(opts)) === "granted") {
    return true;
  }

  // The user did not grant permission, return false.
  return false;
}
```

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

| Specification |
| --- |
| File System Access # api-filesystemhandle-requestpermission |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files


FileSystemHandle: name property - Web APIs

FileSystemHandle: name property
===============================

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

 The **`name`** read-only property of the
 `FileSystemHandle` interface returns the name of the entry represented by
 handle.

Value
-----

A string.

Examples
--------

 The following function allows the user to choose a file from the file picker and
 retrieve the `name` property.

```js
// store a reference to our file handle
let fileHandle;

async function getFile() {
  // open file picker
  [fileHandle] = await window.showOpenFilePicker();

  const fileName = fileHandle.name;
}
```

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

| Specification |
| --- |
| File System Standard # ref-for-dom-filesystemhandle-name① |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files


FileSystemHandle: kind property - Web APIs

FileSystemHandle: kind property
===============================

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

 The **`kind`** read-only property of the
 `FileSystemHandle` interface returns the type of entry. This is
 `'file'` if the associated entry is a file or `'directory'`. It is
 used to distinguish files from directories when iterating over the contents of a
 directory.

Value
-----

A string that can be:

* `'file'`: If the handle is a `FileSystemFileHandle`.
* `'directory'`: If the handle is a `FileSystemDirectoryHandle`.
Examples
--------

 The following function allows the user to choose a file from the file picker and then
 tests to see whether the handle returned is a file or directory

```js
// store a reference to our file handle
let fileHandle;

async function getFile() {
  // open file picker
  [fileHandle] = await window.showOpenFilePicker();

  if (fileHandle.kind === "file") {
    // run file code
  } else if (fileHandle.kind === "directory") {
    // run directory code
  }
}
```

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

| Specification |
| --- |
| File System Standard # ref-for-dom-filesystemhandle-kind① |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files


FileSystemHandle: queryPermission() method - Web APIs

FileSystemHandle: queryPermission() method
==========================================

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

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

 The **`queryPermission()`** method of the
 `FileSystemHandle` interface queries the current permission state of the
 current handle.

Syntax
------

```js
queryPermission(fileSystemHandlePermissionDescriptor)
```

### Parameters

FileSystemHandlePermissionDescriptor Optional

An object which specifies the permission mode to query for. Options are as follows:

* `'mode'`: Can be either `'read'` or
 `'readwrite'`.

### Return value

A `Promise` that resolves to a `PermissionStatus` object.

 If `PermissionStatus.state` returns "prompt" the website will have to call requestPermission() before any
 operations on the handle can be done. If this returns "denied" any operations will
 reject. Usually handles returned by the local file system handle factories will
 initially return "granted" for their read permission state. However, other than through
 the user revoking permission, a handle retrieved from IndexedDB is also likely to return
 "prompt".

### Exceptions

`TypeError`

 Thrown if `mode` is specified with a value other than
 `'read'` or `'readwrite'`

Examples
--------

 The following asynchronous function returns true if user has granted read or readwrite
 permissions to the file handle. Permission is requested if not.

```js
// fileHandle is a FileSystemFileHandle
// withWrite is a boolean set to true if write

async function verifyPermission(fileHandle, withWrite) {
  const opts = {};
  if (withWrite) {
    opts.mode = "readwrite";
  }

  // Check if we already have permission, if so, return true.
  if ((await fileHandle.queryPermission(opts)) === "granted") {
    return true;
  }

  // Request permission to the file, if the user grants permission, return true.
  if ((await fileHandle.requestPermission(opts)) === "granted") {
    return true;
  }

  // The user did not grant permission, return false.
  return false;
}
```

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

| Specification |
| --- |
| File System Access # api-filesystemhandle-querypermission |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files


FileSystemHandle: isSameEntry() method - Web APIs

FileSystemHandle: isSameEntry() method
======================================

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

 The **`isSameEntry()`** method of the
 `FileSystemHandle` interface compares two `handles` to see if the associated entries (either a file or directory) match.

Syntax
------

```js
isSameEntry(fileSystemHandle)
```

### Parameters

`FileSystemHandle`

 The `FileSystemHandle` to match against the handle on which the method is
 invoked.

### Return value

A Promise that fulfills with a `Boolean`.

Examples
--------

 The following function compares a single entry with an array of entries, and returns a
 new array with any matching entries removed.

```js
function removeMatches(fileEntry, entriesArr) {
  let newArr = entriesArr.filter((entry) => !fileEntry.isSameEntry(entry));

  return newArr;
}
```

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

| Specification |
| --- |
| File System Standard # api-filesystemhandle-issameentry |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files


FileSystemHandle: remove() method - Web APIs

FileSystemHandle: remove() method
=================================

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

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

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

The **`remove()`** method of the `FileSystemHandle` interface requests removal of the entry represented by the handle from the underlying file system.

The `remove()` method allows you to remove a file or directory directly from its handle. Without this method, you would have to obtain the handle of the parent directory, then call `FileSystemDirectoryHandle.removeEntry()` on that to remove it.

You can also call `remove()` on the root directory of the Origin Private File System to clear its contents, after which a new empty OPFS is created.

Syntax
------

```js
remove(options)
```

### Parameters

`options` Optional

An object that specifies options for the removal. Possible properties are as follows:

`recursive` Optional

A boolean value that defaults to `false`. When set to `true` and the entry is a directory, its contents will be removed recursively.

### Return value

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

### Exceptions

`InvalidModificationError` `DOMException`

Thrown if `recursive` is set to `false` and the entry to be removed is a directory with children.

`NoModificationAllowedError` `DOMException`

Thrown if the browser was not able to get an exclusive lock on the entry.

`NotAllowedError` `DOMException`

Thrown if `PermissionStatus` is not `granted`.

`NotFoundError` `DOMException`

Thrown if the entry is not found.

Examples
--------

Our FileSystemHandle.remove() demo (see the source code) is a file creator app. You can enter text into the `<textarea>` and press the "Save file" `<button>`, and the app will open a file picker allowing you to save that text onto your local file system in a text file of your choice. You can also choose to delete files you create.

It doesn't allow you to view the content of created files, and it doesn't stay in sync with the underlying file system on page reloads/closes. This means that files created by the app will still exist on the file system if you don't choose to delete them before reloading or closing the tab.

The file picker, file handle, and the file itself if you are creating a new file, are created using `window.showSaveFilePicker()`. The text is written to the file via `FileSystemFileHandle.createWritable()`.

Once a file is created on the file system, an entry is created in the app (see `processNewFile()` in the source code):

* A reference to the file handle is stored in an array called `savedFileRefs` so it can be easily referenced later on.
* A list item is added underneath the "Saved files" heading in the UI, with the file name shown alongside a "Delete" button.

When the "Delete" button is pressed, the `deleteFile()` function is run, which looks like so:

```js
async function deleteFile(e) {
  for (const handle of savedFileRefs) {
    if (handle.name === e.target.id + ".txt") {
      await handle.remove();
      savedFileRefs = savedFileRefs.filter(
        (handle) => handle.name !== e.target.id + ".txt",
      );
      e.target.parentElement.parentElement.removeChild(e.target.parentElement);
    }
  }
}
```

Walking through this:

1. For each file handle saved in the `savedFileRefs` array, we check its name to see if it matches the `id` attribute of the button that triggered the event.
2. When a match is found, we run `FileSystemHandle.remove()` on that handle to remove the file from the underlying file system.
3. We also remove the matched handle from the `savedFileRefs` array.
4. Finally, we remove the list item relating to that file in the UI.
Specifications
--------------

#### No specification found

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

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

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

See also
--------

* File System API
* FileSystemHandle.remove() demo


HTMLTemplateElement: content property - Web APIs

HTMLTemplateElement: content property
=====================================

 The **`HTMLTemplateElement.content`** property returns a
 `<template>` element's template contents (a
 `DocumentFragment`).

Value
-----

A `DocumentFragment`.

Examples
--------

```js
const templateElement = document.querySelector("#foo");
const documentFragment = templateElement.content.cloneNode(true);
```

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

| Specification |
| --- |
| HTML Standard # dom-template-content-dev |

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

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

See also
--------

* `HTMLTemplateElement`


GPUExternalTexture: label property - Web APIs

GPUExternalTexture: label property
==================================

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

 The **`label`** property of the
 `GPUExternalTexture` interface provides a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

This can be set by providing a `label` property in the descriptor object passed into the originating `GPUDevice.importExternalTexture()` call, or you can get and set it directly on the `GPUExternalTexture` object.

Value
-----

A string. If this has not been previously set as described above, it will be an empty string.

Examples
--------

Setting and getting a label via `GPUExternalTexture.label`:

```js
// ...

const externalTexture = device.importExternalTexture({
  source: video,
});

externalTexture.label = "myExtTexture";

console.log(externalTexture.label); // "myExtTexture"
```

Setting a label via the originating `GPUDevice.importExternalTexture()` call, and then getting it via `GPUExternalTexture.label`:

```js
// ...

const externalTexture = device.importExternalTexture({
  source: video,
  label: "myExtTexture",
});

console.log(externalTexture.label); // "myExtTexture"
```

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

| Specification |
| --- |
| WebGPU # dom-gpuobjectbase-label |

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

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

See also
--------

* The WebGPU API


AudioDecoder: dequeue event - Web APIs

AudioDecoder: dequeue event
===========================

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

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

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

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

The **`dequeue`** event of the `AudioDecoder` interface fires to signal a decrease in `AudioDecoder.decodeQueueSize`.

This eliminates the need for developers to use a `setTimeout()` poll to determine when the queue has decreased, and more work should be queued up.

Syntax
------

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

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

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

Example
-------

```js
audioDecoder.addEventListener("dequeue", (event) => {
  // Queue up more decoding work
});
```

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

| Specification |
| --- |
| WebCodecs # eventdef-audiodecoder-dequeue |

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

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


AudioDecoder: decode() method - Web APIs

AudioDecoder: decode() method
=============================

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

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

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

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

The **`decode()`** method of the `AudioDecoder` interface enqueues a control message to decode a given chunk of audio.

Syntax
------

```js
decode(chunk)
```

### Parameters

`chunk`

An `EncodedAudioChunk` object representing a chunk of encoded audio.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `state` is not `"configured"`.

`DataError` `DOMException`

Thrown if the `chunk` is unable to be decoded due to relying on other frames for decoding.

Examples
--------

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

| Specification |
| --- |
| WebCodecs # dom-audiodecoder-decode |

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

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


AudioDecoder: flush() method - Web APIs

AudioDecoder: flush() method
============================

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

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

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

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

The **`flush()`** method of the `AudioDecoder` interface returns a Promise that resolves once all pending messages in the queue have been completed.

Syntax
------

```js
flush()
```

### Parameters

None.

### Return value

A `Promise` that resolves with undefined.

### Exceptions

If an error occurs, the promise will resolve with one of the following exceptions:

`InvalidStateError` `DOMException`

Returned if the Promise is rejected because the `state` is not `configured`.

Examples
--------

The following example flushes the `AudioDecoder`.

```js
await audioDecoder.flush();
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodecoder-flush |

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

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


AudioDecoder: AudioDecoder() constructor - Web APIs

AudioDecoder: AudioDecoder() constructor
========================================

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

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

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

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

The **`AudioDecoder()`** constructor creates a new `AudioDecoder` object with the provided `init.output` callback assigned as the output callback, the provided `init.error` callback as the error callback, and the `AudioDecoder.state` set to `"unconfigured"`.

Syntax
------

```js
new AudioDecoder(init)
```

### Parameters

`init`

A dictionary object containing two required callbacks.

`output`

A callback which is passed a single argument of an `AudioData` object.

`error`

A callback which is passed a single argument of the error that has been thrown.

Examples
--------

In the following example an `AudioDecoder` is created with the two required callback functions, one to deal with the decoded chunk and the other to handle errors.

```js
const audioDecoder = new AudioDecoder({
  output: processAudio,
  error: onEncoderError,
});
```

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

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

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

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


AudioDecoder: isConfigSupported() static method - Web APIs

AudioDecoder: isConfigSupported() static method
===============================================

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

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

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

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

The **`isConfigSupported()`** static method of the `AudioDecoder` interface checks if the given config is supported (that is, if `AudioDecoder` objects can be successfully configured with the given config).

Syntax
------

```js
AudioDecoder.isConfigSupported(config)
```

### Parameters

`config`

The dictionary object accepted by `AudioDecoder.configure`

### Return value

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

`supported`

A boolean value which is `true` if the given config is supported by the decoder.

`config`

A copy of the given config with all the fields recognized by the decoder.

### Exceptions

`TypeError`

Thrown if the provided `config` is invalid; that is, if doesn't have required values (such as an empty `codec` field) or has invalid values (such as a negative `sampleRate`).

Examples
--------

The following example tests if the browser supports several audio codecs.

```js
const codecs = ["mp4a.40.2", "mp3", "alaw", "ulaw"];
const configs = [];
for (const codec of codecs) {
  configs.push({
    codec,
    sampleRate: 48000,
    numberOfChannels: 1,
    not\_supported\_field: 123,
  });
}
for (const config of configs) {
  const support = await AudioDecoder.isConfigSupported(config);
  console.log(
    `AudioDecoder's config ${JSON.stringify(support.config)} support: ${
 support.supported
 }`,
  );
}
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodecoder-isconfigsupported |

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

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


AudioDecoder: decodeQueueSize property - Web APIs

AudioDecoder: decodeQueueSize 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
**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

The **`decodeQueueSize`** read-only property of the `AudioDecoder` interface returns the number of pending decode requests in the queue.

Value
-----

An integer containing the number of requests.

Examples
--------

The following example prints the size of the queue to the console.

```js
console.log(AudioDecoder.decodeQueueSize);
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodecoder-decodequeuesize |

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

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


AudioDecoder: close() method - Web APIs

AudioDecoder: close() method
============================

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

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

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

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

The **`close()`** method of the `AudioDecoder` interface ends all pending work and releases system resources.

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

The following example closes the `AudioDecoder`.

```js
AudioDecoder.close();
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodecoder-close |

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

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


AudioDecoder: configure() method - Web APIs

AudioDecoder: configure() method
================================

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

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

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

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

The **`configure()`** method of the `AudioDecoder` interface enqueues a control message to configure the audio decoder for decoding chunks.

Syntax
------

```js
configure(config)
```

### Parameters

`config`

A dictionary object containing the following members:

`codec`

A string containing a valid codec string. See "codecs" parameter for details on codec string construction.

`sampleRate`

An integer representing the number of frame samples per second.

`numberOfChannels`

An integer representing the number of audio channels.

`description` Optional

An `ArrayBuffer`, a `TypedArray`, or a `DataView` containing a sequence of codec specific bytes, commonly known as extradata.

**Note:** The registrations in the WebCodecs Codec Registry link to a specification detailing whether and how to populate the optional `description` member.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown if the provided `config` is invalid.

`InvalidStateError` `DOMException`

Thrown if the `state` is `"closed"`.

`NotSupportedError` `DOMException`

Thrown if the provided `config` is valid but the user agent cannot provide a codec that can decode this profile.

Examples
--------

The following example configures the `audioDecoder` with the `opus` codec.

```js
audioDecoder.configure({
  codec: "opus",
  sampleRate: 44100,
  numberOfChannels: 2,
});
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodecoder-configure |

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

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


AudioDecoder: state property - Web APIs

AudioDecoder: state 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
**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

The **`state`** read-only property of the `AudioDecoder` interface returns the current state of the underlying codec.

Value
-----

A string containing one of the following values:

`"unconfigured"`

The codec is not configured for decoding.

`"configured"`

The codec has a valid configuration and is ready.

`"closed"`

The codec is no longer usable and system resources have been released.

Examples
--------

The following example prints the state of the `AudioDecoder` to the console.

```js
console.log(AudioDecoder.state);
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodecoder-state |

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

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


AudioDecoder: reset() method - Web APIs

AudioDecoder: reset() method
============================

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

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

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

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

The **`reset()`** method of the `AudioDecoder` interface resets all states including configuration, control messages in the control message queue, and all pending callbacks.

Syntax
------

```js
reset()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

The following example resets the `AudioDecoder`.

```js
AudioDecoder.reset();
```

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

| Specification |
| --- |
| WebCodecs # dom-audiodecoder-reset |

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

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


GPUShaderModule: label property - Web APIs

GPUShaderModule: label property
===============================

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

 The **`label`** property of the
 `GPUShaderModule` interface provides a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

This can be set by providing a `label` property in the descriptor object passed into the originating `GPUDevice.createShaderModule()` call, or you can get and set it directly on the `GPUShaderModule` object.

Value
-----

A string. If this has not been previously set as described above, it will be an empty string.

Examples
--------

Setting and getting a label via `GPUShaderModule.label`:

```js
// ...

const shaderModule = device.createShaderModule({
  code: shaders,
});

shaderModule.label = "myshader";

console.log(shaderModule.label); // "myshader"
```

Setting a label via the originating `GPUDevice.createShaderModule()` call, and then getting it via `GPUShaderModule.label`:

```js
// ...

const shaderModule = device.createShaderModule({
  code: shaders,
  label: "myshader",
});

console.log(shaderModule.label); // "myshader"
```

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

| Specification |
| --- |
| WebGPU # dom-gpuobjectbase-label |

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

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

See also
--------

* The WebGPU API


GPUShaderModule: getCompilationInfo() method - Web APIs

GPUShaderModule: getCompilationInfo() method
============================================

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

 The **`getCompilationInfo()`** method of the
 `GPUShaderModule` interface returns a `Promise` that fulfills with a `GPUCompilationInfo` object containing messages generated during the `GPUShaderModule`'s compilation.

Syntax
------

```js
getCompilationInfo()
```

### Parameters

None.

### Return value

A `Promise` that fulfills with a `GPUCompilationInfo` object.

`GPUCompilationInfo` contains a `messages` property, which is an array of `GPUCompilationMessage` objects, each one containing the details of an individual compilation message.

Examples
--------

In the example below, we have deliberately left a parenthesis out of a function declaration in our shader code:

```js
const shaders = `
struct VertexOut {
 @builtin(position) position : vec4f,
 @location(0) color : vec4f
}

@vertex
fn vertex\_main(@location(0) position: vec4f,
 @location(1) color: vec4f -> VertexOut
{
 var output : VertexOut;
 output.position = position;
 output.color = color;
 return output;
}

@fragment
fn fragment\_main(fragData: VertexOut) -> @location(0) vec4f
{
 return fragData.color;
}
`;
```

When we compile the shader module, we use `getCompilationInfo()` to grab some information about the resulting error:

```js
async function init() {
  // ...

  const shaderModule = device.createShaderModule({
    code: shaders,
  });

  const shaderInfo = await shaderModule.getCompilationInfo();
  const firstMessage = shaderInfo.messages[0];

  console.log(firstMessage.lineNum); // 9
  console.log(firstMessage.message); // "expected ')' for function declaration"
  console.log(firstMessage.type); // "error"

  // ...
}
```

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

| Specification |
| --- |
| WebGPU # dom-gpushadermodule-getcompilationinfo |

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

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

See also
--------

* The WebGPU API


PromiseRejectionEvent: reason property - Web APIs

PromiseRejectionEvent: reason property
======================================

 The `PromiseRejectionEvent` **`reason`** read-only
 property is any JavaScript value or `Object` which provides the reason
 passed into `Promise.reject()`. This in theory provides information about
 why the promise was rejected.

Value
-----

 A value or object which provides information you can use to understand why the promise
 was rejected. This could be anything from an error code to an object with text, links,
 and whatever else you might wish to include.

Examples
--------

```js
window.onunhandledrejection = (e) => {
  console.log(e.reason);
};
```

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

| Specification |
| --- |
| HTML Standard # dom-promiserejectionevent-reason |

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

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

See also
--------

* `Promise`
* `PromiseRejectionEvent`
* `rejectionhandled`
* `unhandledrejection`


PromiseRejectionEvent: PromiseRejectionEvent() constructor - Web APIs

PromiseRejectionEvent: PromiseRejectionEvent() constructor
==========================================================

 The **`PromiseRejectionEvent()`**
 constructor returns a new `PromiseRejectionEvent` object, which
 represents events fired when a JavaScript `Promise` is rejected.

 With promise rejection events, it becomes possible to detect and report promises which
 fail and whose failures go unnoticed. It also becomes easier to write a global handler
 for errors.

 There are two types of `PromiseRejectionEvent`:
 `unhandledrejection` is sent by the JavaScript runtime when a promise is
 rejected but the rejection goes unhandled. A `rejectionhandled`event is
 emitted if a promise is rejected but the rejection is caught by a rejection handler.

Syntax
------

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

### Parameters

`type`

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

`options`

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

`promise`

The `Promise` that was rejected.

`reason`

 Any value or `Object` which represents the reason the promise was
 rejected. This can be anything from a numeric error code to an error
 string to an object which contains detailed information
 describing the situation resulting in the promise being rejected.

### Return value

A new `PromiseRejectionEvent` object configured as specified by the parameters.

Examples
--------

 This example creates a new `unhandledrejection` event for the promise
 `myPromise` with the reason being the string "My house is on fire". The
 `reason` could just as easily be a number, or even an object with detailed
 information including the home address, how serious the fire is, and the phone number of
 an emergency contact who should be notified.

```js
let myRejectionEvent = new PromiseRejectionEvent("unhandledrejection", {
  promise: myPromise,
  reason: "My house is on fire",
});
```

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

| Specification |
| --- |
| HTML Standard # unhandled-promise-rejections:dom-event-constructor |

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

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

See also
--------

* Using promises
* `Promise`
* `PromiseRejectionEvent`


PromiseRejectionEvent: promise property - Web APIs

PromiseRejectionEvent: promise property
=======================================

 The `PromiseRejectionEvent` interface's
 **`promise`** read-only property indicates the JavaScript
 `Promise` which was rejected. You can examine the event's
 `PromiseRejectionEvent.reason` property to learn why the promise was
 rejected.

Value
-----

 The JavaScript `Promise` which was rejected, and whose rejection went
 unhandled.

Examples
--------

 This example listens for unhandled promises and, if the
 `reason` is an object with a
 `code` field containing the text "Module not ready", it sets up an idle
 callback that will retry the task that failed to execute correctly.

`event.preventDefault()` is called to indicate that the promise has now
 been handled.

```js
window.onunhandledrejection = (event) => {
  if (event.reason?.code === "Module not ready") {
    requestIdleCallback((deadline) => {
      loadModule(event.reason.moduleName).then(performStartup);
    });
    event.preventDefault();
  }
};
```

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

| Specification |
| --- |
| HTML Standard # dom-promiserejectionevent-promise |

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

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

See also
--------

* Promise rejection events
* `Promise`
* `PromiseRejectionEvent`
* `rejectionhandled`
* `unhandledrejection`


ServiceWorkerContainer: getRegistration() method - Web APIs

ServiceWorkerContainer: getRegistration() method
================================================

 The **`getRegistration()`** method of the
 `ServiceWorkerContainer` interface gets a
 `ServiceWorkerRegistration` object whose scope URL matches the provided
 client URL. The method returns a `Promise` that resolves to
 a `ServiceWorkerRegistration` or `undefined`.

Syntax
------

```js
getRegistration()
getRegistration(clientURL)
```

### Parameters

`clientURL` Optional

The registration whose scope matches this URL will be returned. Relative URLs are resolved with the current client as the base. If this parameter is not provided, the current client's URL will be used by default.

### Return value

 A `Promise` that resolves to a `ServiceWorkerRegistration`
 object or `undefined`.

Examples
--------

```js
navigator.serviceWorker.getRegistration("/app").then((registration) => {
  if (registration) {
    document.querySelector("#status").textContent =
      "ServiceWorkerRegistration found.";
  }
});
```

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

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

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

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


ServiceWorkerContainer: controller property - Web APIs

ServiceWorkerContainer: controller property
===========================================

 The **`controller`** read-only
 property of the `ServiceWorkerContainer` interface returns a
 `ServiceWorker` object if its state is `activating` or
 `activated` (the same object returned by
 `ServiceWorkerRegistration.active`). This property returns
 `null` if the request is a force refresh (*Shift* + refresh) or if
 there is no active worker.

Value
-----

A `ServiceWorker` object.

Examples
--------

```js
if ("serviceWorker" in navigator) {
  // Do a one-off check to see if a service worker's in control.
  if (navigator.serviceWorker.controller) {
    console.log(
      `This page is currently controlled by: ${navigator.serviceWorker.controller}`,
    );
  } else {
    console.log("This page is not currently controlled by a service worker.");
  }
} else {
  console.log("Service workers are not supported.");
}
```

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

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

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

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


ServiceWorkerContainer: message event - Web APIs

ServiceWorkerContainer: message event
=====================================

The **`message`** event is used in a page controlled by a service worker to receive messages from the service worker.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A `MessageEvent`. Inherits from `Event`.

Event

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

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

`MessageEvent.data` Read only

The data sent by the message emitter.

`MessageEvent.origin` Read only

A string representing the origin of the message emitter.

`MessageEvent.lastEventId` Read only

A string representing a unique ID for the event.

`MessageEvent.source` Read only

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

`MessageEvent.ports` Read only

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

Examples
--------

In this example the service worker get the client's ID from a `fetch` event and then sends it a message using `Client.postMessage`:

```js
// service-worker.js
async function messageClient(clientId) {
  const client = await clients.get(clientId);
  client.postMessage("Hi client!");
}

addEventListener("fetch", (event) => {
  messageClient(event.clientId);
  event.respondWith(() => {
    // …
  });
});
```

The client can receive the message by listening to the `message` event:

```js
// main.js
navigator.serviceWorker.addEventListener("message", (message) => {
  console.log(message);
});
```

Alternatively, the client can receive the message with the `onmessage` event handler:

```js
// main.js
navigator.serviceWorker.onmessage = (message) => {
  console.log(message);
};
```

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

| Specification |
| --- |
| Service Workers # dom-serviceworkercontainer-onmessage |

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


ServiceWorkerContainer: register() method - Web APIs

ServiceWorkerContainer: register() method
=========================================

 The **`register()`** method of the
 `ServiceWorkerContainer` interface creates or updates a
 `ServiceWorkerRegistration` for the given `scriptURL`.

 If successful, a service worker registration ties the provided script URL to a
 *scope*, which is subsequently used for navigation matching. You can call this
 method unconditionally from the controlled page. I.e., you don't need to first check
 whether there's an active registration.

 There is frequent confusion surrounding the meaning and use of *scope*. Since a
 service worker can't have a scope broader than its own location, only use the
 `scope` option when you need a scope that is narrower than the default.

Syntax
------

```js
register(scriptURL)
register(scriptURL, options)
```

### Parameters

`scriptURL`

 The URL of the service worker script. The registered service worker file needs to
 have a valid JavaScript MIME type.

`options` Optional

An object containing registration options. Currently available options are:

`scope`

 A string representing a URL that defines a
 service worker's registration scope; that is, what range of URLs a service worker
 can control. This is usually a relative URL. It is relative to the base URL of the
 application. By default, the `scope` value for a service worker
 registration is set to the directory where the service worker script is located.
 See the Examples section for more information on how it
 works.

`type`

 A string
 specifying the type of worker to create. Valid values are:

`'classic'`

The loaded service worker is in a standard script. This is the default.

`'module'`

 The loaded service worker is in an
 ES module
 and the import statement is available on
 worker contexts. For ES module compatibility info, see the browser compatibility data table for the `ServiceWorker` interface.

`updateViaCache`

A string indicating how the HTTP cache is used for service worker scripts resources during updates. Note: This only refers to the service worker script and its imports, not other resources fetched by these scripts.

`'all'`

The HTTP cache will be queried for the main script, and all imported scripts. If no fresh entry is found in the HTTP cache, then the scripts are fetched from the network.

`'imports'`

The HTTP cache will be queried for imports, but the main script will always be updated from the network. If no fresh entry is found in the HTTP cache for the imports, they're fetched from the network.

`'none'`

The HTTP cache will not be used for the main script or its imports. All service worker script resources will be updated from the network.

### Return value

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

Examples
--------

 The examples described here should be taken together to get a better understanding of
 how service workers scope applies to a page.

 The following example uses the default value of `scope` (by omitting it).
 The service worker code in this case, if
 included in `example.com/index.html`, will
 control `example.com/index.html`, as well as pages underneath it, like
 `example.com/product/description.html`.

```js
if ("serviceWorker" in navigator) {
  // Register a service worker hosted at the root of the
  // site using the default scope.
  navigator.serviceWorker.register("/sw.js").then(
    (registration) => {
      console.log("Service worker registration succeeded:", registration);
    },
    (error) => {
      console.error(`Service worker registration failed: ${error}`);
    },
  );
} else {
  console.error("Service workers are not supported.");
}
```

 The following code, if included in `example.com/index.html`, at the root of
 a site, would apply to exactly the same pages as the example above. Remember the scope,
 when included, uses the page's location as its base.

 Alternatively, if this code were included in a page at
 `example.com/product/description.html`, with the JavaScript file residing
 at `example.com/product/sw.js`, then the service worker would only apply to
 resources under `example.com/product`.

```js
if ("serviceWorker" in navigator) {
  // declaring scope manually
  navigator.serviceWorker.register("/sw.js", { scope: "./" }).then(
    (registration) => {
      console.log("Service worker registration succeeded:", registration);
    },
    (error) => {
      console.error(`Service worker registration failed: ${error}`);
    },
  );
} else {
  console.error("Service workers are not supported.");
}
```

 There is frequent confusion surrounding the meaning and use of *scope*. Since a
 service worker can't have a scope broader than its own location, only use the
 `scope` option when you need a scope that is narrower than the default.

 The following code, if included in `example.com/index.html`, at the root of
 a site, would only apply to resources under `example.com/product`.

```js
if ("serviceWorker" in navigator) {
  // declaring scope manually
  navigator.serviceWorker.register("/sw.js", { scope: "/product/" }).then(
    (registration) => {
      console.log("Service worker registration succeeded:", registration);
    },
    (error) => {
      console.error(`Service worker registration failed: ${error}`);
    },
  );
} else {
  console.error("Service workers are not supported.");
}
```

 However, servers can remove this restriction by setting a Service-Worker-Allowed header on the service
 worker script, and then you can specify a max scope for that service worker above the
 service worker's location.

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

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

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

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

See also
--------

* ServiceWorkerRegistration: `unregister()` method
* Service worker API
* Using service workers


ServiceWorkerContainer: error event - Web APIs

ServiceWorkerContainer: error event
===================================

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

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

The `error` event fires when an error occurs in the service worker.

Syntax
------

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

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

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

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

A generic `Event`.

Example
-------

```js
navigator.serviceWorker.onerror = (errorevent) => {
  console.error(`received error message: ${errorevent.message}`);
};
```

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

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


ServiceWorkerContainer: ready property - Web APIs

ServiceWorkerContainer: ready property
======================================

 The **`ready`** read-only property of
 the `ServiceWorkerContainer` interface provides a way of delaying code
 execution until a service worker is active. It returns a `Promise` that
 will never reject, and which waits indefinitely until
 the `ServiceWorkerRegistration` associated with the current page has
 an `active` worker. Once that
 condition is met, it resolves with
 the `ServiceWorkerRegistration`.

Value
-----

 A `Promise` that will never reject, and which may eventually resolve with a
 `ServiceWorkerRegistration`.

Examples
--------

```js
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.ready.then((registration) => {
    console.log(`A service worker is active: ${registration.active}`);

    // At this point, you can call methods that require an active
    // service worker, like registration.pushManager.subscribe()
  });
} else {
  console.error("Service workers are not supported.");
}
```

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

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

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

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


ServiceWorkerContainer: controllerchange event - Web APIs

ServiceWorkerContainer: controllerchange event
==============================================

The **`controllerchange`** event of the `ServiceWorkerContainer` interface fires when the document's associated `ServiceWorkerRegistration` acquires a new `active` worker.

Syntax
------

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

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

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

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

A generic `Event`.

Example
-------

```js
navigator.serviceWorker.addEventListener("controllerchange", () => {
  console.log("The controller of current browsing context has changed.");
});
```

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

| Specification |
| --- |
| Service Workers # dom-serviceworkercontainer-oncontrollerchange |

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

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


ServiceWorkerContainer: getRegistrations() method - Web APIs

ServiceWorkerContainer: getRegistrations() method
=================================================

 The **`getRegistrations()`** method of the
 `ServiceWorkerContainer` interface gets all
 `ServiceWorkerRegistration`s associated with a
 `ServiceWorkerContainer`, in an array. The method returns a
 `Promise` that resolves to an array of
 `ServiceWorkerRegistration`.

Syntax
------

```js
getRegistrations()
```

### Parameters

None.

### Return value

 A `Promise` that resolves to an array of
 `ServiceWorkerRegistration` objects.

Examples
--------

```js
navigator.serviceWorker.getRegistrations().then((registrations) => {
  document.querySelector("#status").textContent =
    "ServiceWorkerRegistrations found.";
});
```

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

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

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

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


ServiceWorkerContainer: messageerror event - Web APIs

ServiceWorkerContainer: messageerror event
==========================================

The **`messageerror`** event is fired to the `ServiceWorkerContainer` when an incoming message sent to the associated worker can't be deserialized.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A `MessageEvent`. Inherits from `Event`.

Event

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

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

`MessageEvent.data` Read only

The data sent by the message emitter.

`MessageEvent.origin` Read only

A string representing the origin of the message emitter.

`MessageEvent.lastEventId` Read only

A string representing a unique ID for the event.

`MessageEvent.source` Read only

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

`MessageEvent.ports` Read only

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

Examples
--------

In this example the service worker get the client's ID from a `fetch` event and then sends it a message using `Client.postMessage`:

```js
// service-worker.js
async function messageClient(clientId) {
  const client = await self.clients.get(clientId);
  client.postMessage("Hi client!");
}

self.addEventListener("fetch", (event) => {
  messageClient(event.clientId);
  event.respondWith(() => {
    // …
  });
});
```

The service worker can listen for the message deserialization error by listening to the `messageerror` event:

```js
// main.js
navigator.serviceWorker.addEventListener("messageerror", (event) => {
  console.error("Receive message from service worker failed!");
});
```

Alternatively, the script can listen for the message deserialization error using `onmessageerror`:

```js
// main.js
navigator.serviceWorker.onmessageerror = (event) => {
  console.error("Receive message from service worker failed!");
};
```

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

| Specification |
| --- |
| Service Workers # dom-serviceworkerglobalscope-onmessageerror |

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

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

See also
--------

* `message`
* `Client.postMessage()`
* Using Service Workers
* Service workers basic code example
* Using Web Workers


ServiceWorkerContainer: startMessages() method - Web APIs

ServiceWorkerContainer: startMessages() method
==============================================

 The **`startMessages()`** method of
 the `ServiceWorkerContainer` interface explicitly starts the flow of
 messages being dispatched from a service worker to pages under its control (e.g. sent
 via `Client.postMessage()`). This can be used to react to sent messages
 earlier, even before that page's content has finished loading.

Explanation
-----------

 By default, all messages sent from a page's controlling service worker to the page
 (using `Client.postMessage()`) are queued while the page is loading, and
 get dispatched once the page's HTML document has been loaded and parsed (i.e. after the
 `DOMContentLoaded` event fires). It's possible to start dispatching these
 messages earlier by calling `ServiceWorkerContainer.startMessages()`, for
 example if you've invoked a message handler using
 `EventTarget.addEventListener()` before the page has finished loading, but
 want to start processing the messages right away.

**Note:** The messages start being sent automatically when setting the
 handler directly using `onmessage`. In this you
 don't need `startMessages()`.

Syntax
------

```js
startMessages()
```

### Parameters

None.

### Return value

`undefined`.

Examples
--------

```js
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.register("/sw.js").then(() => {
    console.log("Service Worker Registered");
  });
}

// …

navigator.serviceWorker.addEventListener("message", (e) => {
  // …
});

navigator.serviceWorker.startMessages();
```

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

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

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

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


DragEvent: DragEvent() constructor - Web APIs

DragEvent: DragEvent() constructor
==================================

This constructor is used to create a synthetic `DragEvent` object.

 Although this interface has a constructor, it is not possible to create a
 useful `DataTransfer` object from script, since `DataTransfer`
 objects have a processing and security model that is coordinated by the browser during
 drag-and-drops.

 This interface inherits properties from `MouseEvent` and
 `Event`.

Syntax
------

```js
new DragEvent(type)
new DragEvent(type, dragEventInit)
```

### Parameters

`type`

A string representing the name of the event (see DragEvent event types).

`eventInitDict` Optional

An object containing the following properties:

`dataTransfer` Optional

A `DataTransfer`. Defaults to `null`.

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

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

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

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


DragEvent: dataTransfer property - Web APIs

DragEvent: dataTransfer property
================================

 The **`DragEvent.dataTransfer`** read-only property holds the drag
 operation's data (as a `DataTransfer` object).

Value
-----

A `DataTransfer` object which contains the `drag event's data`.

Examples
--------

 This example illustrates accessing the drag and drop data within the
 `dragend` event handler.

```js
function processData(d) {
  // Process the data …
}

dragTarget.addEventListener(
  "dragend",
  (ev) => {
    // Call the drag and drop data processor
    if (ev.dataTransfer !== null) processData(ev.dataTransfer);
  },
  false,
);
```

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

| Specification |
| --- |
| HTML Standard # dom-dragevent-datatransfer-dev |

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

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


AudioListener: positionX property - Web APIs

AudioListener: positionX property
=================================

The `positionX` read-only property of the `AudioListener` interface is an `AudioParam` representing the x position of the listener in 3D cartesian space.

**Note:** The parameter is *a-rate* when used with a `PannerNode` whose `PannerNode` is set to equalpower, or *k-rate* otherwise.

Value
-----

An `AudioParam`. Its default value is 0, and it can range between positive and negative infinity.

Examples
--------

See `BaseAudioContext.createPanner()` for example code.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-positionx |

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

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

See also
--------

* Using the Web Audio API


AudioListener: forwardX property - Web APIs

AudioListener: forwardX property
================================

The `forwardX` read-only property of the `AudioListener` interface is an `AudioParam` representing the x value of the direction vector defining the forward direction the listener is pointing in.

**Note:** The parameter is *a-rate* when used with a `PannerNode` whose `panningModel` is set to equalpower, or *k-rate* otherwise.

Value
-----

An `AudioParam`. Its default value is 0, and it can range between positive and negative infinity.

Examples
--------

See `BaseAudioContext.createPanner()` for example code.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-forwardx |

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

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

See also
--------

* Using the Web Audio API


AudioListener: upZ property - Web APIs

AudioListener: upZ property
===========================

The `upZ` read-only property of the `AudioListener` interface is an `AudioParam` representing the z value of the direction vector defining the up direction the listener is pointing in.

**Note:** The parameter is *a-rate* when used with a `PannerNode` whose `PannerNode` is set to equalpower, or *k-rate* otherwise.

Value
-----

An `AudioParam`. Its default value is 0, and it can range between positive and negative infinity.

Examples
--------

See `BaseAudioContext.createPanner()` for example code.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-upz |

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

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

See also
--------

* Using the Web Audio API


AudioListener: setOrientation() method - Web APIs

AudioListener: setOrientation() method
======================================

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

The `setOrientation()` method of the `AudioListener` interface defines the orientation of the listener.

It consists of two direction vectors:

* The *front vector*, defined by the three unitless parameters `x`, `y` and `z`, describes the direction of the face of the listener, that is the direction the nose of the person is pointing towards. The front vector's default value is `(0, 0, -1)`.
* The *up vector*, defined by three unitless parameters `xUp`, `yUp` and `zUp`, describes the direction of the top of the listener's head. The up vector's default value is `(0, 1, 0)`.

The two vectors must be separated by an angle of 90° — in linear analysis terms, they must be perpendicular to each other.

Syntax
------

```js
setOrientation(x, y, z, xUp, yUp, zUp)
```

### Parameters

`x`

The x value of the front vector of the listener.

`y`

The y value of the front vector of the listener.

`z`

The z value of the front vector of the listener.

`xUp`

The x value of the up vector of the listener.

`yUp`

The y value of the up vector of the listener.

`zUp`

The z value of the up vector of the listener.

### Return value

None (`undefined`).

Examples
--------

See `BaseAudioContext.createPanner()` for example code.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-setorientation |

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

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

See also
--------

* Using the Web Audio API


AudioListener: setPosition() method - Web APIs

AudioListener: setPosition() method
===================================

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

The `setPosition()` method of the `AudioListener` Interface defines the position of the listener.

The three parameters `x`, `y` and `z` are unitless and describe the listener's position in 3D space according to the right-hand Cartesian coordinate system. `PannerNode` objects use this position relative to individual audio sources for spatialization.

The default value of the position vector is `(0, 0, 0)`.

**Note:** As this method is deprecated, use the three `positionX`, `positionY`, and `positionZ` properties instead.

Syntax
------

```js
setPosition(x, y, z)
```

### Parameters

`x`

The x position of the listener in 3D space.

`y`

The y position of the listener in 3D space.

`z`

The z position of the listener in 3D space.

### Return value

None (`undefined`).

Examples
--------

See `BaseAudioContext.createPanner()` for example code.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-setposition |

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

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

See also
--------

* Using the Web Audio API


AudioListener: positionY property - Web APIs

AudioListener: positionY property
=================================

The `positionY` read-only property of the `AudioListener` interface is an `AudioParam` representing the y position of the listener in 3D cartesian space.

**Note:** The parameter is *a-rate* when used with a `PannerNode` whose `PannerNode` is set to equalpower, or *k-rate* otherwise.

Value
-----

An `AudioParam`. Its default value is 0, and it can range between positive and negative infinity.

Examples
--------

See `BaseAudioContext.createPanner()` for example code.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-positiony |

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

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

See also
--------

* Using the Web Audio API


AudioListener: forwardY property - Web APIs

AudioListener: forwardY property
================================

The `forwardY` read-only property of the `AudioListener` interface is an `AudioParam` representing the y value of the direction vector defining the forward direction the listener is pointing in.

**Note:** The parameter is *a-rate* when used with a `PannerNode` whose `panningModel` is set to equalpower, or *k-rate* otherwise.

Value
-----

An `AudioParam`. Its default value is 0, and it can range between positive and negative infinity.

Examples
--------

See BaseAudioContext.createPanner() for example code.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-forwardy |

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

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

See also
--------

* Using the Web Audio API


AudioListener: upY property - Web APIs

AudioListener: upY property
===========================

The `upY` read-only property of the `AudioListener` interface is an `AudioParam` representing the y value of the direction vector defining the up direction the listener is pointing in.

**Note:** The parameter is *a-rate* when used with a `PannerNode` whose `PannerNode` is set to equalpower, or *k-rate* otherwise.

Value
-----

An `AudioParam`. Its default value is 1, and it can range between positive and negative infinity.

Examples
--------

See `BaseAudioContext.createPanner()` for example code.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-upy |

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

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

See also
--------

* Using the Web Audio API


AudioListener: forwardZ property - Web APIs

AudioListener: forwardZ property
================================

The `forwardZ` read-only property of the `AudioListener` interface is an `AudioParam` representing the z value of the direction vector defining the forward direction the listener is pointing in.

**Note:** The parameter is *a-rate* when used with a `PannerNode` whose `panningModel` is set to equalpower, or *k-rate* otherwise.

Value
-----

An `AudioParam`. Its default value is -1, and it can range between positive and negative infinity.

Examples
--------

See `BaseAudioContext.createPanner()` for example code.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-forwardz |

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

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

See also
--------

* Using the Web Audio API


AudioListener: positionZ property - Web APIs

AudioListener: positionZ property
=================================

The `positionZ` read-only property of the `AudioListener` interface is an `AudioParam` representing the z position of the listener in 3D cartesian space.

**Note:** The parameter is *a-rate* when used with a `PannerNode` whose `PannerNode` is set to equalpower, or *k-rate* otherwise.

Value
-----

An `AudioParam`. Its default value is 0, and it can range between positive and negative infinity.

Examples
--------

See `BaseAudioContext.createPanner()` for example code.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-positionz |

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

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

See also
--------

* Using the Web Audio API


AudioListener: upX property - Web APIs

AudioListener: upX property
===========================

The `upX` read-only property of the `AudioListener` interface is an `AudioParam` representing the x value of the direction vector defining the up direction the listener is pointing in.

**Note:** The parameter is *a-rate* when used with a `PannerNode` whose `PannerNode` is set to equalpower, or *k-rate* otherwise.

Value
-----

An `AudioParam`. Its default value is 0, and it can range between positive and negative infinity.

Examples
--------

For more detailed example code see `BaseAudioContext.createPanner()`.

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

| Specification |
| --- |
| Web Audio API # dom-audiolistener-upx |

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

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

See also
--------

* Using the Web Audio API


TrustedHTML: toJSON() method - Web APIs

TrustedHTML: toJSON() method
============================

The **`toJSON()`** method of the `TrustedHTML` interface returns a JSON representation of the stored data.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A string containing a JSON representation of the stored data.

Examples
--------

The constant `escaped` is an object created via the Trusted Types policy escapeHTMLPolicy. The `toString()` method returns a string to safely insert into a document.

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

const escaped = escapeHTMLPolicy.createHTML("<img src=x onerror=alert(1)>");
console.log(escaped.toJSON());
```

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

| Specification |
| --- |
| Trusted Types # dom-trustedhtml-tojson |

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

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


TrustedHTML: toString() method - Web APIs

TrustedHTML: toString() method
==============================

The **`toString()`** method of the `TrustedHTML` interface returns a string which may safely inserted into an injection sink.

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string containing the sanitized HTML.

Examples
--------

The constant `escaped` is an object created via the Trusted Types policy escapeHTMLPolicy. The `toString()` method returns a string to safely insert into a document.

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

const escaped = escapeHTMLPolicy.createHTML("<img src=x onerror=alert(1)>");
console.log(escaped.toString());
```

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

| Specification |
| --- |
| Trusted Types # trustedhtml-stringification-behavior |

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

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


CSSUnitValue: CSSUnitValue() constructor - Web APIs

CSSUnitValue: CSSUnitValue() constructor
========================================

 The **`CSSUnitValue()`** constructor creates a
 new `CSSUnitValue` object which returns a new `CSSUnitValue`
 object which represents values that contain a single unit type. For example, "42px"
 would be represented by a `CSSNumericValue`.

Syntax
------

```js
new CSSUnitValue()
```

### Parameters

`value`

Returns a double indicating the number of units.

`unit`

Returns a string indicating the type of unit.

Examples
--------

 The following shows a method of creating a `CSSPositionValue` from
 individual `CSSUnitValue` constructors.

```js
let pos = new CSSPositionValue(
  new CSSUnitValue(5, "px"),
  new CSSUnitValue(10, "px"),
);
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssunitvalue-cssunitvalue |

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

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

See also
--------

* `CSSUnitValue.unit`
* `CSSUnitValue.value`
* Using the CSS Typed OM
* CSS Typed Object Model API


CSSUnitValue: value property - Web APIs

CSSUnitValue: value property
============================

 The **`CSSUnitValue.value`** property of the
 `CSSUnitValue` interface returns a double indicating the number of units.

Value
-----

A double.

Examples
--------

 The following creates a `CSSPositionValue` from individual
 `CSSUnitValue` constructors, then queries the
 `CSSUnitValue.value`.

```js
const pos = new CSSPositionValue(
  new CSSUnitValue(5, "px"),
  new CSSUnitValue(10, "px"),
);

console.log(pos.x.value); // 5
console.log(pos.y.value); // 10
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssunitvalue-value |

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

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

See also
--------

* `CSSUnitValue.unit`
* Using the CSS Typed OM
* CSS Typed Object Model API


CSSUnitValue: unit property - Web APIs

CSSUnitValue: unit property
===========================

 The **`CSSUnitValue.unit`** read-only property
 of the `CSSUnitValue` interface returns a string
 indicating the type of unit.

Value
-----

A string.

Examples
--------

 The following creates a `CSSPositionValue` from individual
 `CSSUnitValue` constructors, then queries the
 `CSSUnitValue.unit`.

```js
const pos = new CSSPositionValue(
  new CSSUnitValue(5, "px"),
  new CSSUnitValue(10, "em"),
);

console.log(pos.x.unit); // "px"
console.log(pos.y.unit); // "em"
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssunitvalue-unit |

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

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

See also
--------

* `CSSUnitValue.value`
* Dimensions in CSS units and values
* Using the CSS Typed OM
* CSS Typed Object Model API


GPURenderPassEncoder: setViewport() method - Web APIs

GPURenderPassEncoder: setViewport() method
==========================================

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

 The **`setViewport()`** method of the
 `GPURenderPassEncoder` interface sets the viewport used during the rasterization stage to linearly map from normalized device coordinates to viewport coordinates.

Syntax
------

```js
setViewport(x, y, width, height, minDepth, maxDepth)
```

### Parameters

`x`

A number representing the minimum X value of the viewport, in pixels.

`y`

A number representing the minimum Y value of the viewport, in pixels.

`width`

A number representing the width of the viewport, in pixels.

`height`

A number representing the height of the viewport, in pixels.

`minDepth`

A number representing the minimum depth value of the viewport.

`maxDepth`

A number representing the maximum depth value of the viewport.

**Note:** If a `setViewport()` call is not made, the default values are `(0, 0, attachment width, attachment height, 0, 1)` for each render pass.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`setViewport()`**, otherwise a `GPUValidationError` is generated and the `GPURenderPassEncoder` becomes invalid:

* `x`, `y`, `width`, and `height` are all greater than or equal to 0.
* `x` + `width` is less than or equal to the width of the render pass's render attachments (see note below).
* `y` + `height` is less than or equal to the height of the render pass's render attachments (see note below).
* `minDepth` and `maxDepth` are both inside the range 0.0–1.0 inclusive.
* `minDepth` is less than `maxDepth`.

**Note:** See the color and depth/stencil attachments specified in the descriptor of `GPUCommandEncoder.beginRenderPass()`; the width and height are based on that of the `GPUTexture` that their `view`s originate from.

Examples
--------

### Basic snippet

In a typical canvas render, the following could be used to halve the width and height of the rendered graphics:

```js
passEncoder.setViewport(0, 0, canvas.width / 2, canvas.height / 2, 0, 1);
```

### In context

In the WebGPU Samples reversedZ example, `setViewport` is used several times to set the viewport for the different render passes. Study the example code listing for the full context.

For example:

```js
// ...

colorPass.setViewport(
  (canvas.width \* m) / 2,
  0,
  canvas.width / 2,
  canvas.height,
  0,
  1,
);

// ...
```

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

| Specification |
| --- |
| WebGPU # dom-gpurenderpassencoder-setviewport |

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

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

See also
--------

* The WebGPU API


GPURenderPassEncoder: drawIndexed() method - Web APIs

GPURenderPassEncoder: drawIndexed() method
==========================================

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

 The **`drawIndexed()`** method of the
 `GPURenderPassEncoder` interface draws indexed primitives based on the vertex and index buffers provided by `setVertexBuffer()` and `setIndexBuffer()`.

Syntax
------

```js
drawIndexed(indexCount)
drawIndexed(indexCount, instanceCount)
drawIndexed(indexCount, instanceCount, firstIndex)
drawIndexed(indexCount, instanceCount, firstIndex, baseVertex)
drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance)
```

### Parameters

`indexCount`

A number defining the number of indices to draw.

`instanceCount` Optional

A number defining the number of instances to draw. If omitted, `instanceCount` defaults to 1.

`firstIndex` Optional

A number defining the offset into the index buffer, in indices, to begin drawing from. If omitted, `firstIndex` defaults to 0.

`baseVertex` Optional

A number added to each index value before indexing into the vertex buffers. If omitted, `baseVertex` defaults to 0.

`firstInstance` Optional

A number defining the first instance to draw. If omitted, `firstInstance` defaults to 0.

### Return value

None (`Undefined`).

Examples
--------

In the WebGPU Samples Shadow Mapping example, `drawIndexed()` is used in two separate render passes in each animation frame, one to populate the shadow buffer and one to draw the primary view of the scene. Study the example code listing for the full context.

```js
// ...

const commandEncoder = device.createCommandEncoder();
{
  const shadowPass = commandEncoder.beginRenderPass(shadowPassDescriptor);
  shadowPass.setPipeline(shadowPipeline);
  shadowPass.setBindGroup(0, sceneBindGroupForShadow);
  shadowPass.setBindGroup(1, modelBindGroup);
  shadowPass.setVertexBuffer(0, vertexBuffer);
  shadowPass.setIndexBuffer(indexBuffer, "uint16");
  shadowPass.drawIndexed(indexCount);

  shadowPass.end();
}
{
  const renderPass = commandEncoder.beginRenderPass(renderPassDescriptor);
  renderPass.setPipeline(pipeline);
  renderPass.setBindGroup(0, sceneBindGroupForRender);
  renderPass.setBindGroup(1, modelBindGroup);
  renderPass.setVertexBuffer(0, vertexBuffer);
  renderPass.setIndexBuffer(indexBuffer, "uint16");
  renderPass.drawIndexed(indexCount);

  renderPass.end();
}

// ...
```

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

| Specification |
| --- |
| WebGPU # dom-gpurendercommandsmixin-drawindexed |

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

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

See also
--------

* The WebGPU API


GPURenderPassEncoder: setBlendConstant() method - Web APIs

GPURenderPassEncoder: setBlendConstant() method
===============================================

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

 The **`setBlendConstant()`** method of the
 `GPURenderPassEncoder` interface sets the constant blend color and alpha values used with `"constant"` and `"one-minus-constant"` blend factors (as set in the descriptor of the `GPUDevice.createRenderPipeline()` method, in the `blend` property).

Syntax
------

```js
setBlendConstant(color)
```

### Parameters

`color`

An object or array representing the color to use when blending — the `r`, `g`, `b`, and `a` components are represented as floating point numbers between 0.0 and 1.0.

What follows is an object example:

```js
const color = { r: 0.0, g: 0.5, b: 1.0, a: 1.0 };
```

The array equivalent would look like this:

```js
const color = [0.0, 0.5, 1.0, 1.0];
```

**Note:** If a `setBlendConstant()` call is not made, the blend constant color value defaults to `(0, 0, 0, 0)` for each render pass.

### Return value

None (`Undefined`).

Examples
--------

```js
// ...

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.setBlendConstant([1.0, 0.0, 0.0, 1.0]);
passEncoder.draw(3);

passEncoder.end();

// ...
```

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

| Specification |
| --- |
| WebGPU # dom-gpurenderpassencoder-setblendconstant |

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

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

See also
--------

* The WebGPU API


GPURenderPassEncoder: endOcclusionQuery() method - Web APIs

GPURenderPassEncoder: endOcclusionQuery() method
================================================

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

 The **`endOcclusionQuery()`** method of the
 `GPURenderPassEncoder` interface ends an active occlusion query previously started with `beginOcclusionQuery()`.

Syntax
------

```js
endOcclusionQuery()
```

### Parameters

None.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`endOcclusionQuery()`**, otherwise a `GPUValidationError` is generated and the `GPURenderPassEncoder` becomes invalid:

* An occlusion query is active for this render pass (i.e. via a previous `beginOcclusionQuery()` call).
Examples
--------

```js
// ...

// Create a query set to hold the occlusion queries
const querySet = device.createQuerySet({
  type: "occlusion",
  count: 32,
});

// Render pass descriptor object, including the querySet
const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear",
      storeOp: "store",
      view: context.getCurrentTexture().createView(),
    },
  ],
  occlusionQuerySet: querySet,
};

// Begin the render pass
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

// Begin an occlusion query at index 0
passEncoder.beginOcclusionQuery(0);

// Run some rendering commands
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

// End the occlusion query
passEncoder.endOcclusionQuery();

// ...
```

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

| Specification |
| --- |
| WebGPU # dom-gpurenderpassencoder-endocclusionquery |

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

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

See also
--------

* The WebGPU API


GPURenderPassEncoder: popDebugGroup() method - Web APIs

GPURenderPassEncoder: popDebugGroup() method
============================================

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

 The **`popDebugGroup()`** method of the
 `GPURenderPassEncoder` interface ends a render pass debug group, which is begun with a `pushDebugGroup()` call.

This could be used for telemetry, or may be utilized in `GPUError` messages, browser dev tools, or other services in the future to help with debugging.

Syntax
------

```js
popDebugGroup()
```

### Parameters

None.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`popDebugGroup()`**, otherwise a `GPUValidationError` is generated and the `GPURenderPassEncoder` becomes invalid:

* The render pass encoder's debug stack is not empty (i.e. at least one render pass debug group was previously started with `pushDebugGroup()`).
Examples
--------

```js
// ...

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

passEncoder.pushDebugGroup("mygroupmarker"); // Start labeled debug group

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

passEncoder.popDebugGroup();

// ...
```

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

| Specification |
| --- |
| WebGPU # dom-gpudebugcommandsmixin-popdebuggroup |

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

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

See also
--------

* The WebGPU API