MediaTrackSupportedConstraints: logicalSurface property - Web APIs

MediaTrackSupportedConstraints: logicalSurface property
=======================================================

The `MediaTrackSupportedConstraints` dictionary's **`logicalSurface`** property indicates whether or not the `logicalSurface` constraint is supported by the user agent and the device on which the content is being used.

The supported constraints list is obtained by calling `navigator.mediaDevices.getSupportedConstraints()`.

Syntax
------

```js
isLogicalSurfaceSupported = supportedConstraints.logicalSurface
```

### Value

A boolean value which is `true` if the `logicalSurface` constraint is supported by the device and user agent.

Example
-------

 This method sets up the constraints object specifying the options for the call to
 `getDisplayMedia()`. It adds the
 `logicalSurface` constraint (requesting that only logical display
 surfaces—those which may not be entirely visible onscreen—be included among the options
 available to the user) only if it is known to be supported by the browser. Capturing is
 then started by calling `getDisplayMedia()` and attaching the returned stream
 to the video element referenced by the variable `videoElem`.

```js
async function capture() {
  const supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
  const displayMediaOptions = {
    video: {},
    audio: false,
  };

  if (supportedConstraints.logicalSurface) {
    displayMediaOptions.video.logicalSurface = "monitor";
  }

  try {
    videoElem.srcObject =
      await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
  } catch (err) {
    /\* handle the error \*/
  }
}
```

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

| Specification |
| --- |
| Screen Capture # dom-mediatracksupportedconstraints-logicalsurface |

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

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

See also
--------

* Screen Capture API
* Using the screen capture API
* Capabilities, constraints, and settings
* `MediaDevices.getDisplayMedia()`
* `MediaStreamTrack.getConstraints()`
* `MediaStreamTrack.applyConstraints()`
* `MediaStreamTrack.getSettings()`


MediaTrackSupportedConstraints: displaySurface property - Web APIs

MediaTrackSupportedConstraints: displaySurface property
=======================================================

The `MediaTrackSupportedConstraints` dictionary's **`displaySurface`** property indicates whether or not the `displaySurface` constraint is supported by the user agent and the device on which the content is being used.

The supported constraints list is obtained by calling `navigator.mediaDevices.getSupportedConstraints()`.

Value
-----

A Boolean value which is `true` if the `displaySurface` constraint is supported by the device and user agent.

Examples
--------

 This method sets up the constraints object specifying the options for the call to
 `getDisplayMedia()`. It adds the
 `displaySurface` constraint (requesting that only fullscreen sharing be
 allowed) only if it is known to be supported by the browser. Capturing is then started
 by calling `getDisplayMedia()` and attaching the returned stream to the video
 element referenced by the variable `videoElem`.

```js
async function capture() {
  let supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
  let displayMediaOptions = {
    video: {},
    audio: false,
  };

  if (supportedConstraints.displaySurface) {
    displayMediaOptions.video.displaySurface = "monitor";
  }

  try {
    videoElem.srcObject =
      await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
  } catch (err) {
    /\* handle the error \*/
  }
}
```

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

| Specification |
| --- |
| Screen Capture # dom-mediatracksupportedconstraints-displaysurface |

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

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

See also
--------

* Screen Capture API
* Using the screen capture API
* Capabilities, constraints, and settings
* `MediaDevices.getDisplayMedia()`
* `MediaStreamTrack.getConstraints()`
* `MediaStreamTrack.applyConstraints()`
* `MediaStreamTrack.getSettings()`


CSSUnparsedValue: values() method - Web APIs

CSSUnparsedValue: values() method
=================================

 The **`CSSUnparsedValue.values()`** method
 returns a new *array iterator* object that contains the
 values for each index in the CSSUnparsedValue object.

Syntax
------

```js
values()
```

### Parameters

None.

### Return value

A new `Array`.

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

#### No specification found

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

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

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

See also
--------

* `CSSUnparsedValue()`
* `CSSUnparsedValue.entries`
* `CSSUnparsedValue.forEach`
* `CSSUnparsedValue.keys`
* `CSSUnparsedValue.length`
* Using the CSS Typed OM
* CSS Typed Object Model API


CSSUnparsedValue: length property - Web APIs

CSSUnparsedValue: length property
=================================

 The **`length`** read-only property of the
 `CSSUnparsedValue` interface returns the number of items in the object.

Value
-----

An integer.

Examples
--------

 In this example we employ the `CSSUnparsedValue()`
 constructor, then query the length:

```js
const values = new CSSUnparsedValue(["1em", "#445566", "-45px"]);

console.log(values.length); // 3
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssunparsedvalue-length |

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

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

See also
--------

* `CSSUnparsedValue()`
* `CSSUnparsedValue.entries`
* `CSSUnparsedValue.forEach`
* `CSSUnparsedValue.keys`
* `CSSUnparsedValue.values`
* Using the CSS Typed OM
* CSS Typed Object Model API


CSSUnparsedValue: keys() method - Web APIs

CSSUnparsedValue: keys() method
===============================

 The **`CSSUnparsedValue.keys()`** method
 returns a new *array iterator* object that contains the keys
 for each index in the array.

Syntax
------

```js
keys()
```

### Parameters

None.

### Return value

A new `Array`.

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

#### No specification found

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

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

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

See also
--------

* `CSSUnparsedValue()`
* `CSSUnparsedValue.entries`
* `CSSUnparsedValue.forEach`
* `CSSUnparsedValue.length`
* `CSSUnparsedValue.values`
* Using the CSS Typed OM
* CSS Typed Object Model API


CSSUnparsedValue: forEach() method - Web APIs

CSSUnparsedValue: forEach() method
==================================

 The **`CSSUnparsedValue.forEach()`** method
 executes a provided function once for each element of the
 `CSSUnparsedValue`.

Syntax
------

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

### Parameters

`callbackFn`

The function to execute for each element, taking three arguments:

`currentValue`

The value of the current element being processed.

`index` Optional

The index of the current element being processed.

`array` Optional

 The `CSSUnparsedValue` that `forEach()` is being called
 on.

`thisArg` Optional

 Value to use as **`this`** (i.e., the reference
 `Object`) when executing `callback`.

### Return value

None (`undefined`).

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

#### No specification found

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

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

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

See also
--------

* `CSSUnparsedValue()`
* `CSSUnparsedValue.entries`
* `CSSUnparsedValue.keys`
* `CSSUnparsedValue.length`
* `CSSUnparsedValue.values`
* Using the CSS Typed OM
* CSS Typed Object Model API


CSSUnparsedValue: entries() method - Web APIs

CSSUnparsedValue: entries() method
==================================

 The **`CSSUnparsedValue.entries()`** method
 returns an array of a given object's own enumerable property `[key, value]`
 pairs in the same order as that provided by a `for...in` loop (the difference being that a for-in loop enumerates properties in the
 prototype chain as well).

Syntax
------

```js
entries(obj)
```

### Parameters

`obj`

 The `CSSUnparsedValue` whose enumerable own property
 `[key, value]` pairs are to be returned.

### Return value

 An array of the given `CSSUnparsedValue` object's own enumerable property
 `[key, value]` pairs.

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

#### No specification found

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

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

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

See also
--------

* `CSSUnparsedValue()`
* `CSSUnparsedValue.forEach`
* `CSSUnparsedValue.keys`
* `CSSUnparsedValue.length`
* `CSSUnparsedValue.values`
* Using the CSS Typed OM
* CSS Typed Object Model API


CSSUnparsedValue: CSSUnparsedValue() constructor - Web APIs

CSSUnparsedValue: CSSUnparsedValue() constructor
================================================

 The **`CSSUnparsedValue()`** constructor
 creates a new `CSSUnparsedValue` object which represents property values
 that reference custom properties.

Syntax
------

```js
new CSSUnparsedValue(members)
```

### Parameters

`members`

 An array whose values must be either a string or a
 `CSSVariableReferenceValue`.

Examples
--------

```js
const value = new CSSUnparsedValue(["4deg"]);
const values = new CSSUnparsedValue(["1em", "#445566", "-45px"]);

console.log(value); // CSSUnparsedValue {0: "4deg", length: 1}
console.log(values); // CSSUnparsedValue {0: "1em", 1: "#445566", 2: "-45px", length: 3}
```

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

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

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

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

See also
--------

* `CSSUnparsedValue.entries`
* `CSSUnparsedValue.forEach`
* `CSSUnparsedValue.keys`
* `CSSUnparsedValue.length`
* `CSSUnparsedValue.values`
* Using the CSS Typed OM
* CSS Typed Object Model API


PaymentAddress: toJSON() method - Web APIs

PaymentAddress: toJSON() method
===============================

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

**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 **`toJSON()`** method of the `PaymentAddress` interface is a standard serializer that returns a JSON representation of the PaymentAddress object's properties.

Syntax
------

```js
toJSON()
```

### Return value

A JSON object.

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

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


PaymentAddress: region property - Web APIs

PaymentAddress: region property
===============================

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

**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 **`region`** property of the
 `PaymentAddress` interface returns a string containing the top-level
 administrative subdivision of the country in which the address is located. For example,
 this may be a state, province, oblast, or prefecture.

Value
-----

 A string specifying the top-level administrative subdivision within
 the country in which the address is located. This region has different names in
 different countries, such as: state, province, oblast, prefecture, or county.

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

 In some countries, like Belgium, it's uncommon for people to provide a region as part
 of their postal address. In such cases, the browser returns an empty string as the value
 of `region`. However, the address should still be acceptable to use for its
 intended purpose (e.g., to ship a product). However, always verify addresses to make
 sure what the user provides is usable.

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

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


PaymentAddress: city property - Web APIs

PaymentAddress: city property
=============================

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

**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 **`city`** read-only property of
 the `PaymentAddress` interface returns a string containing the city or
 town portion of the address.

Value
-----

 A string indicating the city or town portion of the address described
 by the `PaymentAddress` object.

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

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


PaymentAddress: phone property - Web APIs

PaymentAddress: phone property
==============================

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

**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 **`phone`** property of the
 `PaymentAddress` interface returns a string containing the telephone number
 of the recipient or contact person.

Value
-----

 A string containing the telephone number for the recipient of the
 shipment or of the responsible party for payment. If no phone number is available, this
 value is an empty string.

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

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


PaymentAddress: dependentLocality property - Web APIs

PaymentAddress: dependentLocality property
==========================================

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

**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 **`dependentLocality`**
 property of the `PaymentAddress` interface is a string containing a
 sublocality designation within a city, such as a neighborhood, borough, district, or,
 in the United Kingdom, a dependent locality. Also known as a *post
town*.

Value
-----

 A string indicating the sublocality portion of the address. This may
 be an empty string if no sublocality is available or required. It's used to provide
 disambiguation when a city may include areas that duplicate street names

 A sublocality is an area within a city, such as a neighborhood, borough, or district.
 In the United Kingdom, this is used to indicate the **post town** in the
 United Kingdom (known officially by the Royal Mail as the **dependent
locality**). This is a disambiguating feature of addresses in places where a
 city may have areas that duplicate street names.

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

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


PaymentAddress: postalCode property - Web APIs

PaymentAddress: postalCode property
===================================

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

**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 **`postalCode`** read-only property of the
 `PaymentAddress` interface returns a string containing a code used by a
 jurisdiction for mail routing, for example, the ZIP Code
 in the United States or the Postal Index Number (PIN code)
 in India.

Value
-----

 A string which contains the postal code portion of the address. A
 postal code is a string (either numeric or alphanumeric) which is used by a postal
 service to optimize mail routing and delivery.

 Various countries use different terms for this. In most of the world, it's known as the
 "post code" or "postal code." In the United States, the ZIP code is used. India uses PIN
 codes.

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

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

See also
--------

* Universal Postal Union: Universal Post\*Code® Database


PaymentAddress: addressLine property - Web APIs

PaymentAddress: addressLine property
====================================

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

**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 **`addressLine`** read-only
 property of the `PaymentAddress` interface is an array of
 strings, each specifying a line of the address that is not
 covered by one of the other properties of `PaymentAddress`.

 These
 lines may include the street name, house number, apartment number, rural delivery route,
 descriptive instructions, or post office box.

Value
-----

 An array of strings, each containing one line of the address.
 For example, the `addressLine` array for the Mozilla Space in London would
 have the following entries:

| Index | addressLine[] value |
| --- | --- |
| 0 | Metal Box Factory |
| 1 | Suite 441, 4th floor |
| 2 | 30 Great Guildford Street |

 These, combined with additional values for other properties of the
 `PaymentAddress`, would represent the full address, which is:

 Mozilla
 Metal Box Factory
 Suite 441, 4th floor
 30 Great Guildford Street
 London SE1 0HS
 United Kingdom

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

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


PaymentAddress: sortingCode property - Web APIs

PaymentAddress: sortingCode property
====================================

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

**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 **`sortingCode`** read-only property of the
 `PaymentAddress` interface returns a string containing a postal sorting
 code such as is used in France.

Value
-----

A string containing the sorting code portion of the address.

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

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


PaymentAddress: recipient property - Web APIs

PaymentAddress: recipient property
==================================

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

**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 **`recipient`** property of the
 `PaymentAddress` interface returns a string containing the name of the
 recipient, purchaser, or contact person at the payment address.

Value
-----

 A string giving the name of the person receiving or paying for the
 purchase, or the name of a contact person in other contexts. If no name is available,
 this string is empty.

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

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


PaymentAddress: country property - Web APIs

PaymentAddress: country property
================================

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

**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 **`country`** read-only property of the
 `PaymentAddress` interface is a string identifying the address's country
 using the ISO 3166-1 alpha-2 standard. The string is
 always in its canonical upper-case form.

 Some examples of valid `country` values: `"US"`,
 `"GB"`, `"CN"`, or `"JP"`.

Value
-----

 A string which contains the ISO3166-1 alpha-2 code identifying the
 country in which the address is located, or an empty string if no country is available,
 which frequently can be assumed to mean "same country as the site owner."

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

 If the payment handler validates the address and determines that the value of
 `country` is invalid, a call to
 `PaymentRequestUpdateEvent.updateWith()` will be made with a
 `details` object containing a `shippingAddressErrors`
 field. That field contains an object whose
 `country` property is a string indicating the
 validation error that occurred and, if possible, suggestions on how to fix it.

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

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

See also
--------

* Using the Payment Request API
* `PaymentRequestUpdateEvent.updateWith`


PaymentAddress: organization property - Web APIs

PaymentAddress: organization property
=====================================

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

**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 **`organization`** read-only
 property of the `PaymentAddress` interface returns a string containing
 the name of the organization, firm, company, or institution at the address.

Value
-----

 A string whose value is the name of the organization or company
 located at the address described by the `PaymentAddress` object. This should
 be the name of the organization that is to receive the shipment for shipping addresses,
 or which is responsible for payment addresses.

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

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


ContentIndexEvent: id property - Web APIs

ContentIndexEvent: id property
==============================

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

 The read-only **`id`** property of the
 `ContentIndexEvent` interface is a `String` which identifies
 the deleted content index via its `id`.

Value
-----

A `String` representation of the deleted content index id.

Examples
--------

 This example listens for the `contentdelete` event
 and logs the removed content index id.

 The `ContentIndexEvent` is only available to the
 global scope of a
 `ServiceWorker`.

```js
self.addEventListener("contentdelete", (event) => {
  console.log(event.id);

  // logs content index id, which can then be used to determine what content to delete from your cache
});
```

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

| Specification |
| --- |
| Content Index # dom-contentindexevent-id |

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

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

See also
--------

* An introductory article on the Content Index API
* An app which uses the Content Index API to list and remove 'save for later' content
* Service Worker API, along with information about Cache and CacheStorage


ContentIndexEvent: ContentIndexEvent() constructor - Web APIs

ContentIndexEvent: ContentIndexEvent() constructor
==================================================

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

 The **`ContentIndexEvent()`** constructor creates a new `ContentIndexEvent` object
 whose type and other options are configured as specified.

Syntax
------

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

### Parameters

`type`

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

`options`

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

`id`

The id of the indexed content you want the `ContentIndex` object to remove.

### Return value

A new `ContentIndexEvent` object configured using the given options.

Examples
--------

This examples constructs a new `ContentIndexEvent` with the relevant id.

```js
const removeData = {
  id: "unique-content-id",
};

const ciEvent = new ContentIndexEvent("contentdelete", removeData);

ciEvent.id; // should return 'unique-content-id'
```

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

| Specification |
| --- |
| Content Index # content-index-event |

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

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

See also
--------

* An introductory article on the Content Index API
* An app which uses the Content Index API to list and remove 'save for later' content
* Service Worker API, along with information about Cache and CacheStorage


HIDConnectionEvent: HIDConnectionEvent() constructor - Web APIs

HIDConnectionEvent: HIDConnectionEvent() constructor
====================================================

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

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

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

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

The **`HIDConnectionEvent()`** constructor creates a new `HIDConnectionEvent` object. Typically this constructor is not used as events are created when an input report is received.

Syntax
------

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

### Parameters

`type`

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

`options`

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

`device`

The `HIDDevice` instance representing the device sending the input report.

### Return value

A new `HIDConnectionEvent` object.

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

| Specification |
| --- |
| WebHID API # dom-hidconnectionevent-constructor |

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

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


HIDConnectionEvent: device property - Web APIs

HIDConnectionEvent: device property
===================================

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

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

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

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

The **`device`** read-only property of the `HIDConnectionEvent` interface returns the `HIDDevice` associated with this connection event.

Value
-----

A `HIDDevice`.

Examples
--------

The following example registers event listeners for `connect` and `disconnect` events, then prints the `HIDDevice.productName` to the console.

```js
navigator.hid.addEventListener("connect", ({ device }) => {
  console.log(`HID connected: ${device.productName}`);
});

navigator.hid.addEventListener("disconnect", ({ device }) => {
  console.log(`HID disconnected: ${device.productName}`);
});
```

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

| Specification |
| --- |
| WebHID API # dom-hidconnectionevent-device |

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

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


Touch: target property - Web APIs

Touch: target property
======================

The read-only **`target`** property of the `Touch` interface returns the (`EventTarget`) on which the touch contact started when it was first placed on the surface, even if the touch point has since moved outside the interactive area of that element or even been removed from the document. Note that if the target element is removed from the document, events will still be targeted at it, and hence won't necessarily bubble up to the window or document anymore. If there is any risk of an element being removed while it is being touched, the best practice is to attach the touch listeners directly to the target.

Value
-----

The `EventTarget` the `Touch` object applies to.

Examples
--------

This example illustrates how to access the `Touch` object's `Touch.target` property. The `Touch.target` property is an `Element` (`EventTarget`) on which a touch point is started when contact is first placed on the surface.

In following simple code snippet, we assume the user initiates one or more touch contacts on the `source` element. When the `touchstart` event handler for this element is invoked, each touch point's `Touch.target` property is accessed via the event's `TouchEvent.targetTouches` list.

```js
// Register a touchmove listener for the 'source' element
const src = document.getElementById("source");

src.addEventListener(
  "touchstart",
  (e) => {
    // Iterate through the touch points that were activated
    // for this element.
    for (let i = 0; i < e.targetTouches.length; i++) {
      console.log(`touchpoint[${i}].target = ${e.targetTouches[i].target}`);
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Touch Events # dom-touch-target |

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

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


Touch: clientY property - Web APIs

Touch: clientY property
=======================

 The **`Touch.clientY`** read-only property returns the Y
 coordinate of the touch point relative to the browser's viewport, not including any
 scroll offset.

Value
-----

 A `double` floating point value representing the Y coordinate of the touch point
 relative to the viewport, not including any scroll offset.

Examples
--------

 This example illustrates using the `Touch` object's
 `Touch.clientX` and `Touch.clientY` properties. The
 `Touch.clientX` property is the horizontal coordinate of a touch point
 relative to the browser's viewport excluding any scroll offset. The
 `Touch.clientY` property is the vertical coordinate of the touch point
 relative to the browser's viewport excluding any scroll offset .

 In this example, we assume the user initiates a touch on an element with an id of
 `source`, moves within the element or out of the element and then releases
 contact with the surface. When the `touchend`
 event handler is invoked, the changes in the `Touch.clientX` and
 `Touch.clientY` coordinates, from the starting touch point to the ending
 touch point, are calculated.

```js
// Register touchstart and touchend listeners for element 'source'
const src = document.getElementById("source");
let clientX;
let clientY;

src.addEventListener(
  "touchstart",
  (e) => {
    // Cache the client X/Y coordinates
    clientX = e.touches[0].clientX;
    clientY = e.touches[0].clientY;
  },
  false,
);

src.addEventListener(
  "touchend",
  (e) => {
    let deltaX;
    let deltaY;

    // Compute the change in X and Y coordinates.
    // The first touch point in the changedTouches
    // list is the touch point that was just removed from the surface.
    deltaX = e.changedTouches[0].clientX - clientX;
    deltaY = e.changedTouches[0].clientY - clientY;

    // Process the data…
  },
  false,
);
```

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

| Specification |
| --- |
| Touch Events # dom-touch-clienty |

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

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


Touch: force property - Web APIs

Touch: force property
=====================

 The **`Touch.force`** read-only property returns the amount of
 pressure the user is applying to the touch surface for a `Touch` point.

Value
-----

 A `float` that represents the amount of pressure the user is applying to the
 touch surface. This is a value between `0.0` (no pressure) and
 `1.0` (the maximum amount of pressure the hardware can recognize). A value of
 `0.0` is returned if no value is known (for example the touch device does not
 support this property). In environments where force is known, the absolute pressure
 represented by the force attribute, and the sensitivity in levels of pressure, may vary.

Examples
--------

 This example illustrates using the `Touch` interface's
 `Touch.force` property. This property is a relative value of pressure
 applied, in the range `0.0` to `1.0`, where `0.0` is no
 pressure, and `1.0` is the highest level of pressure the touch device is
 capable of sensing.

 In following code snippet, the `touchstart` event handler iterates through
 the `targetTouches` list and logs the `force` value of each touch
 point but the code could invoke different processing depending on the value.

```js
someElement.addEventListener(
  "touchstart",
  (e) => {
    // Iterate through the list of touch points and log each touch
    // point's force.
    for (let i = 0; i < e.targetTouches.length; i++) {
      // Add code to "switch" based on the force value. For example
      // minimum pressure vs. maximum pressure could result in
      // different handling of the user's input.
      console.log(`targetTouches[${i}].force = ${e.targetTouches[i].force}`);
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Touch Events # dom-touch-force |

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

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


Touch: screenY property - Web APIs

Touch: screenY property
=======================

Returns the Y coordinate of the touch point relative to the screen, not including any scroll offset.

Value
-----

A number.

Examples
--------

The Touch.screenX example includes an example of this property's usage.

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

| Specification |
| --- |
| Touch Events # dom-touch-screeny |

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

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


Touch: screenX property - Web APIs

Touch: screenX property
=======================

Returns the X coordinate of the touch point relative to the screen, not including any scroll offset.

Value
-----

A number.

Examples
--------

This example illustrates how to access the `Touch` object's `Touch.screenX` and `Touch.screenY` properties. The `Touch.screenX` property is the horizontal (x) coordinate of a touch point relative to the screen in CSS pixels. The `Touch.screenY` property is the vertical coordinate of a touch point relative to the screen in CSS pixels.

In following simple code snippet, we assume the user initiates multiple touch contacts on an element with an id of `source` and then releases contacts with the surface. When the `touchstart` event handler is invoked, each touch point's `Touch.screenX` and `Touch.screenY` coordinates are accessed.

```js
// Register a touchstart listeners for the 'source' element
const src = document.getElementById("source");

src.addEventListener(
  "touchstart",
  (e) => {
    // Iterate through the touch points and log each screenX/Y coordinate.
    // The unit of each coordinate is CSS pixels.
    for (let i = 0; i < e.touches.length; i++) {
      console.log(`touchpoint[${i}].screenX = ${e.touches[i].screenX}`);
      console.log(`touchpoint[${i}].screenY = ${e.touches[i].screenY}`);
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Touch Events # dom-touch-screenx |

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

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


Touch: clientX property - Web APIs

Touch: clientX property
=======================

 The `Touch.clientX` read-only property returns the X coordinate of the touch
 point relative to the viewport, not including any scroll offset.

Value
-----

 A `double` floating point value representing the X coordinate of the touch point
 relative to the viewport, not including any scroll offset.

Examples
--------

 This example illustrates using the `Touch` object's
 `Touch.clientX` and `Touch.clientY` properties. The
 `Touch.clientX` property is the horizontal coordinate of a touch point
 relative to the browser's viewport excluding any scroll offset. The
 `Touch.clientY` property is the vertical coordinate of the touch point
 relative to the browser's viewport excluding any scroll offset .

 In this example, we assume the user initiates a touch on an element with an id of
 `source`, moves within the element or out of the element and then releases
 contact with the surface. When the `touchend`
 event handler is invoked, the changes in the `Touch.clientX` and
 `Touch.clientY` coordinates, from the starting touch point to the ending
 touch point, are calculated.

```js
// Register touchstart and touchend listeners for element 'source'
const src = document.getElementById("source");
let clientX;
let clientY;

src.addEventListener(
  "touchstart",
  (e) => {
    // Cache the client X/Y coordinates
    clientX = e.touches[0].clientX;
    clientY = e.touches[0].clientY;
  },
  false,
);

src.addEventListener(
  "touchend",
  (e) => {
    let deltaX;
    let deltaY;

    // Compute the change in X and Y coordinates.
    // The first touch point in the changedTouches
    // list is the touch point that was just removed from the surface.
    deltaX = e.changedTouches[0].clientX - clientX;
    deltaY = e.changedTouches[0].clientY - clientY;

    // Process the data…
  },
  false,
);
```

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

| Specification |
| --- |
| Touch Events # dom-touch-clientx |

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

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


Touch: radiusX property - Web APIs

Touch: radiusX property
=======================

The **`radiusX`** read-only property of the `Touch` interface returns the X radius of the ellipse that most closely circumscribes the area of contact with the touch surface. The value is in CSS pixels of the same scale as `Touch.screenX`.

This value, in combination with `Touch.radiusY` and `Touch.rotationAngle` constructs an ellipse that approximates the size and shape of the area of contact between the user and the screen. This may be a relatively large ellipse representing the contact between a fingertip and the screen or a small area representing the tip of a stylus, for example.

Value
-----

A number.

Examples
--------

This example illustrates using the `Touch` interface's `Touch.radiusX`, `Touch.radiusX` and `Touch.rotationAngle` properties. The `Touch.radiusX` property is the radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the axis **indicated** by the touch point's `Touch.rotationAngle`. Likewise, the `Touch.radiusY` property is the radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the axis **perpendicular** to that indicated by `Touch.rotationAngle`. The `Touch.rotationAngle` is the angle (in degrees) that the ellipse described by `radiusX` and `radiusY` is rotated clockwise about its center.

The following simple code snippet, registers a single handler for the `touchstart`, `touchmove` and `touchend` events. When the `src` element is touched, the element's width and height will be calculate based on the touch point's `radiusX` and `radiusY` values and the element will then be rotated using the touch point's `rotationAngle`.

```html
<div id="src">…</div>
```

```js
const src = document.getElementById("src");

src.addEventListener("touchstart", rotate);
src.addEventListener("touchmove", rotate);
src.addEventListener("touchend", rotate);

function rotate(e) {
  const touch = e.changedTouches.item(0);

  // Turn off default event handling
  e.preventDefault();

  // Rotate element 'src'.
  src.style.width = `${touch.radiusX \* 2}px`;
  src.style.height = `${touch.radiusY \* 2}px`;
  src.style.transform = `rotate(${touch.rotationAngle}deg)`;
}
```

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

| Specification |
| --- |
| Touch Events # dom-touch-radiusx |

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

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


Touch: pageX property - Web APIs

Touch: pageX property
=====================

 The **`Touch.pageX`** read-only property returns the X
 coordinate of the touch point relative to the viewport, including any scroll offset.

Value
-----

 A `double` floating point value representing the X coordinate of the touch point
 relative to the viewport, including any scroll offset.

Examples
--------

 This example illustrates how to access the `Touch` object's
 `Touch.pageX` and `Touch.pageY` properties. The
 `Touch.pageX` property is the horizontal coordinate of a touch point
 relative to the viewport (in CSS pixels), including any scroll offset. The
 `Touch.pageY` property is the vertical coordinate of a touch point relative
 to the viewport (in CSS pixels), including any scroll offset.

 In following simple code snippet, we assume the user initiates one or more touch
 contacts on the `source` element, moves the touch points and then releases
 all contacts with the surface. When the `touchmove` event handler is invoked,
 each touch point's `Touch.pageX` and `Touch.pageY` coordinates
 are accessed via the event's `TouchEvent.changedTouches` list.

```js
// Register a touchmove listeners for the 'source' element
const src = document.getElementById("source");

src.addEventListener(
  "touchmove",
  (e) => {
    // Iterate through the touch points that have moved and log each
    // of the pageX/Y coordinates. The unit of each coordinate is CSS pixels.
    for (let i = 0; i < e.changedTouches.length; i++) {
      console.log(`touchpoint[${i}].pageX = ${e.changedTouches[i].pageX}`);
      console.log(`touchpoint[${i}].pageY = ${e.changedTouches[i].pageY}`);
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Touch Events # dom-touch-pagex |

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

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


Touch: Touch() constructor - Web APIs

Touch: Touch() constructor
==========================

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

Syntax
------

```js
new Touch(options)
```

### Parameters

`touchInit`

An object with the following fields:

`identifier`

A `long` value, that is the identification number for the touch point.

`target`

A `EventTarget` object, the item at which the touch point started when it was first placed on the surface.

`clientX` Optional

Defaults to `0`, of type `double`, that is the horizontal position of the touch on the client window of user's screen, excluding any scroll offset.

`clientY` Optional

Defaults to `0`, of type `double`, that is the vertical position of the touch on the client window of the user's screen, excluding any scroll offset.

`screenX` Optional

Defaults to `0`, of type `double`, that is the horizontal position of the touch on the user's screen.

`screenY` Optional

Defaults to `0`, of type `double`, that is the vertical position of the touch on the user's screen.

`pageX` Optional

Defaults to `0`, of type `double`, that is the horizontal position of the touch on the client window of user's screen, including any scroll offset.

`pageY` Optional

Defaults to `0`, of type `double`, that is the vertical position of the touch on the client window of the user's screen, including any scroll offset.

`radiusX` Optional

Defaults to `0`, of type `float`, that is the radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the axis indicated by rotationAngle, in CSS pixels of the same scale as screenX; `0` if no value is known. The value must not be negative.

`radiusY` Optional

Defaults to `0`, of type `float`, that is the radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the axis perpendicular to that indicated by rotationAngle, in CSS pixels of the same scale as screenY; `0` if no value is known. The value must not be negative.

`rotationAngle` Optional

Defaults to `0`, of type `float`, that is the angle (in degrees) that the ellipse described by radiusX and radiusY is rotated clockwise about its center; `0` if no value is known. The value must be greater than or equal to `0` and less than `90`. If the ellipse described by radiusX and radiusY is circular, then rotationAngle has no effect. The user agent may use `0` as the value in this case, or it may use any other value in the allowed range. (For example, the user agent may use the rotationAngle value from the previous touch event, to avoid sudden changes.).

`force` Optional

Defaults to `0`, of type `float`, that is the relative value of pressure applied, in the range `0` to `1`, where `0` is no pressure, and `1` is the highest level of pressure the touch device is capable of sensing; `0` if no value is known. In environments where force is known, the absolute pressure represented by the force attribute, and the sensitivity in levels of pressure, may vary.

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

| Specification |
| --- |
| Touch Events # dom-touch-constructor |

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

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

See also
--------

* `TouchEvent`, the interface of the objects it constructs.


Touch: rotationAngle property - Web APIs

Touch: rotationAngle property
=============================

The **`rotationAngle`** read-only property of the `Touch` interface returns the rotation angle, in degrees, of the contact area ellipse defined by `Touch.radiusX` and `Touch.radiusY`. The value may be between 0 and 90. Together, these three values describe an ellipse that approximates the size and shape of the area of contact between the user and the screen. This may be a relatively large ellipse representing the contact between a fingertip and the screen or a small area representing the tip of a stylus, for example.

Value
-----

A number.

Examples
--------

The Touch.radiusX example includes an example of this property's usage.

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

| Specification |
| --- |
| Touch Events # dom-touch-rotationangle |

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

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


Touch: identifier property - Web APIs

Touch: identifier property
==========================

 The **`Touch.identifier`** returns a value uniquely identifying
 this point of contact with the touch surface. This value remains consistent for every
 event involving this finger's (or stylus's) movement on the surface until it is lifted
 off the surface.

Value
-----

A `long` that represents the unique ID of the `Touch` object.

Examples
--------

```js
someElement.addEventListener(
  "touchmove",
  (e) => {
    // Iterate through the list of touch points that changed
    // since the last event and print each touch point's identifier.
    for (let i = 0; i < e.changedTouches.length; i++) {
      console.log(
        `changedTouches[${i}].identifier = ${e.changedTouches[i].identifier}`,
      );
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Touch Events # dom-touch-identifier |

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

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


Touch: radiusY property - Web APIs

Touch: radiusY property
=======================

The **`radiusY`** read-only property of the `Touch` interface returns the Y radius of the ellipse that most closely circumscribes the area of contact with the touch surface. The value is in CSS pixels of the same scale as `Touch.screenX`.

This value, in combination with `Touch.radiusX` and `Touch.rotationAngle` constructs an ellipse that approximates the size and shape of the area of contact between the user and the screen. This may be a large ellipse representing the contact between a fingertip and the screen or a small one representing the tip of a stylus, for example.

Value
-----

A number.

Examples
--------

The Touch.radiusX example includes an example of this property's usage.

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

| Specification |
| --- |
| Touch Events # dom-touch-radiusy |

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

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


Touch: pageY property - Web APIs

Touch: pageY property
=====================

 The **`Touch.pageY`** read-only property returns the Y
 coordinate of the touch point relative to the viewport, including any scroll offset.

Value
-----

 A `double` floating point value representing the Y coordinate of the touch point
 relative to the viewport, including any scroll offset.

Examples
--------

 This example illustrates how to access the `Touch` object's
 `Touch.pageX` and `Touch.pageY` properties. The
 `Touch.pageX` property is the horizontal coordinate of a touch point
 relative to the viewport (in CSS pixels), including any scroll offset. The
 `Touch.pageY` property is the vertical coordinate of a touch point relative
 to the viewport (in CSS pixels), including any scroll offset.

 In following simple code snippet, we assume the user initiates one or more touch
 contacts on the `source` element, moves the touch points and then releases
 all contacts with the surface. When the `touchmove` event handler is invoked,
 each touch point's `Touch.pageX` and `Touch.pageY` coordinates
 are accessed via the event's `TouchEvent.changedTouches` list.

```js
// Register a touchmove listeners for the 'source' element
const src = document.getElementById("source");

src.addEventListener(
  "touchmove",
  (e) => {
    // Iterate through the touch points that have moved and log each
    // of the pageX/Y coordinates. The unit of each coordinate is CSS pixels.
    for (let i = 0; i < e.changedTouches.length; i++) {
      console.log(`touchpoint[${i}].pageX = ${e.changedTouches[i].pageX}`);
      console.log(`touchpoint[${i}].pageY = ${e.changedTouches[i].pageY}`);
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Touch Events # dom-touch-pagey |

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

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


Recording a media element - Web APIs

Recording a media element
=========================

While the article Using the MediaStream Recording API demonstrates using the `MediaRecorder` interface to capture a `MediaStream` generated by a hardware device, as returned by `navigator.mediaDevices.getUserMedia()`, you can also use an HTML media element (namely `<audio>` or `<video>`) as the source of the `MediaStream` to be recorded. In this article, we'll look at an example that does just that.

Example of recording a media element
------------------------------------

### HTML
```

<p>
  Click the "Start Recording" button to begin video recording for a few seconds.
  You can stop recording by clicking the "Stop Recording" button. The "Download"
  button will download the received data (although it's in a raw, unwrapped form
  that isn't very useful).
</p>
<br />
```

Let's start by looking at the key bits of the HTML. There's a little more than this, but it's just informational rather than being part of the core operation of the app.

```html
<div class="left">
  <div id="startButton" class="button">Start Recording</div>
  <h2>Preview</h2>
  <video id="preview" width="160" height="120" autoplay muted></video>
</div>
```

We present our main interface in two columns. On the left is a start button and a `<video>` element which displays the video preview; this is the video the user's camera sees. Note that the `autoplay` attribute is used so that as soon as the stream starts to arrive from the camera, it immediately gets displayed, and the `muted` attribute is specified to ensure that the sound from the user's microphone isn't output to their speakers, causing an ugly feedback loop.

```html
<div class="right">
  <div id="stopButton" class="button">Stop Recording</div>
  <h2>Recording</h2>
  <video id="recording" width="160" height="120" controls></video>
  <a id="downloadButton" class="button">Download</a>
</div>
```

On the right we see a stop button and the `<video>` element which will be used to play back the recorded video. Notice that the playback panel doesn't have autoplay set (so the playback doesn't start as soon as media arrives), and it has `controls` set, which tells it to show the user controls to play, pause, and so forth.

Below the playback element is a button for downloading the recorded video.
```

<div class="bottom">
  <pre id="log"></pre>
</div>
```

```
body {
  font:
    14px "Open Sans",
    "Arial",
    sans-serif;
}

video {
  margin-top: 2px;
  border: 1px solid black;
}

.button {
  cursor: pointer;
  display: block;
  width: 160px;
  border: 1px solid black;
  font-size: 16px;
  text-align: center;
  padding-top: 2px;
  padding-bottom: 4px;
  color: white;
  background-color: darkgreen;
  text-decoration: none;
}

h2 {
  margin-bottom: 4px;
}

.left {
  margin-right: 10px;
  float: left;
  width: 160px;
  padding: 0px;
}

.right {
  margin-left: 10px;
  float: left;
  width: 160px;
  padding: 0px;
}

.bottom {
  clear: both;
  padding-top: 10px;
}
```

Now let's have a look at the JavaScript code; this is where the majority of the action happens, after all!

### Setting up global variables

We start by establishing some global variables we'll need.

```js
let preview = document.getElementById("preview");
let recording = document.getElementById("recording");
let startButton = document.getElementById("startButton");
let stopButton = document.getElementById("stopButton");
let downloadButton = document.getElementById("downloadButton");
let logElement = document.getElementById("log");

let recordingTimeMS = 5000;
```

Most of these are references to elements we need to work with. The last, `recordingTimeMS`, is set to 5000 milliseconds (5 seconds); this specifies the length of the videos we'll record.

### Utility functions

Next, we create some utility functions that will get used later.

```js
function log(msg) {
  logElement.innerHTML += `${msg}\n`;
}
```

The `log()` function is used to output text strings to a `<div>` so we can share information with the user. Not very pretty but it gets the job done for our purposes.

```js
function wait(delayInMS) {
  return new Promise((resolve) => setTimeout(resolve, delayInMS));
}
```

The `wait()` function returns a new `Promise` which resolves once the specified number of milliseconds have elapsed. It works by using an arrow function which calls `setTimeout()`, specifying the promise's resolution handler as the timeout handler function. That lets us use promise syntax when using timeouts, which can be very handy when chaining promises, as we'll see later.

### Starting media recording

The `startRecording()` function handles starting the recording process:

```js
function startRecording(stream, lengthInMS) {
  let recorder = new MediaRecorder(stream);
  let data = [];

  recorder.ondataavailable = (event) => data.push(event.data);
  recorder.start();
  log(`${recorder.state} for ${lengthInMS / 1000} seconds…`);

  let stopped = new Promise((resolve, reject) => {
    recorder.onstop = resolve;
    recorder.onerror = (event) => reject(event.name);
  });

  let recorded = wait(lengthInMS).then(() => {
    if (recorder.state === "recording") {
      recorder.stop();
    }
  });

  return Promise.all([stopped, recorded]).then(() => data);
}
```

`startRecording()` takes two input parameters: a `MediaStream` to record from and the length in milliseconds of the recording to make. We always record no more than the specified number of milliseconds of media, although if the media stops before that time is reached, `MediaRecorder` automatically stops recording as well.

Line 2

Creates the `MediaRecorder` that will handle recording the input `stream`.

Line 3

Creates an empty array, `data`, which will be used to hold the `Blob`s of media data provided to our `ondataavailable` event handler.

Line 5

Sets up the handler for the `dataavailable` event. The received event's `data` property is a `Blob` that contains the media data. The event handler pushes the `Blob` onto the `data` array.

Lines 6-7

Starts the recording process by calling `recorder.start()`, and outputs a message to the log with the updated state of the recorder and the number of seconds it will be recording.

Lines 9-12

Creates a new `Promise`, named `stopped`, which is resolved when the `MediaRecorder`'s `onstop` event handler is called, and is rejected if its `onerror` event handler is called. The rejection handler receives as input the name of the error that occurred.

Lines 14-16

Creates a new `Promise`, named `recorded`, which is resolved when the specified number of milliseconds have elapsed. Upon resolution, it stops the `MediaRecorder` if it's recording.

Lines 18-22

These lines create a new `Promise` which is fulfilled when both of the two `Promise`s (`stopped` and `recorded`) have resolved. Once that resolves, the array data is returned by `startRecording()` to its caller.

### Stopping the input stream

The `stop()` function stops the input media:

```js
function stop(stream) {
  stream.getTracks().forEach((track) => track.stop());
}
```

This works by calling `MediaStream.getTracks()`, using `forEach()` to call `MediaStreamTrack.stop()` on each track in the stream.

### Getting an input stream and setting up the recorder

Now let's look at the most intricate piece of code in this example: our event handler for clicks on the start button:

```js
startButton.addEventListener(
  "click",
  () => {
    navigator.mediaDevices
      .getUserMedia({
        video: true,
        audio: true,
      })
      .then((stream) => {
        preview.srcObject = stream;
        downloadButton.href = stream;
        preview.captureStream =
          preview.captureStream || preview.mozCaptureStream;
        return new Promise((resolve) => (preview.onplaying = resolve));
      })
      .then(() => startRecording(preview.captureStream(), recordingTimeMS))
      .then((recordedChunks) => {
        let recordedBlob = new Blob(recordedChunks, { type: "video/webm" });
        recording.src = URL.createObjectURL(recordedBlob);
        downloadButton.href = recording.src;
        downloadButton.download = "RecordedVideo.webm";

        log(
          `Successfully recorded ${recordedBlob.size} bytes of ${recordedBlob.type} media.`,
        );
      })
      .catch((error) => {
        if (error.name === "NotFoundError") {
          log("Camera or microphone not found. Can't record.");
        } else {
          log(error);
        }
      });
  },
  false,
);
```

When a `click` event occurs, here's what happens:

Lines 2-4

`MediaDevices.getUserMedia` is called to request a new `MediaStream` that has both video and audio tracks. This is the stream we'll record.

Lines 5-9

When the Promise returned by `getUserMedia()` is resolved, the preview `<video>` element's `srcObject` property is set to be the input stream, which causes the video being captured by the user's camera to be displayed in the preview box. Since the `<video>` element is muted, the audio won't play. The "Download" button's link is then set to refer to the stream as well. Then, in line 8, we arrange for `preview.captureStream()` to call `preview.mozCaptureStream()` so that our code will work on Firefox, on which the `HTMLMediaElement.captureStream()` method is prefixed. Then a new `Promise` which resolves when the preview video starts to play is created and returned.

Line 10

When the preview video begins to play, we know there's media to record, so we respond by calling the `startRecording()` function we created earlier, passing in the preview video stream (as the source media to be recorded) and `recordingTimeMS` as the number of milliseconds of media to record. As mentioned before, `startRecording()` returns a `Promise` whose resolution handler is called (receiving as input an array of `Blob` objects containing the chunks of recorded media data) once recording has completed.

Lines 11-15

The recording process's resolution handler receives as input an array of media data `Blob`s locally known as `recordedChunks`. The first thing we do is merge the chunks into a single `Blob` whose MIME type is `"video/webm"` by taking advantage of the fact that the `Blob()` constructor concatenates arrays of objects into one object. Then `URL.createObjectURL()` is used to create a URL that references the blob; this is then made the value of the recorded video playback element's `src` attribute (so that you can play the video from the blob) as well as the target of the download button's link.

Then the download button's `download` attribute is set. While the `download` attribute can be a Boolean, you can also set it to a string to use as the name for the downloaded file. So by setting the download link's `download` attribute to "RecordedVideo.webm", we tell the browser that clicking the button should download a file named `"RecordedVideo.webm"` whose contents are the recorded video.

Lines 17-18

The size and type of the recorded media are output to the log area below the two videos and the download button.

Line 20

The `catch()` for all the `Promise`s outputs the error to the logging area by calling our `log()` function.

### Handling the stop button

The last bit of code adds a handler for the `click` event on the stop button using `addEventListener()`:

```js
stopButton.addEventListener(
  "click",
  () => {
    stop(preview.srcObject);
  },
  false,
);
```

This calls the `stop()` function we covered earlier.

### Result

When put all together with the rest of the HTML and the CSS not shown above, it looks and works like this:

You can view the full demo here, and use your browsers developer tools to inspect the page and look at all the code, including the parts hidden above because they aren't critical to the explanation of how the APIs are being used.

See also
--------

* Media Capture and Streams API landing page
* `MediaDevices.getUserMedia()`


Using the MediaStream Recording API - Web APIs

Using the MediaStream Recording API
===================================

The MediaStream Recording API makes it easy to record audio and/or video streams. When used with `navigator.mediaDevices.getUserMedia()`, it provides an easy way to record from the user's input devices and instantly use the result in web apps.

Both audio and video may be recorded, separately or together. This article aims to provide a basic guide on how to use the MediaRecorder interface, which provides this API.

A sample application: Web Dictaphone
------------------------------------

![An image of the Web dictaphone sample app - a sine wave sound visualization, then record and stop buttons, then an audio jukebox of recorded tracks that can be played back.](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API/web-dictaphone.png)

To demonstrate basic usage of the MediaStream Recording API, we have built a web-based dictaphone. It allows you to record snippets of audio and then play them back. It even gives you a visualization of your device's sound input, using the Web Audio API. We'll concentrate on the recording and playback functionality for this article.

You can see this demo running live, or grab the source code on GitHub.

CSS goodies
-----------

The HTML is pretty simple in this app, so we won't go through it here; there are a couple of slightly more interesting bits of CSS worth mentioning, however, so we'll discuss them below. If you are not interested in CSS and want to get straight to the JavaScript, skip to the Basic app setup section.

### Keeping the interface constrained to the viewport, regardless of device height, with calc()

The `calc()` function is one of those useful little utility features that's cropped up in CSS that doesn't look like much initially, but soon starts to make you think "Wow, why didn't we have this before? Why was CSS2 layout so awkward?" It allows you do a calculation to determine the computed value of a CSS unit, mixing different units in the process.

For example, in Web Dictaphone we have three main UI areas, stacked vertically. We wanted to give the first two (the header and the controls) fixed heights:

```css
header {
  height: 70px;
}

.main-controls {
  padding-bottom: 0.7rem;
  height: 170px;
}
```

However, we wanted to make the third area (which contains the recorded samples you can play back) take up whatever space is left, regardless of the device height. Flexbox could be the answer here, but it's a bit overkill for such a simple layout. Instead, the problem was solved by making the third container's height equal to 100% of the parent height, minus the heights and padding of the other two:

```css
.sound-clips {
  box-shadow: inset 0 3px 4px rgb(0 0 0 / 70%);
  background-color: rgb(0 0 0 / 10%);
  height: calc(100% - 240px - 0.7rem);
  overflow: scroll;
}
```

### Checkbox hack for showing/hiding

This is fairly well documented already, but we thought we'd give a mention to the checkbox hack, which abuses the fact that you can click on the `<label>` of a checkbox to toggle it checked/unchecked. In Web Dictaphone this powers the Information screen, which is shown/hidden by clicking the question mark icon in the top right-hand corner. First of all, we style the `<label>` how we want it, making sure that it has enough z-index to always sit above the other elements and therefore be focusable/clickable:

```css
label {
  font-family: "NotoColorEmoji";
  font-size: 3rem;
  position: absolute;
  top: 2px;
  right: 3px;
  z-index: 5;
  cursor: pointer;
}
```

Then we hide the actual checkbox, because we don't want it cluttering up our UI:

```css
input[type="checkbox"] {
  position: absolute;
  top: -100px;
}
```

Next, we style the Information screen (wrapped in an `<aside>` element) how we want it, give it fixed position so that it doesn't appear in the layout flow and affect the main UI, transform it to the position we want it to sit in by default, and give it a transition for smooth showing/hiding:

```css
aside {
  position: fixed;
  top: 0;
  left: 0;
  text-shadow: 1px 1px 1px black;
  width: 100%;
  height: 100%;
  transform: translateX(100%);
  transition: 0.6s all;
  background-color: #999;
  background-image: linear-gradient(
    to top right,
    rgb(0 0 0 / 0%),
    rgb(0 0 0 / 50%)
  );
}
```

Last, we write a rule to say that when the checkbox is checked (when we click/focus the label), the adjacent `<aside>` element will have its horizontal translation value changed and transition smoothly into view:

```css
input[type="checkbox"]:checked ~ aside {
  transform: translateX(0);
}
```

Basic app setup
---------------

To grab the media stream we want to capture, we use `getUserMedia()`. We then use the MediaStream Recording API to record the stream, and output each recorded snippet into the source of a generated `<audio>` element so it can be played back.

We'll declare some variables for the record and stop buttons, and the `<article>` that will contain the generated audio players:

```js
const record = document.querySelector(".record");
const stop = document.querySelector(".stop");
const soundClips = document.querySelector(".sound-clips");
```

Finally for this section, we set up the basic `getUserMedia` structure:

```js
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  console.log("getUserMedia supported.");
  navigator.mediaDevices
    .getUserMedia(
      // constraints - only audio needed for this app
      {
        audio: true,
      },
    )

    // Success callback
    .then((stream) => {})

    // Error callback
    .catch((err) => {
      console.error(`The following getUserMedia error occurred: ${err}`);
    });
} else {
  console.log("getUserMedia not supported on your browser!");
}
```

The whole thing is wrapped in a test that checks whether `getUserMedia` is supported before running anything else. Next, we call `getUserMedia()` and inside it define:

* **The constraints**: Only audio is to be captured for our dictaphone.
* **The success callback**: This code is run once the `getUserMedia` call has been completed successfully.
* **The error/failure callback**: The code is run if the `getUserMedia` call fails for whatever reason.

**Note:** All of the code below is placed inside the `getUserMedia` success callback.

Capturing the media stream
--------------------------

Once `getUserMedia` has created a media stream successfully, you create a new Media Recorder instance with the `MediaRecorder()` constructor and pass it the stream directly. This is your entry point into using the MediaStream Recording API — the stream is now ready to be captured into a `Blob`, in the default encoding format of your browser.

```js
const mediaRecorder = new MediaRecorder(stream);
```

There are a series of methods available in the `MediaRecorder` interface that allow you to control recording of the media stream; in Web Dictaphone we just make use of two, and listen to some events. First of all, `MediaRecorder.start()` is used to start recording the stream once the record button is pressed:

```js
record.onclick = () => {
  mediaRecorder.start();
  console.log(mediaRecorder.state);
  console.log("recorder started");
  record.style.background = "red";
  record.style.color = "black";
};
```

When the `MediaRecorder` is recording, the `MediaRecorder.state` property will return a value of "recording".

As recording progresses, we need to collect the audio data. We register an event handler to do this using `ondataavailable`:

```js
let chunks = [];

mediaRecorder.ondataavailable = (e) => {
  chunks.push(e.data);
};
```

**Note:** The browser will fire `dataavailable` events as needed, but if you want to intervene you can also include a timeslice when invoking the `start()` method — for example `start(10000)` — to control this interval, or call `MediaRecorder.requestData()` to trigger an event when you need it.

Lastly, we use the `MediaRecorder.stop()` method to stop the recording when the stop button is pressed, and finalize the `Blob` ready for use somewhere else in our application.

```js
stop.onclick = () => {
  mediaRecorder.stop();
  console.log(mediaRecorder.state);
  console.log("recorder stopped");
  record.style.background = "";
  record.style.color = "";
};
```

Note that the recording may also stop naturally if the media stream ends (e.g. if you were grabbing a song track and the track ended, or the user stopped sharing their microphone).

Grabbing and using the blob
---------------------------

When recording has stopped, the `state` property returns a value of "inactive", and a stop event is fired. We register an event handler for this using `onstop`, and finalize our blob there from all the chunks we have received:

```js
mediaRecorder.onstop = (e) => {
  console.log("recorder stopped");

  const clipName = prompt("Enter a name for your sound clip");

  const clipContainer = document.createElement("article");
  const clipLabel = document.createElement("p");
  const audio = document.createElement("audio");
  const deleteButton = document.createElement("button");

  clipContainer.classList.add("clip");
  audio.setAttribute("controls", "");
  deleteButton.innerHTML = "Delete";
  clipLabel.innerHTML = clipName;

  clipContainer.appendChild(audio);
  clipContainer.appendChild(clipLabel);
  clipContainer.appendChild(deleteButton);
  soundClips.appendChild(clipContainer);

  const blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
  chunks = [];
  const audioURL = window.URL.createObjectURL(blob);
  audio.src = audioURL;

  deleteButton.onclick = (e) => {
    let evtTgt = e.target;
    evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
  };
};
```

Let's go through the above code and look at what's happening.

First, we display a prompt asking the user to name their clip.

Next, we create an HTML structure like the following, inserting it into our clip container, which is an `<article>` element.

```html
<article class="clip">
  <audio controls></audio>
  <p>your clip name</p>
  <button>Delete</button>
</article>
```

After that, we create a combined `Blob` out of the recorded audio chunks, and create an object URL pointing to it, using `window.URL.createObjectURL(blob)`. We then set the value of the `<audio>` element's `src` attribute to the object URL, so that when the play button is pressed on the audio player, it will play the `Blob`.

Finally, we set an `onclick` handler on the delete button to be a function that deletes the whole clip HTML structure.

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

| Specification |
| --- |
| MediaStream Recording # mediarecorder-api |

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

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

See also
--------

* Media Capture and Streams API landing page
* `MediaDevices.getUserMedia()`


ViewTimeline: startOffset property - Web APIs

ViewTimeline: startOffset property
==================================

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

The **`startOffset`** read-only property of the `ViewTimeline` interface returns a `CSSNumericValue` representing the starting (0% progress) scroll position of the timeline as an offset from the start of the overflowing section of content in the scroller.

Value
-----

A `CSSNumericValue`.

Examples
--------

See the main `ScrollTimeline` page for an example.

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

| Specification |
| --- |
| Scroll-driven Animations # dom-viewtimeline-startoffset |

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

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

See also
--------

* Web Animations API
* CSS scroll-driven animations
* `ViewTimeline`
* `AnimationTimeline`, `ScrollTimeline`


ViewTimeline: ViewTimeline() constructor - Web APIs

ViewTimeline: ViewTimeline() constructor
========================================

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

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

Syntax
------

```js
new ViewTimeline(options)
```

### Parameters

`options`

An object that can contain the following properties:

`subject`

A reference to an `Element` representing the subject element whose visibility within its nearest ancestor scrollable element (scroller) will drive the progress of the timeline.

`axis` Optional

An enumerated value representing the scroll axis that will drive the progress of the timeline. Possible values are:

* `"block"`: The scrollbar on the block axis of the scroll container, which is the axis in the direction perpendicular to the flow of text within a line. For horizontal writing modes, such as standard English, this is the same as `"y"`, while for vertical writing modes, it is the same as `"x"`.
* `"inline"`: The scrollbar on the inline axis of the scroll container, which is the axis in the direction parallel to the flow of text in a line. For horizontal writing modes, this is the same as `"x"`, while for vertical writing modes, this is the same as `"y"`.
* `"y"`: The scrollbar on the vertical axis of the scroll container.
* `"x"`: The scrollbar on the horizontal axis of the scroll container.

If omitted, `axis` defaults to `"block"`.

`inset` Optional

A value or array of values representing an adjustment to the position of the scrollport (see Scroll container for more details) in which the subject is deemed to be visible. Possible values are:

* `"auto"`: The default box position is used.
* A string: If a string is specified, it can consist of one or two values equal to `auto` or a CSS `<length-percentage>` value. To put it another way, the string should be a valid `view-timeline-inset` value.
* An array of one or two values, which can be `"auto"` or a suitable `CSSNumericValue` to represent a length or percentage offset (for example `CSS.px()` or `CSS.percent()`. If an array is provided, the first value represents the start inset (which affects the `ViewTimeline.endOffset` value) and the second value represents the end inset (which affects the `ViewTimeline.startOffset` value).

If the array has only one value, it is duplicated.

If omitted, `inset` defaults to `auto`.

### Return value

A new `ViewTimeline` object instance.

Examples
--------

See the main `ViewTimeline` page for an example.

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

| Specification |
| --- |
| Scroll-driven Animations # dom-viewtimeline-viewtimeline |

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

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

See also
--------

* Web Animations API
* CSS scroll-driven animations
* `ViewTimeline`
* `AnimationTimeline`, `ScrollTimeline`


ViewTimeline: subject property - Web APIs

ViewTimeline: subject property
==============================

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

The **`subject`** read-only property of the `ViewTimeline` interface returns a reference to the subject element whose visibility within its nearest ancestor scrollable element (scroller) is driving the progress of the timeline.

Value
-----

An `Element`.

Examples
--------

See the main `ViewTimeline` page for an example.

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

| Specification |
| --- |
| Scroll-driven Animations # dom-viewtimeline-subject |

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

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

See also
--------

* Web Animations API
* CSS scroll-driven animations
* `ViewTimeline`
* `AnimationTimeline`, `ScrollTimeline`


ViewTimeline: endOffset property - Web APIs

ViewTimeline: endOffset property
================================

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

The **`endOffset`** read-only property of the `ViewTimeline` interface returns a `CSSNumericValue` representing the ending (100% progress) scroll position of the timeline as an offset from the start of the overflowing section of content in the scroller.

Value
-----

A `CSSNumericValue`.

Examples
--------

See the main `ScrollTimeline` page for an example.

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

| Specification |
| --- |
| Scroll-driven Animations # dom-viewtimeline-endoffset |

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

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

See also
--------

* Web Animations API
* CSS scroll-driven animations
* `ViewTimeline`
* `AnimationTimeline`, `ScrollTimeline`


OrientationSensor: quaternion property - Web APIs

OrientationSensor: quaternion property
======================================

 The **`quaternion`** read-only
 property of the `OrientationSensor` interface returns a four element
 `Array` whose elements contain the components of the unit
 quaternion representing the device's orientation.

 Because `OrientationSensor` is a base class, `quaternion` may
 only be read from one of its derived classes.

Value
-----

 An `Array` whose values are the x, y, z, and w components of the quaternion
 representing the device orientation.

Examples
--------

```js
// TBD
```

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

| Specification |
| --- |
| Orientation Sensor # orientationsensor-quaternion |

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

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


OrientationSensor: populateMatrix() method - Web APIs

OrientationSensor: populateMatrix() method
==========================================

 The **`populateMatrix`** method of the
 `OrientationSensor` interface populates the given target matrix with the
 rotation matrix based on the latest sensor reading. The rotation matrix is shown
 below.

![The formulas used to convert the sensor's quaternion to the provided matrix.](/en-US/docs/Web/API/OrientationSensor/populateMatrix/quaternion_to_rotation_matrix.png)

where:

* W = cos(θ/2)
* X = Vx \* sin(θ/2)
* Y = Vy \* sin(θ/2)
* Z = Vz \* sin(θ/2)
Syntax
------

```js
populateMatrix(targetMatrix)
```

 Because `OrientationSensor` is a base class, `populateMatrix`
 may only be read from one of its derived classes.

### Parameters

`targetMatrix`

TBD

### Return value

None (`undefined`).

Examples
--------

```js
// TBD
```

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

| Specification |
| --- |
| Orientation Sensor # orientationsensor-populatematrix |

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

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


Introduction to WebRTC protocols - Web APIs

Introduction to WebRTC protocols
================================

This article introduces the protocols on top of which the WebRTC API is built.

ICE
---

Interactive Connectivity Establishment (ICE) is a framework to allow your web browser to connect with peers. There are many reasons why a straight up connection from Peer A to Peer B won't work. It needs to bypass firewalls that would prevent opening connections, give you a unique address if like most situations your device doesn't have a public IP address, and relay data through a server if your router doesn't allow you to directly connect with peers. ICE uses STUN and/or TURN servers to accomplish this, as described below.

STUN
----

Session Traversal Utilities for NAT (STUN) is a protocol to discover your public address and determine any restrictions in your router that would prevent a direct connection with a peer.

The client will send a request to a STUN server on the Internet who will reply with the client's public address and whether or not the client is accessible behind the router's NAT.

![An interaction between two users of a WebRTC application involving a STUN server.](/en-US/docs/Web/API/WebRTC_API/Protocols/webrtc-stun.png)

NAT
---

Network Address Translation (NAT) is used to give your device a public IP address. A router will have a public IP address and every device connected to the router will have a private IP address. Requests will be translated from the device's private IP to the router's public IP with a unique port. That way you don't need a unique public IP for each device but can still be discovered on the Internet.

Some routers will have restrictions on who can connect to devices on the network. This can mean that even though we have the public IP address found by the STUN server, not anyone can create a connection. In this situation we need to use TURN.

TURN
----

Some routers using NAT employ a restriction called 'Symmetric NAT'. This means the router will only accept connections from peers you've previously connected to.

Traversal Using Relays around NAT (TURN) is meant to bypass the Symmetric NAT restriction by opening a connection with a TURN server and relaying all information through that server. You would create a connection with a TURN server and tell all peers to send packets to the server which will then be forwarded to you. This obviously comes with some overhead so it is only used if there are no other alternatives.

![An interaction between two users of a WebRTC application involving STUN and TURN servers.](/en-US/docs/Web/API/WebRTC_API/Protocols/webrtc-turn.png)

SDP
---

Session Description Protocol (SDP) is a standard for describing the multimedia content of the connection such as resolution, formats, codecs, encryption, etc. so that both peers can understand each other once the data is transferring. This is, in essence, the metadata describing the content and not the media content itself.

Technically, then, SDP is not truly a protocol, but a data format used to describe connection that shares media between devices.

Documenting SDP is well outside the scope of this documentation; however, there are a few things worth noting here.

### Structure

SDP consists of one or more lines of UTF-8 text, each beginning with a one-character type, followed by an equals sign (`"="`), followed by structured text comprising a value or description, whose format depends on the type. The lines of text that begin with a given letter are generally referred to as "*letter*-lines". For example, lines providing media descriptions have the type `"m"`, so those lines are referred to as "m-lines."

### For more information

To learn more about SDP, see the following useful resources:

* Specification: RFC 8866: SDP: Session Description Protocol
* IANA registry of SDP parameters