Attestation and Assertion - Web APIs

Attestation and Assertion
=========================

There are two different types of certificates used in WebAuthn for registration and authentication. They have similar names and similar purposes, but understanding the differences may be an initial point of confusion. The sections below describe attestation, which happens during registration, and assertion which happens during authentication.

Attestation
-----------

When an authenticator registers a new key pair with a service, the authenticator signs the public key with an attestation certificate. The attestation certificate is built into the authenticator during manufacturing time and is specific to a device model. That is, all "Samsung Galaxy S8" phones, manufactured at a specific time or particular manufacturing run, have the same attestation certificate.

The attestation is returned through the WebAuthn API as the AuthenticatorAttestationResponse. The attestation format contains two basic `ArrayBuffer` objects:

* **clientDataJSON** - An ArrayBuffer that contains a JSON representation of what the browser saw when being asked to authenticate.
* attestationObject - Cryptographic attestation that a newly generated keypair was created by that authenticator. This contains:
    + Authenticator data containing an `attestedCredentialData` field, which in turn contains the `credentialId` and `credentialPublicKey`. The `attestedCredentialData` is an optional field used in attestation. It is not included when used in the AuthenticatorAssertionResponse.
    + An attestation statement, which is optionally present depending on whether the relying party requests attestation. In general, relying parties aren't encouraged to request attestation, so it's more likely that this statement won't be present.

Different devices have different attestation formats. The pre-defined attestation formats in WebAuthn are:

* **Packed** - a generic attestation format that is commonly used by devices whose sole function is as a WebAuthn authenticator, such as security keys.
* **TPM** - the Trusted Platform Module (TPM) is a set of specifications from the Trusted Platform Group (TPG). This attestation format is commonly found in desktop computers and is used by Windows Hello as its preferred attestation format.
* **Android Key Attestation** - one of the features added in Android O was Android Key Attestation, which enables the Android operating system to attest to keys.
* **Android SafetyNet** -prior to Android Key Attestation, the only option for Android devices was to create Android SafetyNet attestations.
* **FIDO U2F** - security keys that implement the FIDO U2F standard use this format.
* **none** - browsers may prompt users whether they want a site to be allowed to see their attestation data and/or may remove attestation data from the authenticator's response if the `attestation` parameter in `navigator.credentials.create()` is set to `none`.

The purpose of attestation is to cryptographically prove that a newly generated key pair came from a specific device. This provides a root of trust for a newly generated key pair as well as being able to identify the attributes of a device being used (how the private key is protected; if / what kind of biometric is being used; whether a device has been certified; etc.). It should be noted that while attestation provides the capability for a root of trust, validating the root of trust is frequently not necessary. When registering an authenticator for a new account, typically a Trust On First Use (TOFU) model applies; and when adding an authenticator to an existing account, a user has already been authenticated and has established a secure session.

Assertion
---------

When a user chooses to log into a service, the server sends a challenge and the authenticator signs over it with a key pair previously registered to that service. This creates an assertion. Unlike the attestation, the format of the assertion is always the same regardless of the device being used.

The assertion is returned through the WebAuthn API as the AuthenticatorAssertionResponse. The assertion format is fairly simple as it contains four basic ArrayBuffers:

* clientDataJSON - The same as in attestation. An ArrayBuffer that contains a JSON representation of what the browser saw when being asked to authenticate.
* authenticatorData - data created and/or used by the authenticator (see also authenticator data).
* **signature** - a signature over the clientDataJSON and authenticatorData that can be verified with the public key that was created during registration.
* **userHandle** - Optional. (Nullable) A user identifier. This may be a username, or a hash of a username, etc. Used by a service to give a scope to credentials. Maximum length of 64 bytes. Older authenticators (U2F) do not support this output.

It's important to highlight that the signature for assertion uses a different key pair than attestation. An assertion is signed using the key pair for a service, which was generated during registration. An attestation is signed using the attestation private key and attestation certificate that were burned into all models of the same device. (Except in the case of self-attestation.)


Web Authentication extensions - Web APIs

Web Authentication extensions
=============================

The Web Authentication API has a system of extensions — extra functionality that can be requested during credential creation (`navigator.credentials.create()`) or authentication (`navigator.credentials.get()`) operations. This article explains how to request WebAuthn extensions, retrieve information about the responses from those requests, and the available extensions — including browser support and expected inputs and outputs.

How to use WebAuthn extensions
------------------------------

When invoking `navigator.credentials.create()` or `navigator.credentials.get()`, the `publicKey` object parameter required to initiate a WebAuthn flow can include an `extensions` property. The value of `extensions` is itself an object, the properties of which are the input values for any extensions the relying party wishes to request the use of in the method you call.

Behind the scenes, the inputs are processed by the user agent and/or the authenticator.

For example, in a `publicKey` object for a `create()` call, we might want to request the use of two extensions:

1. The `credProps` extension. Relying parties set `credProps` to request that the browser tells the relying party whether the credential is resident/discoverable after registration. This is useful when calling `create()` with `publicKey.authenticatorSelection.residentKey = "preferred"`. To request it, you also need to set `publicKey.extensions.credProps = true` when the browser makes a credential and, depending on the type of authenticator used, it will be discoverable (for example, the FIDO2 authenticator would typically make it discoverable; FIDO1/U2F security key would be non-discoverable). `credProps` is processed by the user agent only.
2. The `minPinLength` extension allows relying parties to request the authenticator's minimum PIN length. This requires `extensions.minPinLength` to be set to `true`. `minPinLength` is processed by the authenticator, with the user agent only serving to pass the input data along to it.

```js
const publicKey = {
  challenge: new Uint8Array([117, 61, 252, 231, 191, 241, ...]),
  rp: { id: "acme.com", name: "ACME Corporation" },
  user: {
    id: new Uint8Array([79, 252, 83, 72, 214, 7, 89, 26]),
    name: "jamiedoe",
    displayName: "Jamie Doe"
  },
  pubKeyCredParams: [ {type: "public-key", alg: -7} ],
  authenticatorSelection: {
    residentKey: "preferred"
  },
  extensions: {
    credProps: true,
    minPinLength: true
  }
}
```

We can then pass the `publicKey` object into a `create()` call to initiate the credential creation flow:

```js
navigator.credentials.create({ publicKey });
```

Retrieving extension request results
------------------------------------

If successful, the `create()` call will return a `Promise` that resolves with a `PublicKeyCredential` object. Once extension processing has completed, the results of the processing are communicated in the response (although not in all cases — it is possible for extensions to have no output).

```js
navigator.credentials
  .create({ publicKey })
  .then((publicKeyCred) => {
    const myClientExtResults = publicKeyCred.getClientExtensionResults();
    // myClientExtResults will contain the output of processing
    // the "credProps" extension

    const authData = publicKeyCred.response.getAuthenticatorData();
    // authData will contain authenticator data, which will include
    // authenticator extension processing results, i.e., minPinLength
  })
  .catch((err) => {
    console.error(err);
  });
```

As demonstrated by the above code snippet, there are two different places to find your output extension results:

1. You can find the results of client (user agent) extension processing by calling the `PublicKeyCredential.getClientExtensionResults()` method. This returns a `map`, with each entry being an extensions' identifier string as the key, and the output from the processing of the extension by the client as the value. In the example above, if the browser supported the `credProps` extension and it was processed correctly, the `myClientExtResults` map object would contain one entry, `"credProps"`, with a value of `{ rk: true }`. This would verify that the created credential is indeed discoverable.
2. You can find the results of authenticator extension processing in the authenticator data for the operation:
    * In the case of `PublicKeyCredential`s returned from successful `create()` calls, this can be returned via a call to `publicKeyCredential.response.getAuthenticatorData()`.
    * In the case of `PublicKeyCredential`s returned from successful `get()` calls, this can be found in the `publicKeyCredential.response.authenticatorData` property.Authenticator data takes the form of an `ArrayBuffer` with a consistent structure — see authenticator data. The authenticator extension results data is always found in a section at the end, as a CBOR map representing the results. See `AuthenticatorAssertionResponse.authenticatorData` for a detailed description of the complete authenticator data structure.
 Back to our example, if the relying party is authorized to receive the `minPinLength` value, the authenticator data would contain a representation of it in the following form: `"minPinLength": uint`.
Available extensions
--------------------

The extensions below do not represent an exhaustive list of all the extensions available. We have elected to document extensions that we know to be standardized and supported by at least one rendering engine.

### `appid`

* Usable in: Authentication (`get()`)
* Processed by: User agent
* Specification: FIDO AppID Extension (appid)

Allows a relying party to request an assertion for a credential previously registered using the legacy FIDO U2F JavaScript API, avoiding the hassle of re-registering the credential. The `appid` is that API's equivalent to the `rpId` in WebAuthn (although bear in mind that `appid`s are in the form of URLs, whereas `rpId`s are in the form of domains).

#### Input

The `publicKey`'s `extensions` property must contain an `appid` property, the value of which is the application identifier used in the legacy API. For example:

```js
extensions: {
  appid: "https://accounts.example.com";
}
```

You must also list the FIDO U2F credential IDs in the `publicKey`'s `allowCredentials` property, for example:

```js
allowCredentials: {
  [
    id: arrayBuffer, // needs to contain decoded binary form of id
    transports: ["nfc", "usb"]
    type: "public-key"
  ]
}
```

#### Output

Outputs `appid: true` if the `appid` was successfully used for the assertion, or `appid: false` otherwise.

### `appidExclude`

* Usable in: Registration (`create()`)
* Processed by: User agent
* Specification: FIDO AppID Exclusion Extension (appidExclude)

Allows a relying party to exclude authenticators containing specified credentials previously registered using the legacy FIDO U2F JavaScript API during registration. This is required because by default the contents of the `excludeCredentials` field are assumed to be WebAuthn credentials. When using this extension, you can include legacy FIDO U2F credentials inside `excludeCredentials`, and they will be recognized as such.

#### Input

The `publicKey`'s `extensions` property must contain an `appidExclude` property, the value of which is the identifier of the relying party requesting to exclude authenticators by legacy FIDO U2F credentials. For example:

```js
extensions: {
  appidExclude: "https://accounts.example.com";
}
```

You can then list FIDO U2F credentials in the `publicKey`'s `excludeCredentials` property, for example:

```js
excludeCredentials: {
  [
    id: arrayBuffer, // needs to contain decoded binary form of id
    transports: ["nfc", "usb"]
    type: "public-key"
  ]
}
```

#### Output

Outputs `appidExclude: true` if the extension was acted upon, or `appidExclude: false` otherwise.

### `credProps`

* Usable in: Registration (`create()`)
* Processed by: User agent
* Specification: Credential Properties Extension (credProps)

Allows a relying party to request additional information/properties about the credential that was created. This is currently only useful when calling `create()` with `publicKey.authenticatorSelection.residentKey = "preferred"`; it requests information on whether the created credential is discoverable.

#### Input

The `publicKey`'s `extensions` property must contain a `credProps` property with a value of `true`:

```js
extensions: {
  credProps: true;
}
```

You must also set `authenticatorSelection.requireResidentKey` to `true`, which indicates that a resident key is required.

```js
authenticatorSelection: {
  requireResidentKey: true;
}
```

#### Output

Outputs the following if the registered `PublicKeyCredential` is a client-side discoverable credential:

```js
credProps: {
  rk: true;
}
```

If `rk` is set to `false` in the output, the credential is a server-side credential. If `rk` is not present in the output, then it is not known whether the credential is client-side discoverable or server-side.

### `credProtect`

* Usable in: Registration (`create()`)
* Processed by: Authenticator
* Specification: Credential Protection (credProtect)

Allows a relying party to specify a minimum credential protection policy when creating a credential.

#### Input

The `publicKey`'s `extensions` property must contain a `credentialProtectionPolicy` property specifying the protection level of the credential to be created, and a boolean `enforceCredentialProtectionPolicy` property specifying whether the `create()` call should fail rather than creating a credential that does not conform to the specified policy:

```js
extensions: {
  credentialProtectionPolicy: "userVerificationOptional",
  enforceCredentialProtectionPolicy: true
}
```

The available `credentialProtectionPolicy` values are as follows:

`"userVerificationOptional"`
Experimental

User verification is optional. The equivalent `credProtect` value sent to the authenticator for processing is `0x01`.

`"userVerificationOptionalWithCredentialIDList"`

User verification is optional only if the credential is discoverable (i.e., it is client-side discoverable). The equivalent `credProtect` value sent to the authenticator for processing is `0x02`.

`"userVerificationRequired"`

User verification is always required. The equivalent `credProtect` value sent to the authenticator for processing is `0x03`.

**Note:**
 Chromium will default to `userVerificationOptionalWithCredentialIDList` or `userVerificationRequired`, depending on the type of request:

* Chromium will request a protection level of `userVerificationOptionalWithCredentialIDList` when creating a credential if `residentKey` is set to `preferred` or `required`. (Setting `requireResidentKey` is treated the same as required.) This ensures that simple physical possession of a security key does not allow the presence of a discoverable credential for a given `rpId` to be queried.
* Additionally, if `residentKey` is `required` and `userVerification` is preferred, the protection level will be increased to `userVerificationRequired`. This ensures that physical possession of a security key does not allow sign-in to a site that doesn't require user verification. (This is not complete protection; sites should still carefully consider the security of their users.)
* If the site requests an explicit `credProtect` level, that will override these defaults. These defaults never cause the protection level to be lower than the security key's default if that is higher.

Suppose the `enforceCredentialProtectionPolicy` value is `true`. In that case, the `create()` call will fail if the policy cannot be adhered to (for example, it requires user verification, but the authenticator does not support user verification). If it is `false`, the system will make the best attempt to create a credential that conforms to the policy, but it will still create one that conforms as closely as it can if this is not possible.

#### Output

If the `create()` call is successful, the authenticator data will contain a representation of the `credProtect` value representing the set policy in the following form:

```js
{ "credProtect": 0x01 }
```

### `largeBlob`

* Usable in: Registration (`create()`) and authentication (`get()`)
* Processed by: User agent
* Specification: Large blob storage extension (largeBlob)

Allows a relying party to store blobs associated with a credential on the authenticator — for example, it may wish to directly store certificates rather than run a centralized authentication service.

#### Input

During a `create()` call, the `publicKey`'s `extensions` property must contain a `largeBlob` property with the following object structure:

```js
extensions: {
  largeBlob: {
    support: "required";
  }
}
```

The `support` property's value is a string, which can be one of the following:

* `"preferred"`: The credential will be created with an authenticator that can store blobs if possible, but it will still create one if not. The output' supported' property reports the authenticator's ability to store blobs.
* `"required"`: The credential will be created with an authenticator to store blobs. The `create()` call will fail if this is impossible.

During a `get()` call, the `publicKey`'s `extensions` property must contain a `largeBlob` property with one of two sub-properties — `read` or `write` (`get()` fails if both are present):

The `read` property is a boolean. A value of `true` indicates that the relying party would like to fetch a previously-written blob associated with the asserted credential:

```js
extensions: {
  largeBlob: {
    read: true;
  }
}
```

The `write` property takes as a value an `ArrayBuffer`, `TypedArray`, or `DataView` representing a blob that the relying party wants to store alongside an existing credential:

```js
extensions: {
  largeBlob: {
    write: arrayBuffer;
  }
}
```

**Note:** For a write authentication operation to be successful, `publicKey.allowCredentials` must contain only a single element representing the credential you want the blob stored alongside.

#### Output

A successful `create()` call provides the following extension output if the registered credential is capable of storing blobs:

```js
largeBlob: {
  supported: true; // false if it cannot store blobs
}
```

A `get()` read call makes the blob available as an `ArrayBuffer` in the extension output if successful:

```js
largeBlob: {
  blob: arrayBuffer;
}
```

**Note:** if unsuccessful, the `largeBlob` object will be returned, but `blob` will not be present.

A `get()` write call indicates whether the write operation was successful with a `written` boolean value in the extension output. A `true` value means it was written successfully to the associated authenticator, and `false` means it was unsuccessful.

```js
largeBlob: {
  written: true;
}
```

### `minPinLength`

* Usable in: Registration (`create()`)
* Processed by: Authenticator
* Specification: Minimum PIN Length Extension (minPinLength)

Allows relying parties to request the authenticator's minimum PIN length.

#### Input

The `publicKey`'s `extensions` property must contain a `minPinLength` property with a value of `true`:

```js
extensions: {
  minPinLength: true;
}
```

#### Output

If the relying party is authorized to receive the `minPinLength` value (if its `rpId` is present on the authenticator's authorized relying party list), the authenticator data will contain a representation of it in the following form:

```js
{"minPinLength": uint}
```

If the relying party is not authorized, the extension is ignored, and no `"minPinLength"` output value is provided.

### `payment`

* Usable in: Registration (`create()`)
* Processed by: User agent
* Specification: Secure Payment Confirmation

Allows a relying party to request the creation of a WebAuthn credential that may be used – by both the Relying Party and other parties – with Secure Payment Confirmation; see Using Secure Payment Confirmation.

#### Input

The inputs for the `payment` extension are defined in the AuthenticationExtensionsPaymentInputs dictionary

`isPayment`

A boolean that indicates that the extension is active.

`rpID`

The Relying Party id of the credential(s) being used. Only used at authentication time; not registration.

`topOrigin`

The origin of the top-level frame. Only used at authentication time; not registration.

`payeeName`

The payee name, if present, that was displayed to the user. Only used at authentication time; not registration.

`payeeOrigin`

The payee origin, if present, that was displayed to the user. Only used at authentication time; not registration.

`total`

The transaction amount that was displayed to the user. Only used at authentication time; not registration. The total is of type PaymentCurrencyAmount.

`instrument`

The instrument details that were displayed to the user. Only used at authentication time; not registration. The instrument is of type PaymentCredentialInstrument.

#### Output

None

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

There are a number of places that WebAuthn extensions are specified. IANA's WebAuthn Extension Identifiers provides a registry of all extensions, but bear in mind that some may be deprecated.

Places where extensions are specified:

* Web Authentication Level 3, Section 10: Defined extensions
* Client to Authenticator Protocol (CTAP) 2, Section 12: Defined Extensions
Browser compatibility
---------------------

The compatibility data for WebAuthn extensions has been broken down into two tables — extensions that can be used during credential registration (`create()`), and extensions that can be used during authentication (`get()`). Some extensions are usable during both operations.

### api.CredentialsContainer.create.publicKey\_option.extensions

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

### api.CredentialsContainer.get.publicKey\_option.extensions

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


Authenticator data - Web APIs

Authenticator data
==================

The authenticator data structure contains information from the authenticator about the processing of a credential creation or authentication request — such as the Relying Party ID Hash (`rpIdHash`), a signature counter, test of user presence, user verification flags, and any extensions processed by the authenticator. This page explains what is contained in the data structure.

Accessing authenticator data
----------------------------

Authenticator data is made available to the browser as an `ArrayBuffer`, and can be accessed in multiple ways. The two most convenient are:

* In the `PublicKeyCredential.response.authenticatorData` property made available on the `PublicKeyCredential` returned from a successful `navigator.credentials.create()` (credential creation) call.
* Via the `PublicKeyCredential.response.getAuthenticatorData()` method made available on the `PublicKeyCredential` returned from a successful `navigator.credentials.get()` (authentication) call.
Data structure
--------------

An authenticator data `ArrayBuffer` is at least 37 bytes in length, and contains the following fields:

**rpIdHash** (32 bytes)

The SHA-256 hash of the Relying Party ID that the credential is scoped to. The server will ensure that this hash matches the SHA256 hash of its own relying party ID in order to prevent phishing or other man-in-the-middle attacks.

**flags** (1 bytes)

A bitfield that indicates various attributes that were asserted by the authenticator. The bits are as follows, where Bit 0 is the least significant bit and all bits not specifically mentioned below are "reserved for future use":

* Bit 0, User Presence (UP): If set (i.e., to `1`), the authenticator validated that the user was present through some Test of User Presence (TUP), such as touching a button on the authenticator.
* Bit 2, User Verification (UV): If set, the authenticator verified the actual user through a biometric, PIN, or other method.
* Bit 3, Backup Eligibility (BE): If set, the public key credential source used by the authenticator to generate an assertion is backup-eligible. This means that it can be backed up in some fashion (for example via cloud or local network sync) and as such may become present on an authenticator other than its generating authenticator. Backup-eligible credential sources are therefore also known as multi-device credentials.
* Bit 4, Backup State (BS): If set, the public key credential source is currently backed up (see Bit 3 for context).
* Bit 6, Attested Credential Data (AT): If set, the attested credential data will immediately follow the first 37 bytes of this `authenticatorData`.
* Bit 7, Extension Data (ED): If set, extension data is present. Extension data will follow attested credential data if it is present, or will immediately follow the first 37 bytes of the `authenticatorData` if no attested credential data is present.

**signCount** (4 bytes)

A signature counter, if supported by the authenticator (set to 0 otherwise). Servers may optionally use this counter to detect authenticator cloning.

**attestedCredentialData** (variable length)

The credential that was created. This is only present during a `navigator.credentials.create()` call. This is a sequence of bytes with the following format:

* **AAGUID** (16 bytes): The Authenticator Attestation Globally Unique Identifier, a unique number that identifies the model of the authenticator (not the specific instance of the authenticator). A relying party can use this to find out the characteristics of the authenticator by looking up its metadata statement via the FIDO metadata service. This is relevant in certain situations such as enterprise deployments or where regulatory requirements dictate a certain type of authenticator be used; it should be ignored otherwise.
* ***credentialIdLength*** (2 bytes): The length of the credential ID that immediately follows these bytes.
* ***credentialId*** (variable length): A unique identifier for this credential so that it can be requested for future authentications. The credential is "*credentialIdLength*" bytes long.
* **credentialPublicKey** (variable length): A COSE-encoded public key. This public key will be stored on the server associated with a user's account and be used for future authentications. Relying parties can retrieve the DER-encoded form of it without parsing the COSE-encoded authenticator data via the `AuthenticatorAttestationResponse.getPublicKey()` method.

**extensions** (variable length)

An optional CBOR map containing the response outputs from extensions processed by the authenticator

Extensions are optional and different browsers may recognize different extensions. Processing extensions is always optional for the browser: if a browser does not recognize a given extension, it will just ignore it. For information on using extensions, and which ones are supported by which browsers, see Web Authentication extensions.

**Note:** The authenticator data only contains the results from extensions processed by the authenticator. The results from extensions processed by the browser (client) can be accessed via `PublicKeyCredential.getClientExtensionResults`.

See also
--------

Authenticator data definition in the WebAuthn specification


EXT_disjoint_timer_query: deleteQueryEXT() method - Web APIs

EXT\_disjoint\_timer\_query: deleteQueryEXT() method
====================================================

 The **`EXT_disjoint_timer_query.deleteQueryEXT()`** method of
 the WebGL API deletes a given
 `WebGLQuery` object.

Syntax
------

```js
deleteQueryEXT(query)
```

### Parameters

`query`

A `WebGLQuery` object to delete.

### Return value

None (`undefined`).

Examples
--------

```js
const ext = gl.getExtension("EXT\_disjoint\_timer\_query");
const query = ext.createQueryEXT();

// …

ext.deleteQueryEXT(query);
```

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

| Specification |
| --- |
| WebGL EXT\_disjoint\_timer\_query Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLQuery`
* `EXT_disjoint_timer_query`


EXT_disjoint_timer_query: beginQueryEXT() method - Web APIs

EXT\_disjoint\_timer\_query: beginQueryEXT() method
===================================================

 The **`EXT_disjoint_timer_query.beginQueryEXT()`** method of
 the WebGL API starts a timer query.

Syntax
------

```js
beginQueryEXT(target, query)
```

### Parameters

`target`

 A `GLenum` specifying the target of the time query. Must be
 `ext.TIME_ELAPSED_EXT`.

`query`

A `WebGLQuery` object for which to start the time querying.

### Return value

None (`undefined`).

Examples
--------

```js
const ext = gl.getExtension("EXT\_disjoint\_timer\_query");
const query = ext.createQueryEXT();
ext.beginQueryEXT(ext.TIME\_ELAPSED\_EXT, query);

// …
```

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

| Specification |
| --- |
| WebGL EXT\_disjoint\_timer\_query Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLQuery`
* `EXT_disjoint_timer_query`


EXT_disjoint_timer_query: queryCounterEXT() method - Web APIs

EXT\_disjoint\_timer\_query: queryCounterEXT() method
=====================================================

 The **`EXT_disjoint_timer_query.queryCounterEXT()`** method of
 the WebGL API records the current time into
 the corresponding query object.

Syntax
------

```js
queryCounterEXT(query, target)
```

### Parameters

`query`

A `WebGLQuery` object for which to record the current time.

`target`

 A `GLenum` specifying the target of the time query. Must be
 `ext.TIMESTAMP_EXT`.

### Return value

None (`undefined`).

Examples
--------

```js
const ext = gl.getExtension("EXT\_disjoint\_timer\_query");
const startQuery = ext.createQueryEXT();
const endQuery = ext.createQueryEXT();
ext.queryCounterEXT(startQuery, ext.TIMESTAMP\_EXT);

// …

ext.queryCounterEXT(endQuery, ext.TIMESTAMP\_EXT);
```

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

| Specification |
| --- |
| WebGL EXT\_disjoint\_timer\_query Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLQuery`
* `EXT_disjoint_timer_query`


EXT_disjoint_timer_query: endQueryEXT() method - Web APIs

EXT\_disjoint\_timer\_query: endQueryEXT() method
=================================================

 The **`EXT_disjoint_timer_query.endQueryEXT()`** method of the
 WebGL API ends a timer query.

Syntax
------

```js
endQueryEXT(target)
```

### Parameters

`target`

 A `GLenum` specifying the target of the time query. Must be
 `ext.TIME_ELAPSED_EXT`.

### Return value

None (`undefined`).

Examples
--------

```js
const ext = gl.getExtension("EXT\_disjoint\_timer\_query");
const query = ext.createQueryEXT();
ext.beginQueryEXT(ext.TIME\_ELAPSED\_EXT, query);

// …

ext.endQueryEXT(ext.TIME\_ELAPSED\_EXT);
```

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

| Specification |
| --- |
| WebGL EXT\_disjoint\_timer\_query Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLQuery`
* `EXT_disjoint_timer_query`


EXT_disjoint_timer_query: createQueryEXT() method - Web APIs

EXT\_disjoint\_timer\_query: createQueryEXT() method
====================================================

 The **`EXT_disjoint_timer_query.createQueryEXT()`** method of
 the WebGL API creates and initializes
 `WebGLQuery` objects, which track the time needed to fully complete
 a set of GL commands.

Syntax
------

```js
createQueryEXT()
```

### Parameters

None.

### Return value

A `WebGLQuery` object.

Examples
--------

```js
const ext = gl.getExtension("EXT\_disjoint\_timer\_query");
const query = ext.createQueryExt();
```

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

| Specification |
| --- |
| WebGL EXT\_disjoint\_timer\_query Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLQuery`
* `EXT_disjoint_timer_query`


EXT_disjoint_timer_query: getQueryEXT() method - Web APIs

EXT\_disjoint\_timer\_query: getQueryEXT() method
=================================================

 The **`EXT_disjoint_timer_query.getQueryEXT()`** method of the
 WebGL API returns information about a query
 target.

Syntax
------

```js
getQueryEXT(target, pname)
```

### Parameters

`target`

 A `GLenum` specifying the target of the time query. Must be
 `ext.TIMESTAMP_EXT` or `ext.TIME_ELAPSED_EXT`.

`pname`

 A `GLenum` specifying which information to return. Must be
 `ext.CURRENT_QUERY_EXT` or `ext.QUERY_COUNTER_BITS_EXT`.

### Return value

Depends on `pname`:

* If `pname` is `ext.CURRENT_QUERY_EXT`: A
 `WebGLQuery` object, which is the currently active query for the
 given target.
* If `pname` is `ext.QUERY_COUNTER_BITS_EXT`: A
 `GLint` indicating the number of bits used to hold the query result for
 the given target.
Examples
--------

```js
const ext = gl.getExtension("EXT\_disjoint\_timer\_query");
const startQuery = ext.createQueryEXT();
ext.queryCounterEXT(startQuery, ext.TIMESTAMP\_EXT);

const currentQuery = ext.getQueryEXT(ext.TIMESTAMP\_EXT, ext.CURRENT\_QUERY\_EXT);
```

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

| Specification |
| --- |
| WebGL EXT\_disjoint\_timer\_query Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLQuery`
* `EXT_disjoint_timer_query`


EXT_disjoint_timer_query: getQueryObjectEXT() method - Web APIs

EXT\_disjoint\_timer\_query: getQueryObjectEXT() method
=======================================================

 The **`EXT_disjoint_timer_query.getQueryObjectEXT()`** method
 of the WebGL API returns the state of a
 query object.

Syntax
------

```js
getQueryObjectEXT(query, pname)
```

### Parameters

`query`

A `WebGLQuery` object from which to return information.

`pname`

 A `GLenum` specifying which information to return. Must be
 `ext.QUERY_RESULT_EXT` or `ext.QUERY_RESULT_AVAILABLE_EXT`.

### Return value

Depends on `pname`:

* If `pname` is `ext.QUERY_RESULT_EXT`: A
 `GLuint64EXT` containing the query result.
* If `pname` is `ext.QUERY_RESULT_AVAILABLE_EXT`: A
 `GLboolean` indicating whether or not a query result is available.
Examples
--------

```js
const ext = gl.getExtension("EXT\_disjoint\_timer\_query");
const query = ext.createQueryEXT();
ext.beginQueryEXT(ext.TIME\_ELAPSED\_EXT, query);

// Draw
ext.endQueryEXT(ext.TIME\_ELAPSED\_EXT);

// At some point in the future, after returning control to the browser
const available = ext.getQueryObjectEXT(query, ext.QUERY\_RESULT\_AVAILABLE\_EXT);
const disjoint = gl.getParameter(ext.GPU\_DISJOINT\_EXT);

if (available && !disjoint) {
  // See how much time the rendering of the object took in nanoseconds.
  const timeElapsed = ext.getQueryObjectEXT(query, ext.QUERY\_RESULT\_EXT);
}
```

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

| Specification |
| --- |
| WebGL EXT\_disjoint\_timer\_query Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLQuery`
* `EXT_disjoint_timer_query`


EXT_disjoint_timer_query: isQueryEXT() method - Web APIs

EXT\_disjoint\_timer\_query: isQueryEXT() method
================================================

 The **`EXT_disjoint_timer_query.isQueryEXT()`** method of the
 WebGL API returns `true` if the
 passed object is a `WebGLQuery` object.

Syntax
------

```js
isQueryEXT(query)
```

### Parameters

`query`

A `WebGLQuery` object to test.

### Return value

 A `GLboolean` indicating whether the given object is a
 `WebGLQuery` object (`true`) or not
 (`false`).

Examples
--------

```js
const ext = gl.getExtension("EXT\_disjoint\_timer\_query");
const query = ext.createQueryEXT();

// …

ext.isQueryEXT(query);
```

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

| Specification |
| --- |
| WebGL EXT\_disjoint\_timer\_query Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLQuery`
* `EXT_disjoint_timer_query`


RTCRtpTransceiver: mid property - Web APIs

RTCRtpTransceiver: mid property
===============================

 The read-only `RTCRtpTransceiver` interface's
 **`mid`** property specifies the negotiated media ID
 (`mid`) which the local and remote peers have agreed upon to uniquely
 identify the stream's pairing of sender and receiver.

Value
-----

 A string which uniquely identifies the pairing of source and
 destination of the transceiver's stream. Its value is taken from the media ID of the SDP
 m-line. This value is `null` if negotiation has not completed.

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

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

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

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

See also
--------

* Introduction to the Real-time Transport Protocol (RTP)


RTCRtpTransceiver: direction property - Web APIs

RTCRtpTransceiver: direction property
=====================================

The `RTCRtpTransceiver` property **`direction`** is a string that indicates the transceiver's *preferred* directionality.

 The directionality indicates whether the transceiver will offer to send and/or receive RTP data, or whether it is inactive or stopped (terminated).
 When setting the transceiver's direction, the value is not applied immediately.
 The *current* direction is indicated by the `currentDirection` property.

Value
-----

A string with one of the following values:

`"sendrecv"`

Transceiver offers to send and receive RTP data:

* `RTCRtpSender`: Offers to send RTP data, and will do so if the remote peer accepts the connection and at least one of the sender's encodings is active.
* `RTCRtpReceiver`: Offers to receive RTP data, and does so if the remote peer accepts.

`"sendonly"`

Transceiver offers to send but not receive RTP data:

* `RTCRtpSender`: Offers to send RTP data, and will do so if the remote peer accepts the connection and at least one of the sender's encodings is active.
* `RTCRtpReceiver`: Does *not* offer to receive RTP data and will not do so.

`"recvonly"`

Transceiver offers to receive but not set RTP data:

* `RTCRtpSender`: Does *not* offer to send RTP data, and will not do so.
* `RTCRtpReceiver`: Offers to receive RTP data, and will do so if the remote peer offers.

`"inactive"`

Transceiver is inactive:

* `RTCRtpSender`: Does *not* offer to send RTP data, and will not do so.
* `RTCRtpReceiver`: Does *not* offer to receive RTP data and will not do so.

`"stopped"`

 This is the terminal state of the transceiver.
 The transceiver is stopped and will not send or receive RTP data or offer to do so.
 Setting this value when the transceiver is not already stopped raises a `TypeError`.

* `RTCRtpSender`: Does *not* offer to send RTP data, and will not do so.
* `RTCRtpReceiver`: Does *not* offer to receive RTP data and will not do so.

### Exceptions

When setting the value of `direction`, the following exception can occur:

`InvalidStateError` `DOMException`

The receiver's `RTCPeerConnection` is closed or the `RTCRtpReceiver` is stopped.

`TypeError`

The value is being set to `stopped` when the current value is anything other than `stopped`.

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

The **`direction`** property can be used to set or get the transceiver's *preferred* directionality.

 Updating the directionality does not take effect immediately.
 If the new value of `direction` is different from the existing value, renegotiation of the connection is required, so a `negotiationneeded` event is sent to the `RTCPeerConnection`.
 A `direction` value (other than `stopped`) is then used by `RTCPeerConnection.createOffer()` or `RTCPeerConnection.createAnswer()` in order to generate the SDP message created those methods.
 For example, if the `direction` is specified as `"sendrecv"`, the corresponding SDP a-line indicates the directionality:
```

a=sendrecv
```

The new directionality takes effect once the negotiation process is completed and the new session description is successfully applied.

The transceiver's *current* direction is indicated by the `currentDirection` property.

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

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

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

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

See also
--------

* `RTCRtpTransceiver.currentDirection`


RTCRtpTransceiver: stop() method - Web APIs

RTCRtpTransceiver: stop() method
================================

 The **`stop()`** method in the `RTCRtpTransceiver` interface permanently stops the transceiver by stopping both the associated `RTCRtpSender` and
 `RTCRtpReceiver`.

Syntax
------

```js
stop()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the `RTCPeerConnection`, of which the transceiver is a member, is closed.

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

 When you call `stop()` on a transceiver, the sender immediately stops sending media and each of its RTP streams are closed using the RTCP `"BYE"` message.
 The receiver then stops receiving media; the receiver's `track` is stopped, and the transceiver's `direction` is changed to `stopped`.
 Renegotiation is triggered by sending a `negotiationneeded` event to the transceiver's `RTCPeerConnection`, so that the connection can adapt to the change.

 The method does nothing if the transceiver is already stopped.
 You can check whether it has stopped by comparing `currentDirection` to `"stopped"`.

**Note:** Earlier versions of the specification used the deprecated `stopped`
Deprecated
 property to indicate if the transceiver has stopped.

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

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

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

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

See also
--------

* WebRTC API
* Introduction to the Real-time Transport Protocol (RTP)
* `MediaStreamTrack`


RTCRtpTransceiver: stopped property - Web APIs

RTCRtpTransceiver: stopped property
===================================

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

**Note:** Instead of using this deprecated property, compare `currentDirection` to `"stopped"`.

The read-only **`stopped`** property on the `RTCRtpTransceiver` interface indicates whether or not the transceiver's associated sender and receiver have both been stopped.

The transceiver is stopped if the `stop()` method has been called or if a change to either the local or the remote description has caused the transceiver to be stopped for some reason.

Value
-----

 A Boolean value which is `true` if the transceiver's
 `sender` will no longer send data, and its
 `receiver` will no longer receive data. If
 either or both are still at work, the result is `false`.

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

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

This feature is not part of any current specification. It is no longer on track to become a standard.

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

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

See also
--------

* WebRTC API
* Introduction to the Real-time Transport Protocol (RTP)


RTCRtpTransceiver: sender property - Web APIs

RTCRtpTransceiver: sender property
==================================

 The read-only **`sender`** property
 of WebRTC's `RTCRtpTransceiver` interface indicates the
 `RTCRtpSender` responsible for encoding and sending outgoing media data
 for the transceiver's stream.

Value
-----

 An `RTCRtpSender` object used to encode and send media whose media ID
 matches the current value of `mid`.

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

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

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

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

See also
--------

* Introduction to the Real-time Transport Protocol (RTP)
* `RTCRtpSender`


RTCRtpTransceiver: currentDirection property - Web APIs

RTCRtpTransceiver: currentDirection property
============================================

The read-only `RTCRtpTransceiver` property **`currentDirection`** is a string which indicates the current negotiated directionality of the transceiver.

The directionality indicates whether the transceiver will offer to send and/or receive RTP data, or whether it is inactive or stopped and won't send or receive data.

 The transceiver's preferred directionality can be set and read using the `direction` property.
 Changing the `direction` triggers a renegotiation, which may eventually result in the `currentDirection` also changing.

Value
-----

The value is initially `null`, prior to negotiation using an offer/answer.

After negotiation the value is a string with one of the following values:

`"sendrecv"`

Transceiver offers to send and receive RTP data:

* `RTCRtpSender`: Offers to send RTP data, and will do so if the remote peer accepts the connection and at least one of the sender's encodings is active.
* `RTCRtpReceiver`: Offers to receive RTP data, and does so if the remote peer accepts.

`"sendonly"`

Transceiver offers to send but not receive RTP data:

* `RTCRtpSender`: Offers to send RTP data, and will do so if the remote peer accepts the connection and at least one of the sender's encodings is active.
* `RTCRtpReceiver`: Does *not* offer to receive RTP data and will not do so.

`"recvonly"`

Transceiver offers to receive but not set RTP data:

* `RTCRtpSender`: Does *not* offer to send RTP data, and will not do so.
* `RTCRtpReceiver`: Offers to receive RTP data, and will do so if the remote peer offers.

`"inactive"`

Transceiver is inactive:

* `RTCRtpSender`: Does *not* offer to send RTP data, and will not do so.
* `RTCRtpReceiver`: Does *not* offer to receive RTP data and will not do so.

`"stopped"`

 This is the terminal state of the transceiver.
 The transceiver is stopped and will not send or receive RTP data or offer to do so.

* `RTCRtpSender`: Does *not* offer to send RTP data, and will not do so.
* `RTCRtpReceiver`: Does *not* offer to receive RTP data and will not do so.

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

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

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

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

See also
--------

* `RTCRtpTransceiver.direction`


RTCRtpTransceiver: setCodecPreferences() method - Web APIs

RTCRtpTransceiver: setCodecPreferences() method
===============================================

The `RTCRtpTransceiver` method **`setCodecPreferences()`** configures the transceiver's preferred list of codecs.

The specified set of codecs will be used for all future connections that include this transceiver until this method is called again.

When preparing to open an `RTCPeerConnection`, you can change the codec parameters from the user agent's default configuration by calling `setCodecParameters()` *before* calling either `RTCPeerConnection.createOffer()` or `createAnswer()`.

A guide to codecs supported by WebRTC—and each codec's positive and negative characteristics—can be found in Codecs used by WebRTC.

Syntax
------

```js
setCodecPreferences(codecs)
```

### Parameters

`codecs`

 An array of objects, each providing the parameters for one of the transceiver's supported media codecs, ordered by preference.
 If `codecs` is empty, the codec configurations are all returned to the user agent's defaults.

**Note:** Any codecs not included in `codecs` will not be considered during the process of negotiating a connection.
 This lets you prevent the use of codecs you don't wish to use.

Each codec object in the array has the following properties:

`channels` Optional

A positive integer value indicating the maximum number of channels supported by the codec; for example, a codec that supports only mono sound would have a value of 1; stereo codecs would have a 2, etc.

`clockRate`

 A positive integer specifying the codec's clock rate in Hertz (Hz).
 The IANA maintains a list of codecs and their parameters, including their clock rates.

`mimeType`

 A string indicating the codec's MIME media type and subtype.
 The MIME type strings used by RTP differ from those used elsewhere.
 See RFC 3555, section 4 for the complete IANA registry of these types.
 Also see Codecs used by WebRTC for details about potential codecs that might be referenced here.

`sdpFmtpLine` Optional

 A string giving the format specific parameters field from the `a=fmtp` line in the SDP which corresponds to the codec, if such a line exists.
 If there is no parameters field, this property is left out.

### Return value

None (`undefined`).

### Exceptions

`InvalidAccessError` `DOMException`

The `codecs` list includes one or more codecs which are not supported by the transceiver.

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

### Getting a list of supported codecs

 You can only include in the `codecs` list codecs which the transceiver actually supports.
 That means that either the associated `RTCRtpSender` or the `RTCRtpReceiver` needs to support every codec in the list.
 If any unsupported codecs are listed, the browser will throw an `InvalidAccessError` exception when you call this method.

 A good approach to setting codec preferences is to first get the list of codecs that are actually supported, then modify that list to match what you want.
 Pass the altered list into `setCodecPreferences()` to specify your preferences.

To determine which codecs are supported by the transceiver, call the sender's `getCapabilities()` and the receiver's `getCapabilities()` methods and get the `codecs` array from the results of each.

The following code snippet demonstrates how to get both the list of codecs supported by the transceiver's `RTCRtpSender` and `RTCRtpReceiver`.

```js
const availSendCodecs = transceiver.sender.getCapabilities("video").codecs;
const availReceiveCodecs = transceiver.receiver.getCapabilities("video").codecs;
```

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

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

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

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

See also
--------

* WebRTC API
* Codecs used by WebRTC
* Introduction to the Real-time Transport Protocol (RTP)
* Web media technologies


RTCRtpTransceiver: receiver property - Web APIs

RTCRtpTransceiver: receiver property
====================================

 The read-only **`receiver`** property
 of WebRTC's `RTCRtpTransceiver` interface indicates the
 `RTCRtpReceiver` responsible for receiving and decoding incoming media
 data for the transceiver's stream.

Value
-----

 An `RTCRtpReceiver` object which is responsible for receiving and decoding
 incoming media data whose media ID is the same as the current value of
 `mid`.

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

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

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

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

See also
--------

* Introduction to the Real-time Transport Protocol (RTP)
* `RTCRtpReceiver`


WorkerLocation: toString() method - Web APIs

WorkerLocation: toString() method
=================================

The **`toString()`** stringifier method of a `WorkerLocation` object returns a string containing the serialized `URL` for the worker's location. It is a synonym for `WorkerLocation.href`.

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
// In a Web worker, on the page https://developer.mozilla.org/en-US/docs/Web
const result = location.toString(); // Returns 'https://developer.mozilla.org/en-US/docs/Web'
```

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

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

See also
--------

* The `WorkerLocation` interface it belongs to.


WorkerLocation: hash property - Web APIs

WorkerLocation: hash property
=============================

The **`hash`** property of a `WorkerLocation` object returns the `hash` part of the worker's location.

Value
-----

A string.

Examples
--------

```js
// In a Web worker, on the page https://developer.mozilla.org/en-US/docs/Web/API/WorkerLocation/hash#examples
const result = location.hash; // Returns '#examples'
```

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

| Specification |
| --- |
| HTML Standard # dom-workerlocation-hash |

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

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

See also
--------

* The `WorkerLocation` interface it belongs to.


WorkerLocation: pathname property - Web APIs

WorkerLocation: pathname property
=================================

The **`pathname`** property of a `WorkerLocation` object returns the `pathname` part of the worker's location.

Value
-----

A string.

Examples
--------

```js
// In a Web worker, on the page https://developer.mozilla.org/en-US/docs/Web
const result = location.pathname; // Returns '/en-US/docs/Web'
```

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

| Specification |
| --- |
| HTML Standard # dom-workerlocation-pathname |

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

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

See also
--------

* The `WorkerLocation` interface it belongs to.


WorkerLocation: protocol property - Web APIs

WorkerLocation: protocol property
=================================

The **`protocol`** property of a `WorkerLocation` object returns the `protocol` part of the worker's location.

Value
-----

A string.

Examples
--------

```js
// In a Web worker, on the page https://developer.mozilla.org/en-US/docs/Web
const result = location.protocol; // Returns 'https:'
```

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

| Specification |
| --- |
| HTML Standard # dom-workerlocation-protocol |

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

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

See also
--------

* The `WorkerLocation` interface it belongs to.


WorkerLocation: origin property - Web APIs

WorkerLocation: origin property
===============================

The **`origin`** property of a `WorkerLocation` object returns the worker's `origin`.

Value
-----

A string.

Examples
--------

```js
// On this page, returns the origin
const result = self.location.origin; // Returns:'https://developer.mozilla.org:443'
```

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

| Specification |
| --- |
| HTML Standard # dom-workerlocation-origin |

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

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

See also
--------

* The `WorkerLocation` interface it belongs to.


WorkerLocation: host property - Web APIs

WorkerLocation: host property
=============================

The **`host`** property of a `WorkerLocation` object returns the `host` part of the worker's location.

Value
-----

A string.

Examples
--------

```js
// In a Web worker, on the page http://localhost:8080/
const result = location.host; // Returns 'localhost:8080'
```

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

| Specification |
| --- |
| HTML Standard # dom-workerlocation-host |

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

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

See also
--------

* The `WorkerLocation` interface it belongs to.


WorkerLocation: port property - Web APIs

WorkerLocation: port property
=============================

The **`port`** property of a `WorkerLocation` object returns the `port` part of the worker's location.

Value
-----

A string.

Examples
--------

```js
// In a Web worker, on the page http://localhost:8080/
const result = location.port; // Returns '8080'
```

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

| Specification |
| --- |
| HTML Standard # dom-workerlocation-port |

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

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

See also
--------

* The `WorkerLocation` interface it belongs to.


WorkerLocation: hostname property - Web APIs

WorkerLocation: hostname property
=================================

The **`hostname`** property of a `WorkerLocation` object returns the `hostname` part of the worker's location.

Value
-----

A string.

Examples
--------

```js
// In a Web worker, on the page http://localhost:8080/
const result = location.hostname; // Returns 'localhost'
```

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

| Specification |
| --- |
| HTML Standard # dom-workerlocation-hostname |

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

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

See also
--------

* The `WorkerLocation` interface it belongs to.


WorkerLocation: search property - Web APIs

WorkerLocation: search property
===============================

The **`search`** property of a `WorkerLocation` object returns the `search` part of the worker's location.

Value
-----

A string.

Examples
--------

```js
// In a Web worker, on the page https://developer.mozilla.org/en-US/docs/Web?t=67
const result = location.search; // Returns:'?t=67'
```

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

| Specification |
| --- |
| HTML Standard # dom-workerlocation-search |

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

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

See also
--------

* The `WorkerLocation` interface it belongs to.


WorkerLocation: href property - Web APIs

WorkerLocation: href property
=============================

The **`href`** property of a `WorkerLocation` object returns a string containing the serialized `URL` for the worker's location.

Value
-----

A string.

Examples
--------

```js
// In a Web worker, on the page https://developer.mozilla.org/en-US/docs/Web
const result = location.href; // Returns 'https://developer.mozilla.org/en-US/docs/Web'
```

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

| Specification |
| --- |
| HTML Standard # dom-workerlocation-href |

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

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

See also
--------

* The `WorkerLocation` interface it belongs to.


ClipboardEvent: ClipboardEvent() constructor - Web APIs

ClipboardEvent: ClipboardEvent() constructor
============================================

The **`ClipboardEvent()`** constructor returns a new `ClipboardEvent`, representing an event providing information related to modification of the clipboard, that is `cut`, `copy`, and `paste` events.

Syntax
------

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

### Parameters

`type`

 A string with the name of the type of the `ClipboardEvent`.
 It is case-sensitive and browsers set it to `copy`, `cut`, or `paste`.

`options` Optional

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

`clipboardData` Optional

A `DataTransfer` object containing the data concerned by the clipboard event. It defaults to `null`.

`dataType`
Non-standard
 Optional

A string containing the MIME-type of the data contained in the `data` argument. It defaults to `""`.

`data`
Non-standard
 Optional

A string containing the data concerned by the clipboard event. It defaults to `""`.

### Return value

A new `ClipboardEvent` object.

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

| Specification |
| --- |
| Clipboard API and events # dom-clipboardevent-clipboardevent |

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

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

See also
--------

* Copy-related events: `copy`, `cut`, `paste`
* The `ClipboardEvent` interface it belongs to.
* Clipboard API


ClipboardEvent: clipboardData property - Web APIs

ClipboardEvent: clipboardData property
======================================

The **`clipboardData`** property of the `ClipboardEvent` interface holds a `DataTransfer` object, which can be used to:

* specify what data should be put into the clipboard from the `cut` and `copy` event handlers, typically with a `setData(format, data)` call;
* obtain the data to be pasted from the `paste` event handler, typically with a `getData(format)` call.

See the `cut`, `copy`, and `paste` events documentation for more information.

Value
-----

A `DataTransfer` object.

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

| Specification |
| --- |
| Clipboard API and events # clipboardevent-clipboarddata |

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

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

See also
--------

* Copy-related events: `copy`, `cut`, `paste`
* The `ClipboardEvent` interface it belongs to.
* Clipboard API


GPUUncapturedErrorEvent: GPUUncapturedErrorEvent() constructor - Web APIs

GPUUncapturedErrorEvent: GPUUncapturedErrorEvent() constructor
==============================================================

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

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

Syntax
------

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

### Parameters

`type`

An enumerated value specifying the type of error. Possible values are:

`"internal"`

The error is a `GPUInternalError`.

`"out-of-memory"`

The error is a `GPUOutOfMemoryError`.

`"validation"`

The error is a `GPUValidationError`.

`options`

An object, which can contain the following properties:

`error`

A `GPUError` object instance providing access to the details of the error.

Examples
--------

A developer would not manually use the constructor to create a `GPUUncapturedErrorEvent` object. The user agent uses this constructor to create an appropriate object when the `GPUDevice` `uncapturederror` event fires to allow capturing of an unexpected error.

See the main `GPUUncapturedErrorEvent` page for an example.

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

| Specification |
| --- |
| WebGPU # dom-gpuuncapturederrorevent-gpuuncapturederrorevent |

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

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

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices


GPUUncapturedErrorEvent: error property - Web APIs

GPUUncapturedErrorEvent: error property
=======================================

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

 The **`error`** read-only property of the
 `GPUUncapturedErrorEvent` interface is a `GPUError` object instance providing access to the details of the error.

Value
-----

A `GPUError` object instance.

Examples
--------

See the main `GPUUncapturedErrorEvent` page for an example.

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

| Specification |
| --- |
| WebGPU # dom-gpuuncapturederroreventinit-error |

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

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

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices


HTMLLabelElement: form property - Web APIs

HTMLLabelElement: form property
===============================

 The read-only **`HTMLLabelElement.form`** property returns an
 `HTMLFormElement` object which represents the form of which the label's
 associated control is a part, or null if there is either no associated control, or if
 that control isn't in a form.

This property is just a shortcut for `HTMLLabelElement.control.form`.

Value
-----

 An `HTMLFormElement` which represents the form with which the label's
 `control` is associated. If
 `control` is `null` (meaning the
 label isn't associated with a control), or if the control isn't part of a form, this
 property returns `null`.

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

| Specification |
| --- |
| HTML Standard # dom-label-form-dev |

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

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

See also
--------

* `HTMLLabelElement`
* `HTMLElement`
* `<label>`
* HTML forms guide


HTMLLabelElement: htmlFor property - Web APIs

HTMLLabelElement: htmlFor property
==================================

 The **`HTMLLabelElement.htmlFor`** property reflects the value
 of the `for` content property. That means that this
 script-accessible property is used to set and read the value of the content property
 `for`, which is the ID of the label's associated control element.

Value
-----

 A string which contains the ID string of the element which is
 associated with the control.

**Note:** If this property has a value, the `HTMLLabelElement.control` property
 must refer to the same control.

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

| Specification |
| --- |
| HTML Standard # dom-label-htmlfor |

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

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

See also
--------

* `HTMLLabelElement`
* `HTMLLabelElement.control`
* `HTMLElement`
* `<label>`
* HTML forms guide


HTMLLabelElement: control property - Web APIs

HTMLLabelElement: control property
==================================

 The read-only **`HTMLLabelElement.control`** property returns a
 reference to the control (in the form of an object of type `HTMLElement` or
 one of its derivatives) with which the `<label>` element is associated,
 or `null` if the label isn't associated with a control.

Value
-----

 An `HTMLElement` derived object representing the control with which the
 `<label>` is associated, or `null` if the label stands alone.

**Note:** If this property has a value and `HTMLLabelElement.htmlFor` has a value,
 the `HTMLLabelElement.htmlFor` property must refer to the same control.

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

| Specification |
| --- |
| HTML Standard # dom-label-control-dev |

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

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

See also
--------

* `HTMLLabelElement`
* `HTMLElement`
* `<label>`
* HTML forms guide


RTCRtpSender: dtmf property - Web APIs

RTCRtpSender: dtmf property
===========================

 The read-only **`dtmf`** property on the
 **`RTCRtpSender`** interface returns a
 `RTCDTMFSender` object which can be used to send DTMF tones
 over the `RTCPeerConnection`. See Using DTMF for details on how to
 make use of the returned `RTCDTMFSender` object.

Value
-----

 An `RTCDTMFSender` which can be used to send DTMF over the RTP session, or
 `null` if the track being carried by the RTP session or the
 `RTCPeerConnection` as a whole doesn't support DTMF.

**Note:** Only audio tracks can support DTMF, and typically only one audio track per
 `RTCPeerConnection` will have an associated `RTCDTMFSender`

Example
-------

tbd

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

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

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

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

See also
--------

* WebRTC API
* Using DTMF with WebRTC
* `RTCPeerConnection`
* `RTCDTMFSender`
* `RTCRtpSender`


RTCRtpSender: track property - Web APIs

RTCRtpSender: track property
============================

 The **`track`** read-only property of
 the `RTCRtpSender` interface returns the `MediaStreamTrack`
 which is being handled by the `RTCRtpSender`.

Value
-----

 A `MediaStreamTrack` object representing the media associated with the
 `RTCRtpSender`. If no track is associated with the sender, this value is
 `null`, in which case the sender transmits nothing.

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

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

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

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


RTCRtpSender: transform property - Web APIs

RTCRtpSender: transform property
================================

 The **`transform`** property of the `RTCRtpSender` object is used to insert a transform stream (`TransformStream`) running in a worker thread into the sender pipeline.
 This allows stream transforms to be applied to encoded video and audio frames after they are output by a codec, and before they are sent.

 The transform that is to be added is defined using an `RTCRtpScriptTransform` and its associated `Worker`.
 If the transform is set synchronously immediately after creating the `RTCRtpSender` it will receive the first full frame generated by the sender's encoder.

### Value

A `RTCRtpScriptTransform`, or `null` if the sender has no associated transform stream.

Example
-------

 This example shows how you might stream video from a user's webcam over WebRTC, adding a WebRTC encoded transform to modify the outgoing streams.
 Note that this is part of a larger example in the guide topic Using WebRTC Encoded Transforms.

 The code assumes that there is an `RTCPeerConnection` called `peerConnection` that is already connected to a remote peer.
 It first gets a `MediaStreamTrack`, using `getUserMedia()` to get a video `MediaStream` from a media device, and then the `MediaStream.getTracks()` method to get the first `MediaStreamTrack` in the stream.

 The track is added to the peer connection using `addTrack()`.
 This returns a new `RTCRtpSender` that will be used to send it.

```js
const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true });
const [track] = mediaStream.getTracks();
const videoSender = peerConnection.addTrack(track, mediaStream);
```

 The code above sets up the connection and starts sending the track.
 To add a transform stream into the pipeline we need to construct an `RTCRtpScriptTransform` and assign it to the sender's `transform` property.
 As the transform is constructed immediately after creation of the `RTCRtpSender`, it will receive the first frame generated by the sender's encoder, before it is sent.

```js
const worker = new Worker("worker.js");
videoSender.transform = new RTCRtpScriptTransform(worker, {
  name: "senderTransform",
});
```

 Note that you can add the transform at any time.
 However by adding it immediately after calling `addTrack()` the transform will get the first encoded frame that is sent.

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

| Specification |
| --- |
| WebRTC Encoded Transform # dom-rtcrtpsender-transform |

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

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

See also
--------

* Using WebRTC Encoded Transforms
* `RTCRtpReceiver.transform`


RTCRtpSender: setParameters() method - Web APIs

RTCRtpSender: setParameters() method
====================================

The **`setParameters()`** method of the `RTCRtpSender` interface applies changes the configuration of sender's `track`, which is the `MediaStreamTrack` for which the `RTCRtpSender` is responsible.

In other words, `setParameters()` updates the configuration of the RTP transmission as well as the encoding configuration for a specific outgoing media track on the WebRTC connection.

Syntax
------

```js
setParameters(parameters)
```

### Parameters

`parameters`

 A parameters object previously obtained by calling the same sender's `getParameters()` method, with the desired changes to the sender's configuration parameters.
 These parameters include potential codecs that could be use for encoding the sender's `track`.
 The available parameters are:

`encodings`

 An array of objects, each specifying the parameters for a single codec that could be used to encode the track's media.
 The properties of the objects include:

`active`

Setting this value `true` (the default) causes this encoding to be sent, while `false` stops it from being sent and used (but does not cause the SSRC to be removed).

`dtx`
Deprecated

Non-standard

 Only used for an `RTCRtpSender` whose `kind` is `audio`, this property indicates whether or not to use discontinuous transmission (a feature by which a phone is turned off or the microphone muted automatically in the absence of voice activity).
 The value is taken either `enabled` or `disabled`.

`maxBitrate`

 A positive integer indicating the maximum number of bits per second that the user agent is allowed to grant to tracks encoded with this encoding.
 Other parameters may further constrain the bit rate, such as the value of `maxFramerate`, or the bandwidth available for the transport or physical network.

The value is computed using the standard Transport Independent Application Specific Maximum (TIAS) bandwidth as defined by RFC 3890, section 6.2.2; this is the maximum bandwidth needed without considering protocol overheads from IP, TCP or UDP, and so forth.

 Note that the bitrate can be achieved in a number of ways, depending on the media and encoding.
 For example, for video a low bit rate might be achieved by dropping frames (a bitrate of zero might allow just one frame to be sent), while for audio the track might have to stop playing if the bitrate is too low for it to be sent.

`maxFramerate`

A value specifying the maximum number of frames per second to allow for this encoding.

`priority`

 A string indicating the priority of the `RTCRtpSender`, which may determine how the user agent allocates bandwidth between senders.
 Allowed values are `very-low`, `low` (default), `medium`, `high`.

`rid`

 A string which, if set, specifies an *RTP stream ID* (*RID*) to be sent using the RID header extension.
 This parameter cannot be modified using `setParameters()`.
 Its value can only be set when the transceiver is first created.

`scaleResolutionDownBy`

 Only used for senders whose track's `kind` is `video`, this is a floating-point value specifying a factor by which to scale down the video during encoding.
 The default value, 1.0, means that the video will be encoded at its original size.
 A value of 2.0 scales the video frames down by a factor of 2 in each dimension, resulting in a video 1/4 the size of the original.
 The value must not be less than 1.0 (attempting to scale the video to a larger size will throw a `RangeError`).

`transactionId`

 A string containing a unique ID.
 This ID is set in the previous `getParameters()` call, and ensures that the parameters originated from a previous call to `getParameters()`.

`codecs`

 An array of `RTCRtpCodecParameters` objects describing the set of codecs from which the sender will choose.
 This parameter cannot be changed.

`headerExtensions`

 An array of zero or more RTP header extensions, each identifying an extension supported by the sender.
 Header extensions are described in RFC 3550, section 5.3.1.
 This parameter cannot be changed.

`rtcp`

 An `RTCRtcpParameters` object providing the configuration parameters used for RTCP on the sender.
 This parameter cannot be changed.

`degradationPreference`
Deprecated

 Specifies the preferred way the WebRTC layer should handle optimizing bandwidth against quality in constrained-bandwidth situations.
 The possible values are `maintain-framerate`, `maintain-resolution`, or `balanced`.
 The default value is `balanced`.

### Return value

A `Promise` that resolves when the `RTCRtpSender.track` property is updated with the given parameters.

### Exceptions

If an error occurs, the returned promise is rejected with the appropriate exception from the list below.

`InvalidModificationError` `DOMException`

Returned if one of the following problems is detected:

* The number of encodings specified in the `parameters` object's `encodings` property does not match the number of encodings currently listed for the `RTCRtpSender`.
 You cannot change the number of encoding options after the sender has been created.
* The order of the specified `encodings` has changed from the current list's order.
* An attempt has been made to alter a property that cannot be changed after the sender is first created.

`InvalidStateError` `DOMException`

Returned if the transceiver, of which the `RTCRtpSender` is a part, is not running or has no parameters to set.

`OperationError` `DOMException`

Returned if an error occurs that does not match the ones specified here.

`RangeError`

Returned if the value specified for `scaleResolutionDownBy` option is less than 1.0 — which would result in scaling up rather than down, which is not allowed; or if one or more of the specified `encodings` `maxFramerate` values is less than 0.0.

In addition, if a WebRTC error occurs while configuring or accessing the media, an `RTCError` is thrown with its `errorDetail` set to `hardware-encoder-error`.

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

 It's important to keep in mind that you can't create the `parameters` object yourself and expect it to work.
 Instead, you *must* first call `getParameters()`, modify the received parameters object, then pass that object into `setParameters()`.
 WebRTC uses the parameters object's `transactionId` property to ensure that when you set parameters, your changes are based on the most recent parameters rather than an out of date configuration.

Examples
--------

One use case for `setParameters()` is to try to reduce network bandwidth used in constrained environments by altering the resolution and/or bit rate of the media being transmitted by the `RTCRtpSender`.

 Currently, some browsers have limitations on their implementations that may cause issues.
 For that reason, two examples are given here.
 The first shows how to use `setParameters()` when all browsers fully support the parameters being used, while the second example demonstrates workarounds to help solve limitations in browsers with incomplete support for the `maxBitrate` and `scaleResolutionDownBy` parameters.

### By the specification

 Once all browsers implement the spec fully, this implementation of `setVideoParams()` will do the job. This demonstrates how everything *should* work.
 You should probably use the second example, below, for now.
 But this is a clearer demonstration of the basic concept of first fetching the parameters, then altering them, then setting them.

```js
async function setVideoParams(sender, height, bitrate) {
  const scaleRatio = sender.track.getSettings().height / height;
  const params = sender.getParameters();

  params.encodings[0].scaleResolutionDownBy = Math.max(scaleRatio, 1);
  params.encodings[0].maxBitrate = bitrate;
  await sender.setParameters(params);
}
```

 In calling this function, you specify a sender, as well as the height you wish to scale the sender's video to, as well as a maximum bitrate to permit the sender to transmit.
 A scaling factor for the size of the video, `scaleRatio`, is computed.
 Then the sender's current parameters are fetched using `getParameters()`.

The parameters are then altered by changing the first `encodings` object's `scaleResolutionDownBy` and `maxBitrate` to the calculated scaling factor and the specified maximum `bitrate`.

The changed parameters are then saved by calling the sender's `setParameters()` method.

### Currently compatible implementation

 As mentioned above, the previous example shows how things are meant to work.
 Unfortunately, there are implementation issues preventing this in many browsers right now.
 For that reason, if you want to be compatible with iPhone and other devices running Safari, and with Firefox, use code more like this:

```js
async function setVideoParams(sender, height, bitrate) {
  const scaleRatio = sender.track.getSettings().height / height;
  const params = sender.getParameters();

  // If encodings is null, create it

  if (!params.encodings) {
    params.encodings = [{}];
  }

  params.encodings[0].scaleResolutionDownBy = Math.max(scaleRatio, 1);
  params.encodings[0].maxBitrate = bitrate;
  await sender.setParameters(params);

  // If the newly changed value of scaleResolutionDownBy is 1,
  // use applyConstraints() to be sure the height is constrained,
  // since scaleResolutionDownBy may not be implemented

  if (sender.getParameters().encodings[0].scaleResolutionDownBy === 1) {
    await sender.track.applyConstraints({ height });
  }
}
```

The differences here:

* If `encodings` is `null`, we create it, in order to ensure that we can then set the parameters successfully without crashing.
* If, after setting the parameters, the value of `scaleResolutionDownBy` is still 1, we call the sender's track's `applyConstraints()` method to constrain the track's height to `height`.
 This compensates for an unimplemented `scaleResolutionDownBy` (as is the case in Safari as of this writing).

This code will cleanly fall back and work the normal way if the browser fully implements the used features.

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

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

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

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

See also
--------

* WebRTC API
* Codecs used by WebRTC
* Web media technologies


RTCRtpSender: getCapabilities() static method - Web APIs

RTCRtpSender: getCapabilities() static method
=============================================

The *static method* **`RTCRtpSender.getCapabilities()`** returns an object describing the codec and header extension capabilities supported by the `RTCRtpSender`.

You can, similarly, obtain the capabilities of `RTCRtpReceiver` objects on the device by calling the static function `RTCRtpReceiver.getCapabilities()`.

Syntax
------

```js
RTCRtpSender.getCapabilities(kind)
```

### Parameters

`kind`

 A string indicating the type of media for which the browser's send capabilities are requested.
 The supported media kinds are: `audio` and `video`.

### Return value

 A new object that indicates what capabilities the browser has for sending the specified media kind over an `RTCPeerConnection`.
 If the browser doesn't have any support for the given media `kind`, the returned value is `null`.

The returned object has the following properties:

`codecs`

An array of objects, each describing the basic capabilities of a single media codec supported by the `RTCRtpSender`.

**Note:** The array contains special entries that represent the underlying components of the transport — these may be ignored if you're only interested in the actual codecs used for the media itself.
 These are described below in the section The codecs array.

Each codec object has the following properties:

`channels` Optional

A positive integer value indicating the maximum number of channels supported by the codec; for example, a codec that supports only mono sound would have a value of 1; stereo codecs would have a 2, etc.

`clockRate`

 A positive integer specifying the codec's clock rate in Hertz (Hz).
 The IANA maintains a list of codecs and their parameters, including their clock rates.

`mimeType`

 A string indicating the codec's MIME media type and subtype.
 The MIME type strings used by RTP differ from those used elsewhere.
 See RFC 3555, section 4 for the complete IANA registry of these types.
 Also see Codecs used by WebRTC for details about potential codecs that might be referenced here.

`sdpFmtpLine` Optional

 A string giving the format specific parameters field from the `a=fmtp` line in the SDP which corresponds to the codec, if such a line exists.
 If there is no parameters field, this property is left out.

`headerExtensions`

 An array of objects, each providing the URI of a header extension supported for the current `kind` of media.
 Each object has the following property:

`uri`

 A string, specifying the URI of a header extension.
 The URI is formatted as described in RFC 5285.

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

As a static function, this is always called using the form:

```js
capabilities = RTCRtpSender.getCapabilities("audio");
```

 The returned set of capabilities is the most optimistic possible list.
 It is entirely possible that certain combinations of options may fail to work when you actually try to use them.

 Calling `RTCRtpSender.getCapabilities()` doesn't prime the browser in any way to handle media.
 Nothing is loaded, fetched, or otherwise prepared.
 It's a means of determining what might be usable before starting to try to access media.

 Because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user.
 For that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations.

### The codecs array

 The `codecs` array is an array of objects that describes a single codec and its basic capabilities.
 The browser will only report distinct capability combinations separately.
 If two sets of capabilities can be described as one, they will be.
 That means that, for instance, if there are two entries for the H.264 codec (as identified by the `mimeType` being "video/H264"), there are other values in the capabilities objects indicating how they're different in some way.

There are three special entries that should always be present, representing underlying components of the transport. Those components are:

RED (REDundant Audio Data)

 The media type of an RED entry may vary due to there being several versions of it, but it will end with `red`, such as `video/red` or `video/fwdred`.
 The base RED standard can be found in RFC 2198. There may be multiple entries for RED if different forms are supported; each will have a unique media type in that case.

FEC (Forward Error Correction)

 An FEC component handles error correction data; its media type may also vary due to there being advanced versions of the standard available, but it will always end with `fec`.
 One possible value is `video/ulpfec` (a generic error connection model).
 There may also be multiple FEC entries if more than one form is supported.

RTX (Retransmission)

 This component is responsible for retransmission of data; it's media type should be `video/rtx`.
 There will only be one entry for RTX, and it will not have an `sdpFmtpLine` property.

These entries should be ignored if only codecs related to the media are of interest.

Examples
--------

### Feature support

You can use `Object.hasOwn()` to check that `RTCRtpSender.getCapabilities()` is supported:
```

<p id="log"></p>
```

```
const log = document.querySelector("#log");
```

```js
log.textContent = `RTCRtpSender.getCapabilities() supported: ${Object.hasOwn(
 RTCRtpSender,
 "getCapabilities",
)}`;
```

### Checking support for a particular codec

The function below returns a `true` or `false` indicating whether or not the device supports sending H.264 video on an `RTCRtpSender`.

**Note:** Since `RTCRtpSender.getCapabilities()` actually only indicates *probable* support.
 So below H.264 support might still fail even after getting a positive response from this function.

```js
function canSendH264() {
  let capabilities = RTCRtpSender.getCapabilities("video");

  capabilities.codecs.forEach((codec) => {
    if (codec.mimeType === "video/H264") {
      return true;
    }
  });
  return false;
}
```

### Getting all capabilities

 This code example shows how we might get all supported codecs and headers.
 The HTML defines a selection list for the two kinds of capabilities, and a log area.

```html
<select id="kind">
  <option value="audio">audio</option>
  <option value="video">video</option>
</select>
<textarea rows="40" cols="100" id="log"></textarea>
```

 The JavaScript defines a function to log the capabilities for a particular "kind".
 This is called initially with the value `audio`.
 A listener updates the value when the selection list `kind` is changed.

```js
const log = document.querySelector("#log");
const kindSelector = document.querySelector("#kind");

logMediaCapabilities("audio");

kindSelector.addEventListener("click", () => {
  log.textContent = "";
  logMediaCapabilities(kindSelector.value);
});

function logMediaCapabilities(kind) {
  const capabilities = RTCRtpSender.getCapabilities(`${kind}`);
  log.textContent += "Headers\n";
  capabilities.headerExtensions.forEach((header) => {
    log.textContent += ` uri: ${header.uri}\n`;
  });

  log.textContent += "\nCodecs\n";
  capabilities.codecs.forEach((codec) => {
    log.textContent += ` mime type: ${codec.mimeType}\n`;
    log.textContent += ` channels: ${codec.channels}\n`; // max channels - e.g. 2 is stereo
    log.textContent += ` clockRate: ${codec.clockRate}\n`; // clock rate in Hz
    log.textContent += ` sdpFmtpLine: ${codec.sdpFmtpLine}\n`; // mime media type and subtype
  });
}
```

#### Result

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

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

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

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


RTCRtpSender: replaceTrack() method - Web APIs

RTCRtpSender: replaceTrack() method
===================================

 The `RTCRtpSender` method
 **`replaceTrack()`** replaces the track currently being used
 as the sender's source with a new `MediaStreamTrack`.

 The new
 track must be of the same media kind (audio, video, etc.) and switching the track should
 not require negotiation.

 Among the use cases for `replaceTrack()` is the common need to switch
 between the rear- and front-facing cameras on a phone. With `replaceTrack()`,
 you can have a track object for each camera and switch between the two as needed. See
 the example Switching cameras below.

Syntax
------

```js
replaceTrack(newTrack)
```

### Parameters

`newTrack` Optional

 A `MediaStreamTrack` specifying the track with which to replace the
 `RTCRtpSender`'s current source track. The new track's
 `kind` must be the same as the current track's,
 or the replace track request will fail.

### Return value

 A `Promise` which is fulfilled once the track has been successfully
 replaced. The promise is rejected if the track cannot be replaced for any reason; this
 is commonly because the change would require renegotiation of the codec, which is not
 allowed (see Things that require negotiation).

 If `newTrack` was omitted or was `null`,
 `replaceTrack()` stops the sender. No negotiation is required in this case.

 When the promise is fulfilled, the fulfillment handler receives a value of
 `undefined`.

### Exceptions

 If the returned promise is rejected, one of the following exceptions is provided to the
 rejection handler:

`InvalidModificationError` `DOMException`

 Returned if replacing the `RTCRtpSender`'s current track with the new one
 would require negotiation.

`InvalidStateError` `DOMException`

Returned if the track on which this method was called is stopped rather than running.

`TypeError`

Returned if the new track's `kind` doesn't match the original track.

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

### Things that require negotiation

 Most track replacements can be done without renegotiation. In fact, even changes that seem huge
 can be done without requiring negotiation. However, some changes may require
 negotiation and thus fail `replaceTrack()`:

* The new track has a resolution which is outside the bounds of the dimensions negotiated with the peer;
 however, most browser end points allow resolution changes.
* The new track's frame rate is high enough to cause the codec's block rate to be
 exceeded.
* The new track is a video track and its raw or pre-encoded state differs from that of
 the original track.
* The new track is an audio track with a different number of channels from the
 original.
* Media sources that have built-in encoders — such as hardware encoders — may not be
 able to provide the negotiated codec. Software sources may not implement the
 negotiated codec.
Examples
--------

### Switching video cameras

```js
const localConnection = new RTCPeerConnection();
const remoteConnection = new RTCPeerConnection();
// Configuring these to use the WebRTC API can be explored at
// https://developer.mozilla.org/en-US/docs/Web/API/WebRTC\_API/Simple\_RTCDataChannel\_sample
const connections = [localConnection, remoteConnection];
function setCamera(selectedCamera) {
  navigator.mediaDevices
    .getUserMedia({
      video: {
        deviceId: {
          exact: selectedCamera,
        },
      },
    })
    .then((stream) => {
      const [videoTrack] = stream.getVideoTracks();
      connections.forEach((pc) => {
        const sender = pc
          .getSenders()
          .find((s) => s.track.kind === videoTrack.kind);
        console.log("Found sender:", sender);
        sender.replaceTrack(videoTrack);
      });
    })
    .catch((err) => {
      console.error(`Error happened: ${err}`);
    });
}
```

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

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

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

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

See also
--------

* WebRTC API


RTCRtpSender: setStreams() method - Web APIs

RTCRtpSender: setStreams() method
=================================

The `RTCRtpSender` method **`setStreams()`** associates the sender's `track` with the specified `MediaStream` objects.

Syntax
------

```js
setStreams()
setStreams(mediaStream1)
setStreams(mediaStream1, mediaStream2)
setStreams(mediaStream1, mediaStream2, /\* …, \*/ mediaStreamN)
```

### Parameters

`mediaStreamN` Optional

 An arbitrary number of `MediaStream` objects specified as arguments, that identify the streams to which the `RTCRtpSender`'s `track` belongs.
 If this parameter isn't specified, no new streams will be associated with the track.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the sender's connection is closed.

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

`setStreams()` is purely additive. It doesn't remove the track from any streams; it adds it to new ones.
 If you specify streams to which the track already belongs, that stream is unaffected.

Once the track has been added to all of the streams, renegotiation of the connection will be triggered by the `negotiationneeded` event being dispatched to the `RTCPeerConnection` to which the sender belongs.

Examples
--------

This example adds all of an `RTCPeerConnection`'s tracks to the specified stream.

```js
function addTracksToStream(stream) {
  let senders = pc.getSenders();

  senders.forEach((sender) => {
    if (sender.track && sender.transport.state === connected) {
      sender.setStreams(stream);
    }
  });
}
```

 After calling the `RTCPeerConnection` method `getSenders()` to get the list of the connection's senders, the `addTracksToStream()` function iterates over the list.
 For each sender, if the sender's track is non-null and its transport's state is `connected`, we call `setStreams()` to add the track to the `stream` specified.

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

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

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

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