AudioParam: value property - Web APIs

AudioParam: value property
==========================

 The Web Audio API's
`AudioParam` interface property **`value`** gets
 or sets the value of this `AudioParam` at the current time. Initially, the value is set to `AudioParam.defaultValue`.

 Setting `value` has the same effect as
 calling `AudioParam.setValueAtTime` with the time returned by the
 `AudioContext`'s `currentTime`
 property.

Value
-----

 A floating-point `Number` indicating the parameter's value as of the
 current time. This value will be between the values specified by the
 `minValue` and `maxValue` properties.

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

### Value precision and variation

 The data type used internally to store `value` is a single-precision
 (32-bit) floating point number, while JavaScript uses 64-bit double-precision floating
 point numbers. As a result, the value you read from the `value` property may
 not always exactly equal what you set it to.

Consider this example:

```js
const source = new AudioBufferSourceNode(/\* … \*/);
const rate = 5.3;
source.playbackRate.value = rate;
console.log(source.playbackRate.value === rate);
```

 The log output will be `false`, because the playback rate parameter,
 `rate`, was converted to the 32-bit floating-point number closest to 5.3,
 which yields 5.300000190734863. One solution is to use the `Math.fround()`
 method, which returns the single-precision value equivalent to the 64-bit JavaScript
 value specified—when setting `value`, like this:

```js
const source = new AudioBufferSourceNode(/\* … \*/);
const rate = Math.fround(5.3);
source.playbackRate.value = rate;
console.log(source.playbackRate.value === rate);
```

In this case, the log output will be `true`.

### Value of a property which is changing over time

 The `value` of an `AudioParam` can either be fixed or can vary
 over time. This is reflected by the `value` getter, which returns the value
 of the parameter as of the audio rendering engine's most recent **render
quantum**, or moment at which audio buffers are processed and updated. In
 addition to processing audio buffers, each render quantum updates the `value`
 of each `AudioParam` as needed given the current time and any established
 time-based parameter value changes.

 Upon first creating the parameter, its value is set to its default value, given by
 `AudioParam.defaultValue`. This is the parameter's value at a time of 0.0
 seconds, and will remain the parameter's value until the first render quantum in which
 the value is altered.

 During each render quantum, the browser does the following things related to managing
 the value of a parameter:

* If the `value` setter has been used, the parameter's value is changed to
 the value given.
* If the current time equals or exceeds the time specified by a previous call to
 `setValueAtTime()`, the `value`
 is changed to the value passed into `setValueAtTime()`.
* If any graduated or ramped value changing methods have been called and the current
 time is within the time range over which the graduated change should occur, the value
 is updated based on the appropriate algorithm. These ramped or graduated
 value-changing methods include `linearRampToValueAtTime()`, `setTargetAtTime()`, and `setValueCurveAtTime()`.

 Thus, the `value` of a parameter is maintained to accurately reflect the
 state of the parameter over time.

Examples
--------

This example instantly changes the volume of a `GainNode` to 40%.

```js
const audioCtx = new AudioContext();
const gainNode = audioCtx.createGain();
gainNode.gain.value = 0.4;
// which is identical to:
gainNode.gain.setValueAtTime(0.4, audioCtx.currentTime);
```

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-value |

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

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

 When changing the gain value of a `GainNode`, Google Chrome prior to
 version 64 (January 2018) would perform a smooth interpolation to prevent dezippering.
 Starting with version 64, the value is changed instantly to bring it in line with the
 Web Audio spec. See Chrome Platform Status for details.

See also
--------

* Using the Web Audio API


AudioParam: exponentialRampToValueAtTime() method - Web APIs

AudioParam: exponentialRampToValueAtTime() method
=================================================

 The **`exponentialRampToValueAtTime()`** method of the `AudioParam` Interface schedules a gradual exponential change in the value
 of the `AudioParam`. The change starts at the time specified for the
 *previous* event, follows an exponential ramp to the new value given in the
 `value` parameter, and reaches the new value at the time given in the
 `endTime` parameter.

**Note:** Exponential ramps are considered more useful when changing
 frequencies or playback rates than linear ramps because of the way the human ear
 works.

Syntax
------

```js
exponentialRampToValueAtTime(value, endTime)
```

### Parameters

`value`

 A floating point number representing the value the `AudioParam` will ramp
 to by the given time.

`endTime`

 A double representing the exact time (in seconds) after the ramping starts that the
 changing of the value will stop.

### Return value

 A reference to this `AudioParam` object. In some browsers older
 implementations of this interface return `undefined`.

Examples
--------

 In this example, we have a media source with two control buttons (see the audio-param repo for the source code, or view the example live.) When these buttons are pressed, `exponentialRampToValueAtTime()`
 is used to fade the gain value up to 1.0, and down to 0, respectively. This is pretty
 useful for fade in/fade out effects:

```js
// create audio context
const audioCtx = new AudioContext();

// set basic variables for example
const myAudio = document.querySelector("audio");

const expRampPlus = document.querySelector(".exp-ramp-plus");
const expRampMinus = document.querySelector(".exp-ramp-minus");

// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);

// Create a gain node and set its gain value to 0.5
const gainNode = audioCtx.createGain();

// connect the AudioBufferSourceNode to the gainNode
// and the gainNode to the destination
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
source.connect(gainNode);
gainNode.connect(audioCtx.destination);

// set buttons to do something onclick
expRampPlus.onclick = () => {
  gainNode.gain.exponentialRampToValueAtTime(1.0, audioCtx.currentTime + 2);
};

expRampMinus.onclick = () => {
  gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 2);
};
```

**Note:** A value of 0.01 was used for the value to ramp down to in the
 last function rather than 0, as an *invalid or illegal string* error is thrown
 if 0 is used — the value needs to be positive.

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-exponentialramptovalueattime |

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

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

See also
--------

* Using the Web Audio API


AudioParam: minValue property - Web APIs

AudioParam: minValue property
=============================

 The **`minValue`**
 read-only property of the `AudioParam` interface represents the minimum
 possible value for the parameter's nominal (effective) range.

Value
-----

 A floating-point `Number` indicating the minimum value permitted for the
 parameter's nominal range.

 The default value of `minValue` is the minimum negative single-precision
 floating-point value (-340,282,346,638,528,859,811,704,183,484,516,925,440).

Examples
--------

```js
const audioCtx = new AudioContext();
const gainNode = audioCtx.createGain();
console.log(gainNode.gain.minValue); // -3.4028234663852886e38
```

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-minvalue |

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

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

See also
--------

* `AudioParam.maxValue`


AudioParam: linearRampToValueAtTime() method - Web APIs

AudioParam: linearRampToValueAtTime() method
============================================

 The `linearRampToValueAtTime()` method of the `AudioParam`
 Interface schedules a gradual linear change in the value of the
 `AudioParam`. The change starts at the time specified for the
 *previous* event, follows a linear ramp to the new value given in the
 `value` parameter, and reaches the new value at the time given in the
 `endTime` parameter.

Syntax
------

```js
linearRampToValueAtTime(value, endTime)
```

### Parameters

`value`

 A floating point number representing the value the `AudioParam` will ramp
 to by the given time.

`endTime`

 A double representing the exact time (in seconds) after the ramping starts that the
 changing of the value will stop.

### Return value

 A reference to this `AudioParam` object. In some browsers older
 implementations of this interface return `undefined`.

Examples
--------

 In this example, we have a media source with two control buttons (see the audio-param repo for the source code, or view the example live.) When these buttons are pressed, `linearRampToValueAtTime()` is
 used to fade the gain value up to 1.0, and down to 0, respectively. This is pretty
 useful for fade in/fade out effects, although `AudioParam.exponentialRampToValueAtTime()` is often said to be a bit more
 natural.

```js
// create audio context
const audioCtx = new AudioContext();

// set basic variables for example
const myAudio = document.querySelector("audio");

const linearRampPlus = document.querySelector(".linear-ramp-plus");
const linearRampMinus = document.querySelector(".linear-ramp-minus");

// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);

// Create a gain node and set it's gain value to 0.5
const gainNode = audioCtx.createGain();

// connect the AudioBufferSourceNode to the gainNode
// and the gainNode to the destination
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
source.connect(gainNode);
gainNode.connect(audioCtx.destination);

// set buttons to do something onclick
linearRampPlus.onclick = () => {
  gainNode.gain.linearRampToValueAtTime(1.0, audioCtx.currentTime + 2);
};

linearRampMinus.onclick = () => {
  gainNode.gain.linearRampToValueAtTime(0, audioCtx.currentTime + 2);
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-linearramptovalueattime |

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

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

See also
--------

* Using the Web Audio API


AudioParam: maxValue property - Web APIs

AudioParam: maxValue property
=============================

 The **`maxValue`**
 read-only property of the `AudioParam` interface represents the maximum
 possible value for the parameter's nominal (effective) range.

Value
-----

 A floating-point `Number` indicating the maximum value permitted for the
 parameter's nominal range.

 The default value of `maxValue` is the maximum positive single-precision
 floating-point value (+340,282,346,638,528,859,811,704,183,484,516,925,440).

Examples
--------

```js
const audioCtx = new AudioContext();
const gainNode = audioCtx.createGain();
console.log(gainNode.gain.maxValue); // 3.4028234663852886e38
```

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-maxvalue |

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

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

See also
--------

* `AudioParam.minValue`


AudioParam: setValueCurveAtTime() method - Web APIs

AudioParam: setValueCurveAtTime() method
========================================

 The
 **`setValueCurveAtTime()`** method of the
 `AudioParam` interface schedules the parameter's value to change
 following a curve defined by a list of values.

 The curve is a linear
 interpolation between the sequence of values defined in an array of floating-point
 values, which are scaled to fit into the given interval starting at
 `startTime` and a specific duration.

Syntax
------

```js
setValueCurveAtTime(values, startTime, duration)
```

### Parameters

`values`

 An array of floating-point numbers representing the value curve the
 `AudioParam` will change through along the specified
 `duration`. Every value in the array must be a finite number; if any value
 is `NaN`, `Infinity`, or `-Infinity`, a `TypeError` exception is thrown.

`startTime`

 A double representing the time (in seconds) after the `AudioContext`
 was first created that the change in value will happen. If this value is lower than
 `AudioContext.currentTime`, it is clamped to `currentTime`.

`duration`

 A double representing the total time (in seconds) over which the parameter's
 `value` will change following the specified curve. The specified values are
 spaced equally along this duration.

### Return value

 A reference to this `AudioParam` object. Some older browser implementations
 of this interface return `undefined`.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the specified array of `values` has fewer than 2 items in it.

`RangeError`

 Thrown if the specified `startTime` is either negative or a non-finite value, or
 `duration` is not a finite, strictly positive number.

`TypeError`

 Thrown if one or more of the values in the `values` array is non-finite. Non-finite
 values are `NaN`, `Infinity`, and `-Infinity`.

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

 When the parameter's value finishes following the curve, its value is guaranteed to
 match the last value in the set of values specified in the `values`
 parameter.

**Note:** Some early implementations of the Web Audio API did not ensure
 this to be the case, causing unexpected results.

Examples
--------

 In this example, we have a media source with a single button (see the webaudio-examples repo for the source code, or view the example live.) When this button is pressed, `setValueCurveAtTime()` is used to
 change the gain value between the values contained in the waveArray array:

```js
// create audio context
const audioCtx = new AudioContext();

// set basic variables for example
const myAudio = document.querySelector("audio");

const valueCurve = document.querySelector(".value-curve");

// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);

// Create a gain node and set it's gain value to 0.5
const gainNode = audioCtx.createGain();
gainNode.gain.value = 0.5;
const currGain = gainNode.gain.value;

// connect the AudioBufferSourceNode to the gainNode
// and the gainNode to the destination
source.connect(gainNode);
gainNode.connect(audioCtx.destination);

// set button to do something onclick

const waveArray = new Float32Array(9);
waveArray[0] = 0.5;
waveArray[1] = 1;
waveArray[2] = 0.5;
waveArray[3] = 0;
waveArray[4] = 0.5;
waveArray[5] = 1;
waveArray[6] = 0.5;
waveArray[7] = 0;
waveArray[8] = 0.5;

valueCurve.onclick = () => {
  gainNode.gain.setValueCurveAtTime(waveArray, audioCtx.currentTime, 2);
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-setvaluecurveattime |

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

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

Versions before Chrome 46 use nearest neighbor instead of linear interpolation.

See also
--------

* Using the Web Audio API


AudioParam: setTargetAtTime() method - Web APIs

AudioParam: setTargetAtTime() method
====================================

 The `setTargetAtTime()` method of the
 `AudioParam` interface schedules the start of a gradual change to the
 `AudioParam` value. This is useful for decay or release portions of ADSR
 envelopes.

Syntax
------

```js
setTargetAtTime(target, startTime, timeConstant)
```

### Parameters

`target`

The value the parameter will start to transition towards at the given start time.

`startTime`

 The time that the exponential transition will begin, in the same time coordinate
 system as `AudioContext.currentTime`. If it is less than or equal to
 `AudioContext.currentTime`, the parameter will start changing immediately.

`timeConstant`

 The time-constant value, given in seconds, of an exponential approach to the target
 value. The larger this value is, the slower the transition will be.

### Return value

 A reference to this `AudioParam` object. Some older browser implementations
 of this interface return `undefined`.

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

 The change starts at the time specified in `startTime` and exponentially
 moves towards the value given by the `target` parameter. The decay rate as
 defined by the `timeConstant` parameter is exponential; therefore the value
 will never reach `target` completely, but after each timestep of length
 `timeConstant`, the value will have approached `target` by
 another

1
-

e

-
1

≈
63.2
%

1 - e^{-1} \approx 63.2%

. For the complete formula (which uses a first-order linear continuous
 time-invariant system), check the Web Audio specification.

 If you absolutely need to reach the target value by a specific time, you can use
 `AudioParam.exponentialRampToValueAtTime()`. However, for mathematical
 reasons, that method does not work if the current value or the target value is
 `0`.

### Choosing a good `timeConstant`

 As mentioned above, the value changes exponentially, with each
 `timeConstant` bringing you another 63.2% toward the target value. You don't
 have to worry about reaching the target value; once you are close enough, any further
 changes will be imperceptible to a human listener.

 Depending on your use case, getting 95% toward the target value may already be enough;
 in that case, you could set `timeConstant` to one third of the desired
 duration.

 For more details, check the following table on how the value changes from 0% to 100% as
 the time progresses.

| Time since `startTime` | Value |
| --- | --- |
| `0 * timeConstant` | 0% |
| `0.5 * timeConstant` | 39.3% |
| `1 * timeConstant` | 63.2% |
| `2 * timeConstant` | 86.5% |
| `3 * timeConstant` | 95.0% |
| `4 * timeConstant` | 98.2% |
| `5 * timeConstant` | 99.3% |
| `n * timeConstant` |

1

 |

1
-

e

-
n

1 - e^{-n}

Examples
--------

 In this example, we have a media source with two control buttons (see the webaudio-examples repo for the source code, or view the example live.) When these buttons are pressed, `setTargetAtTime()` is used to
 fade the gain value up to 1.0, and down to 0, respectively, with the effect starting
 after 1 second, and the length of time the effect lasts being controlled by the
 timeConstant.

```js
// create audio context
const audioCtx = new AudioContext();

// set basic variables for example
const myAudio = document.querySelector("audio");

const atTimePlus = document.querySelector(".at-time-plus");
const atTimeMinus = document.querySelector(".at-time-minus");

// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);

// Create a gain node and set it's gain value to 0.5
const gainNode = audioCtx.createGain();
gainNode.gain.value = 0.5;
let currGain = gainNode.gain.value;

// connect the AudioBufferSourceNode to the gainNode
// and the gainNode to the destination
source.connect(gainNode);
gainNode.connect(audioCtx.destination);

// set buttons to do something onclick
atTimePlus.onclick = () => {
  currGain = 1.0;
  gainNode.gain.setTargetAtTime(1.0, audioCtx.currentTime + 1, 0.5);
};

atTimeMinus.onclick = () => {
  currGain = 0;
  gainNode.gain.setTargetAtTime(0, audioCtx.currentTime + 1, 0.5);
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-settargetattime |

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

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

See also
--------

* Using the Web Audio API


AudioParam: cancelScheduledValues() method - Web APIs

AudioParam: cancelScheduledValues() method
==========================================

 The `cancelScheduledValues()` method of the `AudioParam`
 Interface cancels all scheduled future changes to the `AudioParam`.

Syntax
------

```js
cancelScheduledValues(startTime)
```

### Parameters

`startTime`

 A double representing the time (in seconds) after the `AudioContext`
 was first created after which all scheduled changes will be cancelled.

### Return value

 A reference to this `AudioParam` object. In some older implementations this
 method returns `undefined`.

Examples
--------

```js
const gainNode = audioCtx.createGain();
gainNode.gain.setValueCurveAtTime(waveArray, audioCtx.currentTime, 2); //'gain' is the AudioParam
gainNode.gain.cancelScheduledValues(audioCtx.currentTime);
```

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-cancelscheduledvalues |

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

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

See also
--------

* Using the Web Audio API


AudioParam: defaultValue property - Web APIs

AudioParam: defaultValue property
=================================

 The **`defaultValue`**
 read-only property of the `AudioParam` interface represents the initial
 value of the attributes as defined by the specific `AudioNode` creating
 the `AudioParam`.

Value
-----

A floating-point `Number`.

Examples
--------

```js
const audioCtx = new AudioContext();
const gainNode = audioCtx.createGain();
const defaultVal = gainNode.gain.defaultValue;
console.log(defaultVal); // 1
console.log(defaultVal === gainNode.gain.value); // true
```

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-defaultvalue |

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

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

See also
--------

* Using the Web Audio API


CompositionEvent: data property - Web APIs

CompositionEvent: data property
===============================

 The **`data`** read-only property of the
 `CompositionEvent` interface returns the characters generated by the input
 method that raised the event; its exact nature varies depending on the type of event
 that generated the `CompositionEvent` object.

Value
-----

A string representing the event data:

* For `compositionstart` events, this is the currently selected text that
 will be replaced by the string being composed. This value doesn't change even if
 content changes the selection range; rather, it indicates the string that was selected
 when composition started.
* For `compositionupdate`, this is the string as it stands currently as
 editing is ongoing.
* For `compositionend` events, this is the string as committed to the
 editor.
Specifications
--------------

| Specification |
| --- |
| UI Events # dom-compositionevent-data |

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

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

See also
--------

* `CompositionEvent`


CompositionEvent: locale property - Web APIs

CompositionEvent: locale property
=================================

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

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

 The **`locale`** read-only property of the
 `CompositionEvent` interface returns the locale of current input method
 (for example, the keyboard layout locale if the composition is associated with IME).

**Warning:** Even for browsers supporting it, don't trust the value contained in this property.
 Even if technically it is accessible, the way to set it up when creating a `CompositionEvent`
 is not guaranteed to be coherent.

Value
-----

A string representing the locale of current input method.

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

 This property was in early versions of different specifications. It is now only kept for compatibility purposes, and the way
 to set its value when creating a `CompositionEvent` is not well defined.

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

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

See also
--------

* `CompositionEvent`


CompositionEvent: initCompositionEvent() method - Web APIs

CompositionEvent: initCompositionEvent() method
===============================================

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

 The **`initCompositionEvent()`**
 method of the `CompositionEvent` interface initializes the attributes of a
 `CompositionEvent` object instance.

**Note:** The correct way of creating a `CompositionEvent` is to use
 the constructor `CompositionEvent()`.

Syntax
------

```js
initCompositionEvent(type, canBubble, cancelable, view, data, locale)
```

### Parameters

`type`

 A string representing the type of composition event; this will be
 one of `compositionstart`, `compositionupdate`, or
 `compositionend`.

`canBubble`

A boolean value specifying whether or not the event can bubble.

`cancelable`

A boolean value indicating whether or not the event can be canceled.

`view`

The `Window` object from which the event was generated.

`data`

 A string representing the value of the `data`
 attribute.

`locale`

 A string representing the value of the `locale`
 attribute.

### Return value

None (`undefined`).

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

This method is no longer on a standardization track. It is kept for compatibility purposes. Use the constructor `CompositionEvent()`.

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

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

See also
--------

* `CompositionEvent`


CompositionEvent: CompositionEvent() constructor - Web APIs

CompositionEvent: CompositionEvent() constructor
================================================

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

Syntax
------

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

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers set it to `compositionstart`, `compositionupdate`, or `compositionend`.

`options` Optional

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

`data` Optional

 A string used to initialize the `data` property of the new
 `CompositionEvent`. Browser-generated events set it to the characters generated by the IME
 composition.

### Return value

A new `CompositionEvent` object.

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

| Specification |
| --- |
| UI Events # dom-compositionevent-compositionevent |

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

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

See also
--------

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


XRView: recommendedViewportScale property - Web APIs

XRView: recommendedViewportScale property
=========================================

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

The read-only **`recommendedViewportScale`** property of the `XRView` interface is the recommended viewport scale value that you can use for `XRView.requestViewportScale()` if the user agent has such a recommendation; `null` otherwise.

Value
-----

A number greater than 0.0 and less than or equal to 1.0; or `null` if the user agent does not provide a recommended scale.

Examples
--------

### Dynamic viewport scaling

Dynamic viewport scaling allows applications to only use a subset of the available `framebuffer`. The feature may not be available on all systems since it depends on driver support, so you might want to ensure that `XRView.requestViewportScale` exists before calling it.

```js
for (const view of pose.views) {
  if (view.requestViewportScale) {
    view.requestViewportScale(view.recommendedViewportScale);
  }
  const viewport = glLayer.getViewport(view);
}
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrview-recommendedviewportscale |

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

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

See also
--------

* `XRView.requestViewportScale()`


XRView: projectionMatrix property - Web APIs

XRView: projectionMatrix property
=================================

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

 The `XRView` interface's read-only
 **`projectionMatrix`** property specifies the projection matrix
 to apply to the underlying view. This should be used to integrate perspective to
 everything in the scene, in order to ensure the result is consistent with what the eye
 expects to see.

**Note:** Failure to apply proper perspective, or inconsistencies
 in perspective, may result in possibly serious user discomfort or distress.

Value
-----

 A `Float32Array` object representing the projection matrix for the view.
 The projection matrix for each eye's view is used to ensure that the correct area of the
 scene is presented to each eye in order to create a believable 3D scene without
 introducing discomfort for the user.

Examples
--------

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

| Specification |
| --- |
| WebXR Device API # dom-xrview-projectionmatrix |

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

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


XRView: eye property - Web APIs

XRView: eye property
====================

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

 The `XRView` interface's read-only **`eye`**
 property is a string indicating which eye's viewpoint the `XRView` represents: `left` or
 `right`. For views which represent neither eye, such as monoscopic views,
 this property's value is `none`.

Value
-----

A string that can be one of the following values:

`left`

The `XRView` represents the point-of-view of the viewer's left eye.

`right`

The view represents the viewer's right eye.

`none`

The `XRView` describes a monoscopic view, or the view otherwise doesn't represent a particular eye's point-of-view.

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

 The primary purpose of this property is to allow the correct area of any pre-rendered
 stereo content to be presented to the correct eye. For dynamically-rendered 3D content,
 you can usually ignore this and render each of the viewer's views, one after another.

Examples
--------

 This code, from the viewer pose's renderer, iterates over the pose's views and renders
 them. *However*, we have flags which, if `true`, indicate that a
 particular eye has been injured during gameplay. When rendering that eye, if the flag is
 `true`, that view is skipped instead of being rendered.

```js
glLayer = xrSession.renderState.baseLayer;
gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);
gl.clearColor(0, 0, 0, 1.0);
gl.clearDepth(1.0);
gl.clear(gl.COLOR\_BUFFER\_BIT, gl.DEPTH\_BUFFER\_BIT);

for (const view of xrPose.views) {
  let skipView = false;

  if (view.eye === "left" && body.leftEye.injured) {
    skipView = updateInjury(body.leftEye);
  } else if (view.eye === "right" && body.rightEye.injured) {
    skipView = updateInjury(body.rightEye);
  }

  if (!skipView) {
    let viewport = glLayer.getViewport(view);
    gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
    renderScene(gl, view);
  }
}
```

 For each of the views, the value of `eye` is checked and if it's either
 `left` or `right`, we check to see if the
 `body.leftEye.injured` or `body.rightEye.injured` property is
 `true`; if so, we call a function `updateInjury()` on that eye to
 do things such as allow a bit of healing to occur, track the progress of a poison
 effect, or the like, as appropriate for the game's needs.

`updateInjury()` returns `true` if the eye is still injured or
 `false` if the eye has been restored to health by the function. If the
 result is `false`, indicating that the eye is now healthy, we render the
 scene for that eye. Otherwise, we don't.

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

| Specification |
| --- |
| WebXR Device API # dom-xrview-eye |

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

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


XRView: isFirstPersonObserver property - Web APIs

XRView: isFirstPersonObserver property
======================================

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

The `XRView` interface's read-only **`isFirstPersonObserver`** property is a boolean indicating if the `XRView` is a first-person observer view.

To create video recordings of AR device cameras, you can't simply use one of the rendered eyes, as there often will be a physical offset. Some devices expose a secondary view, the first-person observer view, which has an `eye` of `none`.

To receive a first-person observer view, you need to enable the "secondary-views" feature descriptor explicitly (typically as an optional feature). See `XRSystem.requestSession()` for details.

The `isFirstPersonObserver` property then allows you to check which secondary view is a first-person observer view.

Examples
--------

### Checking for first-person observer views

```js
// Make sure to enable "secondary-view"
navigator.xr
  .requestSession("immersive-ar", {
    optionalFeatures: ["secondary-views"],
  })
  .then((session) => {
    // …

    session.requestAnimationFrame((frame) => {
      const views = frame.getViewerPose(space);
      // Make sure to iterate over all views
      for (const view of views) {
        if (view.isFirstPersonObserver) {
          renderFPO();
        } else {
          render();
        }
      }
    });
  });
```

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

| Specification |
| --- |
| WebXR Augmented Reality Module - Level 1 # dom-xrview-isfirstpersonobserver |

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

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


XRView: requestViewportScale() method - Web APIs

XRView: requestViewportScale() method
=====================================

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

The **`requestViewportScale()`** method of the `XRView` interface requests that the user agent sets the requested viewport scale for this viewport to the given value. This is used for dynamic viewport scaling which allows rendering to a subset of the WebXR viewport using a scale factor that can be changed every animation frame.

Syntax
------

```js
requestViewportScale(scale)
```

Parameters
----------

`scale`

A number greater than 0.0 and less than or equal to 1.0 representing the scale factor.

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

None (`undefined`).

Dynamic viewport scaling
------------------------

Dynamic viewport scaling allows applications to only use a subset of the available `framebuffer`. The feature may not be available on all systems since it depends on driver support, so you might want to ensure that `requestViewportScale()` exists before calling it.

The `scale` parameter can be a number greater than 0.0 and less than or equal to 1.0.

Alternatively, you can use the `XRView.recommendedViewportScale` property which contains the user agent's recommended value based on internal heuristics. If the user agent doesn't provide a recommended viewport scale, its value is `null` and the call to `requestViewportScale()` is ignored.

Examples
--------

The following example shows how to request and apply a new viewport scale. The call to `XRWebGLLayer.getViewport()` applies the change and returns the updated viewport.

```js
for (const view of pose.views) {
  if (view.requestViewportScale) {
    view.requestViewportScale(0.8);
    // or use view.requestViewportScale(view.recommendedViewportScale);
  }
  const viewport = glLayer.getViewport(view);
}
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrview-requestviewportscale |

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

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

See also
--------

* `XRView.recommendedViewportScale`


XRView: transform property - Web APIs

XRView: transform property
==========================

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

 The read-only **`transform`** property of the
 `XRView` interface is an `XRRigidTransform` object which
 provides the position and orientation of the viewpoint relative to the
 `XRReferenceSpace` specified when the
 `XRFrame.getViewerPose()` method was called to obtain the view object.

 With the `transform`, you can then position the view as a camera within the
 3D scene. If you instead need the more traditional view matrix, you can get using
 `view.transform.inverse.matrix`; this gets the underlying
 `matrix` of the transform's
 `inverse`.

Value
-----

 A `XRRigidTransform` object specifying the position and orientation of the
 viewpoint represented by the `XRView`.

Examples
--------

 For each view making up the presented scene, the view's `transform`
 represents the position and orientation of the viewer or camera relative to the
 reference space's origin. You can then use the inverse of this matrix to transform the
 objects in your scene to adjust their placement and orientation to simulate the viewer's
 movement through space.

 In this example, we see an outline of a code fragment used while rendering an
 `XRFrame`, which makes use of the view transform to place objects in the
 world during rendering.

```js
const modelViewMatrix = mat4.create();
const normalMatrix = mat4.create();

for (const view of pose.views) {
  const viewport = glLayer.getViewport(view);
  gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);

  for (const obj of world.objects) {
    mat4.multiply(modelViewMatrix, view.transform.inverse.matrix, obj.matrix);
    mat4.invert(normalMatrix, modelViewMatrix);
    mat4.transpose(normalMatrix, normalMatrix);

    obj.render(modelViewMatrix, normalMatrix);
  }
}
```

 Two matrices are created outside the rendering loop; this avoids repeatedly allocating
 and deallocating the matrices, and generally reduces overhead by reusing the same matrix
 for each object rendered.

 Then we iterate over each `XRView` found in the
 `XRViewerPose`'s list of `views`. There
 will usually be two: one for the left eye and one for the right, but there may be only
 one if in monoscopic mode. Currently, WebXR doesn't support more than two views per
 pose, although room has been left to extend the specification to support that in the
 future with some additions to the API.

 For each view, we obtain its viewport and pass that to WebGL using
 `gl.viewport()`. For the left eye, this
 will be the left half of the canvas, while the right eye will use the right half.

 Then we iterate over each object that makes up the scene. Each object's model view
 matrix is computed by multiplying its own matrix which describes the object's own
 position and orientation by the additional position and orientation adjustments needed
 to match the camera's movement. To convert the "camera focused" transform matrix into an
 "object focused" transform, we use the transform's inverse, thus taking the matrix
 returned by `view.transform.inverse.matrix`. The
 resulting model view matrix will apply all the transforms needed to move and rotate the
 object based on the relative positions of the object and the camera. This will simulate
 the movement of the camera even though we're actually moving the object.

 We then compute the normals for the model view matrix by inverting it, then transposing
 it.

 Finally, we call the object's `render()` routine, passing along the
 `modelViewMatrix` and `normalMatrix` so the renderer can place and
 light the object properly.

**Note:** This example is derived from a larger example…
 **<<<--- finish and add link --->>>**

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

| Specification |
| --- |
| WebXR Device API # dom-xrview-transform |

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

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


USB: connect event - Web APIs

USB: connect event
==================

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

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

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

The **`connect`** event of the `USB` interface is fired whenever a paired device is connected.

Syntax
------

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

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

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

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

A `USBConnectionEvent`. Inherits from `Event`.

Event

USBConnectionEventEvent properties
----------------

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

`device` Read only

The `USBDevice` the event is fired for.

Examples
--------

Once a USB device is connected, you might want to update the UI.

```js
navigator.usb.addEventListener("connect", (event) => {
  // Add event.device to the UI.
});
```

Alternatively, you can use the `USB.onconnect` event handler property to establish a handler for the `connect` event:

```js
navigator.usb.onconnect = (event) => {
  // Add event.device to the UI.
};
```

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

| Specification |
| --- |
| WebUSB API # connect |
| WebUSB API # ref-for-dom-usb-onconnect |

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

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


USB: requestDevice() method - Web APIs

USB: requestDevice() method
===========================

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

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

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

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

 The **`requestDevice()`** method of the `USB`
 interface returns a `Promise` that resolves with an instance of
 `USBDevice` if the specified device is found. Calling this function
 triggers the user agent's pairing flow.

Syntax
------

```js
requestDevice(filters)
```

### Parameters

`filters`

 An array of filter objects for possible devices you would like to pair. Each filter
 object can have the following properties:

* `vendorId`
* `productId`
* `classCode`
* `subclassCode`
* `protocolCode`
* `serialNumber`

### Return value

A `Promise` that resolves with an instance of `USBDevice`.

Security
--------

Transient user activation is required. The user has to interact with the page or a UI element in order for this feature to work.

Examples
--------

 The following example looks for one of two USB devices. Notice that two product IDs are
 specified. Both are passed to `requestDevice()`. This triggers a user-agent
 flow that prompts the user to select a device for pairing. Only the selected device is
 passed to `then()`.

 The number of filters does not specify the number of devices shown by the user agent.
 For example, if only a USB device with product ID `0xa800` is found, then
 only one device will be listed by the user agent. On the other hand if the user agent
 finds two of the first listed device and one of the second, then all three devices will
 be listed.

```js
const filters = [
  { vendorId: 0x1209, productId: 0xa800 },
  { vendorId: 0x1209, productId: 0xa850 },
];
navigator.usb
  .requestDevice({ filters })
  .then((usbDevice) => {
    console.log(`Product name: ${usbDevice.productName}`);
  })
  .catch((e) => {
    console.error(`There is no device. ${e}`);
  });
```

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

| Specification |
| --- |
| WebUSB API # ref-for-dom-usb-requestdevice④ |

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

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


USB: disconnect event - Web APIs

USB: disconnect event
=====================

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

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

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

The **`disconnect`** event of the `USB` interface is fired whenever a paired device is disconnected.

Syntax
------

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

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

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

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

A `USBConnectionEvent`. Inherits from `Event`.

Event

USBConnectionEventEvent properties
----------------

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

`device` Read only

The `USBDevice` the event is fired for.

Examples
--------

Once a USB device is disconnected, you might want to update the UI.

```js
navigator.usb.addEventListener("disconnect", (event) => {
  // Remove event.device from the UI.
});
```

Alternatively, you can use the `USB.ondiscconnect` event handler property to establish a handler for the `disconnect` event:

```js
navigator.usb.ondisconnect = (event) => {
  // Remove event.device from the UI.
};
```

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

| Specification |
| --- |
| WebUSB API # disconnect |
| WebUSB API # ref-for-dom-usb-ondisconnect |

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

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


USB: getDevices() method - Web APIs

USB: getDevices() method
========================

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

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

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

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

 The **`getDevices`** method of the `USB` interface
 returns a `Promise` that resolves with an array of `USBDevice`
 objects for paired attached devices. For information on pairing devices, see
 `USB.requestDevice()`.

Syntax
------

```js
getDevices()
```

### Parameters

None.

### Return value

 A `Promise` that resolves with an array of `USBDevice`
 objects.

Examples
--------

 The following example logs the product name and serial number of paired devices to the
 console. For information on pairing devices, see
 `USB.requestDevice()`.

```js
navigator.usb.getDevices().then((devices) => {
  console.log(`Total devices: ${devices.length}`);
  devices.forEach((device) => {
    console.log(
      `Product name: ${device.productName}, serial number ${device.serialNumber}`,
    );
  });
});
```

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

| Specification |
| --- |
| WebUSB API # ref-for-dom-usb-getdevices② |

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

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


RTCDataChannelEvent: RTCDataChannelEvent() constructor - Web APIs

RTCDataChannelEvent: RTCDataChannelEvent() constructor
======================================================

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

**Note:** You will rarely if ever construct an `RTCDataChannelEvent` by hand; these
 events are normally created and sent by the WebRTC layer itself.

Syntax
------

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

### Parameters

`type`

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

`options`

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

`channel`

A `RTCDataChannel`, representing the data channel being associated with the event.

### Return value

A new `RTCDataChannelEvent` object configured as specified.

Example
-------

 In this example, a new `datachannel` event is created. `dc` is a
 data channel which already exists.

```js
const event = new RTCDataChannelEvent("datachannel", { channel: dc });
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcdatachannelevent-constructor |

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

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

See also
--------

* WebRTC
* `RTCDataChannel`
* `RTCPeerConnection`
* A simple RTCDataChannel sample


RTCDataChannelEvent: channel property - Web APIs

RTCDataChannelEvent: channel property
=====================================

 The read-only property **`RTCDataChannelEvent.channel`**
 returns the `RTCDataChannel` associated with the event.

Value
-----

 A `RTCDataChannel` object representing the data channel linking the
 receiving `RTCPeerConnection` to its remote peer.

Example
-------

 The first line of code in the `datachannel` event handler shown below takes
 the channel from the event object and saves it locally for use by the code handling data
 traffic.

```js
pc.ondatachannel = (event) => {
  inboundDataChannel = event.channel;
  inboundDataChannel.onmessage = handleIncomingMessage;
  inboundDataChannel.onopen = handleChannelOpen;
  inboundDataChannel.onclose = handleChannelClose;
};
```

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-datachannelevent-channel |

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

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

See also
--------

* `datachannel`
* `RTCDataChannel`
* A simple RTCDataChannel sample
* `RTCPeerConnection`


NDEFRecord: toRecords() method - Web APIs

NDEFRecord: toRecords() method
==============================

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

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

 The **`toRecords()`**
 method of the `NDEFRecord` interface converts
 `NDEFRecord.data` to a sequence of records based on
 `NDEFRecord.recordType`, and returns the result. This allows
 parsing the payloads of record types which may contain nested records, such
 as smart poster and external type records.

Syntax
------

```js
toRecords()
```

### Parameters

None.

### Return value

A list of `NDEFRecord`s.

Exceptions
----------

`NotSupported` `DOMException`

 Indicates that the User Agent does not know how to parse this combination of
 `NDEFRecord.data` and `NDEFRecord.recordType`.

Examples
--------

Read an external record with an NDEF message as payload

 The example uses external type records to create application-defined records.
 These records may contain an `NDEFMessage` as payload, with its own
 `NDEFRecord` objects, including local types that are used in the
 context of the application. Notice that the smart poster record type also
 contains an NDEF message as payload.

 Because NDEF gives no guarantee on the ordering of records, using an external
 type record with an NDEF message as payload can be useful for encapsulating
 related data.

 This example shows how to read an external record for social posts, which
 contains an `NDEFMessage`, containing a text record and a record
 with the local type "act" (action), with a definition borrowed from smart
 poster, but used in local application context.

```js
const ndefReader = new NDEFReader();
await ndefReader.scan();
ndefReader.onreading = (event) => {
  const externalRecord = event.message.records.find(
    (record) => record.type === "example.com:smart-poster",
  );

  let action, text;

  for (const record of externalRecord.toRecords()) {
    if (record.recordType === "text") {
      const decoder = new TextDecoder(record.encoding);
      text = decoder.decode(record.data);
    } else if (record.recordType === ":act") {
      action = record.data.getUint8(0);
    }
  }

  switch (action) {
    case 0: // do the action
      console.log(`Post "${text}" to timeline`);
      break;
    case 1: // save for later
      console.log(`Save "${text}" as a draft`);
      break;
    case 2: // open for editing
      console.log(`Show editable post with "${text}"`);
      break;
  }
};
```

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

| Specification |
| --- |
| Web NFC API # dom-ndefrecord-torecords |

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

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


NDEFRecord: encoding property - Web APIs

NDEFRecord: encoding property
=============================

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

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

 The **`encoding`**
 property of the `NDEFRecord` interface returns the encoding of
 a textual payload, or `null` otherwise.

Syntax
------

```js
NDEFRecord.encoding
```

### Value

 A string which can be one of the following: `"utf-8"`,
 `"utf-16"`, `"utf-16le"`, or `"utf-16be"`.

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

| Specification |
| --- |
| Web NFC API # dom-ndefrecord-encoding |

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

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


NDEFRecord: lang property - Web APIs

NDEFRecord: lang property
=========================

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

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

 The **`lang`**
 property of the `NDEFRecord` interface returns the language of
 a textual payload, or `null` if one was not supplied.

 The record might be missing a language tag, for example, if the recorded information is
 not locale-specific.

Syntax
------

```js
NDEFRecord.lang
```

### Value

A string.

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

| Specification |
| --- |
| Web NFC API # dom-ndefrecord-lang |

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

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

See also
--------

* HTML `lang` attribute, that declares content language of the document or its elements
* HTTP headers that declare content language: `Content-Language` and `Accept-Language`


NDEFRecord: recordType property - Web APIs

NDEFRecord: recordType property
===============================

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

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

 The **`recordType`**
 property of the `NDEFRecord` interface returns the record type of the record.

Syntax
------

```js
NDEFRecord.recordType
```

### Value

A string which can be one of the following:

`"empty"`

An empty NDEF record.

`"text"`

A text NDEF record.

`"url"`

A URI NDEF record.

`"smart-poster"`

A "smart poster" NDEF record.

`"absolute-url"`

An absolute URL NDEF record.

`"mime"`

A MIME type NDEF record.

`"unknown"`

The NDEF record type is not known.

local type name

 Represents a local type name, frequently used to specify NDEF record embedded within
 another record.

external type name

A custom string consisting of a domain name and custom type name separated by a colon (":").

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

| Specification |
| --- |
| Web NFC API # dom-ndefrecord-recordtype |

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

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


NDEFRecord: id property - Web APIs

NDEFRecord: id property
=======================

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

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

 The **`id`** property of the
 `NDEFRecord` interface returns the record identifier, which is an
 absolute or relative URL used to identify the record.

 This identifier is created by the generator of the record which is solely responsible
 for enforcing record identifier uniqueness. Web NFC does not sign the NFC content, thus
 record consumer should not make any assumptions about integrity or authenticity of the
 identifier or any other part of the records.

Syntax
------

```js
NDEFRecord.id
```

### Value

A string.

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

| Specification |
| --- |
| Web NFC API # dom-ndefrecord-id |

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

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


NDEFRecord: NDEFRecord() constructor - Web APIs

NDEFRecord: NDEFRecord() constructor
====================================

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

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

 The **`NDEFRecord()`**
 constructor of the Web NFC API returns a
 newly constructed `NDEFRecord` object that represents data that can be
 read from, or written to, compatible NFC devices; e.g. NFC tags supporting NDEF.

Syntax
------

```js
new NDEFRecord(options)
```

### Parameters

`options`

An object with the following properties:

`data` Optional

Contains the data to be transmitted. It can be a string object or literal, an `ArrayBuffer`, a `TypedArray`, a `DataView`, or an array of nested records.

`encoding` Optional

A string specifying the record's encoding.

`id` Optional

A developer-defined identifier for the record.

`lang` Optional

A valid language tag according to RFC 5646: Tags for Identifying Languages (also known as BCP 47).

`mediaType` Optional

A valid MIME type.

`recordType`

A string indicating the type of data stored in `data`. It must be one of the following values:

`"absolute-url"`

An absolute URL to the data.

`"empty"`

An empty `NDEFRecord`.

`"mime"`

A valid MIME type.

`"smart-poster"`

A smart poster as defined by the NDEF-SMARTPOSTER specification.

`"text"`

Text as defined by the NDEF-TEXT specification.

`"unknown"`

The record type is not known.

`"URL"`

A URL as defined by the NDEF-URI specification.

### Return value

A new `NDEFRecord`.

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

| Specification |
| --- |
| Web NFC API # dom-ndefrecord-constructor |

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

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


NDEFRecord: data property - Web APIs

NDEFRecord: data property
=========================

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

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

 The **`data`**
 property of the `NDEFRecord` interface returns a
 `DataView` containing the raw bytes of the record's payload.

Syntax
------

```js
NDEFRecord.data
```

### Value

A `DataView` that contains encoded payload data of the record.

Examples
--------

 The following example loops over the records in an `NDEFMessage`
 object, which is retrieved from `NDEFReadingEvent.message`. After
 selecting a record based on its `mediaType`, it then decodes what's stored in the `data` property.

```js
const ndef = new NDEFReader();
await ndef.scan();
ndef.onreading = (event) => {
  const decoder = new TextDecoder();
  for (const record of event.message.records) {
    if (record.mediaType === "application/json") {
      const json = JSON.parse(decoder.decode(record.data));
      const article = /^[aeio]/i.test(json.title) ? "an" : "a";
      console.log(`${json.name} is ${article} ${json.title}`);
    }
  }
};
```

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

| Specification |
| --- |
| Web NFC API # dom-ndefrecord-data |

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

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


NDEFRecord: mediaType property - Web APIs

NDEFRecord: mediaType property
==============================

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

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

 The **`mediaType`**
 property of the `NDEFRecord` interface returns the MIME type of the record. This value will be `null` if `recordType` is not equal to `"mime"`.

Syntax
------

```js
NDEFRecord.mediaType
```

### Value

 A string, containing the MIME type of the record
 payload.

Examples
--------

The following example loops over the records in an `NDEFMessage` object, which is retrieved from `NDEFReadingEvent.message`. It then uses the `mediaType` property to determine which of the records to parse.

```js
const ndef = new NDEFReader();
await ndef.scan();
ndef.onreading = (event) => {
  const decoder = new TextDecoder();
  for (const record of event.message.records) {
    if (record.mediaType === "application/json") {
      const json = JSON.parse(decoder.decode(record.data));
      const article = /^[aeio]/i.test(json.title) ? "an" : "a";
      console.log(`${json.name} is ${article} ${json.title}`);
    }
  }
};
```

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

| Specification |
| --- |
| Web NFC API # dom-ndefrecord-mediatype |

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

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


CanvasGradient: addColorStop() method - Web APIs

CanvasGradient: addColorStop() method
=====================================

 The **`CanvasGradient.addColorStop()`** method adds a new color stop,
 defined by an `offset` and a `color`, to a given canvas gradient.

Syntax
------

```js
addColorStop(offset, color)
```

### Parameters

`offset`

 A number between `0` and `1`, inclusive, representing the
 position of the color stop. `0` represents the start of the gradient and
 `1` represents the end.

`color`

 A CSS `<color>` value
 representing the color of the stop.

### Return value

None (`undefined`).

### Exceptions

`IndexSizeError` `DOMException`

Thrown if `offset` is not between 0 and 1 (both included).

`SyntaxError` `DOMException`

Thrown if `color` cannot be parsed as a CSS `<color>` value.

Examples
--------

### Adding stops to a gradient

 This example uses the `addColorStop` method to add stops to a linear
 `CanvasGradient` object. The gradient is then used to fill a rectangle.

#### HTML

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

#### JavaScript

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

let gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "green");
gradient.addColorStop(0.7, "white");
gradient.addColorStop(1, "pink");
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 200, 100);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-canvasgradient-addcolorstop-dev |

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

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

See also
--------

* The interface defining this method: `CanvasGradient`
* `CanvasRenderingContext2D.createLinearGradient()`
* `CanvasRenderingContext2D.createRadialGradient()`


TextTrackList: removeTrack event - Web APIs

TextTrackList: removeTrack event
================================

The **`removetrack`** event is fired when a track is removed from a `TextTrackList`.

Syntax
------

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

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

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

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

A `TrackEvent`. Inherits from `Event`.

Event

TrackEventEvent properties
----------------

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

`track` Read only

The `TextTrack` object to which the event refers.

Examples
--------

Using `addEventListener()`:

```js
const mediaElement = document.querySelector("video, audio");

mediaElement.textTracks.addEventListener("removetrack", (event) => {
  console.log(`Text track: ${event.track.label} removed`);
});
```

Using the `onremovetrack` event handler property:

```js
const mediaElement = document.querySelector("video, audio");

mediaElement.textTracks.onremovetrack = (event) => {
  console.log(`Text track: ${event.track.label} removed`);
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-removetrack |
| HTML Standard # handler-tracklist-onremovetrack |

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

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

See also
--------

* Related events: `addtrack`, `change`
* This event on `VideoTrackList` targets: `removetrack`
* This event on `AudioTrackList` targets: `removetrack`
* This event on `MediaStream` targets: `removetrack`
* Media Capture and Streams API
* WebRTC


TextTrackList: getTrackById() method - Web APIs

TextTrackList: getTrackById() method
====================================

 The **`TextTrackList`** method
 **`getTrackById()`** returns the first
 `TextTrack` object from the track list whose
 `id` matches the
 specified string. This lets you find a specified track if you know its ID
 string.

Syntax
------

```js
getTrackById(id)
```

### Parameters

`id`

 A string indicating the ID of the track to locate within the track
 list.

### Return value

 A `TextTrack` object indicating the first track found within the
 `TextTrackList` whose `id` matches the specified string. If no
 match is found, this method returns `null`.

 The tracks are searched in their natural order; that is, in the order defined by the
 media resource itself, or, if the resource doesn't define an order, the relative order
 in which the tracks are declared by the media resource.

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

| Specification |
| --- |
| HTML Standard # dom-texttracklist-gettrackbyid-dev |

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

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


TextTrackList: length property - Web APIs

TextTrackList: length property
==============================

 The read-only **`TextTrackList`**
 property **`length`** returns the number of entries in the
 `TextTrackList`, each of which is a `TextTrack` representing
 one track in the media element.

 A value of 0 indicates that there are no text
 tracks in the media.

Value
-----

 A number indicating how many text tracks are included in the
 `TextTrackList`. Each track can be accessed by treating the
 `TextTrackList` as an array of objects of type `TextTrack`.

Examples
--------

 This snippet gets the number of text tracks in the first media element found in the
 DOM by `querySelector()`.

```js
const mediaElem = document.querySelector("video, audio");
let numTextTracks = 0;

if (mediaElem.textTracks) {
  numTextTracks = mediaElem.textTracks.length;
}
```

 Note that this sample checks to be sure `HTMLMediaElement.textTracks` is
 defined, to avoid failing on browsers without support for `TextTrack`.

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

| Specification |
| --- |
| HTML Standard # dom-texttracklist-length |

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

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


TextTrackList: change event - Web APIs

TextTrackList: change event
===========================

The **`change`** event is fired when a text track is made active or inactive, or a `TextTrackList` is otherwise changed.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

Using `addEventListener()`:

```js
const mediaElement = document.querySelectorAll("video, audio")[0];
mediaElement.textTracks.addEventListener("change", (event) => {
  console.log(`'${event.type}' event fired`);
});
```

Using the `onchange` event handler property:

```js
const mediaElement = document.querySelector("video, audio");
mediaElement.textTracks.onchange = (event) => {
  console.log(`'${event.type}' event fired`);
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-change |
| HTML Standard # handler-tracklist-onchange |

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

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

See also
--------

* Related events: `addtrack`, `removetrack`
* This event on `VideoTrackList` targets: `change`
* This event on `AudioTrackList` targets: `change`
* Media Capture and Streams API
* WebRTC


TextTrackList: addtrack event - Web APIs

TextTrackList: addtrack event
=============================

The **`addtrack`** event is fired when a track is added to a `TextTrackList`.

Syntax
------

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

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

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

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

A `TrackEvent`. Inherits from `Event`.

Event

TrackEventEvent properties
----------------

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

`track` Read only

The `TextTrack` object to which the event refers.

Examples
--------

Using `addEventListener()`:

```js
const mediaElement = document.querySelector("video, audio");

mediaElement.textTracks.addEventListener("addtrack", (event) => {
  console.log(`Text track: ${event.track.label} added`);
});
```

Using the `onaddtrack` event handler property:

```js
const mediaElement = document.querySelector("video, audio");

mediaElement.textTracks.onaddtrack = (event) => {
  console.log(`Text track: ${event.track.label} added`);
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-addtrack |
| HTML Standard # handler-tracklist-onaddtrack |

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

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

See also
--------

* Related events: `removetrack`, `change`
* This event on `VideoTrackList` targets: `addtrack`
* This event on `AudioTrackList` targets: `addtrack`
* This event on `MediaStream` targets: `addtrack`
* Media Capture and Streams API
* WebRTC


MediaStreamTrackProcessor: readable property - Web APIs

MediaStreamTrackProcessor: readable property
============================================

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

The **`readable`** property of the `MediaStreamTrackProcessor` interface returns a `ReadableStream`.

Value
-----

A `ReadableStream`.

Examples
--------

In the following example video frames from the `ReadableStream` are transformed.

```js
const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });

/\* \*/

trackProcessor.readable
  .pipeThrough(transformer)
  .pipeTo(trackGenerator.writable);
```

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

| Specification |
| --- |
| MediaStreamTrack Insertable Media Processing using Streams # dom-mediastreamtrackprocessor-readable |

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

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


MediaStreamTrackProcessor: MediaStreamTrackProcessor() constructor - Web APIs

MediaStreamTrackProcessor: MediaStreamTrackProcessor() constructor
==================================================================

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

The **`MediaStreamTrackProcessor()`** constructor creates a new `MediaStreamTrackProcessor` object which consumes a `MediaStreamTrack` object's source and generates a stream of media frames.

Syntax
------

```js
new MediaStreamTrackProcessor(options)
```

### Parameters

`options`

An object with the following properties:

`track`

A `MediaStreamTrack`.

`maxBufferSize` Optional

An integer specifying the maximum number of media frames to be buffered.

Examples
--------

In the following example a new `MediaStreamTrackProcessor` is created.

```js
const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
```

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

| Specification |
| --- |
| MediaStreamTrack Insertable Media Processing using Streams # dom-mediastreamtrackprocessor-mediastreamtrackprocessor |

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

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


RTCEncodedAudioFrame: getMetadata() method - Web APIs

RTCEncodedAudioFrame: getMetadata() method
==========================================

The **`getMetadata()`** method of the `RTCEncodedAudioFrame` interface returns an object containing the metadata associated with the frame.

This includes information about the frame, including the audio encoding used, the synchronization source and contributing sources, and the sequence number (for incoming frames).

Syntax
------

```js
getMetadata()
```

### Parameters

None.

### Return value

An object with the following properties:

`synchronizationSource`

 A positive integer value indicating synchronization source ("ssrc") of the stream of RTP packets that are described by this frame.
 A source might be something like a microphone, or a mixer application that combines multiple sources.
 All packets from the same source share the same time source and sequence space, and so can be ordered relative to each other.
 Note that two frames with the same value refer to the same source.

`payloadType`

 A positive integer value in the range from 0 to 127 that describes the format of the RTP payload.
 The mappings of values to formats is defined in RFC3550, and more specifically Section 6: Payload Type Definitions of RFC3551.

`contributingSources`

 An `Array` of sources (ssrc) that have contributed to the frame.
 Consider the case of a conferencing application that combines audio from multiple users.
 The `synchronizationSource` would include the ssrc of the application, while `contributingSources` would include the ssrc values of all the individual audio sources.

`sequenceNumber`

 The sequence number of an incoming audio frame (not used for outgoing frames) that can be used for reconstructing the original send-order of frames.
 This is number between 0 and 32767 .
 Note that while numbers are allocated sequentially when sent, they will overflow at 32767 and restart back at 0.
 Therefore to compare two frame sequence numbers, in order to determine whether one is assumed to be after another, you must use serial number arithmetic.

Examples
--------

This example WebRTC encoded transform implementation shows how you might get the frame metadata in a `transform()` function and log it.

```js
addEventListener("rtctransform", (event) => {
  const async transform = new TransformStream({
    async transform(encodedFrame, controller) {

      // Get the metadata and log
      const frameMetaData = encodedFrame.getMetadata();
      console.log(frameMetaData)

      // Enqueue the frame without modifying
      controller.enqueue(encodedFrame);
    },
  });
  event.transformer.readable
    .pipeThrough(transform)
    .pipeTo(event.transformer.writable);
});
```

 The resulting object from a local microphone might look like the one shown below.
 Note that there are no contributing sources because there is just one source, and no `sequenceNumber` because this is an outgoing frame.

```js
{
  "payloadType": 109,
  "synchronizationSource": 1876443470
}
```

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

| Specification |
| --- |
| WebRTC Encoded Transform # dom-rtcencodedaudioframe-getmetadata |

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

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

See also
--------

* Using WebRTC Encoded Transforms


RTCEncodedAudioFrame: data property - Web APIs

RTCEncodedAudioFrame: data property
===================================

The **`data`** property of the `RTCEncodedAudioFrame` interface returns a buffer containing the data for an encoded frame.

Value
-----

An `ArrayBuffer`.

Examples
--------

This example WebRTC encoded transform shows how you might get the frame data in a `TransformStream` `transform()` function modify the bits.

 The `transform()` function constructs a `DataView` on the buffer in the frame `data` property, and also creates a view on a new `ArrayBuffer`.
 It then writes the negated bytes in the original data to the new buffer, assigns the buffer to the encoded frame `data` property, and enqueues the modified frame on the stream.

```js
addEventListener("rtctransform", (event) => {
  const transform = new TransformStream({
    async transform(encodedFrame, controller) {
      // Reconstruct the original frame.
      const view = new DataView(encodedFrame.data);

      // Construct a new buffer
      const newData = new ArrayBuffer(encodedFrame.data.byteLength);
      const newView = new DataView(newData);

      // Negate all bits in the incoming frame
      for (let i = 0; i < encodedFrame.data.byteLength; ++i) {
        newView.setInt8(i, ~view.getInt8(i));
      }

      encodedFrame.data = newData;
      controller.enqueue(encodedFrame);
    },
  });
  event.transformer.readable
    .pipeThrough(transform)
    .pipeTo(event.transformer.writable);
});
```

Note that the surrounding code shown here is described in Using WebRTC Encoded Transforms.

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

| Specification |
| --- |
| WebRTC Encoded Transform # dom-rtcencodedaudioframe-data |

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

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

See also
--------

* Using WebRTC Encoded Transforms


RTCEncodedAudioFrame: timestamp property - Web APIs

RTCEncodedAudioFrame: timestamp property
========================================

The readonly **`timestamp`** property of the `RTCEncodedAudioFrame` interface indicates the time at which frame sampling started.

Value
-----

A positive integer containing the sampling instant of the first byte in this frame, in microseconds.

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

| Specification |
| --- |
| WebRTC Encoded Transform # dom-rtcencodedaudioframe-timestamp |

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

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

See also
--------

* Using WebRTC Encoded Transforms


CompressionStream: CompressionStream() constructor - Web APIs

CompressionStream: CompressionStream() constructor
==================================================

The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data.

Syntax
------

```js
new CompressionStream(format)
```

### Parameters

`format`

One of the following allowed compression formats:

`"gzip"`

Compresses the stream using the GZIP format.

`"deflate"`

 Compresses the stream using the DEFLATE algorithm in ZLIB Compressed Data Format.
 The ZLIB format includes a header with information about the compression method and the uncompressed size of the data, and a trailing checksum for verifying the integrity of the data

`"deflate-raw"`

Compresses the stream using the DEFLATE algorithm without a header and trailing checksum.

Exceptions
----------

`TypeError`

Thrown if the format passed to the constructor is not supported.

Examples
--------

In this example a stream is compressed using gzip compression.

```js
const compressedReadableStream = inputReadableStream.pipeThrough(
  new CompressionStream("gzip"),
);
```

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

| Specification |
| --- |
| Compression Streams # dom-compressionstream-compressionstream |

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

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


CompressionStream: writable property - Web APIs

CompressionStream: writable property
====================================

The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`.

Value
-----

A `WritableStream`.

Examples
--------

The following example returns a `WritableStream` from a `CompressionStream`.

```js
let stream = new CompressionStream("gzip");
console.log(stream.writable); // A WritableStream
```

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

| Specification |
| --- |
| Streams Standard # dom-generictransformstream-writable |

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

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


CompressionStream: readable property - Web APIs

CompressionStream: readable property
====================================

The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`.

Value
-----

A `ReadableStream`.

Examples
--------

The following example returns a `ReadableStream` from a `CompressionStream`.

```js
let stream = new CompressionStream("gzip");
console.log(stream.readable); //a ReadableStream
```

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

| Specification |
| --- |
| Streams Standard # dom-generictransformstream-readable |

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

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


Request: mode property - Web APIs

Request: mode property
======================

 The **`mode`** read-only property of the `Request`
 interface contains the mode of the request (e.g., `cors`,
 `no-cors`, `same-origin`, `navigate` or `websocket`.) This is used
 to determine if cross-origin requests lead to valid responses, and which properties of the response are readable.

Value
-----

A `RequestMode` value.

The associated *mode*, available values of which are:

`same-origin`

 If a request is made to another origin with this mode
 set, the result is an error. You could use this to ensure that a request is always
 being made to your origin.

`no-cors`

 Prevents the method from being anything other than `HEAD`, `GET` or `POST`, and the headers from being anything other than CORS-safelisted request headers.
 If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are CORS-safelisted request headers.
 In addition, JavaScript may not access any properties of the resulting `Response`.
 This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.

`cors`

 Allows cross-origin requests, for example to access various
 APIs offered by 3rd party vendors. These are expected to adhere to the CORS protocol. Only a limited set of headers are exposed in the `Response`, but the body is
 readable.

`navigate`

A mode for supporting navigation. The `navigate` value is intended to be used only by HTML navigation. A navigate request is created only while navigating between documents.

`websocket`

A special mode used only when establishing a WebSocket connection.

### Default mode

 Requests can be initiated in a variety of ways, and the mode for a request depends on
 the particular means by which it was initiated.

 For example, when a `Request` object is created using the
 `Request()` constructor, the value of the `mode` property
 for that `Request` is set to `cors`.

 However, for requests created other than by the `Request()`
 constructor, `no-cors` is typically used as the mode; for example, for
 embedded resources where the request is initiated from markup, unless the
 `crossorigin`
 attribute is present, the request is in most cases made using the `no-cors`
 mode — that is, for the `<link>` or `<script>` elements
 (except when used with modules), or `<img>`, `<audio>`,
 `<video>`, `<object>`, `<embed>`, or
 `<iframe>` elements.

Examples
--------

 In the following snippet, we create a new request using the
 `Request()` constructor (for an image file in the same directory as
 the script), then save the request mode in a variable:

```js
const myRequest = new Request("flowers.jpg");
const myMode = myRequest.mode; // returns "cors" by default
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-request-mode② |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Request: blob() method - Web APIs

Request: blob() method
======================

 The **`blob()`** method of the `Request` interface
 reads the request body and returns it as a promise that resolves with a `Blob`.

Syntax
------

```js
blob()
```

### Parameters

None.

### Return value

A promise that resolves with a `Blob`.

Examples
--------

```js
const obj = { hello: "world" };
const myBlob = new Blob([JSON.stringify(obj, null, 2)], {
  type: "application/json",
});

const request = new Request("/myEndpoint", {
  method: "POST",
  body: myBlob,
});

request.blob().then((myBlob) => {
  // do something with the blob sent in the request
});
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-blob① |

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

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

See also
--------

* `Response.blob()`


Request: integrity property - Web APIs

Request: integrity property
===========================

The **`integrity`** read-only property of the `Request` interface contains the subresource integrity value of the request.

Value
-----

The value that was passed as the `options.integrity` argument when constructing the `Request`.

If an integrity has not been specified, the property returns `''`.

Examples
--------

In the following snippet, we create a new request using the `Request()` constructor (for an image file in the same directory as the script), then reads the request's integrity. Because the request was created without a specific integrity, the property returns an empty string.

```js
const myRequest = new Request("flowers.jpg");
console.log(myRequest.integrity); // ""
```

In the example below, the request was created with a specific integrity value, so the property returns that value. Note that there's no validation of the integrity value; the property returns exactly what was passed in.

```js
const myRequest = new Request("flowers.jpg", {
  integrity: "sha256-abc123",
});
console.log(myRequest.integrity); // "sha256-abc123"
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-request-integrity② |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Request: headers property - Web APIs

Request: headers property
=========================

 The **`headers`** read-only property of the
 `Request` interface contains the `Headers` object associated
 with the request.

Value
-----

A `Headers` object.

Examples
--------

 In the following snippet, we create a new request using the
 `Request()` constructor (for an image file in the same directory as
 the script), then save the request headers in a variable:

```js
const myRequest = new Request("flowers.jpg");
const myHeaders = myRequest.headers; // Headers {}
```

 To add a header to the `Headers` object we use
 `Headers.append`; we then create a new `Request` along with a
 2nd init parameter, passing headers in as an init option:

```js
const myHeaders = new Headers();
myHeaders.append("Content-Type", "image/jpeg");

const myInit = {
  method: "GET",
  headers: myHeaders,
  mode: "cors",
  cache: "default",
};

const myRequest = new Request("flowers.jpg", myInit);

const myContentType = myRequest.headers.get("Content-Type"); // returns 'image/jpeg'
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-request-headers② |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Request: url property - Web APIs

Request: url property
=====================

 The **`url`** read-only property of the `Request`
 interface contains the URL of the request.

Value
-----

A string indicating the URL of the request.

Examples
--------

 In the following snippet, we create a new request using the
 `Request()` constructor (for an image file in the same directory as
 the script), then save the URL of the request in a variable:

```js
const myRequest = new Request("flowers.jpg");
const myURL = myRequest.url; // "https://github.com/mdn/dom-examples/tree/main/fetch/fetch-request/flowers.jpg"
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-request-url③ |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Request: signal property - Web APIs

Request: signal property
========================

The read-only **`signal`** property of the `Request` interface returns the `AbortSignal` associated with the request.

Value
-----

An `AbortSignal` object.

Examples
--------

```js
// Create a new abort controller
const controller = new AbortController();

// Create a request with this controller's AbortSignal object
const req = new Request("/", { signal: controller.signal });

// Add an event handler logging a message in case of abort
req.signal.addEventListener("abort", () => {
  console.log("abort");
});

// In case of abort, log the AbortSignal reason, if any
fetch(req).catch(() => {
  if (signal.aborted) {
    if (signal.reason) {
      console.log(`Request aborted with reason: ${signal.reason}`);
    } else {
      console.log("Request aborted but no reason was given.");
    }
  } else {
    console.log("Request not aborted, but terminated abnormally.");
  }
});

// Actually abort the request
controller.abort();
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-request-signal② |

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

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


Request: arrayBuffer() method - Web APIs

Request: arrayBuffer() method
=============================

 The **`arrayBuffer()`** method of the `Request` interface
 reads the request body and returns it as a promise that resolves with an `ArrayBuffer`.

Syntax
------

```js
arrayBuffer()
```

### Parameters

None.

### Return value

A promise that resolves with an `ArrayBuffer`.

Examples
--------

```js
const myArray = new Uint8Array(10);

const request = new Request("/myEndpoint", {
  method: "POST",
  body: myArray,
});

request.arrayBuffer().then((buffer) => {
  // do something with the buffer sent in the request
});
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-arraybuffer① |

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

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

See also
--------

* `Response.arrayBuffer()`


Request: destination property - Web APIs

Request: destination property
=============================

 The **`destination`** read-only
 property of the **`Request`** interface returns a string
 describing the type of content being requested.

 The string must be one of the `audio`, `audioworklet`,
 `document`, `embed`, `font`, `frame`,
 `iframe`, `image`, `manifest`, `object`,
 `paintworklet`, `report`, `script`, `sharedworker`,
 `style`, `track`, `video`, `worker`
 or `xslt` strings, or the empty string, which is the default value.

 The `destination` is used by the user agent to, for example,
 help determine which set of rules to follow for CORS purposes, or how to navigate any
 complicated code paths that affect how specific types of request get handled.

 These destinations vary substantially in how they operate. Some are data receptacles,
 where the received data is stored for processing later. Others are script-based, in
 which case the received data is delivered to a script by calling it and passing the data
 along. Script-based destinations include `<script>` elements, as well as
 any of the `Worklet`-based destinations
 (including subclasses like `AudioWorklet`), and the
 `Worker`-based destinations, including `ServiceWorker`
 and `SharedWorker`.

Value
-----

A string which indicates the type of content the request is asking for. This type is much broader than the usual document type values (such as `"document"` or `"manifest"`), and may include contextual cues such as `"image"` or `"worker"` or `"audioworklet"`.

Possible values are:

`""`

The empty string is the default value, and is used for destinations that do not have their own value. This is the value when requests are made using the following APIs (among others):

* `<a ping>`
* `<area ping>`
* `Cache`
* `EventSource`
* `fetch()`
* `navigator.sendBeacon()`
* `WebSocket`
* `XMLHttpRequest`

`"audio"`

The target is audio data.

`"audioworklet"`

The target is data being fetched for use by an audio worklet.

`"document"`

The target is a document (HTML or XML).

`"embed"`

The target is embedded content.

`"font"`

The target is a font.

`"image"`

The target is an image.

`"manifest"`

The target is a manifest.

`"object"`

The target is an object.

`"paintworklet"`

The target is a paint worklet.

`"report"`

The target is a report.

`"script"`

The target is a script.

`"serviceworker"`

The target is a service worker.

`"sharedworker"`

The target is a shared worker.

`"style"`

The target is a style

`"track"`

The target is an HTML `<track>`.

`"video"`

The target is video data.

`"worker"`

The target is a worker.

`"xslt"`

The target is an XSLT transform.

Examples
--------

 In the following snippet, we create a new request using the
 `Request()` constructor (for an image file in the same
 directory as the script), then save the request's destination:

```js
const myRequest = new Request("flowers.jpg");
const myDestination = myRequest.destination; // returns the empty string by default
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-request-destination① |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP


Request: redirect property - Web APIs

Request: redirect property
==========================

The **`redirect`** read-only property of the `Request` interface contains the mode for how redirects are handled.

Value
-----

A `RequestRedirect` enum value, which can be one the following strings:

* `follow`
* `error`
* `manual`

If not specified when the request is created, it takes the default value of `follow`.

Examples
--------

In the following snippet, we create a new request using the `Request()` constructor (for an image file in the same directory as the script), then save the request `redirect` value in a variable:

```js
const myRequest = new Request("flowers.jpg");
const myCred = myRequest.redirect;
```

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

| Specification |
| --- |
| Fetch Standard # ref-for-dom-request-redirect② |

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

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

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP