CookieChangeEvent: changed property - Web APIs

CookieChangeEvent: changed property
===================================

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

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

The **`changed`** read-only property of the `CookieChangeEvent` interface returns an array of the cookies that have been changed.

Value
-----

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

`name`

A string containing the name of the cookie.

`value`

A string containing the value of the cookie.

`domain`

A string containing the domain of the cookie.

`path`

A string containing the path of the cookie.

`expires`

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

`secure`

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

`sameSite`

One of the following `SameSite` values:

`"strict"`

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

`"lax"`

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

`"none"`

Cookies will be sent in all contexts.

`partitioned`

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

Examples
--------

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

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

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

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

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

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

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


CookieChangeEvent: deleted property - Web APIs

CookieChangeEvent: deleted property
===================================

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

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

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

Value
-----

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

`name`

A string containing the name of the cookie.

`value`

A string containing the value of the cookie.

`domain`

A string containing the domain of the cookie.

`path`

A string containing the path of the cookie.

`expires`

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

`secure`

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

`sameSite`

One of the following `SameSite` values:

`"strict"`

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

`"lax"`

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

`"none"`

Cookies will be sent in all contexts.

`partitioned`

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

Examples
--------

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

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

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

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

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

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


CSSStyleSheet: replace() method - Web APIs

CSSStyleSheet: replace() method
===============================

The **`replace()`** method of the `CSSStyleSheet` interface asynchronously replaces the content of the stylesheet with the content passed into it. The method returns a promise that resolves with the `CSSStyleSheet` object.

The `replace()` and `CSSStyleSheet.replaceSync()` methods can only be used on a stylesheet created with the `CSSStyleSheet()` constructor.

Syntax
------

```js
replace(text)
```

### Parameters

`text`

A string containing the style rules to replace the content of the stylesheet. If the string does not contain a parseable list of rules, then the value will be set to an empty string.

**Note:** If any of the rules passed in `text` are an external stylesheet imported with the `@import` rule, those rules will be removed, and a warning printed to the console.

### Return value

A `Promise` that resolves with the `CSSStyleSheet`.

### Exceptions

`NotAllowedError` `DOMException`

Thrown if one of these two conditions is met:

* The stylesheet was not created using the `CSSStyleSheet()` constructor.
* The stylesheet is flagged as unmodifiable.

Examples
--------

In the following example a new stylesheet is created and two CSS rules are added using `replace()`. The first rule is then printed to the console, which will return: `body { font-size: 1.4em; }`

```js
const stylesheet = new CSSStyleSheet();

stylesheet
  .replace("body { font-size: 1.4em; } p { color: red; }")
  .then(() => {
    console.log(stylesheet.cssRules[0].cssText);
  })
  .catch((err) => {
    console.error("Failed to replace styles:", err);
  });
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-replace |

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

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

See also
--------

* Constructable Stylesheets (web.dev)
* Using the Shadow DOM


CSSStyleSheet: replaceSync() method - Web APIs

CSSStyleSheet: replaceSync() method
===================================

The **`replaceSync()`** method of the `CSSStyleSheet` interface synchronously replaces the content of the stylesheet with the content passed into it.

The `replaceSync()` and `CSSStyleSheet.replace()` methods can only be used on a stylesheet created with the `CSSStyleSheet()` constructor.

Syntax
------

```js
replaceSync(text)
```

### Parameters

`text`

A string containing the style rules to replace the content of the stylesheet. If the string does not contain a parseable list of rules, then the value will be set to an empty string.

**Note:** If any of the rules passed in `text` are an external stylesheet imported with the `@import` rule, those rules will be removed, and a warning printed to the console.

### Return value

None (`undefined`).

### Exceptions

`NotAllowedError` `DOMException`

Thrown if the stylesheet was not created using the `CSSStyleSheet()` constructor or if the stylesheet is flagged as unmodifiable.

Examples
--------

In the following example a new stylesheet is created and two CSS rules are added using `replaceSync`.

```js
const stylesheet = new CSSStyleSheet();

stylesheet.replaceSync("body { font-size: 1.4em; } p { color: red; }");
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-replacesync |

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

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

See also
--------

* Constructable Stylesheets (web.dev)
* Using the Shadow DOM


CSSStyleSheet: rules property - Web APIs

CSSStyleSheet: rules 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.

**`rules`** is a *deprecated*
*legacy property* of the `CSSStyleSheet` interface. Functionally
 identical to the preferred `cssRules` property,
 it provides access to a live-updating list of the CSS rules comprising the
 stylesheet.

**Note:** As a legacy property, you should not use `rules` and
 should instead use the preferred `cssRules`.
 While `rules` is unlikely to be removed soon, its availability is not as
 widespread and using it will result in compatibility problems for your site or app.

Value
-----

 A live-updating `CSSRuleList` containing each of the CSS rules making up
 the stylesheet. Each entry in the rule list is a `CSSRule` object
 describing one rule making up the stylesheet.

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-rules |

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

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

See also
--------

* CSS Object Model
* Using dynamic styling information


CSSStyleSheet: CSSStyleSheet() constructor - Web APIs

CSSStyleSheet: CSSStyleSheet() constructor
==========================================

The **`CSSStyleSheet()`** constructor creates a new `CSSStyleSheet` object which represents a single Stylesheet.

After constructing a stylesheet the `CSSStyleSheet.replace()`, `CSSStyleSheet.replaceSync()`, `CSSStyleSheet.insertRule()`, and `CSSStyleSheet.deleteRule()` methods can be used to modify the rules of the new stylesheet.

 A stylesheet created using this method is referred to as a "constructed stylesheet".
 A constructed stylesheet can be shared between a document and its shadow DOM subtrees using `ShadowRoot.adoptedStyleSheets` and `Document.adoptedStyleSheets`.

Syntax
------

```js
new CSSStyleSheet()
new CSSStyleSheet(options)
```

### Parameters

`options` Optional

An object containing the following:

`baseURL` Optional

A string containing the `baseURL` used to resolve relative URLs in the stylesheet.

`media` Optional

A `MediaList` containing a list of media rules, or a string containing a single rule.

`disabled` Optional

A `Boolean` indicating whether the stylesheet is disabled. False by default.

Examples
--------

 In the following example, a new `CSSStyleSheet` is constructed with a media rule of `"print"`.
 Printing `StyleSheet.media` to the console returns a `MediaList` with a single entry for this print rule.

```js
let stylesheet = new CSSStyleSheet({ media: "print" });
console.log(stylesheet.media);
```

### Sharing stylesheets with a shadow DOM

The code below shows the sheet being constructed and then `CSSStyleSheet.replaceSync()` is called to add a rule to the sheet.

```js
// Create an empty "constructed" stylesheet
const sheet = new CSSStyleSheet();
// Apply a rule to the sheet
sheet.replaceSync("a { color: red; }");
```

We then create a `ShadowRoot` and pass the sheet object to the `ShadowRoot.adoptedStyleSheets` property inside an array.

```js
// Create an element in the document and then create a shadow root:
const node = document.createElement("div");
const shadow = node.attachShadow({ mode: "open" });

//Adopt the sheet into the shadow DOM
shadow.adoptedStyleSheets = [sheet];
```

 We can modify the stylesheets after they have been added to the array.
 Below we append a new rule to the same sheet using `CSSStyleSheet.insertRule()`.

```js
sheet.insertRule("\* { background-color: blue; }");
// The document will now have blue background.
```

 The same sheet can be shared with multiple shadow subtrees in the same document.
 For more examples see `ShadowRoot.adoptedStyleSheets`.

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-cssstylesheet |

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

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

See also
--------

* Constructable Stylesheets (web.dev)
* Using the Shadow DOM
* construct-style-sheets-polyfill


CSSStyleSheet: insertRule() method - Web APIs

CSSStyleSheet: insertRule() method
==================================

 The **`CSSStyleSheet.insertRule()`**
 method inserts a new CSS rule into the current style sheet.

**Note:** Although `insertRule()` is exclusively a method of
 `CSSStyleSheet`, it actually inserts the rule into
 `CSSStyleSheet.cssRules` — its internal
 `CSSRuleList`.

Syntax
------

```js
insertRule(rule)
insertRule(rule, index)
```

### Parameters

`rule`

 A string containing the rule to be inserted. What the inserted
 rule must contain depends on its type:

* **For rule-sets**, both
 a selector and a
 style declaration.
* **For at-rules**, both an
 at-identifier and the rule content.

`index` Optional

 A positive integer less than or equal to `stylesheet.cssRules.length`,
 representing the newly inserted rule's position in
 `CSSStyleSheet.cssRules`. The default is
 `0`. (In older implementations, this was required. See Browser compatibility for details.)

### Return value

The newly inserted rule's index within the stylesheet's rule-list.

### Exceptions

`IndexSizeError` `DOMException`

Thrown if `index` > `CSSRuleList.length`.

`HierarchyRequestError` `DOMException`

Thrown if `rule` cannot be inserted at `index` `0` due to some CSS constraint.

`SyntaxError` `DOMException`

Thrown if more than one rule is given in the `rule` parameter.

`HierarchyRequestError` `DOMException`

Thrown if trying to insert an `@import` at-rule after a style rule.

`InvalidStateError` `DOMException`

Thrown if `rule` is `@namespace` and the rule-list has more than just `@import` at-rules and/or `@namespace` at-rules.

Examples
--------

### Inserting a new rule

This snippet pushes a new rule onto the top of my stylesheet.

```js
myStyle.insertRule("#blanc { color: white }", 0);
```

### Function to add a stylesheet rule

```js
/\*\*
 \* Add a stylesheet rule to the document (it may be better practice
 \* to dynamically change classes, so style information can be kept in
 \* genuine stylesheets and avoid adding extra elements to the DOM).
 \* Note that an array is needed for declarations and rules since ECMAScript does
 \* not guarantee a predictable object iteration order, and since CSS is
 \* order-dependent.
 \* @param {Array} rules Accepts an array of JSON-encoded declarations
 \* @example
addStylesheetRules([
 ['h2', // Also accepts a second argument as an array of arrays instead
 ['color', 'red'],
 ['background-color', 'green', true] // 'true' for !important rules
 ],
 ['.myClass',
 ['background-color', 'yellow']
 ]
]);
\*/
function addStylesheetRules(rules) {
  const styleEl = document.createElement("style");

  // Append <style> element to <head>
  document.head.appendChild(styleEl);

  // Grab style element's sheet
  const styleSheet = styleEl.sheet;

  for (let i = 0; i < rules.length; i++) {
    let j = 1,
      rule = rules[i],
      selector = rule[0],
      propStr = "";
    // If the second argument of a rule is an array of arrays, correct our variables.
    if (Array.isArray(rule[1][0])) {
      rule = rule[1];
      j = 0;
    }

    for (let pl = rule.length; j < pl; j++) {
      const prop = rule[j];
      propStr += `${prop[0]}: ${prop[1]}${prop[2] ? " !important" : ""};\n`;
    }

    // Insert CSS Rule
    styleSheet.insertRule(
      `${selector}{${propStr}}`,
      styleSheet.cssRules.length,
    );
  }
}
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-insertrule |

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

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

See also
--------

* `CSSStyleSheet.deleteRule`
* Constructable Stylesheets (web.dev)


CSSStyleSheet: ownerRule property - Web APIs

CSSStyleSheet: ownerRule property
=================================

 The read-only `CSSStyleSheet` property
 **`ownerRule`** returns the `CSSImportRule`
 corresponding to the `@import` at-rule which imported the stylesheet into
 the document. If the stylesheet wasn't imported into the document using
 `@import`, the returned value is `null`.

Value
-----

 A `CSSImportRule` corresponding to the `@import` rule which
 imported the stylesheet into the document. If the stylesheet wasn't imported into the
 document using `@import`, the returned value is `null`.

Examples
--------

 This snippet of code looks for rules which were not imported into the document using an
 `@import` at-rule.

```js
const ruleList = document.styleSheets[0].cssRules;

for (const rule of ruleList) {
  if (!rule.ownerRule) {
    /\* rule is not imported \*/
  }
}
```

 This snippet obtains a reference to the stylesheet associated with the
 `@import` and processes it in some manner:

```js
const ruleList = document.styleSheets[0].cssRules;

for (const rule of ruleList) {
  if (rule.ownerRule) {
    checkStylesheet(rule.ownerRule.styleSheet);
  }
}
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-ownerrule |

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

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

See also
--------

* CSS Object Model
* Using dynamic styling information


CSSStyleSheet: addRule() method - Web APIs

CSSStyleSheet: addRule() method
===============================

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

 The obsolete `CSSStyleSheet` interface's
 **`addRule()`** *legacy method* adds a new rule to the
 stylesheet. You should avoid using this method, and should instead use the more standard
 `insertRule()` method.

Syntax
------

```js
addRule(selector, styleBlock, index)
```

### Parameters

`selector`

 A string specifying the selector portion of the CSS rule. The
 default is the string `undefined`.

`styleBlock`

 A string indicating the style block to apply to elements matching
 the `selector`. The default is the string `undefined`.

`index` Optional

 An optional index into the stylesheet's `CSSRuleList` at which to
 insert the new rule. If `index` is not specified, the next index after the
 last item currently in the list is used (that is, the value of
 `cssStyleSheet.cssRules.length`).

### Return value

Always returns -1.

 Note that due to somewhat esoteric rules about where you can legally insert rules,
 it's possible that an exception may be thrown. See `insertRule()` for more information.

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

 This method is implemented by browsers by constructing a string using the template
 literal ``${selector}{${styleBlock}}``, then passing it into the standard
 `insertRule()` method.

Therefore, given existing code such as the following:

```js
cssStyleSheet.addRule(selector, styles, 0);
```

You can rewrite this to use the more standard `insertRule()` like this:

```js
cssStyleSheet.insertRule(`${selector} {${styles}}`, 0);
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-addrule |

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

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

See also
--------

* CSS Object Model
* Using dynamic styling information


CSSStyleSheet: deleteRule() method - Web APIs

CSSStyleSheet: deleteRule() method
==================================

 The `CSSStyleSheet` method
 **`deleteRule()`** removes a rule from the stylesheet
 object.

Syntax
------

```js
deleteRule(index)
```

### Parameters

`index`

 The index into the stylesheet's `CSSRuleList` indicating the rule to be
 removed.

### Return value

None (`undefined`).

Examples
--------

This example removes the first rule from the stylesheet `myStyles`.

```js
myStyles.deleteRule(0);
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-deleterule |

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

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

See also
--------

* CSS Object Model
* Constructable Stylesheets (web.dev)
* Using dynamic styling information
* `insertRule()`


CSSStyleSheet: removeRule() method - Web APIs

CSSStyleSheet: removeRule() method
==================================

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

 The obsolete `CSSStyleSheet` method
 **`removeRule()`** removes a rule from the stylesheet
 object. It is functionally identical to the standard, preferred method
 `deleteRule()`.

**Note:** This is a *legacy method* which has been replaced by
 the standard method `deleteRule()`. You
 should use that instead.

Syntax
------

```js
removeRule(index)
```

### Parameters

`index`

 The index into the stylesheet's `CSSRuleList` indicating the rule to be
 removed.

### Return value

None (`undefined`).

Examples
--------

This example removes the first rule from the stylesheet `myStyles`.

```js
myStyles.removeRule(0);
```

You can rewrite this to use the standard `deleteRule()` method very easily:

```js
myStyles.deleteRule(0);
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-removerule |

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

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

See also
--------

* CSS Object Model
* Using dynamic styling information
* `insertRule()`


CSSStyleSheet: cssRules property - Web APIs

CSSStyleSheet: cssRules property
================================

 The read-only `CSSStyleSheet` property
 **`cssRules`** returns a live `CSSRuleList` which
 provides a real-time, up-to-date list of every CSS rule which comprises the
 stylesheet. Each item in the list is a `CSSRule` defining a single
 rule.

Value
-----

 A live-updating `CSSRuleList` containing each of the CSS rules making up
 the stylesheet. Each entry in the rule list is a `CSSRule` object
 describing one rule making up the stylesheet.

Examples
--------

Individual rules within the stylesheet can then be accessed by index:

```js
const ruleList = document.styleSheets[0].cssRules;

for (let i = 0; i < ruleList.length; i++) {
  processRule(ruleList[i]);
}
```

Rules can also be accessed using `for...of`:

```js
const ruleList = document.styleSheets[0].cssRules;

for (const rule of ruleList) {
  processRule(rule);
}
```

 However, because `CSSRule` is not a proper array, you can't use
 `forEach()`.

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-cssrules |

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

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

See also
--------

* CSS Object Model
* Using dynamic styling information


ResizeObserverSize: inlineSize property - Web APIs

ResizeObserverSize: inlineSize property
=======================================

The **`inlineSize`** read-only property of the `ResizeObserverSize` interface returns the length of the observed element's border box in the inline dimension. For boxes with a horizontal `writing-mode`, this is the horizontal dimension, or width; if the writing-mode is vertical, this is the vertical dimension, or height.

**Note:** For more explanation of writing modes and block and inline dimensions, read Handling different text directions.

Value
-----

A decimal representing the inline size in pixels.

Examples
--------

In this example we return an array of sizing information with `ResizeObserverEntry.contentBoxSize`. The `inlineSize` property returns the inline dimension size of the observed element.

```js
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    const elemSize = entry.contentBoxSize[0];
    console.log(elemSize.inlineSize); // a decimal
  }
});

resizeObserver.observe(divElem);
```

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

| Specification |
| --- |
| Resize Observer # dom-resizeobserversize-inlinesize |

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

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


ResizeObserverSize: blockSize property - Web APIs

ResizeObserverSize: blockSize property
======================================

The **`blockSize`** read-only property of the `ResizeObserverSize` interface returns the length of the observed element's border box in the block dimension. For boxes with a horizontal `writing-mode`, this is the vertical dimension, or height; if the writing-mode is vertical, this is the horizontal dimension, or width.

**Note:** For more explanation of writing modes and block and inline dimensions, read Handling different text directions.

Value
-----

A decimal representing the block size in pixels.

Examples
--------

In this example we return an array of sizing information with `ResizeObserverEntry.contentBoxSize`. The `blockSize` property returns the block dimension size of the observed element.

```js
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    const elemSize = entry.contentBoxSize[0];
    console.log(elemSize.blockSize); // a decimal
  }
});

resizeObserver.observe(divElem);
```

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

| Specification |
| --- |
| Resize Observer # dom-resizeobserversize-blocksize |

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

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


NavigatorUAData: mobile property - Web APIs

NavigatorUAData: mobile property
================================

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

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

The **`mobile`** read-only property of the `NavigatorUAData` interface returns a value indicating whether the device is a mobile device.

Value
-----

A `Boolean`, `true` if this is a mobile device.

Examples
--------

The following example prints the value of `mobile` to the console.

```js
console.log(navigator.userAgentData.mobile);
```

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

| Specification |
| --- |
| User-Agent Client Hints # dom-navigatoruadata-mobile |

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

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

See also
--------

* The `Sec-CH-UA-Mobile` header (a low-entropy client hint) contains the same information.


NavigatorUAData: brands property - Web APIs

NavigatorUAData: brands property
================================

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

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

The **`brands`** read-only property of the `NavigatorUAData` interface returns an array of brand information.

Value
-----

An array containing the following information for each brand:

`brand`

A string containing the brand. For example, `"Google Chrome"`.

`version`

A string containing the version. For example, `"91"`.

Examples
--------

The following example prints the value of `NavigatorUAData.brands` to the console.

```js
console.log(navigator.userAgentData.brands);
```

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

| Specification |
| --- |
| User-Agent Client Hints # dom-navigatoruadata-brands |

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

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

See also
--------

* `Sec-CH-UA` (a low-entropy client hint) contains the same information.


NavigatorUAData: getHighEntropyValues() method - Web APIs

NavigatorUAData: getHighEntropyValues() method
==============================================

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

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

The **`getHighEntropyValues()`** method of the `NavigatorUAData` interface is a `Promise` that resolves with a dictionary object containing the *high entropy* values the user-agent returns.

**Note:** The terms *high entropy* and *low entropy* refer to the amount of information these values reveal about the browser.
 The values returned as properties are deemed low entropy, and unlikely to identify a user.
 The values returned by `NavigatorUAData.getHighEntropyValues()` could potentially reveal more information.
 These values are therefore retrieved via a `Promise`, allowing time for the browser to request user permission, or make other checks.

Syntax
------

```js
getHighEntropyValues(hints)
```

### Parameters

`hints`

An array containing the hints to be returned, one or more of:

* `"architecture"`
* `"bitness"`
* `"formFactor"`
* `"fullVersionList"`
* `"model"`
* `"platformVersion"`
* `"uaFullVersion"`
Deprecated
* `"wow64"`

### Return value

A `Promise` that resolves to an object containing some or all of the following values (based on the hints requested):

`brands`

 Returns an array of objects containing `brand` and `version` specifying the browser brand and its version (the same information as provided by `NavigatorUAData.brands`).
 Note that this information can be sent to a server in the `Sec-CH-UA` header (a low-entropy client hint).

`mobile`

 Returns `true` if the user agent is running on a mobile device (the same information as provided by `NavigatorUAData.mobile`).
 Note that this information can be sent to a server in the `Sec-CH-UA-Mobile` header (a low-entropy client hint).

`platform`

 Returns a string describing the platform the user agent is running on, like `"Windows"` (the same information as provided by `NavigatorUAData.platform`).
 Note that this information can be sent to a server in the `Sec-CH-UA-Platform` header (a low-entropy client hint).

`architecture`

 A string containing the platform architecture. For example, `"x86"`.
 Note that this information can be sent to a server in the `Sec-CH-UA-Arch` header after the server explicitly requests it in the `Accept-CH` header.

`bitness`

 A string containing the architecture bitness. For example, `"32"` or `"64"`.
 Note that this information can be sent to a server in the `Sec-CH-UA-Bitness` header if the server explicitly requests it in the `Accept-CH` header.

`formFactor`

 A string containing the form-factor of a device. For example, `"Tablet"` or `"VR"`.
 Note that this information can be sent to a server in the `Sec-CH-UA-Form-Factor` header if the server explicitly requests it in the `Accept-CH` header.

`fullVersionList`

 An array of objects with properties `"brand"` and `"version"` representing the browser name and full version respectively.
 For example, `{"brand": "Google Chrome", "version": "103.0.5060.134"}, {"brand": "Chromium", "version": "103.0.5060.134"}`.
 Please note that one object may intentionally contain invalid information to prevent sites from relying on a fixed list of browsers.
 Note that this information can be sent to a server in the `Sec-CH-UA-Full-Version-List` header if the server explicitly requests it in the `Accept-CH` header.

`model`

 A string containing the model of mobile device. For example, `"Pixel 2XL"`. If device is not a mobile device or if device model is not known, `model` will be `""`.
 Note that this information can be sent to a server in the `Sec-CH-UA-Model` header if the server explicitly requests it in the `Accept-CH` header.

`platformVersion`

 A string containing the platform version. Platform name itself is always available as low-entropy hint `platform`. For example, `"10.0"`.
 Note that this information can be sent to a server in the `Sec-CH-UA-Platform-Version` header if the server explicitly requests it in the `Accept-CH` header.

`uaFullVersion`
Deprecated

 A string containing the full browser version. For example, `"103.0.5060.134"`. Deprecated in favor of `fullVersionList`.
 Note that this information can be sent to a server in the `Sec-CH-UA-Full-Version` header if the server explicitly requests it in the `Accept-CH` header.

`wow64`

 A boolean indicating if the user agent's binary is running in 32-bit mode on 64-bit Windows.
 Note that this information can be sent to a server in the `Sec-CH-UA-WoW64` header if the server explicitly requests it in the `Accept-CH` header.

### Exceptions

`NotAllowedError` `DOMException`

Thrown if the user-agent decides that one or more of the `hints` requested should not be returned.

Examples
--------

 In the following example a number of hints are requested using the `getHighEntropyValues()` method.
 When the promise resolves, this information is printed to the console.

```js
navigator.userAgentData
  .getHighEntropyValues([
    "architecture",
    "model",
    "platformVersion",
    "fullVersionList",
  ])
  .then((values) => console.log(values));
```

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

| Specification |
| --- |
| User-Agent Client Hints # dom-navigatoruadata-gethighentropyvalues |

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

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

See also
--------

* These values are also available as via HTTP request headers:
    + Low-entropy client hints) are sent automatically:
        - `Sec-CH-UA`
        - `Sec-CH-UA-Mobile`
        - `Sec-CH-UA-Platform`
    + Servers can request to receive high-entropy client hints on subsequent requests, using the `Accept-CH` header:
        - `Sec-CH-UA-Arch`
        - `Sec-CH-UA-Bitness`
        - `Sec-CH-UA-Full-Version`
        - `Sec-CH-UA-Model`
        - `Sec-CH-UA-Platform-Version`


NavigatorUAData: platform property - Web APIs

NavigatorUAData: platform property
==================================

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

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

The **`platform`** read-only property of the `NavigatorUAData` interface returns the platform brand information.

Value
-----

 A string containing the platform brand.
 For example, `"Windows"`.

Examples
--------

The following example prints the value of `platform` to the console.

```js
console.log(navigator.userAgentData.platform);
```

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

| Specification |
| --- |
| User-Agent Client Hints # dom-navigatoruadata-platform |

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

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

See also
--------

* The `Sec-CH-UA-Platform` header (a low-entropy client hint) contains the same information.


NavigatorUAData: toJSON() method - Web APIs

NavigatorUAData: toJSON() method
================================

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

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

The **`toJSON()`** method of the `NavigatorUAData` interface is a *serializer* that returns a JSON representation of the *low entropy* properties of the `NavigatorUAData` object.

**Note:** The terms *high entropy* and *low entropy* refer to the amount of information these values reveal about the browser. The low entropy values returned by this method are those which do not reveal information able to identify a user. High entropy values can only be returned by the `NavigatorUAData.getHighEntropyValues()` method.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A JSON object.

Examples
--------

The following example prints the JSON object to the console.

```js
console.log(navigator.userAgentData.toJSON());
```

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

| Specification |
| --- |
| User-Agent Client Hints # dom-navigatoruadata-tojson |

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

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


AbortController: AbortController() constructor - Web APIs

AbortController: AbortController() constructor
==============================================

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

Syntax
------

```js
new AbortController()
```

### Parameters

None.

Examples
--------

In the following snippet, we aim to download a video using the Fetch API.

We first create a controller using the `AbortController()` constructor, then grab a reference to its associated `AbortSignal` object using the `AbortController.signal` property.

When the fetch request is initiated, we pass in the `AbortSignal` as an option inside the request's options object (the `{ signal }` below). This associates the signal and controller with the fetch request and allows us to abort it by calling `AbortController.abort()`, as seen below in the second event listener.

```js
const controller = new AbortController();
const signal = controller.signal;

const url = "video.mp4";
const downloadBtn = document.querySelector(".download");
const abortBtn = document.querySelector(".abort");

downloadBtn.addEventListener("click", fetchVideo);

abortBtn.addEventListener("click", () => {
  controller.abort();
  console.log("Download aborted");
});

function fetchVideo() {
  fetch(url, { signal })
    .then((response) => {
      console.log("Download complete", response);
    })
    .catch((err) => {
      console.error(`Download error: ${err.message}`);
    });
}
```

**Note:** When `abort()` is called, the `fetch()` promise rejects with an `AbortError`.

You can find a full working example on GitHub; you can also see it running live.

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-abortcontroller-abortcontroller① |

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

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

See also
--------

* Fetch API


AbortController: signal property - Web APIs

AbortController: signal property
================================

The **`signal`** read-only property of the `AbortController` interface returns an `AbortSignal` object instance, which can be used to communicate with/abort an asynchronous operation as desired.

Value
-----

An `AbortSignal` object instance.

Examples
--------

In the following snippet, we aim to download a video using the Fetch API.

We first create a controller using the `AbortController()` constructor, then grab a reference to its associated `AbortSignal` object using the `AbortController.signal` property.

When the fetch request is initiated, we pass in the `AbortSignal` as an option inside the request's options object (the `{signal}` below). This associates the signal and controller with the fetch request and allows us to abort it by calling `AbortController.abort()`, as seen below in the second event listener.

```js
const controller = new AbortController();
const signal = controller.signal;

const url = "video.mp4";
const downloadBtn = document.querySelector(".download");
const abortBtn = document.querySelector(".abort");

downloadBtn.addEventListener("click", fetchVideo);

abortBtn.addEventListener("click", () => {
  controller.abort();
  console.log("Download aborted");
});

function fetchVideo() {
  fetch(url, { signal })
    .then((response) => {
      console.log("Download complete", response);
    })
    .catch((err) => {
      console.error(`Download error: ${err.message}`);
    });
}
```

**Note:** When `abort()` is called, the `fetch()` promise rejects with an `AbortError`.

You can find a full working example on GitHub; you can also see it running live.

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-abortcontroller-signal② |

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

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

See also
--------

* Fetch API


AbortController: abort() method - Web APIs

AbortController: abort() method
===============================

 The **`abort()`** method of the `AbortController` interface aborts an asynchronous operation before it has completed.
 This is able to abort fetch requests, the consumption of any response bodies, or streams.

Syntax
------

```js
abort()
abort(reason)
```

### Parameters

`reason` Optional

 The reason why the operation was aborted, which can be any JavaScript value.
 If not specified, the reason is set to "AbortError" `DOMException`.

### Return value

None (`undefined`).

Examples
--------

In the following snippet, we aim to download a video using the Fetch API.

We first create a controller using the `AbortController()` constructor, then grab a reference to its associated `AbortSignal` object using the `AbortController.signal` property.

When the fetch request is initiated, we pass in the `AbortSignal` as an option inside the request's options object (the `{signal}` below). This associates the signal and controller with the fetch request and allows us to abort it by calling `AbortController.abort()`, as seen below in the second event listener.

```js
const controller = new AbortController();
const signal = controller.signal;

const url = "video.mp4";
const downloadBtn = document.querySelector(".download");
const abortBtn = document.querySelector(".abort");

downloadBtn.addEventListener("click", fetchVideo);

abortBtn.addEventListener("click", () => {
  controller.abort();
  console.log("Download aborted");
});

function fetchVideo() {
  fetch(url, { signal })
    .then((response) => {
      console.log("Download complete", response);
    })
    .catch((err) => {
      console.error(`Download error: ${err.message}`);
    });
}
```

**Note:** When `abort()` is called, the `fetch()` promise rejects with an `Error` of type `DOMException`, with name `AbortError`.

You can find a full working example on GitHub; you can also see it running live.

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-abortcontroller-abortcontroller① |

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

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

See also
--------

* Fetch API


EyeDropper: open() method - Web APIs

EyeDropper: open() method
=========================

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

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

The **`EyeDropper.open()`** method starts the eyedropper mode, returning a promise which is fulfilled once the user has selected a color and exited the eyedropper mode.

Syntax
------

```js
open()
open(options)
```

### Parameters

`options` Optional

An options object to pass an `AbortSignal` signal:

`signal` Optional

An `AbortSignal`. The eyedropper mode will be aborted when the `AbortSignal`'s `abort()` method is called.

### Return value

A `Promise` that eventually resolves when the user selects a pixel color from the screen.

The promise resolves to an object with the following property:

`sRGBHex`

A string representing the selected color, in hexadecimal sRGB format (`#aabbcc`).

### Exceptions

Exceptions are not thrown but returned when the `Promise` is rejected.

`NotAllowedError` `DOMException`

Thrown if `open()` is not called via a transient user activation.

`InvalidStateError` `DOMException`

Thrown if another eye dropper has already opened.

`AbortError` `DOMException`

Thrown if the user aborts the selection by pressing the `Esc` key or if the selection is aborted by an `AbortController` being passed as an argument to `open()`.

`OperationError` `DOMException`

Thrown if the selection fails for other reasons.

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

| Specification |
| --- |
| EyeDropper API # dom-eyedropper-open |

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

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

See also
--------

* The `EyeDropper` interface it belongs to.


EyeDropper: EyeDropper() constructor - Web APIs

EyeDropper: EyeDropper() constructor
====================================

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

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

The **`EyeDropper()`** constructor returns a new `EyeDropper` object.

Syntax
------

```js
new EyeDropper()
```

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

| Specification |
| --- |
| EyeDropper API # eyedropper-interface |

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

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

See also
--------

* The `EyeDropper` interface it belongs to.


WindowClient: visibilityState property - Web APIs

WindowClient: visibilityState property
======================================

 The **`visibilityState`** read-only property of the
 `WindowClient` interface indicates the visibility of the current client.
 This value can be one of `"hidden"`, `"visible"`, or
 `"prerender"`.

Value
-----

A string (See `Document.visibilityState` for values).

Examples
--------

```js
event.waitUntil(
  clients
    .matchAll({
      type: "window",
    })
    .then((clientList) => {
      for (const client of clientList) {
        if (client.url === "/" && "focus" in client) {
          if (client.visibilityState === "hidden") return client.focus();
        }
      }
      if (clients.openWindow) {
        return clients.openWindow("/");
      }
    }),
);
```

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

| Specification |
| --- |
| Service Workers # client-visibilitystate |

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

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


WindowClient: focus() method - Web APIs

WindowClient: focus() method
============================

 The **`focus()`** method of the `WindowClient`
 interface gives user input focus to the current client and returns a
 `Promise` that resolves to the existing
 `WindowClient`.

Syntax
------

```js
focus()
```

### Parameters

None.

### Return value

A `Promise` that resolves to the existing `WindowClient`.

### Exceptions

`InvalidAccessError` `DOMException`

The promise is rejected with this exception if none of the windows in the app's origin have transient activation.

Security requirements
---------------------

* At least one window in the app's origin must have transient activation.
Examples
--------

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

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

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

| Specification |
| --- |
| Service Workers # client-focus |

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

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


WindowClient: ancestorOrigins property - Web APIs

WindowClient: ancestorOrigins property
======================================

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

The **`ancestorOrigins`** read-only property of the `WindowClient` interface is an array of strings listing the origins of all ancestors of the browsing context represented by this `WindowClient` in reverse order.

The first element in the array is the origin of this window's parent, and the last element is the origin of the top-level browsing context. If this window is itself a top-level browsing context, then `ancestorOrigins` is an empty array.

Value
-----

An array of strings.

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

| Specification |
| --- |
| Service Workers # client-ancestororigins |

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

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


WindowClient: navigate() method - Web APIs

WindowClient: navigate() method
===============================

 The **`navigate()`** method of the `WindowClient`
 interface loads a specified URL into a controlled client page then returns a
 `Promise` that resolves to the existing `WindowClient`.

Syntax
------

```js
navigate(url)
```

### Parameters

`url`

The location to navigate to.

### Return value

A `Promise` that resolves to the existing `WindowClient` if the URL is from the same origin as the service worker, or `null` otherwise.

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

| Specification |
| --- |
| Service Workers # client-navigate |

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

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


WindowClient: focused property - Web APIs

WindowClient: focused property
==============================

 The **`focused`** read-only property of the
 `WindowClient` interface is a boolean value that indicates whether
 the current client has focus.

Value
-----

A boolean value.

Examples
--------

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

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

        if (clients.openWindow) return clients.openWindow("/");
      }),
  );
});
```

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

| Specification |
| --- |
| Service Workers # client-focused |

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

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


RTCRtpReceiver: getContributingSources() method - Web APIs

RTCRtpReceiver: getContributingSources() method
===============================================

The **`getContributingSources()`** method of the `RTCRtpReceiver` interface returns an array of objects, each corresponding to one CSRC (contributing source) identifier received by the current `RTCRtpReceiver` in the last ten seconds.

Syntax
------

```js
getContributingSources()
```

### Parameters

None.

### Return value

 An array of objects, each describing one of the contributing sources that provided data to the incoming stream in the past ten seconds.
 These objects contain the following properties:

`audioLevel` Optional

A floating-point value between 0.0 and 1.0 specifying the audio level contained in the last RTP packet played from the contributing source.

 The value is on a linear scale and is defined in units of dBov, or decibels (overload).
 This is the amplitude relative to the point at which clipping of the audio begins to occur.
 A value of 1.0 represents 0 dBov (maximum volume), a value of 0.0 represents silence, and a value of 0.5 represents approximately 6 dB SPL (decibels of sound pressure level) change in the sound pressure level from 0 dBov.

If this property is not present then no volume level was provided by the source.

`rtpTimestamp` Optional

 The RTP timestamp (an integer `DOMHighResTimeStamp`) of the media.
 This source-generated timestamp indicates the time at which the media in this packet, scheduled for play out at the time indicated by `timestamp`, was initially sampled or generated.
 It may be useful for sequencing and synchronization purposes.

`source` Optional

 A positive integer value specifying the CSRC identifier of the contributing source.
 This uniquely identifies the source of the particular stream RTP packets.

`timestamp` Optional

A `DOMHighResTimeStamp` indicating the most recent time at which a frame originating from this source was delivered to the receiver's `MediaStreamTrack`

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcrtpreceiver-getcontributingsources |

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

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


RTCRtpReceiver: getParameters() method - Web APIs

RTCRtpReceiver: getParameters() method
======================================

The **`getParameters()`** method of the `RTCRtpReceiver` interface returns an object describing the current configuration for the encoding and transmission of media on the receiver's `track`.

Syntax
------

```js
getParameters()
```

### Parameters

None.

### Return value

An object indicating the current configuration of the receiver.

`codecs`

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

`headerExtensions`

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

`rtcp`

 An `RTCRtcpParameters` object providing the configuration parameters used for RTCP on the sender or receiver.
 This parameter cannot be changed once initially set.

Examples
--------

This example obtains the canonical name (CNAME) being used for RTCP on an `RTCRtpReceiver`.

```js
function getRtcpCNAME(receiver) {
  let parameters = receiver.getParameters();

  return parameters.rtcp.cname;
}
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcrtpreceiver-getparameters |

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

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


RTCRtpReceiver: getSynchronizationSources() method - Web APIs

RTCRtpReceiver: getSynchronizationSources() method
==================================================

The **`getSynchronizationSources()`** method of the `RTCRtpReceiver` interface returns an array of objects, each corresponding to one SSRC (synchronization source) identifier received by the current `RTCRtpReceiver` in the last ten seconds.

Syntax
------

```js
getSynchronizationSources()
```

### Parameters

None.

### Return value

 An array of objects, each describing one of the synchronization sources that provided data to the incoming stream in the past ten seconds.
 These objects contain the following properties:

`audioLevel`

A floating-point value between 0.0 and 1.0 specifying the audio level contained in the last RTP packet played from the synchronization source.

 The value is on a linear scale and is defined in units of dBov, or decibels (overload).
 This is the amplitude relative to the point at which clipping of the audio begins to occur.
 A value of 1.0 represents 0 dBov (maximum volume), a value of 0.0 represents silence, and a value of 0.5 represents approximately 6 dB SPL (decibels of sound pressure level) change in the sound pressure level from 0 dBov.

This value is required and always present.

`rtpTimestamp` Optional

 The RTP timestamp (an integer `DOMHighResTimeStamp`) of the media.
 This source-generated timestamp indicates the time at which the media in this packet, scheduled for play out at the time indicated by `timestamp`, was initially sampled or generated.
 It may be useful for sequencing and synchronization purposes.

`source` Optional

 A positive integer value specifying the SSRC identifier of the synchronization source.
 This uniquely identifies the source of the particular stream RTP packets.

`timestamp` Optional

A `DOMHighResTimeStamp` indicating the most recent time at which a frame originating from this source was delivered to the receiver's `MediaStreamTrack`

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcrtpreceiver-getsynchronizationsources |

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

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


RTCRtpReceiver: transform property - Web APIs

RTCRtpReceiver: transform property
==================================

 The **`transform`** property of the `RTCRtpReceiver` object is used to insert a transform stream (`TransformStream`) running in a worker thread into the receiver pipeline.
 This allows stream transforms to be applied to encoded video and audio frames as they arrive from the packetizer (before they are played/rendered).

 The transform that is to be added is defined using an `RTCRtpScriptTransform` and its associated `Worker`.
 If the transform is set in the peer connection `track` event handler, the transform stream will receive the first full incoming frame for the track.

### Value

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

Example
-------

Note that this is part of a larger example in the guide topic Using WebRTC Encoded Transforms.

Adding a transform for incoming frames
--------------------------------------

 This example shows how you add a WebRTC encoded transform to modify an incoming stream.
 The code assumes that there is an `RTCPeerConnection` called `peerConnection` that is already connected to a remote peer.

 To add a transform stream into the pipeline for incoming frames we need to construct an `RTCRtpScriptTransform` and assign it to the receiver's `transform` property.
 We can do this in the `track` event handler as shown.
 This event is fired on the peer connection whenever the remote end sends a track.
 The `event.receiver` property is an `RTCRtpReceiver`.

```js
const worker = new Worker("worker.js");
peerConnection.ontrack = (event) => {
  event.receiver.transform = new RTCRtpScriptTransform(worker, {
    someOption: "receiverTransform",
  });
};
```

 Because the transform is constructed immediately after creation of the `RTCRtpReceiver`, it will receive the first incoming frame.
 The object passed as the second parameter in the `RTCRtpScriptTransform` constructor is sent to the worker thread, and can be used by worker code to provide a different transform for the incoming frames than is used for outgoing frames.

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
* `RTCRtpSender.transform`


RTCRtpReceiver: getStats() method - Web APIs

RTCRtpReceiver: getStats() method
=================================

The `RTCRtpReceiver` method **`getStats()`** asynchronously requests an `RTCStatsReport` object which provides statistics about incoming traffic on the owning `RTCPeerConnection`, returning a `Promise` whose fulfillment handler will be called once the results are available.

Syntax
------

```js
getStats()
```

### Parameters

None.

### Return value

 A JavaScript `Promise` which is fulfilled once the statistics are available.
 The promise's fulfillment handler receives as a parameter a `RTCStatsReport` object containing the collected statistics.

The returned statistics include those from all streams which are coming in through the `RTCRtpReceiver`, as well as any of their dependencies.

These might include, for example, statistics with types: `inbound-rtp`, `candidate-pair`, `local-candidate`, `remote-candidate`.

Examples
--------

This simple example obtains the statistics for an `RTCRtpReceiver` and updates an element's `innerText` to display the number of packets lost.

```js
receiver.getStats().then((stats) => {
  document.getElementById("lostpackets").innerText = stats.packetsLost;
});
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # widl-RTCRtpReceiver-getStats-Promise-RTCStatsReport |

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

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

See also
--------

* WebRTC API
* `RTCStatsReport`
* `RTCRtpSender.getStats()`
* `RTCPeerConnection.getStats()`


RTCRtpReceiver: track property - Web APIs

RTCRtpReceiver: track property
==============================

 The **`track`** read-only property of the
 `RTCRtpReceiver` interface returns the `MediaStreamTrack`
 associated with the current `RTCRtpReceiver` instance.

Value
-----

A `MediaStreamTrack` instance.

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

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

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

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


RTCRtpReceiver: getCapabilities() static method - Web APIs

RTCRtpReceiver: getCapabilities() static method
===============================================

The *static method* **`RTCRtpReceiver.getCapabilities()`** returns an object describing the codec and header extension capabilities supported by `RTCRtpReceiver` objects on the current device.

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

Syntax
------

```js
RTCRtpReceiver.getCapabilities(kind)
```

### Parameters

`kind`

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

### Return value

 A new object that indicates what capabilities the browser has for receiving 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 `RTCRtpReceiver`.

**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 = RTCRtpReceiver.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 `RTCRtpReceiver.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 `RTCRtpReceiver.getCapabilities()` is supported:
```

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

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

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

### Checking support for a particular codec

The function below returns a Boolean indicating whether or not the device supports receiving H.264 video on a WebRTC connection.

**Note:** Since `RTCRtpReceiver.getCapabilities()` actually only indicates > *probable* support, attempting to receive H.264 video might still fail even after getting a positive response from this function.

```js
function canReceiveH264() {
  let capabilities = RTCRtpReceiver.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) {
  if (!Object.hasOwn(RTCRtpReceiver, "getCapabilities")) {
    log.textContent = "RTCRtpReceiver.getCapabilities() not supported";
    return;
  }
  const capabilities = RTCRtpReceiver.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-rtcrtpreceiver-getcapabilities |

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

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


RTCRtpReceiver: transport property - Web APIs

RTCRtpReceiver: transport property
==================================

 The read-only **`transport`** property of an
 `RTCRtpReceiver` object provides the `RTCDtlsTransport` object
 used to interact with the underlying transport over which the receiver is exchanging
 Real-time Transport Control Protocol (RTCP) packets.

 This transport is responsible for receiving the data for the media on the receiver's
 `track`.

Syntax
------

```js
rtcRtpReceiver.transport
```

### Value

 An `RTCDtlsTransport` object representing the underlying transport being
 used by the receiver to exchange packets with the remote peer, or `null` if
 the receiver isn't yet connected to a transport.

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

 When the `RTCRtpReceiver` is first created, the value of
 `transport` is `null`. This is replaced with an
 `RTCDtlsTransport` once the receiver's transport has been established.

 Note that when bundling is in effect—that is, when the `RTCPeerConnection`
 was created with a configuration object whose `bundlePolicy` is `max-compat`
 or `max-bundle`—multiple receivers may be sharing the same transport; in this
 case, all of them are using the same connection to transmit and/or receive
 RTP and RTCP packets.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcrtpreceiver-transport |

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

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


RTCDataChannel: label property - Web APIs

RTCDataChannel: label property
==============================

 The read-only `RTCDataChannel` property **`label`**
 returns a string containing a name describing the data channel. These
 labels are not required to be unique.

 You may use the label as you wish; you could use it to identify all the channels that
 are being used for the same purpose, by giving them all the same name. Or you could give
 each channel a unique label for tracking purposes. It's entirely up to the design
 decisions made when building your site or app.

A unique ID can be found in the `id` property.

**Note:** A data channel's label is set when the channel is created by calling
 `RTCPeerConnection.createDataChannel()`. It cannot be changed after that.

Value
-----

 A string identifier assigned by the website or app when the data channel was created,
 as specified when `RTCPeerConnection.createDataChannel()` was called to
 create the channel.

Example
-------

 This sample creates a data channel on an `RTCPeerConnection`, then, some
 time later, sets the content of a UI element to display the channel's name.

```js
const pc = new RTCPeerConnection();
const dc = pc.createDataChannel("my channel");

// …

document.getElementById("channel-name").innerHTML =
  `<span class='channelName'>${dc.label}</span>`;
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-datachannel-label |

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

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

See also
--------

* WebRTC
* `RTCDataChannel`
* `RTCDataChannel.id`
* `RTCPeerConnection.createDataChannel()`


RTCDataChannel: reliable property - Web APIs

RTCDataChannel: reliable property
=================================

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

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

 The read-only `RTCDataChannel` property
 **`reliable`** indicates whether or not the data channel is
 reliable.

**Warning:** This property is obsolete. Use `RTCDataChannel.ordered` instead in any
 new code, and update existing code as soon as possible.

Value
-----

`true` if the `RTCDataChannel`'s connection is reliable;
 `false` if it isn't.

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

No longer part of any specification.

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

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

See also
--------

* WebRTC
* `RTCDataChannel`
* `RTCDataChannel.ordered`


RTCDataChannel: protocol property - Web APIs

RTCDataChannel: protocol property
=================================

 The read-only `RTCDataChannel` property
 **`protocol`** returns a string containing the
 name of the subprotocol in use. If no protocol was specified when the data channel was
 created, then this property's value is the empty string (`""`).

**Note:** The permitted values of this property are defined by the website or app using the
 data channel.

 The ability for each channel to have a defined subprotocol lets your app, for example,
 use JSON objects as messages on one channel while another channel is plaintext and
 another is raw binary or even some other format.

Value
-----

 A string identifying the app-defined subprotocol being used for exchanging data on the
 channel. If none has been established, this is an empty string ("").

Example
-------

```js
const pc = new RTCPeerConnection();
const dc = pc.createDataChannel("my channel", {
  protocol: "json",
});

function handleChannelMessage(dataChannel, msg) {
  switch (dataChannel.protocol) {
    case "json":
      /\* process JSON data \*/
      break;
    case "raw":
      /\* process raw binary data \*/
      break;
  }
}
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-datachannel-protocol |

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

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

See also
--------

* WebRTC
* `RTCDataChannel`
* `RTCPeerConnection.createDataChannel()`


RTCDataChannel: bufferedAmountLowThreshold property - Web APIs

RTCDataChannel: bufferedAmountLowThreshold property
===================================================

 The `RTCDataChannel` property
 **`bufferedAmountLowThreshold`** is used to specify the number
 of bytes of buffered outgoing data that is considered "low." The default value is
 0. When the number of buffered outgoing bytes, as indicated by the
 `bufferedAmount` property, falls to or
 below this value, a `bufferedamountlow` event is fired. This event may be
 used, for example, to implement code which queues more messages to be sent whenever
 there's room to buffer them. Listeners may be added with
 `onbufferedamountlow` or
 `addEventListener()`.

 The user agent may implement the process of actually sending data in any way it
 chooses; this may be done periodically during the event loop or truly asynchronously. As
 messages are actually sent, this value is reduced accordingly.

**Note:** `bufferedamountlow` events are not fired after the data channel is closed.

Value
-----

 The number of queued outgoing data bytes below which the buffer is considered to be
 "low."

Example
-------

 In this snippet of code, `bufferedAmountLowThreshold` is set to 64kB, and a
 handler for the `bufferedamountlow` event is established by setting the
 `onbufferedamountlow` property to a function which should
 send more data into the buffer by calling `send()`.

```js
const dc = peerConnection.createDataChannel("File Transfer");
dc.bufferedAmountLowThreshold = 65535;

dc.onbufferedamountlow = () => {
  /\* use send() to queue more data to be sent \*/
};
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcdatachannel-bufferedamountlowthreshold |

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

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

See also
--------

* WebRTC
* Using WebRTC data channels
* `RTCDataChannel`
* `RTCDataChannel.bufferedAmount`
* `bufferedamountlow` event


RTCDataChannel: ordered property - Web APIs

RTCDataChannel: ordered property
================================

 The read-only `RTCDataChannel` property **`ordered`** indicates
 whether or not the data channel guarantees in-order delivery of messages;
 the default is `true`,
 which indicates that the data channel is indeed ordered.
 This is set when the `RTCDataChannel` is created,
 by setting the `ordered` property
 on the object passed as `RTCPeerConnection.createDataChannel()`'s `options` parameter.

Value
-----

 A boolean value which is `true` if in-order delivery is
 guaranteed and is otherwise `false`.

Example
-------

```js
const pc = new RTCPeerConnection();
const dc = pc.createDataChannel("my channel");

if (!dc.ordered) {
  // Handle unordered messaging
}
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-datachannel-ordered |

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

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

See also
--------

* WebRTC
* `RTCDataChannel`
* `RTCPeerConnection.createDataChannel()`


RTCDataChannel: negotiated property - Web APIs

RTCDataChannel: negotiated property
===================================

 The read-only `RTCDataChannel` property
 **`negotiated`** indicates whether the
 `RTCDataChannel`'s connection was negotiated by the Web app
 (`true`) or by the WebRTC layer (`false`). **The
default is `false`.**

See Creating a data channel for further information about this property.

Value
-----

`true` if the `RTCDataChannel`'s connection was negotiated by
 the Web app itself; `false` if the negotiation was handled by the WebRTC
 layer. The default is `false`.

Example
-------

 The code snippet below checks the value of `negotiated`; if it's
 `true`, a function called `shutdownRemoteChannel()` is called
 with the channel's `id`; presumably this would be
 implemented to transmit a shutdown signal to the remote peer prior to terminating the
 connection.

```js
if (dataChannel.negotiated) {
  shutdownRemoteChannel(dataChannel.id);
}
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-datachannel-negotiated |

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

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

See also
--------

* WebRTC
* Using WebRTC data channels
* `RTCDataChannel`
* `RTCPeerConnection.createDataChannel()`


RTCDataChannel: message event - Web APIs

RTCDataChannel: message event
=============================

The WebRTC **`message`** event is sent to the `onmessage` event handler on an `RTCDataChannel` object when a message has been received from the remote peer.

**Note:** The `message` event uses as its event object type the `MessageEvent` interface defined by the HTML specification.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A `MessageEvent`. Inherits from `Event`.

Event

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

*Also inherits properties from its parent interface, `Event`.*

`MessageEvent.data` Read only

The data sent by the message emitter.

`MessageEvent.origin` Read only

A string representing the origin of the message emitter.

`MessageEvent.lastEventId` Read only

A string representing a unique ID for the event.

`MessageEvent.source` Read only

A reference to the message emitter, one of WindowProxy, `MessagePort`, or `ServiceWorker`.

`MessageEvent.ports` Read only

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

Examples
--------

For a given `RTCDataChannel`, `dc`, created for a peer connection using its `createDataChannel()` method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new `<p>` (paragraph) element.

```js
dc.addEventListener(
  "message",
  (event) => {
    let newParagraph = document.createElement("p");
    let textNode = document.createTextNode(event.data);
    newParagraph.appendChild(textNode);

    document.body.appendChild(newParagraph);
  },
  false,
);
```

Lines 2-4 create the new paragraph element and add the message data to it as a new text node. Line 6 appends the new paragraph to the end of the document's body.

You can also use an `RTCDataChannel` object's `onmessage` event handler property to set the event handler:

```js
dc.onmessage = (event) => {
  let newParagraph = document.createElement("p");
  let textNode = document.createTextNode(event.data);
  newParagraph.appendChild(textNode);

  document.body.appendChild(newParagraph);
};
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # event-datachannel-message |
| WebRTC: Real-Time Communication in Browsers # dom-rtcdatachannel-onmessage |

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

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

See also
--------

* WebRTC API
* A simple RTCDataChannel example
* Related events: `open`, `close`, and `error`
* `RTCDataChannel.send()`


RTCDataChannel: closing event - Web APIs

RTCDataChannel: closing event
=============================

The **`closing`** event is sent to an `RTCDataChannel` just before the channel begins the process of shutting down its underlying data transport.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

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

While the `closing` event is sent to the channel just before beginning to close the channel's data transport, the `close` event is sent once the closing process is complete.

Examples
--------

This example updates a connection status interface when the `closing` event arrives.

First, an example using `addEventListener()`:

```js
dataChannel.addEventListener("closing", (ev) => {
  myConnectionStatus.icon = closingIcon;
  myConnectionStatus.text = "Connection closing";
});
```

You can also set the `onclosing` event handler property directly:

```js
pc.onclosing = (ev) => {
  myConnectionStatus.icon = closingIcon;
  myConnectionStatus.text = "Connection closing";
};
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # event-datachannel-closing |
| WebRTC: Real-Time Communication in Browsers # dom-rtcdatachannel-onclosing |

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

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

See also
--------

* WebRTC API
* Signaling and video calling


RTCDataChannel: close event - Web APIs

RTCDataChannel: close event
===========================

The **`close`** event is sent to the `onclose` event handler on an `RTCDataChannel` instance when the data transport for the data channel has closed. Before any further data can be transferred using `RTCDataChannel`, a new 'RTCDataChannel' instance must be created.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

This example sets up a handler for the `close` event for the `RTCDataChannel` named `dc`; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a new call to be started.

```js
dc.addEventListener(
  "close",
  (ev) => {
    messageInputBox.disabled = true;
    sendButton.disabled = true;
    connectButton.disabled = false;
    disconnectButton.disabled = true;
  },
  false,
);
```

All this code does in response to receiving the `close` event is to disable an input box and its "Send" button, and to enable the button used to start a call (while disabling the one that ends a call).

You can also use the `onclose` event handler property to set a handler for `close` events:

```js
dc.onclose = (ev) => {
  messageInputBox.disabled = true;
  sendButton.disabled = true;
  connectButton.disabled = false;
  disconnectButton.disabled = true;
};
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # event-datachannel-close |
| WebRTC: Real-Time Communication in Browsers # dom-rtcdatachannel-onclose |

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

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

See also
--------

* WebRTC API
* A simple RTCDataChannel example
* Related events: `open`, `message`, and `error`


RTCDataChannel: close() method - Web APIs

RTCDataChannel: close() method
==============================

 The **`RTCDataChannel.close()`** method closes the
 `RTCDataChannel`. Either peer is permitted to call this method to initiate
 closure of the channel.

 Closure of the data channel is not instantaneous. Most of the process of closing the
 connection is handled asynchronously; you can detect when the channel has finished
 closing by watching for a `close` event on the data channel.

The sequence of events which occurs in response to this method being called:

1. `RTCDataChannel.readyState` is set to `closing`.
2. A background task is established to handle the remainder of the steps below, and
 `close()` returns to the caller.
3. The transport layer deals with any buffered messages; the protocol layer decides
 whether to send them or discard them.
4. The underlying data transport is closed.
5. The `RTCDataChannel.readyState` property is set to
 `closed`.
6. If the transport was closed with an error,
 the `RTCDataChannel` is sent
 an `error` event
 with its `name` set to `NetworkError`.
7. A `close` event is sent to the channel.
Syntax
------

```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Return value
------------

`undefined`.

Examples
--------

```js
const pc = new RTCPeerConnection();
const dc = pc.createDataChannel("my channel");

dc.onmessage = (event) => {
  console.log(`received: ${event.data}`);
  dc.close(); // We decided to close after the first received message
};

dc.onopen = () => {
  console.log("datachannel open");
};

dc.onclose = () => {
  console.log("datachannel close");
};

// Now negotiate the connection and so forth…
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcdatachannel-close |

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

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

See also
--------

* WebRTC
* `RTCDataChannel`
* `RTCDataChannel.readyState`
* `close` event


RTCDataChannel: maxPacketLifeTime property - Web APIs

RTCDataChannel: maxPacketLifeTime property
==========================================

 The read-only `RTCDataChannel` property
 **`maxPacketLifeTime`** returns the amount of time, in
 milliseconds, the browser is allowed to take to attempt to transmit a message, as set
 when the data channel was created, or `null`. This limits how long
 the browser can continue to attempt to transmit and retransmit the message before giving
 up.

Value
-----

 The number of milliseconds over which the browser may continue to attempt to transmit
 the message until it either succeeds or gives up. If not set when
 `RTCPeerConnection.createDataChannel()` was called to create the data
 channel, this value is `null`.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-datachannel-maxpacketlifetime |

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

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

See also
--------

* WebRTC
* `RTCDataChannel`
* `RTCDataChannel.maxRetransmits`
* `RTCPeerConnection.createDataChannel()`


RTCDataChannel: error event - Web APIs

RTCDataChannel: error event
===========================

A WebRTC `error` event is sent to an `RTCDataChannel` object's `onerror` event handler when an error occurs on the data channel.

The `RTCErrorEvent` object provides details about the error that occurred; see that article for details.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

An `RTCErrorEvent`. Inherits from `Event`.

Event

RTCErrorEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`error` Read only

An `RTCError` object specifying the error which occurred; this object includes the type of error that occurred, and information about where the error occurred (such as which line number in the SDP or what SCTP cause code was at issue).

Examples
--------

```js
// Strings for each of the SCTP cause codes found in RFC
// 4960, section 3.3.10:
// https://datatracker.ietf.org/doc/html/rfc4960#section-3.3.10

const sctpCauseCodes = [
  "No SCTP error",
  "Invalid stream identifier",
  "Missing mandatory parameter",
  "Stale cookie error",
  "Sender is out of resource (i.e., memory)",
  "Unable to resolve address",
  "Unrecognized SCTP chunk type received",
  "Invalid mandatory parameter",
  "Unrecognized parameters",
  "No user data (SCTP DATA chunk has no data)",
  "Cookie received while shutting down",
  "Restart of an association with new addresses",
  "User-initiated abort",
  "Protocol violation",
];

dc.addEventListener(
  "error",
  (ev) => {
    const err = ev.error;

    console.error("WebRTC error: ", err.message);

    // Handle specific error detail types

    switch (err.errorDetail) {
      case "sdp-syntax-error":
        console.error(" SDP syntax error in line ", err.sdpLineNumber);
        break;
      case "idp-load-failure":
        console.error(
          " Identity provider load failure: HTTP error ",
          err.httpRequestStatusCode,
        );
        break;
      case "sctp-failure":
        if (err.sctpCauseCode < sctpCauseCodes.length) {
          console.error(" SCTP failure: ", err.sctpCauseCode);
        } else {
          console.error(" Unknown SCTP error");
        }
        break;
      case "dtls-failure":
        if (err.receivedAlert) {
          console.error(" Received DLTS failure alert: ", err.receivedAlert);
        }
        if (err.sentAlert) {
          console.error(" Sent DLTS failure alert: ", err.receivedAlert);
        }
        break;
    }

    // Add source file name and line information

    console.error(
      " Error in file ",
      err.filename,
      " at line ",
      err.lineNumber,
      ", column ",
      err.columnNumber,
    );
  },
  false,
);
```

The received event provides details in an `RTCError` object called `error`; `RTCError` is an extension of the `DOMException` interface. The error's `name` is `RTCError` and the `message` is an error string specified by the WebRTC layer.

Error information is output to the console using `console.error()`. The `message` string is always output, as is information about the source file's name, line number, and column number at which the error occurred.

In addition, however, depending on the value of `errorDetail`, additional information may be output. Each error type has a different set of information output. For example, an SDP syntax error displays the line number of the error within the SDP, and an SCTP error displays a message corresponding to the SCTP cause code. Other error types similarly output appropriate information.

You can also set up an event handler for `error` events using the `RTCDataChannel` interface's `onerror` event handler property:

```js
dc.onerror = (ev) => {
  const err = ev.error;

  // …
};
```

**Note:** Since `RTCError` is not one of the legacy errors, the value of `RTCError.code` is always 0.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # event-datachannel-error |
| WebRTC: Real-Time Communication in Browsers # dom-rtcdatachannel-onerror |

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

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

See also
--------

* WebRTC API
* A simple RTCDataChannel example
* Related events: `open`, `message`, and `close`


RTCDataChannel: send() method - Web APIs

RTCDataChannel: send() method
=============================

 The **`send()`** method of the
 `RTCDataChannel` interface sends data across the data channel to the
 remote peer.
 This can be done any time except during the initial process of
 creating the underlying transport channel. Data sent before connecting is buffered if
 possible (or an error occurs if it's not possible), and is also buffered if sent while
 the connection is closing or closed.

**Note:** Different browsers have different limitations on the size of the message you can
 send. Specifications exist to define how to automatically fragment large messages, but
 not all browsers implement them, and those that do have various additional
 restrictions. This will get less complicated over time, but for now, if you have
 questions, see Understanding message size limits.

Syntax
------

```js
send(data)
```

### Parameters

`data`

 The data to transmit across the connection. This may be a string,
 a `Blob`, an `ArrayBuffer`, a `TypedArray` or a `DataView` object.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

 Thrown when the data channel has not finished establishing its own connection (that is, its
 `readyState` is `connecting`). The data channel
 must establish its own connection because it uses a transport channel separate from that of the media content. This error occurs without sending or buffering the `data`.

`NetworkError` `DOMException`

 Thrown when the specified `data` would need to be buffered, and there isn't room for
 it in the buffer. In this scenario, the underlying transport is immediately closed.

`TypeError`

 Thrown if the specified `data` is too large for the other peer to receive. Since
 there are multiple techniques for breaking up large data into smaller pieces for
 transfer, it's possible to encounter scenarios in which the other peer does not
 support the same ones. For example, if one peer is a modern browser that supports
 using the `EOR` (End of Record) flag to indicate when a received message is
 the last piece of a multi-part object sent using `send()`. For more
 information about message size restrictions, see
 Understanding message size limits.

Examples
--------

 In this example, a routine called `sendMessage()` is created; it accepts an
 object as input and sends to the remote peer, over the `RTCDataChannel`, a
 JSON string with the specified object and a timestamp.

```js
const pc = new RTCPeerConnection();
const dc = pc.createDataChannel("BackChannel");

function sendMessage(msg) {
  const obj = {
    message: msg,
    timestamp: new Date(),
  };
  dc.send(JSON.stringify(obj));
}
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcdatachannel-send |

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

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

See also
--------

* WebRTC
* `RTCDataChannel`
* `RTCDataChannel.readyState`
* `close` event