repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/api/devicemotioneventacceleration | data/mdn-content/files/en-us/web/api/devicemotioneventacceleration/z/index.md | ---
title: "DeviceMotionEventAcceleration: z property"
short-title: z
slug: Web/API/DeviceMotionEventAcceleration/z
page-type: web-api-instance-property
browser-compat: api.DeviceMotionEventAcceleration.z
---
{{APIRef("Device Orientation Events")}}{{securecontext_header}}
The **`z`** read-only property of the {{domxref("DeviceMotionEventAcceleration")}} interface indicates the amount of acceleration that occurred along the Z
axis in a [`DeviceMotionEventAcceleration`](/en-US/docs/Web/API/DeviceMotionEventAcceleration)
object.
## Value
A `double` indicating the amount of acceleration along the Z axis.
See [Accelerometer values explained](/en-US/docs/Web/API/Device_orientation_events/Detecting_device_orientation) for details.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/devicemotioneventacceleration | data/mdn-content/files/en-us/web/api/devicemotioneventacceleration/y/index.md | ---
title: "DeviceMotionEventAcceleration: y property"
short-title: "y"
slug: Web/API/DeviceMotionEventAcceleration/y
page-type: web-api-instance-property
browser-compat: api.DeviceMotionEventAcceleration.y
---
{{APIRef("Device Orientation Events")}}{{securecontext_header}}
The **`y`** read-only property of the {{domxref("DeviceMotionEventAcceleration")}} interface indicates the amount of acceleration that occurred along the Y
axis in a [`DeviceMotionEventAcceleration`](/en-US/docs/Web/API/DeviceMotionEventAcceleration)
object.
## Value
A `double` indicating the amount of acceleration along the Y axis.
See [Accelerometer values explained](/en-US/docs/Web/API/Device_orientation_events/Detecting_device_orientation) for details.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/devicemotioneventacceleration | data/mdn-content/files/en-us/web/api/devicemotioneventacceleration/x/index.md | ---
title: "DeviceMotionEventAcceleration: x property"
short-title: x
slug: Web/API/DeviceMotionEventAcceleration/x
page-type: web-api-instance-property
browser-compat: api.DeviceMotionEventAcceleration.x
---
{{APIRef("Device Orientation Events")}}{{securecontext_header}}
The **`x`** read-only property of the {{domxref("DeviceMotionEventAcceleration")}} interface indicates the amount of acceleration that occurred along the X
axis in a [`DeviceMotionEventAcceleration`](/en-US/docs/Web/API/DeviceMotionEventAcceleration)
object.
## Value
A `double` indicating the amount of acceleration along the X axis.
See [Accelerometer values explained](/en-US/docs/Web/API/Device_orientation_events/Detecting_device_orientation) for details.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/csstransformvalue/index.md | ---
title: CSSTransformValue
slug: Web/API/CSSTransformValue
page-type: web-api-interface
browser-compat: api.CSSTransformValue
---
{{APIRef("CSS Typed OM")}}
The **`CSSTransformValue`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents `transform-list` values as used by the CSS {{CSSxref('transform')}} property.
{{InheritanceDiagram}}
## Interfaces based on CSSTransformValue
Below is a list of interfaces based on the `CSSTransformValue` interface.
- {{domxref('CSSTranslate')}}
- {{domxref('CSSRotate')}}
- {{domxref('CSSScale')}}
- {{domxref('CSSSkew')}}
- {{domxref('CSSSkewX')}}
- {{domxref('CSSSkewY')}}
- {{domxref('CSSPerspective')}}
- {{domxref('CSSMatrixComponent')}}
## Constructor
- {{domxref("CSSTransformValue.CSSTransformValue", "CSSTransformValue()")}}
- : Creates a new `CSSTransformValue` object.
## Instance properties
- {{domxref("CSSTransformValue.length")}} {{ReadOnlyInline}}
- : Returns how many transform components are contained within the `CSSTransformValue`.
- {{domxref("CSSTransformValue.is2D")}} {{ReadOnlyInline}}
- : Returns a boolean indicating whether the transform is 2D or 3D.
## Instance methods
_Inherits methods from its ancestor {{domxref('CSSStyleValue')}}._
- {{domxref("CSSTransformValue.toMatrix()")}}
- : Returns a new {{domxref('DOMMatrix')}} object.
- {{domxref('CSSUnparsedValue.entries()')}}
- : Returns an array of a given object's own enumerable property `[key, value]` pairs in the same order as that provided by a {{jsxref("Statements/for...in", "for...in")}} loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
- {{domxref('CSSUnparsedValue.forEach()')}}
- : Executes a provided function once for each element of the `CSSTransformValue` object.
- {{domxref('CSSUnparsedValue.keys()')}}
- : Returns a new _array iterator_ object that contains the keys for each index in the `CSSTransformValue` object.
- {{domxref('CSSUnparsedValue.values()')}}
- : Returns a new _array iterator_ object that contains the values for each index in the `CSSTransformValue` object.
## Examples
To Do.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/csstransformvalue | data/mdn-content/files/en-us/web/api/csstransformvalue/length/index.md | ---
title: "CSSTransformValue: length property"
short-title: length
slug: Web/API/CSSTransformValue/length
page-type: web-api-instance-property
browser-compat: api.CSSTransformValue.length
---
{{APIRef("CSS Typed OM")}}
The read-only **`length`** property of the
{{domxref("CSSTransformValue")}} interface returns the number of transform components in
the list.
## Value
An integer representing the number of transform components in the list.
## Examples
To Do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/csstransformvalue | data/mdn-content/files/en-us/web/api/csstransformvalue/tomatrix/index.md | ---
title: "CSSTransformValue: toMatrix() method"
short-title: toMatrix()
slug: Web/API/CSSTransformValue/toMatrix
page-type: web-api-instance-method
browser-compat: api.CSSTransformValue.toMatrix
---
{{APIRef("CSS Typed OM")}}
The **`toMatrix()`** method of the
{{domxref("CSSTransformValue")}} interface returns a {{domxref('DOMMatrix')}} object.
## Syntax
```js-nolint
toMatrix()
```
### Parameters
None.
### Return value
A {{domxref('DOMMatrix')}} object.
### Exceptions
- {{jsxref("TypeError")}}
- : Raised if any lengths involved in generating the matrix are not compatible units
with px (such as relative lengths or percentages).
## Examples
To Do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/csstransformvalue | data/mdn-content/files/en-us/web/api/csstransformvalue/keys/index.md | ---
title: "CSSTransformValue: keys() method"
short-title: keys()
slug: Web/API/CSSTransformValue/keys
page-type: web-api-instance-method
browser-compat: api.CSSTransformValue.keys
---
{{APIRef("CSS Typed OM")}}
The **`CSSTransformValue.keys()`** method
returns a new _array iterator_ object that contains the keys
for each index in the array.
## Syntax
```js-nolint
keys()
```
### Parameters
None.
### Return value
A new {{jsxref("Array")}}.
## Examples
To Do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/csstransformvalue | data/mdn-content/files/en-us/web/api/csstransformvalue/values/index.md | ---
title: "CSSTransformValue: values() method"
short-title: values()
slug: Web/API/CSSTransformValue/values
page-type: web-api-instance-method
browser-compat: api.CSSTransformValue.values
---
{{APIRef("CSS Typed OM")}}
The **`CSSTransformValue.values()`** returns a
new _array iterator_ object that contains the values for
each index in the CSSTransformValue object.
## Syntax
```js-nolint
values()
```
### Parameters
None.
### Return value
A new {{jsxref("Array")}}.
## Examples
To Do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/csstransformvalue | data/mdn-content/files/en-us/web/api/csstransformvalue/foreach/index.md | ---
title: "CSSTransformValue: forEach() method"
short-title: forEach()
slug: Web/API/CSSTransformValue/forEach
page-type: web-api-instance-method
browser-compat: api.CSSTransformValue.forEach
---
{{APIRef("CSS Typed OM")}}
The **`CSSTransformValue.forEach()`** method executes a provided function once for each element of the `CSSTransformValue`.
## Syntax
```js-nolint
forEach(callbackFn)
forEach(callbackFn, thisArg)
```
### Parameters
- `callbackFn`
- : The function to execute for each element, taking three arguments:
- `currentValue`
- : The value of the current element being processed.
- `index` {{optional_inline}}
- : The index of the current element being processed.
- `array` {{optional_inline}}
- : The `CSSTransformValue` that `forEach()` is being called on.
- `thisArg` {{Optional_inline}}
- : Value to use as **`this`** (i.e., the reference `Object`) when executing `callback`.
### Return value
None ({{jsxref("undefined")}}).
## Examples
To Do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/csstransformvalue | data/mdn-content/files/en-us/web/api/csstransformvalue/is2d/index.md | ---
title: "CSSTransformValue: is2D property"
short-title: is2D
slug: Web/API/CSSTransformValue/is2D
page-type: web-api-instance-property
browser-compat: api.CSSTransformValue.is2D
---
{{APIRef("CSS Typed OM")}}
The read-only **`is2D`** property of the
{{domxref("CSSTransformValue")}} interface returns whether the transform is 2D or 3D.
In the case of the `CSSTransformValue` this property returns
true unless any of the individual functions return false for `Is2D`, in which
case it returns false.
## Value
A boolean. True indicates that the transform is a 2D transform, false that it is a 3D
transform.
## Examples
To Do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/csstransformvalue | data/mdn-content/files/en-us/web/api/csstransformvalue/csstransformvalue/index.md | ---
title: "CSSTransformValue: CSSTransformValue() constructor"
short-title: CSSTransformValue()
slug: Web/API/CSSTransformValue/CSSTransformValue
page-type: web-api-constructor
browser-compat: api.CSSTransformValue.CSSTransformValue
---
{{APIRef("CSS Typed OM")}}
The **`CSSTransformValue()`** constructor
creates a new {{domxref("CSSTransformValue")}} object which represents a list of
individual transform objects.
## Syntax
```js-nolint
new CSSTransformValue(transforms)
```
### Parameters
- `transforms`
- : A list of {{domxref("CSSTransformComponent")}} objects to iterate over.
### Return value
A new {{domxref("CSSTransformValue")}}.
### Exceptions
- {{jsxref("TypeError")}}
- : Raised if transforms is empty.
## Examples
To do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/csstransformvalue | data/mdn-content/files/en-us/web/api/csstransformvalue/entries/index.md | ---
title: "CSSTransformValue: entries() method"
short-title: entries()
slug: Web/API/CSSTransformValue/entries
page-type: web-api-instance-method
browser-compat: api.CSSTransformValue.entries
---
{{APIRef("CSS Typed OM")}}
The **`CSSTransformValue.entries()`** method
returns an array of a given object's own enumerable
property `[key, value]` pairs in the same order as that provided by a
[`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop (the difference being that a for-in loop enumerates
properties in the prototype chain as well).
## Syntax
```js-nolint
entries(obj)
```
### Parameters
- `obj`
- : The {{domxref('CSSTransformValue')}} whose enumerable own property
`[key, value]` pairs are to be returned.
### Return value
An array of the given `CSSTransformValue` object's own enumerable property
`[key, value]` pairs.
## Examples
To Do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfedistantlightelement/index.md | ---
title: SVGFEDistantLightElement
slug: Web/API/SVGFEDistantLightElement
page-type: web-api-interface
browser-compat: api.SVGFEDistantLightElement
---
{{APIRef("SVG")}}
The **`SVGFEDistantLightElement`** interface corresponds to the {{SVGElement("feDistantLight")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
- {{domxref("SVGFEDistantLightElement.azimuth")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("azimuth")}} attribute of the given element.
- {{domxref("SVGFEDistantLightElement.elevation")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("elevation")}} attribute of the given element.
## Instance methods
_This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("feDistantLight")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gyroscope/index.md | ---
title: Gyroscope
slug: Web/API/Gyroscope
page-type: web-api-interface
browser-compat: api.Gyroscope
---
{{securecontext_header}}{{APIRef("Sensor API")}}
The **`Gyroscope`** interface of the [Sensor APIs](/en-US/docs/Web/API/Sensor_APIs) provides on each reading the angular velocity of the device along all three axes.
To use this sensor, the user must grant permission to the `'gyroscope'` device sensor through the [Permissions API](/en-US/docs/Web/API/Permissions_API). In addition, this feature may be blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.
{{InheritanceDiagram}}
## Constructor
- {{domxref("Gyroscope.Gyroscope", "Gyroscope()")}}
- : Creates a new `Gyroscope` object.
## Instance properties
- {{domxref('Gyroscope.x')}} {{ReadOnlyInline}}
- : Returns a double, containing the angular velocity of the device along the device's x axis.
- {{domxref('Gyroscope.y')}} {{ReadOnlyInline}}
- : Returns a double, containing the angular velocity of the device along the device's y axis.
- {{domxref('Gyroscope.z')}} {{ReadOnlyInline}}
- : Returns a double, containing the angular velocity of the device along the device's z axis.
## Instance methods
_`Gyroscope` doesn't have own methods. However, it inherits methods from its parent interfaces, {{domxref("Sensor")}} and {{domxref("EventTarget")}}._
## Events
_`Gyroscope` doesn't have own events. However, it inherits events from its parent interface, {{domxref('Sensor')}}._
## Example
The gyroscope is typically read in the {{domxref('Sensor.reading_event', 'reading')}} event callback. In the example below this occurs sixty times a second.
```js
let gyroscope = new Gyroscope({ frequency: 60 });
gyroscope.addEventListener("reading", (e) => {
console.log(`Angular velocity along the X-axis ${gyroscope.x}`);
console.log(`Angular velocity along the Y-axis ${gyroscope.y}`);
console.log(`Angular velocity along the Z-axis ${gyroscope.z}`);
});
gyroscope.start();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/gyroscope | data/mdn-content/files/en-us/web/api/gyroscope/z/index.md | ---
title: "Gyroscope: z property"
short-title: z
slug: Web/API/Gyroscope/z
page-type: web-api-instance-property
browser-compat: api.Gyroscope.z
---
{{securecontext_header}}{{APIRef("Sensor API")}}
The **`z`** read-only property of the
{{domxref("Gyroscope")}} interface returns a number specifying the
angular velocity of the device along its z-axis.
## Value
A {{jsxref('Number')}}.
## Examples
The gyroscope is typically read in the {{domxref('Sensor.reading_event', 'reading')}} event callback.
In the example below this occurs sixty times a second.
```js
let gyroscope = new Gyroscope({ frequency: 60 });
gyroscope.addEventListener("reading", (e) => {
console.log(`Angular velocity along the X-axis ${gyroscope.x}`);
console.log(`Angular velocity along the Y-axis ${gyroscope.y}`);
console.log(`Angular velocity along the Z-axis ${gyroscope.z}`);
});
gyroscope.start();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/gyroscope | data/mdn-content/files/en-us/web/api/gyroscope/y/index.md | ---
title: "Gyroscope: y property"
short-title: "y"
slug: Web/API/Gyroscope/y
page-type: web-api-instance-property
browser-compat: api.Gyroscope.y
---
{{securecontext_header}}{{APIRef("Sensor API")}}
The **`y`** read-only property of the {{domxref("Gyroscope")}} interface returns a number specifying the angular velocity of the device along its y-axis.
## Value
A {{jsxref('Number')}}.
## Examples
The gyroscope is typically read in the {{domxref('Sensor.reading_event', 'reading')}} event callback.
In the example below this occurs sixty times a second.
```js
let gyroscope = new Gyroscope({ frequency: 60 });
gyroscope.addEventListener("reading", (e) => {
console.log(`Angular velocity along the X-axis ${gyroscope.x}`);
console.log(`Angular velocity along the Y-axis ${gyroscope.y}`);
console.log(`Angular velocity along the Z-axis ${gyroscope.z}`);
});
gyroscope.start();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/gyroscope | data/mdn-content/files/en-us/web/api/gyroscope/x/index.md | ---
title: "Gyroscope: x property"
short-title: x
slug: Web/API/Gyroscope/x
page-type: web-api-instance-property
browser-compat: api.Gyroscope.x
---
{{securecontext_header}}{{APIRef("Sensor API")}}
The **`x`** read-only property of the
{{domxref("Gyroscope")}} interface returns a number specifying the
angular velocity of the device along its x-axis.
## Value
A {{jsxref('Number')}}.
## Examples
The gyroscope is typically read in the {{domxref('Sensor.reading_event', 'reading')}} event callback.
In the example below this occurs sixty times a second.
```js
let gyroscope = new Gyroscope({ frequency: 60 });
gyroscope.addEventListener("reading", (e) => {
console.log(`Angular velocity along the X-axis ${gyroscope.x}`);
console.log(`Angular velocity along the Y-axis ${gyroscope.y}`);
console.log(`Angular velocity along the Z-axis ${gyroscope.z}`);
});
gyroscope.start();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/gyroscope | data/mdn-content/files/en-us/web/api/gyroscope/gyroscope/index.md | ---
title: "Gyroscope: Gyroscope() constructor"
short-title: Gyroscope()
slug: Web/API/Gyroscope/Gyroscope
page-type: web-api-constructor
browser-compat: api.Gyroscope.Gyroscope
---
{{securecontext_header}}{{APIRef("Sensor API")}}
The **`Gyroscope()`** constructor
creates a new {{domxref("Gyroscope")}} object which provides on each reading the
angular velocity of the device along all three axes.
## Syntax
```js-nolint
new Gyroscope()
new Gyroscope(options)
```
### Parameters
- `options` {{optional_inline}}
- : Options are as follows:
- `frequency` {{optional_inline}}
- : The desired number of times per second a sample should
be taken, meaning the number of times per second that the
{{domxref('sensor.reading_event', 'reading')}} event will be called. A whole number or decimal may be
used, the latter for frequencies less than a second. The actual reading frequency
depends device hardware and consequently may be less than requested.
- `referenceFrame` {{optional_inline}}
- : Either `'device'` or
`'screen'`. The default is `'device'`.
### Exceptions
- `SecurityError` {{domxref("DOMException")}}
- : Use of this feature was blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref('sensor.reading_event', 'reading')}} event
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediaquerylistevent/index.md | ---
title: MediaQueryListEvent
slug: Web/API/MediaQueryListEvent
page-type: web-api-interface
browser-compat: api.MediaQueryListEvent
---
{{APIRef("CSSOM")}}
The `MediaQueryListEvent` object stores information on the changes that have happened to a {{DOMxRef("MediaQueryList")}} object — instances are available as the event object on a function referenced by a {{DOMxRef("MediaQueryList.change_event", "change")}} event.
{{InheritanceDiagram}}
## Constructor
- {{DOMxRef("MediaQueryListEvent.MediaQueryListEvent()", "MediaQueryListEvent()")}}
- : Creates a new `MediaQueryListEvent` instance.
## Instance properties
_The `MediaQueryListEvent` interface inherits properties from its parent interface, {{DOMxRef("Event")}}._
- {{DOMxRef("MediaQueryListEvent.matches")}} {{ReadOnlyInline}}
- : A boolean value that is `true` if the {{DOMxRef("document")}} currently matches the media query list, or `false` if not.
- {{DOMxRef("MediaQueryListEvent.media")}} {{ReadOnlyInline}}
- : A string representing a serialized media query.
## Instance methods
_The `MediaQueryListEvent` interface inherits methods from its parent interface, {{DOMxRef("Event")}}._
## Examples
```js
const para = document.querySelector("p"); // This is the UI element where to display the text
const mql = window.matchMedia("(max-width: 600px)");
mql.addEventListener("change", (event) => {
if (event.matches) {
// The viewport is 600 pixels wide or less
para.textContent = "This is a narrow screen — less than 600px wide.";
document.body.style.backgroundColor = "red";
} else {
// The viewport is more than 600 pixels wide
para.textContent = "This is a wide screen — more than 600px wide.";
document.body.style.backgroundColor = "blue";
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries)
- [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries)
- {{DOMxRef("window.matchMedia()")}}
- {{DOMxRef("MediaQueryList")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediaquerylistevent | data/mdn-content/files/en-us/web/api/mediaquerylistevent/media/index.md | ---
title: "MediaQueryListEvent: media property"
short-title: media
slug: Web/API/MediaQueryListEvent/media
page-type: web-api-instance-property
browser-compat: api.MediaQueryListEvent.media
---
{{APIRef("CSSOM")}}
The **`media`** read-only property of the
{{DOMxRef("MediaQueryListEvent")}} interface is a string representing
a serialized media query.
## Value
A string representing a serialized media query.
## Examples
```js
const para = document.querySelector("p"); // This is the UI element where to display the text
const mql = window.matchMedia("(max-width: 600px)");
mql.addEventListener("change", (event) => {
if (event.matches) {
// The viewport is 600 pixels wide or less
para.textContent = "This is a narrow screen — less than 600px wide.";
document.body.style.backgroundColor = "red";
} else {
// The viewport is more than 600 pixels wide
para.textContent = "This is a wide screen — more than 600px wide.";
document.body.style.backgroundColor = "blue";
}
console.log(event.media);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries)
- [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries)
- {{DOMxRef("window.matchMedia()")}}
- {{DOMxRef("MediaQueryList")}}
- {{DOMxRef("MediaQueryListEvent")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediaquerylistevent | data/mdn-content/files/en-us/web/api/mediaquerylistevent/mediaquerylistevent/index.md | ---
title: "MediaQueryListEvent: MediaQueryListEvent() constructor"
short-title: MediaQueryListEvent()
slug: Web/API/MediaQueryListEvent/MediaQueryListEvent
page-type: web-api-constructor
browser-compat: api.MediaQueryListEvent.MediaQueryListEvent
---
{{APIRef("CSSOM")}}
The **`MediaQueryListEvent()`** constructor creates a new {{domxref("MediaQueryListEvent")}} object.
## Syntax
```js-nolint
new MediaQueryListEvent(type)
new MediaQueryListEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `change`.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `media` {{optional_inline}}
- : A string representing a serialized media query. It defaults to `""`.
- `matches` {{optional_inline}}
- : A boolean value representing the media query status; `true` if it matches, `false` if not. It defaults to `false`.
### Return value
A new {{domxref("MediaQueryListEvent")}} object.
## Examples
```js
const media = "(max-width: 600px)";
const matches = true;
const myMediaQueryListEvent = new MediaQueryListEvent("change", {
media,
matches,
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries)
- [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries)
- {{DOMxRef("window.matchMedia()")}}
- {{DOMxRef("MediaQueryList")}}
- {{DOMxRef("MediaQueryListEvent")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediaquerylistevent | data/mdn-content/files/en-us/web/api/mediaquerylistevent/matches/index.md | ---
title: "MediaQueryListEvent: matches property"
short-title: matches
slug: Web/API/MediaQueryListEvent/matches
page-type: web-api-instance-property
browser-compat: api.MediaQueryListEvent.matches
---
{{APIRef("CSSOM")}}
The **`matches`** read-only property of the
{{DOMxRef("MediaQueryListEvent")}} interface is a boolean value that is
`true` if the {{DOMxRef("document")}} currently matches the media query list,
or `false` if not.
## Value
A boolean value; returns `true` if the {{DOMxRef("document")}}
currently matches the media query list, `false` if not.
## Examples
```js
const para = document.querySelector("p"); // This is the UI element where to display the text
const mql = window.matchMedia("(max-width: 600px)");
mql.addEventListener("change", (event) => {
if (event.matches) {
// The viewport is 600 pixels wide or less
para.textContent = "This is a narrow screen — less than 600px wide.";
document.body.style.backgroundColor = "red";
} else {
// The viewport is more than 600 pixels wide
para.textContent = "This is a wide screen — more than 600px wide.";
document.body.style.backgroundColor = "blue";
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries)
- [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries)
- {{DOMxRef("window.matchMedia()")}}
- {{DOMxRef("MediaQueryList")}}
- {{DOMxRef("MediaQueryListEvent")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/transformstreamdefaultcontroller/index.md | ---
title: TransformStreamDefaultController
slug: Web/API/TransformStreamDefaultController
page-type: web-api-interface
browser-compat: api.TransformStreamDefaultController
---
{{APIRef("Streams")}}
The **`TransformStreamDefaultController`** interface of the [Streams API](/en-US/docs/Web/API/Streams_API) provides methods to manipulate the associated {{domxref("ReadableStream")}} and {{domxref("WritableStream")}}.
When constructing a {{domxref("TransformStream")}}, the `TransformStreamDefaultController` is created. It therefore has no constructor. The way to get an instance of `TransformStreamDefaultController` is via the callback methods of {{domxref("TransformStream.TransformStream", "TransformStream()")}}.
## Instance properties
- {{domxref("TransformStreamDefaultController.desiredSize")}} {{ReadOnlyInline}}
- : Returns the desired size to fill the readable side of the stream's internal queue.
## Instance methods
- {{domxref("TransformStreamDefaultController.enqueue()")}}
- : Enqueues a chunk (single piece of data) in the readable side of the stream.
- {{domxref("TransformStreamDefaultController.error()")}}
- : Errors both the readable and writable side of the transform stream.
- {{domxref("TransformStreamDefaultController.terminate()")}}
- : Closes the readable side and errors the writable side of the stream.
## Examples
In the following example, a transform stream passes through all chunks it receives as {{jsxref("Uint8Array")}} values, using the {{domxref("TransformStreamDefaultController.error()","error()")}} and {{domxref("TransformStreamDefaultController.enqueue()","enqueue()")}} methods.
```js
const transformContent = {
start() {}, // required.
async transform(chunk, controller) {
chunk = await chunk;
switch (typeof chunk) {
case "object":
// just say the stream is done I guess
if (chunk === null) {
controller.terminate();
} else if (ArrayBuffer.isView(chunk)) {
controller.enqueue(
new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength),
);
} else if (
Array.isArray(chunk) &&
chunk.every((value) => typeof value === "number")
) {
controller.enqueue(new Uint8Array(chunk));
} else if (
typeof chunk.valueOf === "function" &&
chunk.valueOf() !== chunk
) {
this.transform(chunk.valueOf(), controller); // hack
} else if ("toJSON" in chunk) {
this.transform(JSON.stringify(chunk), controller);
}
break;
case "symbol":
controller.error("Cannot send a symbol as a chunk part");
break;
case "undefined":
controller.error("Cannot send undefined as a chunk part");
break;
default:
controller.enqueue(this.textencoder.encode(String(chunk)));
break;
}
},
flush() {
/* do any destructor work here */
},
};
class AnyToU8Stream extends TransformStream {
constructor() {
super({ ...transformContent, textencoder: new TextEncoder() });
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/transformstreamdefaultcontroller | data/mdn-content/files/en-us/web/api/transformstreamdefaultcontroller/terminate/index.md | ---
title: "TransformStreamDefaultController: terminate() method"
short-title: terminate()
slug: Web/API/TransformStreamDefaultController/terminate
page-type: web-api-instance-method
browser-compat: api.TransformStreamDefaultController.terminate
---
{{DefaultAPISidebar("Streams API")}}
The **`terminate()`** method of the {{domxref("TransformStreamDefaultController")}} interface closes the readable side and errors the writable side of the stream.
## Syntax
```js-nolint
terminate()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
In the below example the `terminate()` method is called on a {{domxref("TransformStreamDefaultController")}}.
```js
controller.terminate();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/transformstreamdefaultcontroller | data/mdn-content/files/en-us/web/api/transformstreamdefaultcontroller/desiredsize/index.md | ---
title: "TransformStreamDefaultController: desiredSize property"
short-title: desiredSize
slug: Web/API/TransformStreamDefaultController/desiredSize
page-type: web-api-instance-property
browser-compat: api.TransformStreamDefaultController.desiredSize
---
{{DefaultAPISidebar("Streams API")}}
The **`desiredSize`** read-only property of the {{domxref("TransformStreamDefaultController")}} interface returns the desired size to fill the queue of the associated {{domxref("ReadableStream")}}.
The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. The browser determines the **desired size** to fill the stream, and it is this value returned by the `desiredSize` property.
If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to [manually apply backpressure](/en-US/docs/Web/API/Streams_API/Concepts#backpressure) to manage the queue.
## Value
The desired size.
## Examples
In the next example the `desiredSize` is logged to the console.
```js
console.log(controller.desiredSize);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/transformstreamdefaultcontroller | data/mdn-content/files/en-us/web/api/transformstreamdefaultcontroller/error/index.md | ---
title: "TransformStreamDefaultController: error() method"
short-title: error()
slug: Web/API/TransformStreamDefaultController/error
page-type: web-api-instance-method
browser-compat: api.TransformStreamDefaultController.error
---
{{DefaultAPISidebar("Streams API")}}
The **`error()`** method of the {{domxref("TransformStreamDefaultController")}} interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded.
## Syntax
```js-nolint
error(reason)
```
### Parameters
- `reason`
- : A string containing the error message to be returned on any further interaction with the stream.
### Return value
None ({{jsxref("undefined")}}).
## Examples
In this example the `error()` method is used when a chunk could not be transformed.
```js
const transformContent = {
start() {
/* … */
},
async transform(chunk, controller) {
try {
chunk = await applyMyTransformation(chunk);
} catch (err) {
controller.error(`Unable to transform chunk: ${err}`);
}
// …
},
// …
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/transformstreamdefaultcontroller | data/mdn-content/files/en-us/web/api/transformstreamdefaultcontroller/enqueue/index.md | ---
title: "TransformStreamDefaultController: enqueue() method"
short-title: enqueue()
slug: Web/API/TransformStreamDefaultController/enqueue
page-type: web-api-instance-method
browser-compat: api.TransformStreamDefaultController.enqueue
---
{{DefaultAPISidebar("Streams API")}}
The **`enqueue()`** method of the {{domxref("TransformStreamDefaultController")}} interface enqueues the given chunk in the readable side of the stream.
For more information on readable streams and chunks see [Using Readable Streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams).
## Syntax
```js-nolint
enqueue(chunk)
```
### Parameters
- `chunk`
- : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : The stream is not readable.
This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called.
## Examples
In this example an encoded chunk is passed to the queue using the `enqueue()` method.
```js
const textEncoderStream = new TransformStream({
transform(chunk, controller) {
controller.enqueue(new TextEncoder().encode(chunk));
},
flush(controller) {
controller.terminate();
},
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrjointspace/index.md | ---
title: XRJointSpace
slug: Web/API/XRJointSpace
page-type: web-api-interface
browser-compat: api.XRJointSpace
---
{{APIRef("WebXR Device API")}}
The **`XRJointSpace`** interface is an {{domxref("XRSpace")}} and represents the position and orientation of an {{domxref("XRHand")}} joint.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("XRJointSpace.jointName")}} {{ReadOnlyInline}}
- : The name of the joint that is tracked. See {{domxref("XRHand")}} for possible hand joint names.
## Examples
### Using `XRJointSpace` objects
You can use an `XRJointSpace` object and an {{domxref("XRReferenceSpace")}} to get an {{domxref("XRJointPose")}} by calling {{domxref("XRFrame.getJointPose()")}}.
```js
navigator.xr
.requestSession({ optionalFeatures: ["hand-tracking"] })
.then(/** … */);
function renderFrame(session, frame) {
// …
for (const inputSource of session.inputSources) {
if (inputSource.hand) {
const indexFingerTipJoint = inputSource.hand.get("index-finger-tip"); // XRJointSpace
indexFingerTipJoint.jointName; // "index-finger-tip"
frame.getJointPose(indexFingerTipJoint, referenceSpace); // XRJointPose
}
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRHand")}}
- {{domxref("XRReferenceSpace")}}
- {{domxref("XRJointPose")}}
- {{domxref("XRFrame.getJointPose()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrjointspace | data/mdn-content/files/en-us/web/api/xrjointspace/jointname/index.md | ---
title: "XRJointSpace: jointName property"
short-title: jointName
slug: Web/API/XRJointSpace/jointName
page-type: web-api-instance-property
browser-compat: api.XRJointSpace.jointName
---
{{APIRef("WebXR Device API")}}
The read-only **`jointName`** property of the {{domxref("XRJointSpace")}} interface contains the name of the joint it tracks.
## Value
A string indicating the name of the joint. See the list of hand joints on the {{domxref("XRHand")}} page.
## Examples
### Getting the `jointName`
Given a `XRJointSpace`, the `jointName` property will contain the hand joint name.
```js
navigator.xr
.requestSession({ optionalFeatures: ["hand-tracking"] })
.then(/** … */);
function renderFrame(session, frame) {
// …
for (const inputSource of session.inputSources) {
if (inputSource.hand) {
const indexFingerTipJoint = inputSource.hand.get("index-finger-tip"); // XRJointSpace
indexFingerTipJoint.jointName; // "index-finger-tip"
}
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRHand")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter/index.md | ---
title: WritableStreamDefaultWriter
slug: Web/API/WritableStreamDefaultWriter
page-type: web-api-interface
browser-compat: api.WritableStreamDefaultWriter
---
{{APIRef("Streams")}}
The **`WritableStreamDefaultWriter`** interface of the [Streams API](/en-US/docs/Web/API/Streams_API) is the object returned by {{domxref("WritableStream.getWriter()")}} and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink.
## Constructor
- {{domxref("WritableStreamDefaultWriter.WritableStreamDefaultWriter", "WritableStreamDefaultWriter()")}}
- : Creates a new `WritableStreamDefaultWriter` object instance.
## Instance properties
- {{domxref("WritableStreamDefaultWriter.closed")}} {{ReadOnlyInline}}
- : Allows you to write code that responds to an end to the streaming process. Returns a promise that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released.
- {{domxref("WritableStreamDefaultWriter.desiredSize")}} {{ReadOnlyInline}}
- : Returns the desired size required to fill the stream's internal queue.
- {{domxref("WritableStreamDefaultWriter.ready")}} {{ReadOnlyInline}}
- : Returns a {{jsxref("Promise")}} that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure.
## Instance methods
- {{domxref("WritableStreamDefaultWriter.abort()")}}
- : Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.
- {{domxref("WritableStreamDefaultWriter.close()")}}
- : Closes the associated writable stream.
- {{domxref("WritableStreamDefaultWriter.releaseLock()")}}
- : Releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed.
- {{domxref("WritableStreamDefaultWriter.write()")}}
- : Writes a passed chunk of data to a {{domxref("WritableStream")}} and its underlying sink, then returns a {{jsxref("Promise")}} that resolves to indicate the success or failure of the write operation.
## Examples
The following example shows the creation of a `WritableStream` with a custom sink and an API-supplied queuing strategy. It then calls a function called `sendMessage()`, passing the newly created stream and a string. Inside this function it calls the stream's `getWriter()` method, which returns an instance of {{domxref("WritableStreamDefaultWriter")}}. A `forEach()` call is used to write each chunk of the string to the stream. Finally, `write()` and `close()` return promises that are processed to deal with success or failure of chunks and streams.
```js
const list = document.querySelector("ul");
async function sendMessage(message, writableStream) {
// defaultWriter is of type WritableStreamDefaultWriter
const defaultWriter = writableStream.getWriter();
const encoder = new TextEncoder();
const encoded = encoder.encode(message);
try {
for (const chunk of encoded) {
await defaultWriter.ready;
await defaultWriter.write(chunk);
console.log("Chunk written to sink.");
}
// Call ready again to ensure that all chunks are written
// before closing the writer.
await defaultWriter.ready;
await defaultWriter.close();
console.log("All chunks written");
} catch (err) {
console.log("Error:", err);
}
}
const decoder = new TextDecoder("utf-8");
const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });
let result = "";
const writableStream = new WritableStream(
{
// Implement the sink
write(chunk) {
return new Promise((resolve, reject) => {
const buffer = new ArrayBuffer(1);
const view = new Uint8Array(buffer);
view[0] = chunk;
const decoded = decoder.decode(view, { stream: true });
const listItem = document.createElement("li");
listItem.textContent = `Chunk decoded: ${decoded}`;
list.appendChild(listItem);
result += decoded;
resolve();
});
},
close() {
const listItem = document.createElement("li");
listItem.textContent = `[MESSAGE RECEIVED] ${result}`;
list.appendChild(listItem);
},
abort(err) {
console.log("Sink error:", err);
},
},
queuingStrategy,
);
sendMessage("Hello, world.", writableStream);
```
You can find the full code in our [Simple writer example](https://mdn.github.io/dom-examples/streams/simple-writer/).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter | data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter/closed/index.md | ---
title: "WritableStreamDefaultWriter: closed property"
short-title: closed
slug: Web/API/WritableStreamDefaultWriter/closed
page-type: web-api-instance-property
browser-compat: api.WritableStreamDefaultWriter.closed
---
{{APIRef("Streams")}}
The **`closed`** read-only property of the
{{domxref("WritableStreamDefaultWriter")}} interface returns a
{{jsxref("Promise")}} that fulfills if the stream becomes closed, or rejects if
the stream errors or the writer's lock is released.
## Value
A {{jsxref("Promise")}}.
## Examples
```js
const writableStream = new WritableStream(
{
start(controller) {},
write(chunk, controller) {
// ...
},
close(controller) {
// ...
},
abort(err) {
// ...
},
},
queuingStrategy,
);
// ...
const writer = writableStream.getWriter();
// ..
// check if the stream is closed
writer.closed.then(() => {
console.log("writer closed");
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter | data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter/desiredsize/index.md | ---
title: "WritableStreamDefaultWriter: desiredSize property"
short-title: desiredSize
slug: Web/API/WritableStreamDefaultWriter/desiredSize
page-type: web-api-instance-property
browser-compat: api.WritableStreamDefaultWriter.desiredSize
---
{{APIRef("Streams")}}
The **`desiredSize`** read-only property of the
{{domxref("WritableStreamDefaultWriter")}} interface returns the desired size required
to fill the stream's internal queue.
## Value
An integer. Note that this can be negative if the queue is over-full.
The value will be `null` if the stream cannot be successfully written to
(due to either being errored, or having an abort queued up), and zero if the stream is
closed.
### Exceptions
- {{jsxref("TypeError")}}
- : The writer's lock is released.
## Examples
```js
const writableStream = new WritableStream(
{
write(chunk) {
// ...
},
close() {
// ...
},
abort(err) {
// ...
},
},
queuingStrategy,
);
// ...
const writer = writableStream.getWriter();
// ...
// return stream's desired size
let size = writer.desiredSize;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter | data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter/write/index.md | ---
title: "WritableStreamDefaultWriter: write() method"
short-title: write()
slug: Web/API/WritableStreamDefaultWriter/write
page-type: web-api-instance-method
browser-compat: api.WritableStreamDefaultWriter.write
---
{{APIRef("Streams")}}
The **`write()`** method of the
{{domxref("WritableStreamDefaultWriter")}} interface writes a passed chunk of data to a
{{domxref("WritableStream")}} and its underlying sink, then returns a
{{jsxref("Promise")}} that resolves to indicate the success or failure of the write
operation.
Note that what "success" means is up to the underlying sink; it might indicate that the
chunk has been accepted, and not necessarily that it is safely saved to its ultimate
destination.
## Syntax
```js-nolint
write(chunk)
```
### Parameters
- `chunk`
- : A block of binary data to pass to the `WritableStream`.
### Return value
A {{jsxref("Promise")}}, which fulfills with the `undefined` upon a
successful write, or rejects if the write fails or stream becomes errored before the
writing process is initiated.
### Exceptions
- {{jsxref("TypeError")}}
- : The target stream is not a writable stream, or it does not have an owner.
## Examples
The following example shows the creation of a `WritableStream` with a custom
sink and an API-supplied queuing strategy. It then calls a function called
`sendMessage()`, passing the newly created stream and a string. Inside this
function it calls the stream's `getWriter()` method, which returns an
instance of {{domxref("WritableStreamDefaultWriter")}}. A `forEach()` call is
used to write each chunk of the string to the stream. Finally, `write()` and
`close()` return promises that are processed to deal with success or failure
of chunks and streams.
```js
const list = document.querySelector("ul");
function sendMessage(message, writableStream) {
// defaultWriter is of type WritableStreamDefaultWriter
const defaultWriter = writableStream.getWriter();
const encoder = new TextEncoder();
const encoded = encoder.encode(message);
encoded.forEach((chunk) => {
defaultWriter.ready
.then(() => defaultWriter.write(chunk))
.then(() => {
console.log("Chunk written to sink.");
})
.catch((err) => {
console.log("Chunk error:", err);
});
});
// Call ready again to ensure that all chunks are written
// before closing the writer.
defaultWriter.ready
.then(() => {
defaultWriter.close();
})
.then(() => {
console.log("All chunks written");
})
.catch((err) => {
console.log("Stream error:", err);
});
}
const decoder = new TextDecoder("utf-8");
const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });
let result = "";
const writableStream = new WritableStream(
{
// Implement the sink
write(chunk) {
return new Promise((resolve, reject) => {
const buffer = new ArrayBuffer(1);
const view = new Uint8Array(buffer);
view[0] = chunk;
const decoded = decoder.decode(view, { stream: true });
const listItem = document.createElement("li");
listItem.textContent = `Chunk decoded: ${decoded}`;
list.appendChild(listItem);
result += decoded;
resolve();
});
},
close() {
const listItem = document.createElement("li");
listItem.textContent = `[MESSAGE RECEIVED] ${result}`;
list.appendChild(listItem);
},
abort(err) {
console.log("Sink error:", err);
},
},
queuingStrategy,
);
sendMessage("Hello, world.", writableStream);
```
You can find the full code in our [Simple writer example](https://mdn.github.io/dom-examples/streams/simple-writer/).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter | data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter/abort/index.md | ---
title: "WritableStreamDefaultWriter: abort() method"
short-title: abort()
slug: Web/API/WritableStreamDefaultWriter/abort
page-type: web-api-instance-method
browser-compat: api.WritableStreamDefaultWriter.abort
---
{{APIRef("Streams")}}
The **`abort()`** method of the
{{domxref("WritableStreamDefaultWriter")}} interface aborts the stream, signaling that
the producer can no longer successfully write to the stream and it is to be immediately
moved to an error state, with any queued writes discarded.
If the writer is active, the `abort()` method behaves the same as that for
the associated stream ({{domxref("WritableStream.abort()")}}). If not, it returns a
rejected promise.
## Syntax
```js-nolint
abort()
abort(reason)
```
### Parameters
- `reason` {{optional_inline}}
- : A string representing a human-readable reason for the abort.
### Return value
A {{jsxref("Promise")}}, which fulfills to `undefined` when the stream is aborted, or
rejects with an error if the writer was inactive or the receiver stream is invalid.
### Exceptions
- {{jsxref("TypeError")}}
- : The stream you are trying to abort is not a {{domxref("WritableStream")}}, or it is
locked.
## Examples
```js
const writableStream = new WritableStream(
{
write(chunk) {
// ...
},
close() {
// ...
},
abort(err) {
// ...
},
},
queuingStrategy,
);
// ...
const writer = writableStream.getWriter();
// ...
// abort the stream when desired
await writer.abort("WritableStream aborted. Reason: ...");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter | data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter/ready/index.md | ---
title: "WritableStreamDefaultWriter: ready property"
short-title: ready
slug: Web/API/WritableStreamDefaultWriter/ready
page-type: web-api-instance-property
browser-compat: api.WritableStreamDefaultWriter.ready
---
{{APIRef("Streams")}}
The **`ready`** read-only property of the
{{domxref("WritableStreamDefaultWriter")}} interface returns a {{jsxref("Promise")}}
that resolves when the desired size of the stream's internal queue transitions from
non-positive to positive, signaling that it is no longer applying backpressure.
## Value
A {{jsxref("Promise")}}.
## Examples
The following example shows two uses of the `ready` property. The first uses
`ready` to ensure that the `WritableStream` is done writing and
thus able to receive data before sending a binary chunk. The second also checks whether
the `WritableStream` is done writing, but this time because the writing
must be finished before the writer can be closed.
```js
function sendMessage(message, writableStream) {
// defaultWriter is of type WritableStreamDefaultWriter
const defaultWriter = writableStream.getWriter();
const encoder = new TextEncoder();
const encoded = encoder.encode(message);
encoded.forEach((chunk) => {
// Make sure the stream and its writer are able to
// receive data.
defaultWriter.ready
.then(() => defaultWriter.write(chunk))
.then(() => {
console.log("Chunk written to sink.");
})
.catch((err) => {
console.error(`Chunk error: ${err}`);
});
// Call ready again to ensure that all chunks are written
// before closing the writer.
defaultWriter.ready
.then(() => defaultWriter.close())
.then(() => {
console.log("All chunks written");
})
.catch((err) => {
console.error(`Stream error: ${err}`);
});
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter | data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter/releaselock/index.md | ---
title: "WritableStreamDefaultWriter: releaseLock() method"
short-title: releaseLock()
slug: Web/API/WritableStreamDefaultWriter/releaseLock
page-type: web-api-instance-method
browser-compat: api.WritableStreamDefaultWriter.releaseLock
---
{{APIRef("Streams")}}
The **`releaseLock()`** method of the
{{domxref("WritableStreamDefaultWriter")}} interface releases the writer's lock on the
corresponding stream. After the lock is released, the writer is no longer active. If the
associated stream is errored when the lock is released, the writer will appear errored
in the same way from now on; otherwise, the writer will appear closed.
## Syntax
```js-nolint
releaseLock()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
const writableStream = new WritableStream(
{
write(chunk) {
// ...
},
close() {
// ...
},
abort(err) {
// ...
},
},
queuingStrategy,
);
// ...
const writer = writableStream.getWriter();
// ...
// release writer's lock on the stream when desired
writer.releaseLock();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter | data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter/close/index.md | ---
title: "WritableStreamDefaultWriter: close() method"
short-title: close()
slug: Web/API/WritableStreamDefaultWriter/close
page-type: web-api-instance-method
browser-compat: api.WritableStreamDefaultWriter.close
---
{{APIRef("Streams")}}
The **`close()`** method of the
{{domxref("WritableStreamDefaultWriter")}} interface closes the associated writable
stream.
The underlying sink will finish processing any previously-written chunks, before
invoking the close behavior. During this time any further attempts to write will fail
(without erroring the stream).
## Syntax
```js-nolint
close()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}}, which fulfills with the `undefined` if all
remaining chunks were successfully written before the close, or rejects with an error if
a problem was encountered during the process.
### Exceptions
- {{jsxref("TypeError")}}
- : The stream you are trying to close is not a {{domxref("WritableStream")}}.
## Examples
The following example shows the creation of a `WritableStream` with a custom
sink and an API-supplied queuing strategy. It then calls a function called
`sendMessage()`, passing the newly created stream and a string. Inside this
function it calls the stream's `getWriter()` method, which returns an
instance of {{domxref("WritableStreamDefaultWriter")}}. Each chunk of the
encoded string is written to the stream using the `write()` method, and the
`forEach()` method of the encoded `Uint8Array` to process it byte-by-byte.
Finally, `close()` is called and the Promise it returns is handled to deal
with success (or any failures) of the chunked write operations.
```js
const list = document.querySelector("ul");
function sendMessage(message, writableStream) {
// defaultWriter is of type WritableStreamDefaultWriter
const defaultWriter = writableStream.getWriter();
const encoder = new TextEncoder();
const encoded = encoder.encode(message);
encoded.forEach((chunk) => {
defaultWriter.ready
.then(() => {
defaultWriter.write(chunk);
})
.then(() => {
console.log("Chunk written to sink.");
})
.catch((err) => {
console.log("Chunk error:", err);
});
});
// Call ready again to ensure that all chunks are written
// before closing the writer.
defaultWriter.ready
.then(() => {
defaultWriter.close();
})
.then(() => {
console.log("All chunks written");
})
.catch((err) => {
console.log("Stream error:", err);
});
}
const decoder = new TextDecoder("utf-8");
const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });
let result = "";
const writableStream = new WritableStream(
{
// Implement the sink
write(chunk) {
return new Promise((resolve, reject) => {
const buffer = new ArrayBuffer(1);
const view = new Uint8Array(buffer);
view[0] = chunk;
const decoded = decoder.decode(view, { stream: true });
const listItem = document.createElement("li");
listItem.textContent = `Chunk decoded: ${decoded}`;
list.appendChild(listItem);
result += decoded;
resolve();
});
},
close() {
const listItem = document.createElement("li");
listItem.textContent = `[MESSAGE RECEIVED] ${result}`;
list.appendChild(listItem);
},
abort(err) {
console.log("Sink error:", err);
},
},
queuingStrategy,
);
sendMessage("Hello, world.", writableStream);
```
You can view a live demonstration of this at our [simple writer example](https://mdn.github.io/dom-examples/streams/simple-writer/).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter | data/mdn-content/files/en-us/web/api/writablestreamdefaultwriter/writablestreamdefaultwriter/index.md | ---
title: "WritableStreamDefaultWriter: WritableStreamDefaultWriter() constructor"
short-title: WritableStreamDefaultWriter()
slug: Web/API/WritableStreamDefaultWriter/WritableStreamDefaultWriter
page-type: web-api-constructor
browser-compat: api.WritableStreamDefaultWriter.WritableStreamDefaultWriter
---
{{APIRef("Streams")}}
The **`WritableStreamDefaultWriter()`**
constructor creates a new {{domxref("WritableStreamDefaultWriter")}} object instance.
> **Note:** You generally wouldn't use this constructor manually; instead,
> you'd use the {{domxref("WritableStream.getWriter()")}} method.
## Syntax
```js-nolint
new WritableStreamDefaultWriter(stream)
```
### Parameters
- `stream`
- : The {{domxref("WritableStream")}} to be written to.
### Return value
An instance of the {{domxref("WritableStreamDefaultWriter")}} object.
### Exceptions
- {{jsxref("TypeError")}}
- : The provided `stream` value is not a {{domxref("WritableStream")}}, or it
is locked to another writer already.
## Examples
The following example shows the creation of a `WritableStream` with a custom
sink and an API-supplied queuing strategy. It then calls a function called
`sendMessage()`, passing the newly created stream and a string. Inside this
function it calls the stream's `getWriter()` method, which returns an
instance of {{domxref("WritableStreamDefaultWriter")}}. A `forEach()` call is
used to write each chunk of the string to the stream. Finally, `write()` and
`close()` return promises that are processed to deal with success or failure
of chunks and streams.
```js
const list = document.querySelector("ul");
function sendMessage(message, writableStream) {
// defaultWriter is of type WritableStreamDefaultWriter
const defaultWriter = writableStream.getWriter();
const encoder = new TextEncoder();
const encoded = encoder.encode(message, { stream: true });
encoded.forEach((chunk) => {
defaultWriter.ready
.then(() => defaultWriter.write(chunk))
.then(() => {
console.log("Chunk written to sink.");
})
.catch((err) => {
console.log("Chunk error:", err);
});
});
// Call ready again to ensure that all chunks are written
// before closing the writer.
defaultWriter.ready
.then(() => {
defaultWriter.close();
})
.then(() => {
console.log("All chunks written");
})
.catch((err) => {
console.log("Stream error:", err);
});
}
const decoder = new TextDecoder("utf-8");
const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });
let result = "";
const writableStream = new WritableStream(
{
// Implement the sink
write(chunk) {
return new Promise((resolve, reject) => {
const buffer = new ArrayBuffer(1);
const view = new Uint8Array(buffer);
view[0] = chunk;
const decoded = decoder.decode(view, { stream: true });
const listItem = document.createElement("li");
listItem.textContent = `Chunk decoded: ${decoded}`;
list.appendChild(listItem);
result += decoded;
resolve();
});
},
close() {
const listItem = document.createElement("li");
listItem.textContent = `[MESSAGE RECEIVED] ${result}`;
list.appendChild(listItem);
},
abort(err) {
console.log("Sink error:", err);
},
},
queuingStrategy,
);
sendMessage("Hello, world.", writableStream);
```
You can find the full code in our [Simple writer example](https://mdn.github.io/dom-examples/streams/simple-writer/).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/backgroundfetchevent/index.md | ---
title: BackgroundFetchEvent
slug: Web/API/BackgroundFetchEvent
page-type: web-api-interface
status:
- experimental
browser-compat: api.BackgroundFetchEvent
---
{{APIRef("Background Fetch API")}}{{SeeCompatTable}}
The **`BackgroundFetchEvent`** interface of the {{domxref('Background Fetch API','','',' ')}} is the event type for background fetch events dispatched on the {{domxref("ServiceWorkerGlobalScope", "service worker global scope")}}.
It is the event type passed to `onbackgroundfetchabort` and `onbackgroundfetchclick`.
{{InheritanceDiagram}}
## Constructor
- {{domxref("BackgroundFetchEvent.BackgroundFetchEvent()", "BackgroundFetchEvent()")}} {{Experimental_Inline}}
- : Creates a new `BackgroundFetchEvent` object. This constructor is not typically used, as the browser creates these objects itself and provides them to background fetch event callbacks.
## Instance properties
_Inherits properties from its ancestor, {{domxref("Event")}}_.
- {{domxref("BackgroundFetchEvent.registration")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the {{domxref("BackgroundFetchRegistration")}} that the event was initialized to.
## Instance methods
None.
## Examples
In this example, if the user clicks on the user interface displaying the download progress, a new window will open. The current {{domxref("BackgroundFetchRegistration")}} is returned by calling `event.registration`.
```js
addEventListener("backgroundfetchclick", (event) => {
const bgFetch = event.registration;
if (bgFetch.result === "success") {
clients.openWindow("/latest-podcasts");
} else {
clients.openWindow("/download-progress");
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/backgroundfetchevent | data/mdn-content/files/en-us/web/api/backgroundfetchevent/registration/index.md | ---
title: "BackgroundFetchEvent: registration property"
short-title: registration
slug: Web/API/BackgroundFetchEvent/registration
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BackgroundFetchEvent.registration
---
{{APIRef("Background Fetch API")}}{{SeeCompatTable}}
The **`registration`** read-only property of the {{domxref("BackgroundFetchEvent")}} interface returns a {{domxref("BackgroundFetchRegistration")}} object.
## Value
A {{domxref("BackgroundFetchRegistration")}}.
## Examples
In this example, if the user clicks on the user interface displaying the download progress, this fires the `onbackgroundfetchclick` event. The current {{domxref("BackgroundFetchRegistration")}} is returned by calling `event.registration`.
```js
addEventListener("backgroundfetchclick", (event) => {
console.log(event.registration);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/backgroundfetchevent | data/mdn-content/files/en-us/web/api/backgroundfetchevent/backgroundfetchevent/index.md | ---
title: "BackgroundFetchEvent: BackgroundFetchEvent() constructor"
short-title: BackgroundFetchEvent()
slug: Web/API/BackgroundFetchEvent/BackgroundFetchEvent
page-type: web-api-constructor
status:
- experimental
browser-compat: api.BackgroundFetchEvent.BackgroundFetchEvent
---
{{APIRef("Background Fetch API")}}{{SeeCompatTable}}
The **`BackgroundFetchEvent()`** constructor creates a new {{domxref("BackgroundFetchEvent")}} object. This constructor is not typically used as the browser creates these objects itself and provides them to background fetch event callbacks.
## Syntax
```js-nolint
new BackgroundFetchEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers set it to `backgroundfetchabort` or `backgroundfetchclick`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("ExtendableEvent/ExtendableEvent", "ExtendableEvent()")}}_, has the following properties:
- `registration`
- : A {{domxref("BackgroundFetchRegistration")}} object.
### Return value
A new {{domxref("BackgroundFetchEvent")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/focusevent/index.md | ---
title: FocusEvent
slug: Web/API/FocusEvent
page-type: web-api-interface
browser-compat: api.FocusEvent
---
{{APIRef("UI Events")}}
The **`FocusEvent`** interface represents focus-related events, including {{domxref("Element/focus_event", "focus")}}, {{domxref("Element/blur_event", "blur")}}, {{domxref("Element/focusin_event", "focusin")}}, and {{domxref("Element/focusout_event", "focusout")}}.
{{InheritanceDiagram}}
## Constructor
- {{domxref("FocusEvent.FocusEvent", "FocusEvent()")}}
- : Creates a `FocusEvent` event with the given parameters.
## Instance properties
_This interface also inherits properties from its parent {{domxref("UIEvent")}}, and indirectly from {{domxref("Event")}}_.
- {{domxref("FocusEvent.relatedTarget")}}
- : An {{domxref("EventTarget")}} representing a secondary target for this event. In some cases (such as when tabbing in or out a page), this property may be set to `null` for security reasons.
## Instance methods
_This interface has no specific methods. It inherits methods from its parent {{domxref("UIEvent")}}, and indirectly from {{domxref("Event")}}._
## Order of events
When focus is shifted from element A to element B, focus events are dispatched in the following order:
1. `blur`: sent after element A loses focus.
2. `focusout`: sent after the `blur` event.
3. `focus`: sent after element B receives focus.
4. `focusin`: sent after the `focus` event.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("Event")}} base interface
| 0 |
data/mdn-content/files/en-us/web/api/focusevent | data/mdn-content/files/en-us/web/api/focusevent/relatedtarget/index.md | ---
title: "FocusEvent: relatedTarget property"
short-title: relatedTarget
slug: Web/API/FocusEvent/relatedTarget
page-type: web-api-instance-property
browser-compat: api.FocusEvent.relatedTarget
---
{{ apiref("DOM Events") }}
The **`FocusEvent.relatedTarget`** read-only property is the
secondary target, depending on the type of event:
<table class="no-markdown">
<thead>
<tr>
<th scope="col">Event name</th>
<th scope="col"><code>target</code></th>
<th scope="col"><code>relatedTarget</code></th>
</tr>
</thead>
<tbody>
<tr>
<td>{{domxref("Element/blur_event", "blur")}}</td>
<td>The {{domxref("EventTarget")}} losing focus</td>
<td>
The {{domxref("EventTarget")}} receiving focus (if any).
</td>
</tr>
<tr>
<td>{{domxref("Element/focus_event", "focus")}}</td>
<td>The {{domxref("EventTarget")}} receiving focus</td>
<td>The {{domxref("EventTarget")}} losing focus (if any)</td>
</tr>
<tr>
<td>{{domxref("Element/focusin_event", "focusin")}}</td>
<td>The {{domxref("EventTarget")}} receiving focus</td>
<td>The {{domxref("EventTarget")}} losing focus (if any)</td>
</tr>
<tr>
<td>{{domxref("Element/focusout_event", "focusout")}}</td>
<td>The {{domxref("EventTarget")}} losing focus</td>
<td>The {{domxref("EventTarget")}} receiving focus (if any)</td>
</tr>
</tbody>
</table>
Note that [many elements can't have focus](https://stackoverflow.com/questions/42764494/blur-event-relatedtarget-returns-null/42764495), which is a common reason for `relatedTarget` to be
`null`. `relatedTarget` may also be set to `null` for
security reasons, like when tabbing in or out of a page.
{{domxref("MouseEvent.relatedTarget")}} is a similar property for mouse events.
## Value
An instance of {{domxref("EventTarget")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("FocusEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/focusevent | data/mdn-content/files/en-us/web/api/focusevent/focusevent/index.md | ---
title: "FocusEvent: FocusEvent() constructor"
short-title: FocusEvent()
slug: Web/API/FocusEvent/FocusEvent
page-type: web-api-constructor
browser-compat: api.FocusEvent.FocusEvent
---
{{APIRef("UI Events")}}
The **`FocusEvent()`** constructor returns a newly created
{{domxref("FocusEvent")}} object with an optional {{domxref("EventTarget")}}. When the
event has both a source and a destination, the `relatedTarget` value must be
set to the other target.
## Syntax
```js-nolint
new FocusEvent(type)
new FocusEvent(type, options)
```
### Parameters
_The `FocusEvent()` constructor also inherits arguments from
{{domxref("UIEvent.UIEvent", "UIEvent()")}} and from {{domxref("Event.Event",
"Event()")}}._
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers set it to `blur`, `focus`, `focusin`, or `focusout`.
- `options` {{optional_inline}}
- : An object that, in addition of the properties defined in {{domxref("UIEvent/UIEvent", "UIEvent()")}}, can have the following properties:
- `relatedTarget` {{optional_inline}}
- : An {{domxref("EventTarget")}} representing the secondary target of a {{domxref("FocusEvent")}}. It defaults to `null`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("FocusEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/idbtransaction/index.md | ---
title: IDBTransaction
slug: Web/API/IDBTransaction
page-type: web-api-interface
browser-compat: api.IDBTransaction
---
{{APIRef("IndexedDB")}}
The **`IDBTransaction`** interface of the [IndexedDB API](/en-US/docs/Web/API/IndexedDB_API) provides a static, asynchronous transaction on a database using event handler attributes. All reading and writing of data is done within transactions. You use {{domxref("IDBDatabase")}} to start transactions, {{domxref("IDBTransaction")}} to set the mode of the transaction (e.g. is it `readonly` or `readwrite`), and you access an {{domxref("IDBObjectStore")}} to make a request. You can also use an `IDBTransaction` object to abort transactions.
{{AvailableInWorkers}}
{{InheritanceDiagram}}
Transactions are started when the transaction is created, not when the first request is placed; for example consider this:
```js
const trans1 = db.transaction("foo", "readwrite");
const trans2 = db.transaction("foo", "readwrite");
const objectStore2 = trans2.objectStore("foo");
const objectStore1 = trans1.objectStore("foo");
objectStore2.put("2", "key");
objectStore1.put("1", "key");
```
After the code is executed the object store should contain the value "2", since `trans2` should run after `trans1`.
## Transaction failures
Transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback:
- Abort due to bad requests, e.g. trying to `add()` the same key twice, or `put()` with the same index key with a uniqueness constraint. This causes an error on the request, which can bubble up to an error on the transaction, which aborts the transaction. This can be prevented by using `preventDefault()` on the error event on the request.
- An explicit `abort()` call from script.
- An uncaught exception in the request's `success`/`error` handler.
- An I/O error (e.g. an actual failure to write to disk, or other OS/hardware failure).
- Quota exceeded.
- A user agent crash.
## Firefox durability guarantees
Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see [Firefox bug 1112702](https://bugzil.la/1112702).) Previously in a `readwrite` transaction, a {{domxref("IDBTransaction.complete_event","complete")}} event was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the `complete` event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The `complete` event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.
If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the `complete` event by creating a transaction using the experimental (non-standard) `readwriteflush` mode (see {{domxref("IDBDatabase.transaction")}}.
## Instance properties
- {{domxref("IDBTransaction.db")}} {{ReadOnlyInline}}
- : The database connection with which this transaction is associated.
- {{domxref("IDBTransaction.durability")}} {{ReadOnlyInline}}
- : Returns the durability hint the transaction was created with.
- {{domxref("IDBTransaction.error")}} {{ReadOnlyInline}}
- : Returns a {{domxref("DOMException")}} indicating the type of error that occurred when there is an unsuccessful transaction. This property is `null` if the transaction is not finished, is finished and successfully committed, or was aborted with the {{domxref("IDBTransaction.abort()")}} function.
- {{domxref("IDBTransaction.mode")}} {{ReadOnlyInline}}
- : The mode for isolating access to data in the object stores that are in the scope of the transaction. The default value is [`readonly`](#const_read_only).
- {{domxref("IDBTransaction.objectStoreNames")}} {{ReadOnlyInline}}
- : Returns a {{domxref("DOMStringList")}} of the names of {{domxref("IDBObjectStore")}} objects associated with the transaction.
## Instance methods
Inherits from: {{domxref("EventTarget")}}
- {{domxref("IDBTransaction.abort()")}}
- : Rolls back all the changes to objects in the database associated with this transaction. If this transaction has been aborted or completed, this method fires an error event.
- {{domxref("IDBTransaction.objectStore()")}}
- : Returns an {{domxref("IDBObjectStore")}} object representing an object store that is part of the scope of this transaction.
- {{domxref("IDBTransaction.commit()")}}
- : For an active transaction, commits the transaction. Note that this doesn't normally _have_ to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made. `commit()` can be used to start the commit process without waiting for events from outstanding requests to be dispatched.
## Events
Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.
- [`abort`](/en-US/docs/Web/API/IDBTransaction/abort_event)
- : An event fired when the `IndexedDB` transaction is aborted.
Also available via the `onabort` property; this event bubbles to {{domxref("IDBDatabase")}}.
- [`complete`](/en-US/docs/Web/API/IDBTransaction/complete_event)
- : An event fired when the transaction successfully completes.
Also available via the `oncomplete` property.
- [`error`](/en-US/docs/Web/API/IDBTransaction/error_event)
- : An event fired when a request returns an error and the event bubbles up to the connection object ({{domxref("IDBDatabase")}}).
Also available via the `onerror` property.
## Mode constants
{{Deprecated_Header}}
> **Warning:** These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. ([Firefox bug 888598](https://bugzil.la/888598))
Transactions can have one of three modes:
<table class="standard-table">
<thead>
<tr>
<th scope="col">Constant</th>
<th scope="col">Value</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code><a>READ_ONLY</a></code>
</td>
<td>"readonly" (0 in Chrome)</td>
<td><p>Allows data to be read but not changed.</p></td>
</tr>
<tr>
<td>
<code><a>READ_WRITE</a></code>
</td>
<td>"readwrite" (1 in Chrome)</td>
<td>
Allows reading and writing of data in existing data stores to be
changed.
</td>
</tr>
<tr>
<td>
<code><a>VERSION_CHANGE</a></code>
</td>
<td>"versionchange" (2 in Chrome)</td>
<td>
Allows any operation to be performed, including ones that delete and
create object stores and indexes. Transactions of this mode cannot run
concurrently with other transactions. Transactions in this mode are
known as "upgrade transactions."
</td>
</tr>
</tbody>
</table>
Even if these constants are now deprecated, you can still use them to provide backward compatibility if required (in Chrome [the change was made in version 21](https://peter.sh/2012/05/tab-sizing-string-values-for-indexeddb-and-chrome-21/)). You should code defensively in case the object is not available anymore:
```js
const myIDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction || { READ_WRITE: "readwrite" };
```
## Examples
In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const note = document.getElementById("notifications");
// an instance of a db object for us to store the IDB data in
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.innerHTML += "<li>Database initialized.</li>";
// store the result of opening the database in the db
// variable. This is used a lot below
db = DBOpenRequest.result;
// Add the data to the database
addData();
};
function addData() {
// Create a new object to insert into the IDB
const newItem = [
{
taskTitle: "Walk dog",
hours: 19,
minutes: 30,
day: 24,
month: "December",
year: 2013,
notified: "no",
},
];
// open a read/write db transaction, ready to add data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.innerHTML +=
"<li>Transaction completed: database modification finished.</li>";
};
transaction.onerror = (event) => {
note.innerHTML +=
"<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.oncomplete)
note.innerHTML += "<li>Request successful.</li>";
};
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/mode/index.md | ---
title: "IDBTransaction: mode property"
short-title: mode
slug: Web/API/IDBTransaction/mode
page-type: web-api-instance-property
browser-compat: api.IDBTransaction.mode
---
{{ APIRef("IndexedDB") }}
The **`mode`** read-only property of the
{{domxref("IDBTransaction")}} interface returns the current mode for accessing the
data in the object stores in the scope of the transaction (i.e. is the mode to be
read-only, or do you want to write to the object stores?) The default value is
`readonly`.
{{AvailableInWorkers}}
## Value
An object defining the mode for isolating access to
data in the current object stores:
A string defining the mode for isolating access to data in the current object stores.
The following values are available:
- `readonly`
- : Allows data to be read but not changed.
- `readwrite`
- : Allows reading and writing of data in existing data stores to be changed.
- `versionchange`
- : Allows any operation, including ones that delete and
create object stores and indexes.
This mode is for updating the version number of transactions if the need is detected when calling {{domxref("IDBFactory.open()")}}.
Transactions of this mode cannot run concurrently with other transactions.
Transactions in this mode are known as _upgrade transactions_.
## Examples
In the following code snippet, we open a read/write transaction on our database and add
some data to an object store. Note also the functions attached to transaction event
handlers to report on the outcome of the transaction opening in the event of success or
failure. At the end, we log the mode of the current transaction using `mode`.
For a full working example, see our [To-do Notifications app](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const note = document.getElementById("notifications");
// an instance of a db object for us to store the IDB data in
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.innerHTML += "<li>Database initialized.</li>";
// store the result of opening the database in the db variable.
// This is used a lot below
db = DBOpenRequest.result;
// Run the addData() function to add the data to the database
addData();
};
function addData() {
// Create a new object ready for being inserted into the IDB
const newItem = [
{
taskTitle: "Walk dog",
hours: 19,
minutes: 30,
day: 24,
month: "December",
year: 2013,
notified: "no",
},
];
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.innerHTML +=
"<li>Transaction completed: database modification finished.</li>";
};
transaction.onerror = (event) => {
note.innerHTML +=
"<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.onsuccess)
note.innerHTML += "<li>Request successful.</li>";
};
// Return the mode this transaction has been opened in (should be "readwrite" in this case)
transaction.mode;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/abort_event/index.md | ---
title: "IDBTransaction: abort event"
short-title: abort
slug: Web/API/IDBTransaction/abort_event
page-type: web-api-event
browser-compat: api.IDBTransaction.abort_event
---
{{APIRef("IndexedDB")}}
The `abort` event is fired when an `IndexedDB` transaction is aborted.
This can happen for any of the following reasons:
- Bad requests, (E.g., trying to add the same key twice, or put the same index key when the key has a uniqueness constraint).
- An explicit {{DOMxRef("IDBTransaction.abort", "abort()")}} call.
- An uncaught exception in the request's success/error handler.
- An I/O error (an actual failure to write to disk, for example disk detached, or other OS/hardware failure).
- Quota exceeded.
This non-cancelable event [bubbles](/en-US/docs/Learn/JavaScript/Building_blocks/Events#bubbling_and_capturing_explained) to the associated {{domxref("IDBDatabase")}} object.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("abort", (event) => {});
onabort = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Bubbling
This event bubbles to {{domxref("IDBDatabase")}}. The `event.target` property refers to the {{domxref('IDBTransaction')}} object that bubbles up.
For more information, see [Event bubbling and capture](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture).
## Examples
This example opens a database (creating the database if it does not exist), then opens a transaction, adds a listener to the `abort` event, then aborts the transaction to trigger the event.
```js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
DBOpenRequest.onsuccess = (event) => {
const db = DBOpenRequest.result;
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// add a listener for `abort`
transaction.addEventListener("abort", () => {
console.log("Transaction was aborted");
});
// abort the transaction
transaction.abort();
};
```
The same example, but assigning the event handler to the {{DOMxRef("IDBTransaction.abort_event", "onabort")}} property:
```js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
DBOpenRequest.onsuccess = (event) => {
const db = DBOpenRequest.result;
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// add a listener for `abort`
transaction.onabort = (event) => {
console.log("Transaction was aborted");
};
// abort the transaction
transaction.abort();
};
```
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/error/index.md | ---
title: "IDBTransaction: error property"
short-title: error
slug: Web/API/IDBTransaction/error
page-type: web-api-instance-property
browser-compat: api.IDBTransaction.error
---
{{ APIRef("IndexedDB") }}
The **`IDBTransaction.error`** property of the {{domxref("IDBTransaction")}} interface
returns the type of error when there is an unsuccessful transaction.
{{AvailableInWorkers}}
## Value
A {{domxref("DOMException")}} containing the relevant error, or `null` if there are none.
It can be a reference to the same error as the request object that raised it, or a transaction
failure (for example `QuotaExceededError`).
This property is `null` if the transaction is not finished, or is finished and
was successfully committed.
## Examples
In the following code snippet, we open a read/write transaction on our database and add
some data to an object store. Note also the functions attached to transaction event
handlers to report on the outcome of the transaction opening in the event of success or
failure. Note the `transaction.onerror = (event) => { };` block, making
use of `transaction.error` to help in reporting what went wrong when the
transaction was unsuccessful. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([View example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const note = document.getElementById("notifications");
// an instance of a db object for us to store the IDB data in
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.innerHTML += "<li>Database initialized.</li>";
// store the result of opening the database in the db variable.
// This is used a lot below
db = DBOpenRequest.result;
// Run the addData() function to add the data to the database
addData();
};
function addData() {
// Create a new object ready for being inserted into the IDB
const newItem = [
{
taskTitle: "Walk dog",
hours: 19,
minutes: 30,
day: 24,
month: "December",
year: 2013,
notified: "no",
},
];
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.innerHTML +=
"<li>Transaction completed: database modification finished.</li>";
};
transaction.onerror = (event) => {
note.innerHTML += `<li>Transaction not opened due to error: ${transaction.error}</li>`;
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.onsuccess)
note.innerHTML += "<li>Request successful.</li>";
};
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/complete_event/index.md | ---
title: "IDBTransaction: complete event"
short-title: complete
slug: Web/API/IDBTransaction/complete_event
page-type: web-api-event
browser-compat: api.IDBTransaction.complete_event
---
{{APIRef("IndexedDB")}}
The **`complete`** event of the [IndexedDB API](/en-US/docs/Web/API/IndexedDB_API) is fired when the transaction successfully completed.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("complete", (event) => {});
oncomplete = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
Using {{DOMxRef("EventTarget.addEventListener", "addEventListener()")}}:
```js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
DBOpenRequest.onsuccess = (event) => {
const db = DBOpenRequest.result;
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// add a listener for `complete`
transaction.addEventListener("complete", (event) => {
console.log("Transaction was completed");
});
const objectStore = transaction.objectStore("toDoList");
const newItem = {
taskTitle: "my task",
hours: 10,
minutes: 10,
day: 10,
month: "January",
year: 2019,
};
const objectStoreRequest = objectStore.add(newItem);
};
```
Using the `oncomplete` property:
```js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
DBOpenRequest.onsuccess = (event) => {
const db = DBOpenRequest.result;
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// add a listener for `complete`
transaction.oncomplete = (event) => {
console.log("Transaction was completed");
};
const objectStore = transaction.objectStore("toDoList");
const newItem = {
taskTitle: "my task",
hours: 10,
minutes: 10,
day: 10,
month: "January",
year: 2019,
};
const objectStoreRequest = objectStore.add(newItem);
};
```
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/objectstorenames/index.md | ---
title: "IDBTransaction: objectStoreNames property"
short-title: objectStoreNames
slug: Web/API/IDBTransaction/ObjectStoreNames
page-type: web-api-instance-property
browser-compat: api.IDBTransaction.objectStoreNames
---
{{ APIRef("IndexedDB") }}
The **`objectStoreNames`** read-only property of the
{{domxref("IDBTransaction")}} interface returns a {{domxref("DOMStringList")}} of names
of {{domxref("IDBObjectStore")}} objects.
## Value
A {{domxref("DOMStringList")}} of names of {{domxref("IDBObjectStore")}} objects.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/objectstore/index.md | ---
title: "IDBTransaction: objectStore() method"
short-title: objectStore()
slug: Web/API/IDBTransaction/objectStore
page-type: web-api-instance-method
browser-compat: api.IDBTransaction.objectStore
---
{{ APIRef("IndexedDB") }}
The **`objectStore()`** method of the
{{domxref("IDBTransaction")}} interface returns an object store that has already been
added to the scope of this transaction.
Every call to this method on the same transaction object, with the same name, returns
the same {{domxref("IDBObjectStore")}} instance. If this method is called on a different
transaction object, a different {{domxref("IDBObjectStore")}} instance is returned.
{{AvailableInWorkers}}
## Syntax
```js-nolint
objectStore(name)
```
### Parameters
- `name`
- : The name of the requested object store.
### Return value
An {{domxref("IDBObjectStore")}} object for accessing an object store.
### Exceptions
- `NotFoundError` {{domxref("DOMException")}}
- : Thrown if the requested object store is not in this transaction's scope.
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the request was made on a source object that has been deleted or removed, or if the transaction has finished.
## Examples
In the following code snippet, we open a read/write transaction on our database and add
some data to an object store. Note also the functions attached to transaction event
handlers to report on the outcome of the transaction opening in the event of success or
failure. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([View example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const note = document.getElementById("notifications");
// an instance of a db object for us to store the IDB data in
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.innerHTML += "<li>Database initialized.</li>";
// store the result of opening the database in the db variable.
// This is used a lot below
db = DBOpenRequest.result;
// Run the addData() function to add the data to the database
addData();
};
function addData() {
// Create a new object ready for being inserted into the IDB
const newItem = [
{
taskTitle: "Walk dog",
hours: 19,
minutes: 30,
day: 24,
month: "December",
year: 2013,
notified: "no",
},
];
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.innerHTML +=
"<li>Transaction completed: database modification finished.</li>";
};
transaction.onerror = (event) => {
note.innerHTML +=
"<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.onsuccess)
note.innerHTML += "<li>Request successful.</li>";
};
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/abort/index.md | ---
title: "IDBTransaction: abort() method"
short-title: abort()
slug: Web/API/IDBTransaction/abort
page-type: web-api-instance-method
browser-compat: api.IDBTransaction.abort
---
{{ APIRef("IndexedDB") }}
The **`abort()`** method of the {{domxref("IDBTransaction")}}
interface rolls back all the changes to objects in the database associated with this
transaction.
All pending {{domxref("IDBRequest")}} objects created during this transaction have
their {{domxref("IDBRequest.error")}} attribute set to an `AbortError` {{domxref("DOMException")}}.
{{AvailableInWorkers}}
## Syntax
```js-nolint
abort()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the transaction has already been committed or aborted.
## Examples
In the following code snippet, we open a read/write transaction on our database and add
some data to an object store. Note also the functions attached to transaction event
handlers to report on the outcome of the transaction opening in the event of success or
failure. At the end, we abort any activity done under the current transaction using
`abort()`. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([View example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const note = document.getElementById("notifications");
// an instance of a db object for us to store the IDB data in
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.innerHTML += "<li>Database initialized.</li>";
// store the result of opening the database in the db variable. This is used a lot below
db = DBOpenRequest.result;
// Run the addData() function to add the data to the database
addData();
};
function addData() {
// Create a new object ready for being inserted into the IDB
const newItem = [
{
taskTitle: "Walk dog",
hours: 19,
minutes: 30,
day: 24,
month: "December",
year: 2013,
notified: "no",
},
];
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.innerHTML +=
"<li>Transaction completed: database modification finished.</li>";
};
transaction.onerror = (event) => {
note.innerHTML +=
"<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.onsuccess)
note.innerHTML += "<li>Request successful.</li>";
};
// Abort the transaction we just did
transaction.abort();
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/commit/index.md | ---
title: "IDBTransaction: commit() method"
short-title: commit()
slug: Web/API/IDBTransaction/commit
page-type: web-api-instance-method
browser-compat: api.IDBTransaction.commit
---
{{ APIRef("IndexedDB") }}
The **`commit()`** method of the {{domxref("IDBTransaction")}} interface commits the transaction if it is called on an active transaction.
Note that `commit()` doesn't normally _have_ to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made. `commit()` can be used to start the commit process without waiting for events from outstanding requests to be dispatched.
If it is called on a transaction that is not active, it throws an `InvalidStateError` {{domxref("DOMException")}}.
{{AvailableInWorkers}}
## Syntax
```js-nolint
commit()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the transaction state is not active.
## Examples
```js
const note = document.getElementById("notifications");
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["myDB"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.innerHTML +=
"<li>Transaction completed: database modification finished.</li>";
};
transaction.onerror = (event) => {
note.innerHTML +=
"<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};
// create an object store on the transaction
const objectStore = transaction.objectStore("myObjStore");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.onsuccess)
note.innerHTML += "<li>Request successful.</li>";
};
// Force the changes to be committed to the database asap
transaction.commit();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/db/index.md | ---
title: "IDBTransaction: db property"
short-title: db
slug: Web/API/IDBTransaction/db
page-type: web-api-instance-property
browser-compat: api.IDBTransaction.db
---
{{ APIRef("IndexedDB") }}
The **`db`** read-only property of the {{domxref("IDBTransaction")}} interface returns the database connection
with which this transaction is associated.
{{AvailableInWorkers}}
## Value
An {{domxref("IDBDatabase")}} object.
## Examples
In the following code snippet, we open a read/write transaction on our database and add
some data to an object store. Note also the functions attached to transaction event
handlers to report on the outcome of the transaction opening in the event of success or
failure. At the end, we return the associated database connection using `db`.
For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const note = document.getElementById("notifications");
// an instance of a db object for us to store the IDB data in
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.innerHTML += "<li>Database initialized.</li>";
// store the result of opening the database in the db variable.
// This is used a lot below
db = DBOpenRequest.result;
// Run the addData() function to add the data to the database
addData();
};
function addData() {
// Create a new object ready for being inserted into the IDB
const newItem = [
{
taskTitle: "Walk dog",
hours: 19,
minutes: 30,
day: 24,
month: "December",
year: 2013,
notified: "no",
},
];
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.innerHTML +=
"<li>Transaction completed: database modification finished.</li>";
};
transaction.onerror = (event) => {
note.innerHTML +=
"<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.onsuccess)
note.innerHTML += "<li>Request successful.</li>";
};
// Return the database (IDBDatabase) connection with which this transaction is associated
transaction.db;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/durability/index.md | ---
title: "IDBTransaction: durability property"
short-title: durability
slug: Web/API/IDBTransaction/durability
page-type: web-api-instance-property
browser-compat: api.IDBTransaction.durability
---
{{securecontext_header}}{{DefaultAPISidebar("IndexedDB")}}
The **`durability`** read-only property of the
{{domxref("IDBTransaction")}} interface returns the durability hint the transaction was
created with. This is a hint to the user agent of whether to prioritize performance or
durability when committing the transaction.
The value of this property is defined in the `options` parameter when creating a transaction using {{domxref("IDBDatabase.transaction()")}}.
## Value
Any of the following literal {{jsxref('String', 'strings')}}:
- `"strict"`
- : The user agent may consider that the transaction has
successfully committed only after verifying that all outstanding changes have been
successfully written to a persistent storage medium.
- `"relaxed"`
- : The user agent may consider that the transaction has
successfully committed as soon as all outstanding changes have been written to the
operating system, without subsequent verification.
- `"default"`
- : The user agent should use its default durability behavior
for the storage bucket. This is the default for transactions if not otherwise
specified.
## Examples
For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/idbtransaction | data/mdn-content/files/en-us/web/api/idbtransaction/error_event/index.md | ---
title: "IDBTransaction: error event"
short-title: error
slug: Web/API/IDBTransaction/error_event
page-type: web-api-event
browser-compat: api.IDBTransaction.error_event
---
{{ APIRef("IndexedDB") }}
The `error` event is fired on `IDBTransaction` when a request returns an error and the event bubbles up to the transaction object.
> **Note:** To handle all the ways a transaction can fail, consider listening for the {{domxref("IDBTransaction.abort_event", "abort")}} event instead.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("error", (event) => {});
onerror = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Bubbling
This event bubbles to {{domxref("IDBDatabase")}}. The `event.target` property refers to the {{domxref('IDBTransaction')}} object that bubbles up.
For more information, see [Event bubbling and capture](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture).
## Examples
This example opens a database and tries to add a record, listening for the `error` event for the `add()` operation (this will occur if, for example, a record with the given `taskTitle` already exists):
```js
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);
dBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
dBOpenRequest.onsuccess = (event) => {
const db = dBOpenRequest.result;
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
transaction.addEventListener("error", () => {
console.log(`Error adding new item: ${newItem.taskTitle}`);
});
const objectStore = transaction.objectStore("toDoList");
const newItem = {
taskTitle: "my task",
hours: 10,
minutes: 10,
day: 10,
month: "January",
year: 2020,
};
const objectStoreRequest = objectStore.add(newItem);
};
```
The same example, using the `onerror` property instead of `addEventListener()`:
```js
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);
dBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
dBOpenRequest.onsuccess = (event) => {
const db = dBOpenRequest.result;
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
transaction.onerror = () => {
console.log(`Error adding new item: ${newItem.taskTitle}`);
};
const objectStore = transaction.objectStore("toDoList");
const newItem = {
taskTitle: "my task",
hours: 10,
minutes: 10,
day: 10,
month: "January",
year: 2020,
};
const objectStoreRequest = objectStore.add(newItem);
};
```
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/fedcm_api/index.md | ---
title: Federated Credential Management (FedCM) API
slug: Web/API/FedCM_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.IdentityCredential
---
{{SeeCompatTable}}{{DefaultAPISidebar("FedCM API")}}
The **Federated Credential Management API** (or _FedCM API_) provides a standard mechanism for identity providers (IdPs) to make identity federation services available on the web in a privacy-preserving way, without the need for third-party cookies and redirects. This includes a JavaScript API that enables the use of federated authentication for activities such as signing in or signing up on a website.
## FedCM concepts
Identity federation is the delegation of user authentication from a website requiring user sign-up or sign-in, such as an e-commerce or social networking site (also known as a relying party or RP), to a trusted third-party identity provider (IdP) such as Google, Facebook/Meta, GitHub, etc.
Relying parties (RPs) can integrate with IdPs, allowing users to sign-in using the accounts they have registered with the IdP. Identity federation via a small set of dedicated IdPs has improved web authentication in terms of security, consumer confidence, and user experience, as compared to each site managing its own sign-in needs with separate usernames and passwords.
The problem is that traditional identity federation relies on {{htmlelement("iframe")}}s, redirects, and third-party cookies, which are also used for third-party tracking. Browsers are limiting the usage of these features in an effort to preserve user privacy, but a side effect is that this makes valid, non-tracking uses more difficult to implement, which includes identity federation.
This affects federated sign-in in general, as well as more specific identity federation use cases:
- [OIDC front-channel logout](https://openid.net/specs/openid-connect-frontchannel-1_0.html): This flow requires the IDP to embed several RP `<iframe>`s, which rely on RP cookies.
- Social Widgets: In order to provide social widgets, the IdP third-party cookie must be provided from the RP top-level origin.
- Personalized buttons: The display of personalized sign in information on a {{htmlelement("button")}} in the RP origin is implemented as an IdP `<iframe>` that requires third party cookies.
- Session Refresh without top-level navigation or popups.
FedCM aims to work around this problem, providing a dedicated mechanism for federated identity flows on the web, and enabling supporting browsers to provide special UI elements on RPs, allowing users to choose an IdP account to use for sign-in.
There are two parts to using the FedCM API, which are covered in the linked guides below:
1. [IdP integration with FedCM](/en-US/docs/Web/API/FedCM_API/IDP_integration) — what an identity provider needs to provide so that an RP can integrate with it.
2. [RP federated sign-in](/en-US/docs/Web/API/FedCM_API/RP_sign-in) — the FedCM functionality an RP needs to use to sign a user in using their IdP account. A FedCM sign-in request is initiated using the {{domxref("CredentialsContainer.get", "navigator.credentials.get()")}} method.
> **Note:** [Google Sign In](https://developers.google.com/identity/gsi/web/guides/overview) is an example of an IdP that already supports FedCM. [Migrate to FedCM](https://developers.google.com/identity/gsi/web/guides/fedcm-migration) provides instructions for RPs wishing to migrate existing apps using Google Sign In to federated sign-in.
## Permissions Policy integration and `<iframe>` support
The {{httpheader("Permissions-Policy/identity-credentials-get", "identity-credentials-get")}} [Permissions-Policy](/en-US/docs/Web/HTTP/Permissions_Policy) can be used to control permission to use FedCM, more specifically usage of the {{domxref("CredentialsContainer.get", "get()")}} method.
Developers can explicitly grant permission for an {{htmlelement("iframe")}} to use FedCM via the `allow` attribute:
```html
<iframe src="3rd-party.example" allow="identity-credentials-get"></iframe>
```
The availability of FedCM within `<iframe>`s enables a couple of use cases:
- Larger sites won't want a third-party sign-in script to gain control over the top-level frame; instead they will want to add that script and invoke FedCM from within an {{htmlelement("iframe")}}.
- Some `<iframes>` may themselves require federated authentication.
## Interfaces
- {{domxref("IdentityCredential")}}
- : Represents a user identity credential arising from successful federated authentication. A successful {{domxref("CredentialsContainer.get", "navigator.credentials.get()")}} call that includes an `identity` option fulfills with an {{domxref("IdentityCredential")}} instance.
- {{domxref("IdentityProvider")}}
- : Represents an IdP and provides access to related information and functionality.
- {{domxref("NavigatorLogin")}}
- : Defines login functionality for IdPs, including the {{domxref("NavigatorLogin.setStatus", "Navigator.login.setStatus()")}} method for [updating IdP login status](/en-US/docs/Web/API/FedCM_API/IDP_integration#update_login_status_using_the_login_status_api).
## Extensions to other interfaces
- {{domxref("CredentialsContainer.get()")}}, the `identity` option.
- : `identity` is an object containing details of federated IdPs that a relying party (RP) website can use to sign users in. It causes a `get()` call to initiate a request for a user to sign in to an RP with an IdP.
- {{domxref("Navigator.login")}}
- : Provides access to the browser's {{domxref("NavigatorLogin")}} object.
## HTTP headers
- {{httpheader("Set-Login")}}
- : Provides an HTTP mechanism for [updating login status](/en-US/docs/Web/API/FedCM_API/IDP_integration#update_login_status_using_the_login_status_api) via HTTP.
## Examples
- [FedCM sign-in example](https://fedcm-rp-demo.glitch.me/)
- [RP source code](https://glitch.com/edit/#!/fedcm-rp-demo?path=server.js%3A1%3A0)
- [IdP source code](https://glitch.com/edit/#!/fedcm-idp-demo?path=server.js%3A1%3A0)
- [FedCM `<iframe>` sign-in](https://fedcm-main-frame.glitch.me/)
- [RP `<iframe>` page source code](https://glitch.com/edit/#!/fedcm-main-frame?path=index.html%3A1%3A0)
- [IdP source code](https://glitch.com/edit/#!/webid-fcm-idp-single?path=server.js%3A1%3A0)
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Federated Credential Management API](https://developer.chrome.com/docs/privacy-sandbox/fedcm/)
| 0 |
data/mdn-content/files/en-us/web/api/fedcm_api | data/mdn-content/files/en-us/web/api/fedcm_api/idp_integration/index.md | ---
title: Identity provider integration with FedCM
slug: Web/API/FedCM_API/IDP_integration
page-type: guide
---
{{DefaultAPISidebar("FedCM API")}}
This article details all the steps an identity provider (IdP) needs to take to integrate with the Federated Credential Management (FedCM) API.
## IdP integration steps
To integrate with FedCM, an IdP needs to do the following:
1. [Provide a well-known file](#provide_a_well-known_file) to identify the IdP.
2. [Provide a config file and endpoints](#provide_a_config_file_and_endpoints) for accounts list and assertion issuance (and optionally, client metadata).
3. [Update its login status](#update_login_status_using_the_login_status_api) using the Login Status API.
## Provide a well-known file
There is a potential privacy issue whereby an [IdP is able to discern whether a user visited an RP without explicit consent](https://github.com/fedidcg/FedCM/issues/230). This has tracking implications, so an IdP is required to provide a well-known file to verify its identity and mitigate this issue.
The well-known file is requested via an uncredentialed [`GET`](/en-US/docs/Web/HTTP/Methods/GET) request, which doesn't follow redirects. This effectively prevents the IdP from learning who made the request and which RP is attempting to connect.
The well-known file must be served from the [eTLD+1](https://web.dev/articles/same-site-same-origin#site) of the IdP at `/.well-known/web-identity`. For example, if the IdP endpoints are served under `https://accounts.idp.example/`, they must serve a well-known file at `https://idp.example/.well-known/web-identity`. The well-known file's content should have the following JSON structure:
```json
{
"provider_urls": ["https://accounts.idp.example/config.json"]
}
```
The `provider_urls` member should contain an array of URLs pointing to valid IdP config files that can be used by RPs to interact with the IdP. The array length is currently limited to one.
## The `Sec-Fetch-Dest` HTTP header
All requests sent from the browser via FedCM include a `{{httpheader("Sec-Fetch-Dest")}}: webidentity` header. All IdP endpoints that receive credentialed requests (i.e. `accounts_endpoint` and `id_assertion_endpoint`) must confirm this header is included to protect against {{glossary("CSRF")}} attacks.
## Provide a config file and endpoints
The IdP config file provides a list of the endpoints the browser needs to process the identity federation flow and manage the sign-ins. The endpoints need to be same-origin with the config.
The browser makes an uncredentialed request for the config file via the [`GET`](/en-US/docs/Web/HTTP/Methods/GET) method, which doesn't follow redirects. This effectively prevents the IdP from learning who made the request and which RP is attempting to connect.
The config file (hosted at `https://accounts.idp.example/config.json` in our example) should have the following JSON structure:
```json
{
"accounts_endpoint": "/accounts.php",
"client_metadata_endpoint": "/client_metadata.php",
"id_assertion_endpoint": "/assertion.php",
"login_url": "/login",
"branding": {
"background_color": "green",
"color": "0xFFEEAA",
"icons": [
{
"url": "https://idp.example/icon.ico",
"size": 25
}
]
}
}
```
The properties are as follows:
- `accounts_endpoint`
- : The URL for the accounts list endpoint, which returns a list of accounts that the user is currently signed in to on the IdP. The browser uses these to create a list of sign-in choices to show to the user in the browser-provided FedCM UI.
- `client_metadata_endpoint` {{optional_inline}}
- : The URL for the client metadata endpoint, which provides URLs pointing to the RP's metadata and terms of service pages, to be used in the FedCM UI.
- `id_assertion_endpoint`
- : The URL for the ID assertion endpoint, which when sent valid user credentials should respond with a validation token that the RP can use to validate the authentication.
- `login_url`
- : The login page URL for the user to sign into the IdP.
- `branding` {{optional_inline}}
- : Contains branding information that will be used in the browser-supplied FedCM UI to customize its appearance as desired by the IdP.
The following table summarizes the different requests made by the FedCM API:
| Endpoint/resource | Method | Credentialed (with cookies) | Includes {{httpheader("Origin")}} |
| -------------------------- | ------ | --------------------------- | --------------------------------- |
| `well-known`/`config.json` | `GET` | No | No |
| `accounts_endpoint` | `GET` | Yes | No |
| `client_metadata_endpoint` | `GET` | No | Yes |
| `id_assertion_endpoint` | `POST` | Yes | Yes |
> **Note:** For a description of the FedCM flow in which these endpoints are accessed, see [FedCM sign-in flow](/en-US/docs/Web/API/FedCM_API/RP_sign-in#fedcm_sign-in_flow).
> **Note:** None of the requests made by the FedCM API to the endpoints detailed here allow for following redirects, for privacy purposes.
### The accounts list endpoint
The browser sends credentialed requests (i.e. with a cookie that identifies the user that is signed in) to this endpoint via the `GET` method. The request has no `client_id` parameter, {{httpheader("Origin")}} header, or {{httpheader("Referer")}} header. This effectively prevents the IdP from learning which RP the user is trying to sign in to. The list of accounts returned is RP-agnostic.
For example:
```http
GET /accounts.php HTTP/1.1
Host: idp.example
Accept: application/json
Cookie: 0x23223
Sec-Fetch-Dest: webidentity
```
The response to a successful request returns a list of all the IdP accounts that the user is currently signed in with (not specific to any particular RP), with a JSON structure that matches the following:
```json
{
"accounts": [
{
"id": "john_doe",
"given_name": "John",
"name": "John Doe",
"email": "[email protected]",
"picture": "https://idp.example/profile/123",
"approved_clients": ["123", "456", "789"],
"login_hints": ["john_doe", "[email protected]"]
},
{
"id": "johnny",
"given_name": "Johnny",
"name": "Johnny",
"email": "[email protected]",
"picture": "https://idp.example/profile/456",
"approved_clients": ["abc", "def", "ghi"],
"login_hints": ["johnny", "[email protected]"]
}
]
}
```
This includes the following information:
- `id`
- : The unique ID of the user.
- `name`
- : The family name of the user.
- `email`
- : The email address of the user.
- `given_name` {{optional_inline}}
- : The given name of the user.
- `picture` {{optional_inline}}
- : The URL of the user's avatar image.
- `approved_clients` {{optional_inline}}
- : An array of RP clients that the user has registered with.
- `login_hints` {{optional_inline}}
- : An array of strings representing the account. These strings are used to filter the list of account options that the browser offers for the user to sign-in. This occurs when the `loginHint` property is provided within [`identity.providers`](/en-US/docs/Web/API/CredentialsContainer/get#providers_2) in a related `get()` call. Any account with a string in its `login_hints` array that matches the provided `loginHint` is included.
> **Note:**: If the user is not signed in to any IdP accounts, the endpoint should respond with [HTTP 401 (Unauthorized)](/en-US/docs/Web/HTTP/Status/401).
### The client metadata endpoint
The browser sends uncredentialed requests to this endpoint via the `GET` method, with the `clientId` passed into the `get()` call as a parameter.
For example:
```http
GET /client_metadata.php?client_id=1234 HTTP/1.1
Host: idp.example
Origin: https://rp.example/
Accept: application/json
Sec-Fetch-Dest: webidentity
```
The response to a successful request includes URLs pointing to the RP's metadata and terms of service pages, to be used in the browser-supplied FedCM UI. This should follow the JSON structure seen below:
```json
{
"privacy_policy_url": "https://rp.example/privacy_policy.html",
"terms_of_service_url": "https://rp.example/terms_of_service.html"
}
```
### The ID assertion endpoint
The browser sends credentialed requests to this endpoint via the [`POST`](/en-US/docs/Web/HTTP/Methods/POST) method, with a content type of `application/x-www-form-urlencoded`. The request also includes a payload including details about the attempted sign-in and the account to be validated.
It should look something like this:
```http
POST /assertion.php HTTP/1.1
Host: idp.example
Origin: https://rp.example/
Content-Type: application/x-www-form-urlencoded
Cookie: 0x23223
Sec-Fetch-Dest: webidentity
account_id=123&client_id=client1234&nonce=Ct60bD&disclosure_text_shown=true&is_auto_selected=true
```
A request to this endpoint is sent as a result of the user choosing an account to sign in with from the relevant browser UI. When sent valid user credentials, this endpoint should respond with a validation token that the RP can use to validate the user on its own server, according to the usage instructions outlined by the IdP they are using for identity federation. Once the RP validates the user, they can sign them in, sign them up to their service, etc.
```json
{
"token": "***********"
}
```
The request payload contains the following params:
- `client_id`
- : The RP's client identifier (which matches the `clientId` from the original `get()` request).
- `account_id`
- : The unique ID of the user account to be signed in (which matches the user's `id` from the accounts list endpoint response).
- `nonce` {{optional_inline}}
- : The request nonce, provided by the RP.
- `disclosure_text_shown`
- : A string of `"true"` or `"false"` indicating whether the disclosure text was shown or not. The disclosure text is the information shown to the user (which can include the terms of service and privacy policy links, if provided) if the user is signed in to the IdP but doesn't have an account specifically on the current RP (in which case they'd need to choose to "Continue as..." their IdP identity and then create a corresponding account on the RP).
- `is_auto_selected`
- : A string of `"true"` or `"false"` indicating whether the authentication validation request has been issued as a result of [auto-reauthentication](/en-US/docs/Web/API/FedCM_API/RP_sign-in#auto-reauthentication), i.e. without user mediation. This can occur when the {{domxref("CredentialsContainer.get", "get()")}} call is issued with a [`mediation`](/en-US/docs/Web/API/CredentialsContainer/get#mediation) option value of `"optional"` or `"silent"`. It is useful for the IdP to know whether auto reauthentication occurred for performance evaluation and in case higher security is desired. For example, the IdP could return an error code telling the RP that it requires explicit user mediation (`mediation="required"`).
> **Note:** If the {{domxref("CredentialsContainer.get", "get()")}} call succeeds, the `is_auto_selected` value is also communicated to the RP via the {{domxref("IdentityCredential.isAutoSelected")}} property.
#### ID assertion error responses
If the IdP cannot issue a token — for example if the client is unauthorized — the ID assertion endpoint will respond with an error response containing information about the nature of the error. For example:
```json
{
"error": {
"code": "access_denied",
"url": "https://idp.example/error?type=access_denied"
}
}
```
The error response fields are as follows:
- `code` {{optional_inline}}
- : A string. This can be either a known error from the [OAuth 2.0 specified error list](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1) or an arbitrary string.
- `url` {{optional_inline}}
- : A URL. This should be a web page containing human-readable information about the error to display to users, such as how to fix the error or contact customer. The URL must be same-site with the IdP's config URL.
This information can be used in a couple of different ways:
- The browser can display a custom UI to the user informing them of what went wrong (see the [Chrome documentation](https://developers.google.com/privacy-sandbox/blog/fedcm-chrome-120-updates#error-api) for an example). Bear in mind that if the request failed because the IdP server is unavailable, it obviously can't return any information. In such cases, the browser will report this via a generic message.
- The associated RP {{domxref("CredentialsContainer.get", "navigator.credentials.get()")}} call used to attempt sign-in will return the above information when the promise rejects, which can be used to handle the error. For example, an RP may wish to follow-up the browser's custom UI with some information to help the user succeed in a future sign-in attempt. The [`get()` Error API example](/en-US/docs/Web/API/CredentialsContainer/get#example_including_error_api_information) shows what this looks like in code.
## Update login status using the Login Status API
The **Login Status API** allows an IdP to inform a browser of its login (sign-in) status in that particular browser — by this, we mean "whether any users are logged into the IdP on the current browser or not". The browser stores this state for each IdP; the FedCM API then uses it to reduce the number of requests it makes to the IdP (because it does not need to waste time requesting accounts when there are no users logged in to the IdP). It also mitigates [potential timing attacks](https://github.com/fedidcg/FedCM/issues/447).
For each known IdP (identified by its config URL) the browser keeps a tri-state variable representing the login state with three possible values:
- `"logged-in"`: The IdP has at least one user account signed in. Note that, at this stage, the RP and browser don't know which user that is. Information on specific users is returned from the IdP's [`accounts_endpoint`](#the_accounts_list_endpoint) at a later point in the FedCM flow.
- `"logged-out"`: All IdP accounts are currently signed out.
- `"unknown"`: The sign-in status of this IdP is not known. This is the default value.
### Setting login status
The IdP should update its login status when a user signs into or out of the IdP. This can be done in two different ways:
- The {{httpheader("Set-Login")}} HTTP response header can be set in a top-level navigation or a same-origin subresource request:
```http
Set-Login: logged-in
Set-Login: logged-out
```
- The {{domxref("NavigatorLogin.setStatus", "Navigator.login.setStatus()")}} method can be called from the IdP origin:
```js
/* Set logged-in status */
navigator.login.setStatus("logged-in");
/* Set logged-out status */
navigator.login.setStatus("logged-out");
```
### How login status affects federated sign-in flow
When an [RP attempts federated sign-in](/en-US/docs/Web/API/FedCM_API/RP_sign-in), the login status is checked:
- If the login status is `"logged-in"`, a request is made to the IdP's [accounts list endpoint](#the_accounts_list_endpoint) and available accounts for sign-in are displayed to the user in the browser-provided FedCM dialog.
- If the login status is `"logged-out"`, the promise returned by the FedCM `get()` request rejects without making a request to the accounts list endpoint. In such a case it is up to the developer to handle the flow, for example by prompting the user to go and sign in to a suitable IdP.
- If the login status is `"unknown"`, a request is made to the IdP's accounts list endpoint and the login status is updated depending on the response:
- If the endpoint returns a list of available accounts for sign-in, update the status to `"logged-in"` and display the sign-in options to the user in the browser-provided FedCM dialog.
- If the endpoint returns no accounts, update the status to `"logged-out"`; the promise returned by the FedCM `get()` request then rejects.
### What if the browser and the IdP login status become out of sync?
Despite the Login Status API informing the browser of the IdP's login status, it is possible for the browser and IdP to become out of sync. For example, the IdP sessions might expire, meaning that all user accounts end up signed out but the login status is still set to `"logged-in"` (the application was not able to set the login status to `"logged-out"`). In such a case, when federated sign-in is attempted, a request will be made to the IdP's accounts list endpoint but no available accounts will be returned because the session is no longer available.
When this occurs, the browser can dynamically let a user sign into the IdP by opening the IdP's sign-in page in a dialog (the sign-in URL is found in the IdP's [config file](#provide_a_config_file_and_endpoints) `login_url` ). The exact nature of this flow is up to the browser; for example, [Chrome handles it like this](https://developers.google.com/privacy-sandbox/blog/fedcm-chrome-120-updates#what_if_the_user_session_expires_let_the_user_sign_in_through_a_dynamic_login_flow).
Once the user is signed in to the IdP, the IdP should:
- Inform the browser that the user has signed in by [setting login status](#setting_login_status) to `"logged-in"`.
- Close the sign-in dialog by calling the {{domxref("IdentityProvider.close_static", "IdentityProvider.close()")}} method.
## See also
- [Federated Credential Management API](https://developer.chrome.com/docs/privacy-sandbox/fedcm/) on developer.chrome.com (2023)
| 0 |
data/mdn-content/files/en-us/web/api/fedcm_api | data/mdn-content/files/en-us/web/api/fedcm_api/rp_sign-in/index.md | ---
title: Relying party federated sign-in
slug: Web/API/FedCM_API/RP_sign-in
page-type: guide
---
{{DefaultAPISidebar("FedCM API")}}
This article describes the process by which a relying party (RP) can use the [Federated Credential Management (FedCM) API](/en-US/docs/Web/API/FedCM_API) to perform a federated sign-in via an identity provider (IdP).
## Calling the get() method
RPs can call {{domxref("CredentialsContainer.get", "navigator.credentials.get()")}} with an `identity` option to request that a user signs in to the RP with an existing IdP account that they are already signed in to on the browser. The IdP identifies the RP by its `clientId`, which was issued by the IdP to the RP in a separate process that is specific to the IdP. The IdP identifies the specific user using credentials (cookies) provided to the browser on login.
The method returns a promise that fulfills with an {{domxref("IdentityCredential")}} object if the user identity is successfully validated by the IdP. This object contains a token that includes user identity information that has been signed with the IdP's {{glossary("digital certificate")}}.
The RP sends the token to its server to validate the certificate, and on success can use the (now trusted) identity information in the token to sign them into their service (starting a new session), sign them up to their service if they are a new user, etc.
If the user has never signed into the IdP or is logged out, the `get()` method rejects with an error and the RP can direct the user to the IdP login page to sign in or create an account.
> **Note:** The exact structure and content of the validation token token is opaque to the FedCM API, and to the browser. The IdP decides on the syntax and usage of it, and the RP needs to follow the instructions provided by the IdP (see [Verify the Google ID token on your server side](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token), for example) to make sure they are using it correctly.
A typical request might look like this:
```js
async function signIn() {
const identityCredential = await navigator.credentials.get({
identity: {
context: "signup",
providers: [
{
configURL: "https://accounts.idp.example/config.json",
clientId: "********",
nonce: "******",
loginHint: "[email protected]",
},
],
},
});
}
```
The `identity.providers` property takes an array containing a single object specifying the path to an IdP config file (`configURL`) and the RP's client identifier (`clientId`) issued by the IdP.
> **Note:** Currently FedCM only allows the API to be invoked with a single IdP, i.e. the `identity.providers` array has to have a length of 1. To offer users a choice of identity provider, the RP will need to call `get()` separately for each. This may change in the future.
The example above also includes a couple of optional features:
- `identity.context` specifies the context in which the user is authenticating with FedCM. For example, is it a first-time signup for this account, or a sign-in with an existing account? The browser uses this information to vary the text in its FedCM UI to better suit the context.
- The `nonce` property provides a random nonce value that ensures the response is issued for this specific request, preventing {{glossary("replay attack", "replay attacks")}}.
- The `loginHint` property provides a hint about the account option(s) the browser should present for user sign-in. This hint is matched against the `login_hints` values that the IdP provides from the [accounts list endpoint](/en-US/docs/Web/API/FedCM_API/IDP_integration#the_accounts_list_endpoint).
The browser requests the IdP config file and carries out the sign-in flow detailed below. For more information on the kind of interaction a user might expect from the browser-supplied UI, see [Sign in to the relying party with the identity provider](https://developers.google.com/privacy-sandbox/3pcd/fedcm#sign-in).
## FedCM sign-in flow
There are three parties involved in the sign-in flow — the RP app, the browser itself, and the IdP. The following diagram summarizes what is happening visually.

The flow is as follows:
1. The RP invokes {{domxref("CredentialsContainer.get", "navigator.credentials.get()")}} to start off the sign-in flow.
2. From the `configURL` provided in the `get()` call, the browser requests two files:
1. The well-known file (`/.well-known/web-identity`), available from `/.well-known/web-identity` at the [eTLD+1](https://web.dev/articles/same-site-same-origin#site) of the `configURL`.
2. The [IdP config file](/en-US/docs/Web/API/FedCM_API/IDP_integration#provide_a_config_file_and_endpoints) (`/config.json`), available at the `configURL`.
These are both [`GET`](/en-US/docs/Web/HTTP/Methods/GET) requests, which don't have cookies and don't follow redirects. This effectively prevents the IdP from learning who made the request and which RP is attempting to connect.
All requests sent from the browser via FedCM include a `{{httpheader("Sec-Fetch-Dest")}}: webidentity` header to prevent {{glossary("CSRF")}} attacks. All IdP endpoints must confirm this header is included.
3. The IdP responds with the requested well-known file and `config.json` files. The browser validates the config file URL in the `get()` request against the list of valid config URLs inside the well-known file.
4. If the browser has the [IdP's login status](/en-US/docs/Web/API/FedCM_API/IDP_integration#update_login_status_using_the_login_status_api) set to `"logged-in"`, it makes a credentialed request (i.e. with a cookie that identifies the user that is signed in) to the [`accounts_endpoint`](/en-US/docs/Web/API/FedCM_API/IDP_integration#the_accounts_list_endpoint) inside the IdP config file for the user's account details. This is a `GET` request with cookies, but without a `client_id` parameter or the {{httpheader("Origin")}} header. This effectively prevents the IdP from learning which RP the user is trying to sign in to. As a result, the list of accounts returned is RP-agnostic.
> **Note:** If the IdP login status is `"logged-out"`, the `get()` call rejects with a `NetworkError` {{domxref("DOMException")}} and does not make a request to the IdP's `accounts_endpoint`. In this case it is up to the developer to handle the flow, for example by prompting the user to go and sign in to a suitable IdP. Note that there may be some delay in the rejection to avoid leaking the IdP login status to the RP.
5. The IdP responds with the account information requested from the `accounts_endpoint`. This is an array of all accounts associated with the user's IdP cookies for any RPs associated with the IdP.
6. {{optional_inline}} If included in the IdP config file, the browser makes an uncredentialed request to the [`client_metadata_endpoint`](/en-US/docs/Web/API/FedCM_API/IDP_integration#the_client_metadata_endpoint) for the location of the IdP terms of service and privacy policy pages. This is a `GET` request sent with the `clientId` passed into the `get()` call as a parameter, without cookies.
7. {{optional_inline}} The IdP responds with the URLs requested from the `client_metadata_endpoint`.
8. The browser uses the information obtained by the previous two requests to create the UI asking the user to choose an account to sign in to the RP with (in the case where there is more than one available). The UI also asks the user for permission to sign in to the RP using their chosen federated IdP account.
> **Note:** At this stage, if the user has previously authenticated with a federated RP account in the current browser instance (i.e. created a new account with the RP or signed into the RP's website using an existing account), they may be able to **auto-reauthenticate**, depending on what the [`mediation`](/en-US/docs/Web/API/CredentialsContainer/get#mediation) option is set to in the `get()` call. If so the user will be signed in automatically without entering their credentials, as soon as `get()` is invoked. See the [Auto-reauthentication](#auto-reauthentication) section for more details.
9. If the user grants permission to do so, the browser makes a credentialed request to the [`id_assertion_endpoint`](/en-US/docs/Web/API/FedCM_API/IDP_integration#the_id_assertion_endpoint) to request a validation token from the IdP for the selected account.
The credentials are sent in an HTTP [`POST`](/en-US/docs/Web/HTTP/Methods/POST) request with cookies and a content type of `application/x-www-form-urlencoded`.
If the call fails, an error payload is returned as explained in [ID assertion error responses](/en-US/docs/Web/API/FedCM_API/IDP_integration#id_assertion_error_responses) and the promise returned by `get()` will reject with the error.
10. The IdP checks that the account ID sent by the RP matches the ID for the account that is already signed in, and that the `Origin` matches the origin of the RP, which will have been registered in advance with the IdP. If everything looks good, it responds with the requested validation token.
> **Note:** The origin of the RP will be registered with the IdP in a completely separate process when the RP first integrates with the IdP. This process will be specific to each IdP.
11. When the flow is complete, the `get()` promise resolves with an {{domxref("IdentityCredential")}} object, which provides further RP functionality. Most notably, this object contains a token that the RP can verify comes from the IdP (using a certificate) and that contains trusted information about the signed in user. Once the RP validates the token, they can use the contained information to sign the user in and start a new session, sign them up to their service, etc. The format and structure of the token depends on the IdP and has nothing to do with the FedCM API (the RP needs to follow the IdP's instructions).
## Auto-reauthentication
FedCM auto-reauthentication lets users reauthenticate automatically when they try to sign in to an RP again after their initial authentication using FedCM. "Initial authentication" refers to when the user creates an account or signs into the RP's website via the FedCM sign-in dialog for the first time on the RP site, on the same browser instance.
After the initial authentication, auto-reauthentication can be used to sign into the RP website again automatically, without needing to show the user a "Continue as..." confirmation prompt. If the user has recently granted permission to allow federated sign-in to occur with a particular account, there's no privacy or security benefit to immediately enforcing another explicit user confirmation.
Auto-reauthentication behavior is controlled by the [`mediation`](/en-US/docs/Web/API/CredentialsContainer/get#mediation) option in the `get()` call:
```js
async function signIn() {
const identityCredential = await navigator.credentials.get({
identity: {
providers: [
{
configURL: "https://accounts.idp.example/config.json",
clientId: "********",
},
],
},
mediation: "optional", // this is the default
});
// isAutoSelected is true if auto-reauthentication occurred.
const isAutoSelected = identityCredential.isAutoSelected;
}
```
Auto-reauthentication can occur if `mediation` is set to `optional` or `silent`.
With these `mediation` options, auto-reauthentication will occur under the following conditions:
- FedCM is available to use. For example, the user has not disabled FedCM either globally or in the RP's settings.
- The user has only used one account to sign into the RP website on this browser via FedCM.
- The user is signed into the IdP with that account.
- Auto-reauthentication didn't happen within the last 10 minutes. This restriction is put into place to stop users being auto-reauthenticated immediately after they sign out — which would make for a pretty confusing user experience.
- The RP hasn't called {{domxref("CredentialsContainer.preventSilentAccess", "preventSilentAccess()")}} after the previous sign in. This can be used by an RP to explicitly disable auto-reauthentication if desired.
When these conditions are met, an attempt to automatically reauthenticate the user starts as soon as the `get()` is invoked. If auto-reauthentication is successful, the user will log into the RP site again, without being shown a confirmation prompt, using the same IdP account and validated token as they did before.
If auto-reauthentication fails, the behavior depends on the `mediation` value that was chosen:
- `optional`: the user _will_ be shown the dialog box and asked for confirmation again. As a result, this option tends to make sense to use on a page where a user journey is not in mid-flow, such an RP sign-in page.
- `silent`: The `get()` promise will reject and the developer will need to handle guiding the user back to the sign-in page to start the process again. This option makes sense on pages where a user journey is in flow and you need to keep them signed in until completion, for example the pages of a checkout flow on an e-commerce website.
> **Note:** The {{domxref("IdentityCredential.isAutoSelected")}} property provides an indication of whether the federated sign-in was carried out using auto-reauthentication. This is helpful to evaluate the API performance and improve UX accordingly. Also, when it's unavailable, the user may be prompted to sign in with explicit user mediation, which is a `get()` call with `mediation: required`.
## See also
- [Federated Credential Management API](https://developer.chrome.com/docs/privacy-sandbox/fedcm/) on developer.chrome.com (2023)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/transformstream/index.md | ---
title: TransformStream
slug: Web/API/TransformStream
page-type: web-api-interface
browser-compat: api.TransformStream
---
{{APIRef("Streams")}}
The **`TransformStream`** interface of the [Streams API](/en-US/docs/Web/API/Streams_API) represents a concrete implementation of the [pipe chain](/en-US/docs/Web/API/Streams_API/Concepts#pipe_chains) _transform stream_ concept.
It may be passed to the {{domxref("ReadableStream.pipeThrough()")}} method in order to transform a stream of data from one format into another.
For example, it might be used to decode (or encode) video frames, decompress data, or convert the stream from XML to JSON.
A transformation algorithm may be provided as an optional argument to the object constructor.
If not supplied, data is not modified when piped through the stream.
`TransformStream` is a [transferable object](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects).
## Constructor
- {{domxref("TransformStream.TransformStream", "TransformStream()")}}
- : Creates and returns a transform stream object, optionally specifying a transformation object and queuing strategies for the streams.
## Instance properties
- {{domxref("TransformStream.readable")}} {{ReadOnlyInline}}
- : The `readable` end of a `TransformStream`.
- {{domxref("TransformStream.writable")}} {{ReadOnlyInline}}
- : The `writable` end of a `TransformStream`.
## Instance methods
None
## Examples
### Anything-to-uint8array stream
In the following example, a transform stream passes through all chunks it receives as {{jsxref("Uint8Array")}} values.
```js
const transformContent = {
start() {}, // required.
async transform(chunk, controller) {
chunk = await chunk;
switch (typeof chunk) {
case "object":
// just say the stream is done I guess
if (chunk === null) {
controller.terminate();
} else if (ArrayBuffer.isView(chunk)) {
controller.enqueue(
new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength),
);
} else if (
Array.isArray(chunk) &&
chunk.every((value) => typeof value === "number")
) {
controller.enqueue(new Uint8Array(chunk));
} else if (
typeof chunk.valueOf === "function" &&
chunk.valueOf() !== chunk
) {
this.transform(chunk.valueOf(), controller); // hack
} else if ("toJSON" in chunk) {
this.transform(JSON.stringify(chunk), controller);
}
break;
case "symbol":
controller.error("Cannot send a symbol as a chunk part");
break;
case "undefined":
controller.error("Cannot send undefined as a chunk part");
break;
default:
controller.enqueue(this.textencoder.encode(String(chunk)));
break;
}
},
flush() {
/* do any destructor work here */
},
};
class AnyToU8Stream extends TransformStream {
constructor() {
super({ ...transformContent, textencoder: new TextEncoder() });
}
}
```
### Polyfilling TextEncoderStream and TextDecoderStream
Note that this is deprecated by the native constructors. This is intended as a polyfill for unsupported platforms.
```js
const tes = {
start() {
this.encoder = new TextEncoder();
},
transform(chunk, controller) {
controller.enqueue(this.encoder.encode(chunk));
},
};
let _jstes_wm = new WeakMap(); /* info holder */
class JSTextEncoderStream extends TransformStream {
constructor() {
let t = { ...tes };
super(t);
_jstes_wm.set(this, t);
}
get encoding() {
return _jstes_wm.get(this).encoder.encoding;
}
}
```
Similarly, `TextDecoderStream` can be written as such:
```js
const tds = {
start() {
this.decoder = new TextDecoder(this.encoding, this.options);
},
transform(chunk, controller) {
controller.enqueue(this.decoder.decode(chunk, { stream: true }));
},
};
let _jstds_wm = new WeakMap(); /* info holder */
class JSTextDecoderStream extends TransformStream {
constructor(encoding = "utf-8", { ...options } = {}) {
let t = { ...tds, encoding, options };
super(t);
_jstds_wm.set(this, t);
}
get encoding() {
return _jstds_wm.get(this).decoder.encoding;
}
get fatal() {
return _jstds_wm.get(this).decoder.fatal;
}
get ignoreBOM() {
return _jstds_wm.get(this).decoder.ignoreBOM;
}
}
```
### Chaining multiple ReadableStreams together
This is a useful one, where multiple streams can be conjoined. Examples include building a PWA with progressive loading and progressive streaming.
```js
let responses = [
/* conjoined response tree */
];
let { readable, writable } = new TransformStream();
responses.reduce(
(a, res, i, arr) =>
a.then(() => res.pipeTo(writable, { preventClose: i + 1 !== arr.length })),
Promise.resolve(),
);
```
Note that this is not resilient to other influences.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WHATWG Stream Visualizer](https://whatwg-stream-visualizer.glitch.me/), for a basic visualization of readable, writable, and transform streams.
- [Streams—The Definitive Guide](https://web.dev/articles/streams)
| 0 |
data/mdn-content/files/en-us/web/api/transformstream | data/mdn-content/files/en-us/web/api/transformstream/readable/index.md | ---
title: "TransformStream: readable property"
short-title: readable
slug: Web/API/TransformStream/readable
page-type: web-api-instance-property
browser-compat: api.TransformStream.readable
---
{{APIRef("Streams")}}
The **`readable`** read-only property of the {{domxref("TransformStream")}} interface returns the {{domxref("ReadableStream")}} instance controlled by this `TransformStream`.
## Value
A {{domxref("ReadableStream")}}.
## Examples
The following example creates a new {{domxref("TransformStream")}} as `textEncoderStream`, and prints the value of `readable` to the console.
```js
const textEncoderStream = new TransformStream();
console.log(textEncoderStream.readable); // a ReadableStream
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/transformstream | data/mdn-content/files/en-us/web/api/transformstream/writable/index.md | ---
title: "TransformStream: writable property"
short-title: writable
slug: Web/API/TransformStream/writable
page-type: web-api-instance-property
browser-compat: api.TransformStream.writable
---
{{APIRef("Streams")}}
The **`writable`** read-only property of the {{domxref("TransformStream")}} interface returns the {{domxref("WritableStream")}} instance controlled by this `TransformStream`.
## Value
A {{domxref("WritableStream")}}.
## Examples
The following example creates a new {{domxref("TransformStream")}} as a `textEncoderStream`, and prints the value of `writable` to the console.
```js
const textEncoderStream = new TransformStream();
console.log(textEncoderStream.writable); // a WritableStream
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/transformstream | data/mdn-content/files/en-us/web/api/transformstream/transformstream/index.md | ---
title: "TransformStream: TransformStream() constructor"
short-title: TransformStream()
slug: Web/API/TransformStream/TransformStream
page-type: web-api-constructor
browser-compat: api.TransformStream.TransformStream
---
{{APIRef("Streams")}}
The **`TransformStream()`** constructor creates a new {{domxref("TransformStream")}} object which represents a pair of streams: a {{domxref("WritableStream")}} representing the writable side, and a {{domxref("ReadableStream")}} representing the readable side.
## Syntax
```js-nolint
new TransformStream()
new TransformStream(transformer)
new TransformStream(transformer, writableStrategy)
new TransformStream(transformer, writableStrategy, readableStrategy)
```
### Parameters
- `transformer` {{optional_inline}}
- : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes.
The transformer object can contain any of the following methods. In each method `controller` is an instance of {{domxref("TransformStreamDefaultController")}}.
- `start(controller)`
- : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using {{domxref("TransformStreamDefaultController.enqueue()")}}.
- `transform(chunk, controller)`
- : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. It can return a promise to signal success or failure of the write operation. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes.
- `flush(controller)`
- : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed.
- `writableStrategy` {{optional_inline}}
- : An object that optionally defines a queuing strategy for the stream. This takes two
parameters:
- `highWaterMark`
- : A non-negative integer. This defines the total number of chunks that can be
contained in the internal queue before backpressure is applied.
- `size(chunk)`
- : A method containing a parameter `chunk`. This indicates the size to
use for each chunk, in bytes.
- `readableStrategy` {{optional_inline}}
- : An object that optionally defines a queuing strategy for the stream. This takes two
parameters:
- `highWaterMark`
- : A non-negative integer. This defines the total number of chunks that can be
contained in the internal queue before backpressure is applied.
- `size(chunk)`
- : A method containing a parameter `chunk`. This indicates the size to
use for each chunk, in bytes.
> **Note:** You could define your own custom
> `readableStrategy` or `writableStrategy`, or use an instance of
> {{domxref("ByteLengthQueuingStrategy")}} or {{domxref("CountQueuingStrategy")}}
> for the object values.
## Examples
### Transforming text to uppercase
The following example transforms text to uppercase chunk by chunk. This example is from [Streams—The Definitive Guide](https://web.dev/articles/streams), which has a number of examples of different types of streams.
```js
function upperCaseStream() {
return new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
},
});
}
function appendToDOMStream(el) {
return new WritableStream({
write(chunk) {
el.append(chunk);
},
});
}
fetch("./lorem-ipsum.txt").then((response) =>
response.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(upperCaseStream())
.pipeTo(appendToDOMStream(document.body)),
);
```
### Creating an identity transform stream
If no `transformer` argument is supplied then the result will be an identity transform stream which forwards all chunks written to the writable side to the readable side with no changes. In the following example an identity transform stream is used to add buffering to a pipe.
```js
const writableStrategy = new ByteLengthQueuingStrategy({
highWaterMark: 1024 * 1024,
});
readableStream
.pipeThrough(new TransformStream(undefined, writableStrategy))
.pipeTo(writableStream);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/urlpattern/index.md | ---
title: URLPattern
slug: Web/API/URLPattern
page-type: web-api-interface
status:
- experimental
browser-compat: api.URLPattern
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`URLPattern`** interface of the {{domxref("URL Pattern API", "", "", "nocode")}} matches URLs or parts of URLs against a pattern. The pattern can contain capturing groups that extract parts of the matched URL.
More information about the syntax of patterns can be found on the API overview
page: {{domxref("URL Pattern API", "", "", "nocode")}}.
{{AvailableInWorkers}}
## Constructor
- {{domxref("URLPattern.URLPattern", "URLPattern()")}} {{Experimental_Inline}}
- : Returns a new `URLPattern` object based on the given pattern and base URL.
## Instance properties
- {{domxref("URLPattern.hash", "hash")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A string containing a pattern to match the _hash_ part
of a URL.
- {{domxref("URLPattern.hostname", "hostname")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A string containing a pattern to match the _hostname_
part of a URL.
- {{domxref("URLPattern.password", "password")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A string containing a pattern to match the _password_
part of a URL.
- {{domxref("URLPattern.pathname", "pathname")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A string containing a pattern to match the _pathname_
part of a URL.
- {{domxref("URLPattern.port", "port")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A string containing a pattern to match the _port_ part
of a URL.
- {{domxref("URLPattern.protocol", "protocol")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A string containing a pattern to match the _protocol_
part of a URL.
- {{domxref("URLPattern.search", "search")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A string containing a pattern to match the _search_ part
of a URL.
- {{domxref("URLPattern.username","username")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A string containing a pattern to match the _username_
part of a URL.
## Instance methods
- {{domxref("URLPattern.exec", "exec()")}} {{Experimental_Inline}}
- : Returns an object with the matched parts of the URL or `null` if the URL
does not match.
- {{domxref("URLPattern.test", "test()")}} {{Experimental_Inline}}
- : Returns `true` if the URL matches the given pattern, `false` otherwise.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- A polyfill of `URLPattern` is available
[on GitHub](https://github.com/kenchris/urlpattern-polyfill)
- The pattern syntax used by URLPattern is similar to the syntax used by
[path-to-regexp](https://github.com/pillarjs/path-to-regexp)
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/test/index.md | ---
title: "URLPattern: test() method"
short-title: test()
slug: Web/API/URLPattern/test
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.URLPattern.test
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`test()`** method of the {{domxref("URLPattern")}} interface takes a URL or
object of URL parts, and returns a boolean indicating if the given input matches
the current pattern.
{{AvailableInWorkers}}
## Syntax
```js-nolint
test(input)
test(input, baseURL)
```
### Parameters
- `input`
- : The URL or URL parts to match against. This can either be a
string, or an object providing the individual URL parts.
The object members can be any of `protocol`, `username`, `password`,
`hostname`, `port`, `pathname`, `search`, `hash`, or `baseURL`. Omitted
parts in the object will be treated as empty strings. If the input cannot be
parsed, or a relative URL without a base is provided, the method will return
`null`.
- `baseURL` {{optional_inline}}
- : A string representing the base URL to use in cases where
`input` is a relative URL. If not specified, it defaults to `undefined`. If
this parameter cannot be parsed, the method will return `false`.
### Return value
A {{jsxref("boolean")}}.
## Examples
This example shows how to use the `test()` method to match a URL against a
pattern. The example prints the result of the `test()` calls to the console.
```js
const pattern = new URLPattern("http{s}?://*.example.com/books/:id");
// Absolute URL strings
console.log(pattern.test("https://store.example.com/books/123")); // true
console.log(pattern.test("https://example.com/books/123")); // false
// Relative URL strings
console.log(pattern.test("/books/123", "http://store.example.com")); // true
console.log(pattern.test("/books/123", "data:text/plain,hello world!")); // false
console.log(pattern.test("/books/123")); // false
// Structured objects
console.log(
pattern.test({
pathname: "/books/123",
baseURL: "http://store.example.com",
}),
); // true
console.log(
pattern.test({
protocol: "https",
hostname: "store.example.com",
pathname: "/books/123",
}),
); // true
console.log(
pattern.test({
protocol: "file",
hostname: "store.example.com",
pathname: "/books/123",
}),
); // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- A polyfill of `URLPattern` is available
[on GitHub](https://github.com/kenchris/urlpattern-polyfill)
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/username/index.md | ---
title: "URLPattern: username property"
short-title: username
slug: Web/API/URLPattern/username
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.URLPattern.username
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`username`** read-only property of the {{domxref("URLPattern")}} interface is a
string containing the pattern used to match the username part
of a URL. This value may differ from the input to the constructor due to
normalization.
{{AvailableInWorkers}}
## Value
A string.
## Examples
The below example creates a {{domxref("URLPattern")}} object with `admin` for
the `username` part. This pattern matches only if the username part of the URL
is `admin`.
```js
const pattern = new URLPattern({ username: "admin" });
console.log(pattern.username); // 'admin'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/search/index.md | ---
title: "URLPattern: search property"
short-title: search
slug: Web/API/URLPattern/search
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.URLPattern.search
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`search`** read-only property of the {{domxref("URLPattern")}} interface is a
string containing the pattern used to match the search part of
a URL. This value may differ from the input to the constructor due to
normalization.
{{AvailableInWorkers}}
## Value
A string.
## Examples
The below example creates a {{domxref("URLPattern")}} object with `*` for the
`search` part. This pattern is a wildcard, thus matching any search part.
```js
const pattern = new URLPattern("https://example.com?*");
console.log(pattern.search); // '*'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/port/index.md | ---
title: "URLPattern: port property"
short-title: port
slug: Web/API/URLPattern/port
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.URLPattern.port
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`port`** read-only property of the {{domxref("URLPattern")}} interface is a
string containing the pattern used to match the port part of a
URL. This value may differ from the input to the constructor due to
normalization.
{{AvailableInWorkers}}
## Value
A string.
## Examples
The below example creates a {{domxref("URLPattern")}} object with
`(80|443|8080)` for the `port` part. This pattern matches the port `80`, `443`,
and `8080`.
```js
const pattern = new URLPattern({ port: "(80|443|8080)" });
console.log(pattern.port); // '(80|443|8080)'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/hash/index.md | ---
title: "URLPattern: hash property"
short-title: hash
slug: Web/API/URLPattern/hash
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.URLPattern.hash
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`hash`** read-only property of the {{domxref("URLPattern")}} interface is a
string containing the pattern used to match the fragment part
of a URL. This value may differ from the input to the constructor due to
normalization.
{{AvailableInWorkers}}
## Value
A string.
## Examples
The below example creates a {{domxref("URLPattern")}} object with `books/:id`
for the `hash` part. This pattern matches any fragment that starts with `books/`
and ends with an arbitrary string identifier.
```js
const pattern = new URLPattern("https://example.org#books/:id");
console.log(pattern.hash); // 'books/:id'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/pathname/index.md | ---
title: "URLPattern: pathname property"
short-title: pathname
slug: Web/API/URLPattern/pathname
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.URLPattern.pathname
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`pathname`** read-only property of the {{domxref("URLPattern")}} interface is a
string containing the pattern used to match the pathname part
of a URL. This value may differ from the input to the constructor due to
normalization.
{{AvailableInWorkers}}
## Value
A string.
## Examples
The below example creates a {{domxref("URLPattern")}} object with
`/books/:id(\\d)` for the `pathname` part. This pattern matches URLs starting
with `/books/`, followed by an integer.
```js
const pattern = new URLPattern({ pathname: "/books/:id(\\d)" });
console.log(pattern.pathname); // '/books/:id(\\d)'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/exec/index.md | ---
title: "URLPattern: exec() method"
short-title: exec()
slug: Web/API/URLPattern/exec
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.URLPattern.exec
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`exec()`** method of the {{domxref("URLPattern")}} interface takes a URL or
object of URL parts, and returns either an object containing the results of
matching the URL to the pattern, or `null` if the URL does not match the
pattern.
{{AvailableInWorkers}}
## Syntax
```js-nolint
exec(input)
exec(input, baseURL)
```
### Parameters
- `input`
- : The URL or URL parts to match against. This can either be a
string, or an object providing the individual URL parts.
The object members can be any of `protocol`, `username`, `password`,
`hostname`, `port`, `pathname`, `search`, `hash`, or `baseURL`. Omitted
parts in the object will be treated as empty strings. If the input cannot be
parsed, or a relative URL without a base is provided, the method will return
`null`.
- `baseURL` {{optional_inline}}
- : A string representing the base URL to use in cases where
`input` is a relative URL. If not specified, it defaults to `undefined`. If
this parameter cannot be parsed, the method will return `null`.
### Return value
An {{jsxref("object")}} with an `inputs` key containing the array of arguments
passed into the function, and keys for each of the URL parts containing the
matched input, and matched groups for that part.
## Examples
This example shows how to use the `exec()` method to match a URL against a
pattern. The example prints the result of the `exec()` calls to the console.
```js
const pattern = new URLPattern("http{s}?://*.example.com/books/:id");
// Absolute URL strings
console.log(pattern.exec("https://example.com/books/123")); // null
let match = pattern.exec("https://store.example.com/books/123");
console.log(match.inputs); // ['https://store.example.com/books/123']
console.log(match.protocol); // { input: "https", groups: {} }
console.log(match.username); // { input: "", groups: {} }
console.log(match.password); // { input: "", groups: {} }
console.log(match.hostname); // { input: "store.example.com", groups: { "0": "store" } }
console.log(match.port); // { input: "", groups: {} }
console.log(match.pathname); // { input: "/books/123", groups: { "id": "123" } }
console.log(match.search); // { input: "", groups: {} }
console.log(match.hash); // { input: "", groups: {} }
// Relative URL strings
pattern.exec("/books/123", "http://store.example.com"); // returns object
pattern.exec("/books/123", "data:text/plain,hello world!"); // returns object
pattern.exec("/books/123"); // returns null
// Structured objects
pattern.exec({
pathname: "/books/123",
baseURL: "http://store.example.com",
}); // returns object
pattern.exec({
protocol: "https",
hostname: "store.example.com",
pathname: "/books/123",
}); // returns object
pattern.exec({
protocol: "file",
hostname: "store.example.com",
pathname: "/books/123",
}); // returns null
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- A polyfill of `URLPattern` is available
[on GitHub](https://github.com/kenchris/urlpattern-polyfill)
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/hostname/index.md | ---
title: "URLPattern: hostname property"
short-title: hostname
slug: Web/API/URLPattern/hostname
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.URLPattern.hostname
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`hostname`** read-only property of the {{domxref("URLPattern")}} interface is a
string containing the pattern used to match the hostname part
of a URL. This value may differ from the input to the constructor due to
normalization.
{{AvailableInWorkers}}
## Value
A string.
## Examples
The below example creates a {{domxref("URLPattern")}} object with
`*.example.org` for the `hostname` part. This pattern matches any hostname that
is a direct subdomain of `example.org`.
```js
const pattern = new URLPattern("https://*.example.org");
console.log(pattern.hostname); // '*.example.org'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/password/index.md | ---
title: "URLPattern: password property"
short-title: password
slug: Web/API/URLPattern/password
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.URLPattern.password
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`password`** read-only property of the {{domxref("URLPattern")}} interface is a
string containing the pattern used to match the password part
of a URL. This value may differ from the input to the constructor due to
normalization.
{{AvailableInWorkers}}
## Value
A string.
## Examples
The below example creates a {{domxref("URLPattern")}} object with
`correct-horse-battery{-staple}?` for the `password` part. This pattern matches
the passwords `correct-horse-battery` and `correct-horse-battery-staple`.
```js
const pattern = new URLPattern({ password: "correct-horse-battery{-staple}?" });
console.log(pattern.password); // 'correct-horse-battery{-staple}?'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/protocol/index.md | ---
title: "URLPattern: protocol property"
short-title: protocol
slug: Web/API/URLPattern/protocol
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.URLPattern.protocol
---
{{APIRef("URL Pattern API")}}{{SeeCompatTable}}
The **`protocol`** read-only property of the {{domxref("URLPattern")}} interface is a
string containing the pattern used to match the protocol part
of a URL. This value may differ from the input to the constructor due to
normalization.
{{AvailableInWorkers}}
## Value
A string.
## Examples
The below example creates a {{domxref("URLPattern")}} object with `http{s}?` for
the `protocol` part. This pattern matches the `http` and `https` protocols.
```js
const pattern = new URLPattern({ protocol: "http{s}?" });
console.log(pattern.protocol); // 'http{s}?'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/urlpattern | data/mdn-content/files/en-us/web/api/urlpattern/urlpattern/index.md | ---
title: "URLPattern: URLPattern() constructor"
short-title: URLPattern()
slug: Web/API/URLPattern/URLPattern
page-type: web-api-constructor
status:
- experimental
browser-compat: api.URLPattern.URLPattern
---
{{APIRef("URLPattern API")}}{{SeeCompatTable}}
The **`URLPattern()`** constructor returns a new {{domxref("URLPattern")}}
object representing the url pattern defined by the parameters.
{{AvailableInWorkers}}
## Syntax
```js-nolint
new URLPattern(input)
new URLPattern(input, baseURL)
new URLPattern(input, options)
new URLPattern(input, baseURL, options)
```
### Parameters
- `input`
- : The input pattern that will be used for matching. This can either be a
string, or an object providing patterns for each URL part
individually. The object members can be any of:
- `protocol`
- `username`
- `password`
- `hostname`
- `port`
- `pathname`
- `search`
- `hash`
- `baseURL`
> **Note:** Omitted parts of the object will be treated as wildcards (`*`).
- `baseURL` {{Optional_Inline}}
- : A string representing the base URL to use in cases where
`input` is a relative pattern. If not specified, it defaults to `undefined`.
- `options` {{Optional_Inline}}
- : An object providing options for matching the given pattern. The possible object members are as follows:
- `ignoreCase` {{Optional_Inline}}
- : Enables case-insensitive matching if set to `true`. If omitted or set to `false`, matching will be case-sensitive.
### Exceptions
- {{jsxref("TypeError")}}
- : Indicates one of the following:
- The given `input` or `baseURL` is not valid or syntactically correct.
- The given `input` is relative, but no `baseURL` is provided to form a complete absolute URL.
- A `baseURL` is provided, and input is an absolute pattern or a structured object.
## Examples
### Matching a pathname
```js
let pattern1 = new URLPattern("https://example.com/books/:id");
// same as
let pattern2 = new URLPattern("/books/:id", "https://example.com");
// or
let pattern3 = new URLPattern({
protocol: "https",
hostname: "example.com",
pathname: "/books/:id",
});
// or
let pattern4 = new URLPattern({
pathname: "/books/:id",
baseURL: "https://example.com",
});
```
### Match the protocol and hostname
```js
let pattern = new URLPattern({
protocol: "http{s}?",
hostname: ":subdomain.example.com",
});
```
### Match all possible structured parts
```js
let pattern = new URLPattern({
protocol: "http{s}?",
username: ":username",
password: ":password",
hostname: ":subdomain.example.com",
port: ":port(80|443)",
pathname: "/:path",
search: "*",
hash: "*",
});
```
### Case-insensitive matching
```js
// Case-sensitive matching by default
const pattern = new URLPattern("https://example.com/2022/feb/*");
console.log(pattern.test("https://example.com/2022/feb/xc44rsz")); // true
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz")); // false
```
Setting the `ignoreCase` option to `true` in the constructor switches all matching operations to case-insensitive for the given pattern:
```js
// Case-insensitive matching
const pattern = new URLPattern("https://example.com/2022/feb/*", {
ignoreCase: true,
});
console.log(pattern.test("https://example.com/2022/feb/xc44rsz")); // true
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz")); // true
```
## Usage notes
The `URLPattern` constructor's input pattern can take two forms — a
pattern object, or a pattern string and optional baseURL.
```js
new URLPattern(obj);
new URLPattern(pattern);
new URLPattern(pattern, baseURL);
```
The first type of constructor takes an object that describes the
URLs that should be matched by specifying patterns for each individual URL part.
Its members can be any of `protocol`, `username`, `password`, `hostname`,
`port`, `pathname`, `search`, `hash`, or `baseURL`. If the `baseURL` property is
provided it will be parsed as a URL and used to populate any other properties
that are missing. If the `baseURL` property is missing, then any other missing
properties default to the pattern `*` wildcard, accepting any input.
The second type of constructor takes a URL string that contains
patterns embedded in it. The URL string may be relative if a `baseURL` is
provided as the second argument. Note that it may be necessary to escape some
characters in the URL string if it is ambiguous whether the character is
separating different URL components or is part of a pattern. For
example, you must write `about\\:blank` to indicate that the `:` is the protocol
suffix and not the start of a `:blank` named group pattern.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- A polyfill of `URLPattern` is available
[on GitHub](https://github.com/kenchris/urlpattern-polyfill)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/presentationconnectionlist/index.md | ---
title: PresentationConnectionList
slug: Web/API/PresentationConnectionList
page-type: web-api-interface
status:
- experimental
browser-compat: api.PresentationConnectionList
---
{{securecontext_header}}{{SeeCompatTable}}{{APIRef("Presentation API")}}
`PresentationConnectionList` is the collection of incoming presentation connections.
{{InheritanceDiagram}}
## Instance properties
- {{domxref('PresentationConnectionList.connections')}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the non-terminated set of {{DOMxRef("PresentationConnection")}}s in the [set of presentation controllers](https://www.w3.org/TR/presentation-api/#dfn-set-of-presentation-controllers).
## Events
- {{domxref('PresentationConnectionList/connectionavailable_event', "connectionavailable")}} {{Experimental_Inline}}
- : Fired whenever a new [presentation connection](https://www.w3.org/TR/presentation-api/#dfn-presentation-connection) becomes available.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/useractivation/index.md | ---
title: UserActivation
slug: Web/API/UserActivation
page-type: web-api-interface
browser-compat: api.UserActivation
---
{{APIRef("HTML DOM")}}
The **`UserActivation`** interface provides information about whether a user is currently interacting with the page, or has completed an interaction since page load.
This API is only available in the window context and not exposed to workers.
## Instance properties
- {{domxref("UserActivation.hasBeenActive")}} {{ReadOnlyInline}}
- : Indicates whether the current window has sticky user activation.
- {{domxref("UserActivation.isActive")}} {{ReadOnlyInline}}
- : Indicates whether the current window has transient user activation.
## Description
An object of this type is accessed via the {{domxref("navigator.userActivation")}} property, and can be used to query information about a window's user activation state.
A user activation either implies that the user is currently interacting with the page, or has completed an interaction since page load.
User activation can be triggered by a button click, pointer touch, or some other user interaction with the page.
There are two kinds of window user activation states:
- {{Glossary("Transient activation")}} (user is currently interacting with the page) and
- {{Glossary("Sticky activation")}} (user has interacted at least once since page load).
See [Features gated by user activation](/en-US/docs/Web/Security/User_activation) for more information and a list of APIs that require either sticky or transient user activation.
## Examples
### Checking if a user gesture was recently performed
Use {{domxref("navigator.userActivation")}} to access the `UserActivation` object, and then {{domxref("UserActivation.isActive")}} to check whether the user is currently interacting with the page ({{Glossary("Transient activation")}}).
```js
if (navigator.userActivation.isActive) {
// proceed to request playing media, for example
}
```
### Checking if a user gesture was ever performed
Use {{domxref("UserActivation.hasBeenActive")}} to check whether the user has ever interacted with the page ({{Glossary("Sticky activation")}}).
```js
if (navigator.userActivation.hasBeenActive) {
// proceed with auto-playing an animation, for example
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("navigator.userActivation")}}
- [Features gated by user activation](/en-US/docs/Web/Security/User_activation)
| 0 |
data/mdn-content/files/en-us/web/api/useractivation | data/mdn-content/files/en-us/web/api/useractivation/hasbeenactive/index.md | ---
title: "UserActivation: hasBeenActive property"
short-title: hasBeenActive
slug: Web/API/UserActivation/hasBeenActive
page-type: web-api-instance-property
browser-compat: api.UserActivation.hasBeenActive
---
{{APIRef("HTML DOM")}}
The read-only **`hasBeenActive`** property of the {{domxref("UserActivation")}} interface indicates whether the current window has {{Glossary("sticky activation","sticky user activation")}}.
## Value
A boolean.
## Examples
### Checking if a user gesture was ever performed
Use the `hasBeenActive` property to check whether the user has interacted with the page since it was loaded.
```js
if (navigator.userActivation.hasBeenActive) {
// proceed with auto-playing an animation, for example
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("UserActivation")}}
- {{domxref("UserActivation.isActive")}}
- [Features gated by user activation](/en-US/docs/Web/Security/User_activation)
| 0 |
data/mdn-content/files/en-us/web/api/useractivation | data/mdn-content/files/en-us/web/api/useractivation/isactive/index.md | ---
title: "UserActivation: isActive property"
short-title: isActive
slug: Web/API/UserActivation/isActive
page-type: web-api-instance-property
browser-compat: api.UserActivation.isActive
---
{{APIRef("HTML DOM")}}
The read-only **`isActive`** property of the {{domxref("UserActivation")}} interface indicates whether the current window has {{Glossary("transient activation", "transient user activation")}}.
## Value
A boolean.
## Examples
### Checking if a user gesture was recently performed
Use the `isActive` property to check whether the user is currently interacting with the page.
```js
if (navigator.userActivation.isActive) {
// proceed to request playing media, for example
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("UserActivation")}}
- {{domxref("UserActivation.hasBeenActive")}}
- [Features gated by user activation](/en-US/docs/Web/Security/User_activation)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rsapssparams/index.md | ---
title: RsaPssParams
slug: Web/API/RsaPssParams
page-type: web-api-interface
spec-urls: https://w3c.github.io/webcrypto/#dfn-RsaPssParams
---
{{ APIRef("Web Crypto API") }}
The **`RsaPssParams`** dictionary of the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) represents the object that should be passed as the `algorithm` parameter into {{domxref("SubtleCrypto.sign()")}} or {{domxref("SubtleCrypto.verify()")}}, when using the [RSA-PSS](/en-US/docs/Web/API/SubtleCrypto/sign#rsa-pss) algorithm.
## Instance properties
- `name`
- : A string. This should be set to `RSA-PSS`.
- `saltLength`
- : A `long` integer representing the length of the random salt to use, in bytes.
[RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447) says that "Typical salt lengths" are either 0 or the length of the output of the [digest algorithm](/en-US/docs/Web/API/SubtleCrypto#supported_algorithms) that was selected when this key was [generated](/en-US/docs/Web/API/SubtleCrypto/generateKey). For example, if you use [SHA-256](/en-US/docs/Web/API/SubtleCrypto/digest#supported_algorithms) as the digest algorithm, this could be 32.
The maximum size of `saltLength` is given by:
```js
Math.ceil((keySizeInBits - 1) / 8) - digestSizeInBytes - 2;
```
So for a key length of 2048 bits and a digest output size of 32 bytes, the maximum size would be 222.
## Examples
See the examples for {{domxref("SubtleCrypto.sign()")}} and {{domxref("SubtleCrypto.verify()")}}.
## Specifications
{{Specifications}}
## Browser compatibility
Browsers that support the "RSA-PSS" algorithm for the {{domxref("SubtleCrypto.sign()")}} and {{domxref("SubtleCrypto.verify()")}} methods will support this type.
## See also
- [RFC 3447: RSASSA-PSS](https://datatracker.ietf.org/doc/html/rfc3447#section-8.1)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/csssupportsrule/index.md | ---
title: CSSSupportsRule
slug: Web/API/CSSSupportsRule
page-type: web-api-interface
browser-compat: api.CSSSupportsRule
---
{{APIRef("CSSOM")}}
The **`CSSSupportsRule`** interface represents a single CSS {{cssxref("@supports")}} [at-rule](/en-US/docs/Web/CSS/At-rule).
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its ancestors {{domxref("CSSConditionRule")}}, {{domxref("CSSGroupingRule")}}, and {{domxref("CSSRule")}}._
## Instance methods
_Inherits methods from its ancestors {{domxref("CSSConditionRule")}}, {{domxref("CSSGroupingRule")}}, and {{domxref("CSSRule")}}._
## Examples
The CSS includes a CSS feature query using the {{cssxref("@supports")}} [at-rule](/en-US/docs/Web/CSS/At-rule), containing one style rule. This will be the first CSSRule returned by `document.styleSheets[0].cssRules`.
`myRules[0]` therefore returns a {{domxref("CSSSupportsRule")}} object.
```css
@supports (display: grid) {
body {
color: blue;
}
}
```
```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); // a CSSSupportsRule representing the feature query.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{cssxref("@supports")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmllabelelement/index.md | ---
title: HTMLLabelElement
slug: Web/API/HTMLLabelElement
page-type: web-api-interface
browser-compat: api.HTMLLabelElement
---
{{ APIRef("HTML DOM") }}
The **`HTMLLabelElement`** interface gives access to properties specific to {{HTMLElement("label")}} elements. It inherits methods and properties from the base {{domxref("HTMLElement")}} interface.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLLabelElement.control")}} {{ReadOnlyInline}}
- : A {{domxref("HTMLElement")}} representing the control with which the label is associated.
- {{domxref("HTMLLabelElement.form")}} {{ReadOnlyInline}}
- : A {{domxref("HTMLFormElement")}} object representing the form with which the labeled control is associated, or `null` if there is no associated control, or if that control isn't associated with a form. In other words, this is just a shortcut for `HTMLLabelElement.control.form`.
- {{domxref("HTMLLabelElement.htmlFor")}}
- : A string containing the ID of the labeled control. This reflects the [`for`](/en-US/docs/Web/HTML/Element/label#for) attribute.
> **Note:** To programmatically set the `for` attribute, use [`htmlFor`](/en-US/docs/Web/API/HTMLLabelElement/htmlFor).
## Instance methods
_No specific methods; inherits methods from its parent, {{domxref("HTMLElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{HTMLElement("label")}}
- {{HTMLElement("form")}}
- {{domxref("HTMLFormElement")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmllabelelement | data/mdn-content/files/en-us/web/api/htmllabelelement/form/index.md | ---
title: "HTMLLabelElement: form property"
short-title: form
slug: Web/API/HTMLLabelElement/form
page-type: web-api-instance-property
browser-compat: api.HTMLLabelElement.form
---
{{APIRef("HTML DOM")}}
The read-only **`HTMLLabelElement.form`** property returns an
{{domxref("HTMLFormElement")}} object which represents the form of which the label's
associated control is a part, or null if there is either no associated control, or if
that control isn't in a form.
This property is just a shortcut for `HTMLLabelElement.control.form`.
## Value
An {{domxref("HTMLFormElement")}} which represents the form with which the label's
{{domxref("HTMLLabelElement.control", "control")}} is associated. If
{{domxref("HTMLLabelElement.control", "control")}} is `null` (meaning the
label isn't associated with a control), or if the control isn't part of a form, this
property returns `null`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLLabelElement")}}
- {{domxref("HTMLElement")}}
- {{HTMLElement("label")}}
- [HTML forms guide](/en-US/docs/Learn/Forms)
| 0 |
data/mdn-content/files/en-us/web/api/htmllabelelement | data/mdn-content/files/en-us/web/api/htmllabelelement/control/index.md | ---
title: "HTMLLabelElement: control property"
short-title: control
slug: Web/API/HTMLLabelElement/control
page-type: web-api-instance-property
browser-compat: api.HTMLLabelElement.control
---
{{APIRef("HTML DOM")}}
The read-only **`HTMLLabelElement.control`** property returns a
reference to the control (in the form of an object of type {{domxref("HTMLElement")}} or
one of its derivatives) with which the {{HTMLElement("label")}} element is associated,
or `null` if the label isn't associated with a control.
## Value
An {{domxref("HTMLElement")}} derived object representing the control with which the
{{HTMLElement("label")}} is associated, or `null` if the label stands alone.
> **Note:** If this property has a value and {{domxref("HTMLLabelElement.htmlFor")}} has a value,
> the {{domxref("HTMLLabelElement.htmlFor")}} property must refer to the same control.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLLabelElement")}}
- {{domxref("HTMLElement")}}
- {{HTMLElement("label")}}
- [HTML forms guide](/en-US/docs/Learn/Forms)
| 0 |
data/mdn-content/files/en-us/web/api/htmllabelelement | data/mdn-content/files/en-us/web/api/htmllabelelement/htmlfor/index.md | ---
title: "HTMLLabelElement: htmlFor property"
short-title: htmlFor
slug: Web/API/HTMLLabelElement/htmlFor
page-type: web-api-instance-property
browser-compat: api.HTMLLabelElement.htmlFor
---
{{APIRef("HTML DOM")}}
The **`HTMLLabelElement.htmlFor`** property reflects the value
of the [`for`](/en-US/docs/Web/HTML/Element/label#for) content property. That means that this
script-accessible property is used to set and read the value of the content property
`for`, which is the ID of the label's associated control element.
## Value
A string which contains the ID string of the element which is
associated with the control.
> **Note:** If this property has a value, the {{domxref("HTMLLabelElement.control")}} property
> must refer to the same control.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLLabelElement")}}
- {{domxref("HTMLLabelElement.control")}}
- {{domxref("HTMLElement")}}
- {{HTMLElement("label")}}
- [HTML forms guide](/en-US/docs/Learn/Forms)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/offlineaudiocontext/index.md | ---
title: OfflineAudioContext
slug: Web/API/OfflineAudioContext
page-type: web-api-interface
browser-compat: api.OfflineAudioContext
---
{{APIRef("Web Audio API")}}
The `OfflineAudioContext` interface is an {{domxref("AudioContext")}} interface representing an audio-processing graph built from linked together {{domxref("AudioNode")}}s. In contrast with a standard {{domxref("AudioContext")}}, an `OfflineAudioContext` doesn't render the audio to the device hardware; instead, it generates it, as fast as it can, and outputs the result to an {{domxref("AudioBuffer")}}.
{{InheritanceDiagram}}
## Constructor
- {{domxref("OfflineAudioContext.OfflineAudioContext()", "OfflineAudioContext()")}}
- : Creates a new `OfflineAudioContext` instance.
## Instance properties
_Also inherits properties from its parent interface, {{domxref("BaseAudioContext")}}._
- {{domxref('OfflineAudioContext.length')}} {{ReadOnlyInline}}
- : An integer representing the size of the buffer in sample-frames.
## Instance methods
_Also inherits methods from its parent interface, {{domxref("BaseAudioContext")}}._
- {{domxref("OfflineAudioContext.suspend()")}}
- : Schedules a suspension of the time progression in the audio context at the specified time and returns a promise.
- {{domxref("OfflineAudioContext.startRendering()")}}
- : Starts rendering the audio, taking into account the current connections and the current scheduled changes. This page covers both the event-based version and the promise-based version.
### Deprecated methods
- {{domxref("OfflineAudioContext.resume()")}}
- : Resumes the progression of time in an audio context that has previously been suspended.
> **Note:** The `resume()` method is still available — it is now defined on the {{domxref("BaseAudioContext")}} interface (see {{domxref("AudioContext.resume")}}) and thus can be accessed by both the {{domxref("AudioContext")}} and {{domxref("OfflineAudioContext")}} interfaces.
## Events
Listen to these events using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or by assigning an event listener to the `oneventname` property of this interface:
- [`complete`](/en-US/docs/Web/API/OfflineAudioContext/complete_event)
- : Fired when the rendering of an offline audio context is complete.
## Examples
### Playing audio with an offline audio context
In this example, we declare both an {{domxref("AudioContext")}} and an `OfflineAudioContext` object. We use the `AudioContext` to load an audio track {{domxref("fetch()")}}, then the `OfflineAudioContext` to render the audio into an {{domxref("AudioBufferSourceNode")}} and play the track through. After the offline audio graph is set up, we render it to an {{domxref("AudioBuffer")}} using `OfflineAudioContext.startRendering()`.
When the `startRendering()` promise resolves, rendering has completed and the output `AudioBuffer` is returned out of the promise.
At this point we create another audio context, create an {{domxref("AudioBufferSourceNode")}} inside it, and set its buffer to be equal to the promise `AudioBuffer`. This is then played as part of a simple standard audio graph.
> **Note:** You can [run the full example live](https://mdn.github.io/webaudio-examples/offline-audio-context-promise/), or [view the source](https://github.com/mdn/webaudio-examples/blob/main/offline-audio-context-promise/).
```js
// Define both online and offline audio contexts
let audioCtx; // Must be initialized after a user interaction
const offlineCtx = new OfflineAudioContext(2, 44100 * 40, 44100);
// Define constants for dom nodes
const play = document.querySelector("#play");
function getData() {
// Fetch an audio track, decode it and stick it in a buffer.
// Then we put the buffer into the source and can play it.
fetch("viper.ogg")
.then((response) => response.arrayBuffer())
.then((downloadedBuffer) => audioCtx.decodeAudioData(downloadedBuffer))
.then((decodedBuffer) => {
console.log("File downloaded successfully.");
const source = new AudioBufferSourceNode(offlineCtx, {
buffer: decodedBuffer,
});
source.connect(offlineCtx.destination);
return source.start();
})
.then(() => offlineCtx.startRendering())
.then((renderedBuffer) => {
console.log("Rendering completed successfully.");
play.disabled = false;
const song = new AudioBufferSourceNode(audioCtx, {
buffer: renderedBuffer,
});
song.connect(audioCtx.destination);
// Start the song
song.start();
})
.catch((err) => {
console.error(`Error encountered: ${err}`);
});
}
// Activate the play button
play.onclick = () => {
play.disabled = true;
// We can initialize the context as the user clicked.
audioCtx = new AudioContext();
// Fetch the data and start the song
getData();
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/offlineaudiocontext | data/mdn-content/files/en-us/web/api/offlineaudiocontext/startrendering/index.md | ---
title: "OfflineAudioContext: startRendering() method"
short-title: startRendering()
slug: Web/API/OfflineAudioContext/startRendering
page-type: web-api-instance-method
browser-compat: api.OfflineAudioContext.startRendering
---
{{ APIRef("Web Audio API") }}
The `startRendering()` method of the {{ domxref("OfflineAudioContext") }} Interface starts rendering the audio graph, taking into account the current connections and the current scheduled changes.
The {{domxref("OfflineAudioContext/complete_event", "complete")}} event (of type {{domxref("OfflineAudioCompletionEvent")}}) is raised when the rendering is finished, containing the resulting {{domxref("AudioBuffer")}} in its `renderedBuffer` property.
Browsers currently support two versions of the `startRendering()` method — an older event-based version and a newer promise-based version.
The former will eventually be removed, but currently both mechanisms are provided for legacy reasons.
## Syntax
```js-nolint
startRendering()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that fulfills with an {{domxref("AudioBuffer")}}.
## Examples
### Playing audio with an offline audio context
In this example, we declare both an {{domxref("AudioContext")}} and an `OfflineAudioContext` object. We use the `AudioContext` to load an audio track {{domxref("fetch()")}}, then the `OfflineAudioContext` to render the audio into an {{domxref("AudioBufferSourceNode")}} and play the track through. After the offline audio graph is set up, we render it to an {{domxref("AudioBuffer")}} using `OfflineAudioContext.startRendering()`.
When the `startRendering()` promise resolves, rendering has completed and the output `AudioBuffer` is returned out of the promise.
At this point we create another audio context, create an {{domxref("AudioBufferSourceNode")}} inside it, and set its buffer to be equal to the promise `AudioBuffer`. This is then played as part of a simple standard audio graph.
> **Note:** You can [run the full example live](https://mdn.github.io/webaudio-examples/offline-audio-context-promise/), or [view the source](https://github.com/mdn/webaudio-examples/blob/main/offline-audio-context-promise/).
```js
// Define both online and offline audio contexts
let audioCtx; // Must be initialized after a user interaction
const offlineCtx = new OfflineAudioContext(2, 44100 * 40, 44100);
// Define constants for dom nodes
const play = document.querySelector("#play");
function getData() {
// Fetch an audio track, decode it and stick it in a buffer.
// Then we put the buffer into the source and can play it.
fetch("viper.ogg")
.then((response) => response.arrayBuffer())
.then((downloadedBuffer) => audioCtx.decodeAudioData(downloadedBuffer))
.then((decodedBuffer) => {
console.log("File downloaded successfully.");
const source = new AudioBufferSourceNode(offlineCtx, {
buffer: decodedBuffer,
});
source.connect(offlineCtx.destination);
return source.start();
})
.then(() => offlineCtx.startRendering())
.then((renderedBuffer) => {
console.log("Rendering completed successfully.");
play.disabled = false;
const song = new AudioBufferSourceNode(audioCtx, {
buffer: renderedBuffer,
});
song.connect(audioCtx.destination);
// Start the song
song.start();
})
.catch((err) => {
console.error(`Error encountered: ${err}`);
});
}
// Activate the play button
play.onclick = () => {
play.disabled = true;
// We can initialize the context as the user clicked.
audioCtx = new AudioContext();
// Fetch the data and start the song
getData();
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/offlineaudiocontext | data/mdn-content/files/en-us/web/api/offlineaudiocontext/resume/index.md | ---
title: "OfflineAudioContext: resume() method"
short-title: resume()
slug: Web/API/OfflineAudioContext/resume
page-type: web-api-instance-method
browser-compat: api.OfflineAudioContext.resume
---
{{ APIRef("Web Audio API") }}
The **`resume()`** method of the
{{domxref("OfflineAudioContext")}} interface resumes the progression of time in an audio
context that has been suspended. The promise resolves immediately because the
`OfflineAudioContext` does not require the audio hardware.
## Syntax
```js-nolint
resume()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} resolving to {{jsxref('undefined')}}.
### Exceptions
The promise is rejected when an exception is encountered.
- `InvalidStateError` {{domxref("DOMException")}}
- : Returned if the context is not currently suspended or the rendering has not started.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/offlineaudiocontext | data/mdn-content/files/en-us/web/api/offlineaudiocontext/length/index.md | ---
title: "OfflineAudioContext: length property"
short-title: length
slug: Web/API/OfflineAudioContext/length
page-type: web-api-instance-property
browser-compat: api.OfflineAudioContext.length
---
{{ APIRef("Web Audio API") }}
The **`length`** property of the
{{domxref("OfflineAudioContext")}} interface returns an integer representing the size of
the buffer in sample-frames.
## Value
An integer representing the size of the buffer in sample-frames.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/offlineaudiocontext | data/mdn-content/files/en-us/web/api/offlineaudiocontext/complete_event/index.md | ---
title: "OfflineAudioContext: complete event"
short-title: complete
slug: Web/API/OfflineAudioContext/complete_event
page-type: web-api-event
browser-compat: api.OfflineAudioContext.complete_event
---
{{DefaultAPISidebar("Web Audio API")}}
The `complete` event of the {{domxref("OfflineAudioContext")}} interface is fired when the rendering of an offline audio context is complete.
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("complete", (event) => {});
oncomplete = (event) => {};
```
## Event type
An {{domxref("OfflineAudioCompletionEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("OfflineAudioCompletionEvent")}}
## Event properties
_Also inherits properties from its parent, {{domxref("Event")}}_.
- {{domxref("OfflineAudioCompletionEvent.renderedBuffer")}} {{ReadOnlyInline}}
- : An {{domxref("AudioBuffer")}} containing the result of processing an {{domxref("OfflineAudioContext")}}.
## Examples
When processing is complete, you might want to use the `complete` event handler to prompt the user that the audio can now be played, and enable the play button:
```js
const offlineAudioCtx = new OfflineAudioContext();
offlineAudioCtx.addEventListener("complete", () => {
console.log("Offline audio processing now complete");
showModalDialog("Song processed and ready to play");
playBtn.disabled = false;
});
```
You can also set up the event handler using the `oncomplete` property:
```js
const offlineAudioCtx = new OfflineAudioContext();
offlineAudioCtx.oncomplete = () => {
console.log("Offline audio processing now complete");
showModalDialog("Song processed and ready to play");
playBtn.disabled = false;
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/offlineaudiocontext | data/mdn-content/files/en-us/web/api/offlineaudiocontext/suspend/index.md | ---
title: "OfflineAudioContext: suspend() method"
short-title: suspend()
slug: Web/API/OfflineAudioContext/suspend
page-type: web-api-instance-method
browser-compat: api.OfflineAudioContext.suspend
---
{{ APIRef("Web Audio API") }}
The **`suspend()`** method of the {{
domxref("OfflineAudioContext") }} interface schedules a suspension of the time
progression in the audio context at the specified time and returns a promise. This is
generally useful at the time of manipulating the audio graph synchronously on
OfflineAudioContext.
Note that the maximum precision of suspension is the size of the render quantum and the
specified suspension time will be rounded down to the nearest render quantum boundary.
For this reason, it is not allowed to schedule multiple suspends at the same quantized
frame. Also scheduling should be done while the context is not running to ensure the
precise suspension.
## Syntax
```js-nolint
suspend(suspendTime)
```
### Parameters
- `suspendTime`
- : A floating-point number specifying the suspend time, in seconds.
### Return value
A {{jsxref("Promise")}} resolving to {{jsxref('undefined')}}.
### Exceptions
The promise is rejected when any exception is encountered.
- `InvalidStateError` {{domxref("DOMException")}}
- : Returned if the quantized frame number is one of the following:
- a negative number
- less than or equal to the current time
- greater than or equal to the total render duration
- scheduled by another suspend for the same time
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/offlineaudiocontext | data/mdn-content/files/en-us/web/api/offlineaudiocontext/offlineaudiocontext/index.md | ---
title: "OfflineAudioContext: OfflineAudioContext() constructor"
short-title: OfflineAudioContext()
slug: Web/API/OfflineAudioContext/OfflineAudioContext
page-type: web-api-constructor
browser-compat: api.OfflineAudioContext.OfflineAudioContext
---
{{APIRef("Web Audio API")}}
The
**`OfflineAudioContext()`** constructor—part of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)—creates and returns a new
{{domxref("OfflineAudioContext")}} object instance, which can then be used to render
audio to an {{domxref("AudioBuffer")}} rather than to an audio output device.
## Syntax
```js-nolint
new OfflineAudioContext(options)
new OfflineAudioContext(numberOfChannels, length, sampleRate)
```
### Parameters
You can specify the parameters for the `OfflineAudioContext()` constructor
as either the same set of parameters as are inputs into the
{{domxref("BaseAudioContext.createBuffer")}} method, or by passing those parameters in an
`options` object. Either way, the individual parameters are the same.
- `numberOfChannels`
- : An integer specifying the number of channels the resulting
{{domxref("AudioBuffer")}} should have.
- `length`
- : An integer specifying the size of the buffer to create for the audio context, in
sample-frames, where one sample-frame is a unit that can contain a single sample of
audio data for every channel in the audio data. For example, a 5-second buffer with a
`sampleRate` of 48000Hz would have a length of
`5 * 48000 = 240000` sample-frames.
- `sampleRate`
- : The sample-rate of the linear audio data in sample-frames per second. All user
agents are required to support a range of 8000Hz to 96000Hz, and may support a wider
range than that. The most commonly-used rate is 44100Hz, which is the sample rate used
by CD audio.
It is important to note that, whereas you can create a new {{domxref("AudioContext")}}
using the {{domxref("AudioContext.AudioContext()", "new AudioContext()")}} constructor
with no arguments, the `OfflineAudioContext()` constructor requires three
arguments, since it needs to create an `AudioBuffer`. This works in exactly
the same way as when you create a new {{domxref("AudioBuffer")}} with the
{{domxref("BaseAudioContext.createBuffer")}} method. For more detail, read [Audio buffers: frames, samples and channels](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#audio_buffers.3a_frames.2c_samples_and_channels) from our [Basic concepts](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API) guide.
### Return value
A new {{domxref("OfflineAudioContext")}} object whose associated
`AudioBuffer` is configured as requested.
Like a regular `AudioContext`, an
`OfflineAudioContext` can be the target of events, therefore it implements
the {{domxref("EventTarget")}} interface.
## Examples
```js
const offlineCtx = new OfflineAudioContext({
numberOfChannels: 2,
length: 44100 * 40,
sampleRate: 44100,
});
const source = offlineCtx.createBufferSource();
// …
```
For a full working example, see our [offline-audio-context-promise](https://mdn.github.io/webaudio-examples/offline-audio-context-promise/)
GitHub repo (see the [source code](https://github.com/mdn/webaudio-examples/blob/main/offline-audio-context-promise/index.html) too.)
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/ext_shader_texture_lod/index.md | ---
title: EXT_shader_texture_lod extension
short-title: EXT_shader_texture_lod
slug: Web/API/EXT_shader_texture_lod
page-type: webgl-extension
browser-compat: api.EXT_shader_texture_lod
---
{{APIRef("WebGL")}}
The **`EXT_shader_texture_lod`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and adds additional texture functions to the OpenGL ES Shading Language which provide the shader writer with explicit control of LOD ([Level of detail](https://en.wikipedia.org/wiki/Level_of_detail)).
WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial).
> **Note:** This extension is only available to {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} contexts. In {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}}, the functionality of this extension is available on the WebGL2 context by default. It requires GLSL `#version 300 es`.
## GLSL built-in functions
The following new functions can be used in GLSL shader code, if this extension is enabled:
```cpp
vec4 texture2DLodEXT(sampler2D sampler, vec2 coord, float lod)
vec4 texture2DProjLodEXT(sampler2D sampler, vec3 coord, float lod)
vec4 texture2DProjLodEXT(sampler2D sampler, vec4 coord, float lod)
vec4 textureCubeLodEXT(samplerCube sampler, vec3 coord, float lod)
vec4 texture2DGradEXT(sampler2D sampler, vec2 P, vec2 dPdx, vec2 dPdy)
vec4 texture2DProjGradEXT(sampler2D sampler, vec3 P, vec2 dPdx, vec2 dPdy)
vec4 texture2DProjGradEXT(sampler2D sampler, vec4 P, vec2 dPdx, vec2 dPdy)
vec4 textureCubeGradEXT(samplerCube sampler, vec3 P, vec3 dPdx, vec3 dPdy)
```
## Examples
Enabling the extensions:
```js
gl.getExtension("EXT_shader_texture_lod");
```
Shader code that avoids artifacts when wrapping texture coordinates:
```html
<script type="x-shader/x-fragment">
#extension GL_EXT_shader_texture_lod : enable
#extension GL_OES_standard_derivatives : enable
uniform sampler2D myTexture;
varying vec2 texcoord;
void main(){
gl_FragColor = texture2DGradEXT(myTexture, mod(texcoord, vec2(0.1, 0.5)),
dFdx(texcoord), dFdy(texcoord));
}
</script>
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.getExtension()")}}
- {{domxref("OES_standard_derivatives")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webglquery/index.md | ---
title: WebGLQuery
slug: Web/API/WebGLQuery
page-type: web-api-interface
browser-compat: api.WebGLQuery
---
{{APIRef("WebGL")}}
The **`WebGLQuery`** interface is part of the [WebGL 2](/en-US/docs/Web/API/WebGL_API) API and provides ways to asynchronously query for information. By default, occlusion queries and primitive queries are available.
Another kind of queries are disjoint timer queries, which allow you to measure performance and profiling of your GPU. Disjoint timer queries are available with the {{domxref("EXT_disjoint_timer_query")}} extension only.
{{InheritanceDiagram}}
When working with `WebGLQuery` objects, the following methods of the {{domxref("WebGL2RenderingContext")}} are useful:
- {{domxref("WebGL2RenderingContext.createQuery()")}}
- {{domxref("WebGL2RenderingContext.deleteQuery()")}}
- {{domxref("WebGL2RenderingContext.isQuery()")}}
- {{domxref("WebGL2RenderingContext.beginQuery()")}}
- {{domxref("WebGL2RenderingContext.endQuery()")}}
- {{domxref("WebGL2RenderingContext.getQuery()")}}
- {{domxref("WebGL2RenderingContext.getQueryParameter()")}}
## Examples
### Creating a `WebGLQuery` object
in this example, `gl` must be a {{domxref("WebGL2RenderingContext")}}. `WebGLQuery` objects are not available in WebGL 1.
```js
const query = gl.createQuery();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("EXT_disjoint_timer_query")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webgl_compressed_texture_etc/index.md | ---
title: WEBGL_compressed_texture_etc extension
short-title: WEBGL_compressed_texture_etc
slug: Web/API/WEBGL_compressed_texture_etc
page-type: webgl-extension
browser-compat: api.WEBGL_compressed_texture_etc
---
{{APIRef("WebGL")}}
The **`WEBGL_compressed_texture_etc`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and exposes 10 [ETC/EAC compressed texture formats](https://en.wikipedia.org/wiki/Ericsson_Texture_Compression).
Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures.
WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial).
> **Note:** This extension is available to both, {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} and {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} contexts.
## Constants
The compressed texture formats are exposed by 10 constants and can be used in two functions: {{domxref("WebGLRenderingContext.compressedTexImage2D", "compressedTexImage2D()")}} and {{domxref("WebGLRenderingContext.compressedTexSubImage2D", "compressedTexSubImage2D()")}}.
- `ext.COMPRESSED_R11_EAC`
- : One-channel (red) unsigned format compression.
- `ext.COMPRESSED_SIGNED_R11_EAC`
- : One-channel (red) signed format compression.
- `ext.COMPRESSED_RG11_EAC`
- : Two-channel (red and green) unsigned format compression.
- `ext.COMPRESSED_SIGNED_RG11_EAC`
- : Two-channel (red and green) signed format compression.
- `ext.COMPRESSED_RGB8_ETC2`
- : Compresses RGB8 data with no alpha channel.
- `ext.COMPRESSED_RGBA8_ETC2_EAC`
- : Compresses RGBA8 data. The RGB part is encoded the same as `RGB_ETC2`, but the alpha part is encoded separately.
- `ext.COMPRESSED_SRGB8_ETC2`
- : Compresses sRGB8 data with no alpha channel.
- `ext.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC`
- : Compresses sRGBA8 data. The sRGB part is encoded the same as `SRGB_ETC2`, but the alpha part is encoded separately.
- `ext.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2`
- : Similar to `RGB8_ETC`, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
- `ext.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2`
- : Similar to `SRGB8_ETC`, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
## Examples
```js
const ext = gl.getExtension("WEBGL_compressed_texture_etc");
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.compressedTexImage2D(
gl.TEXTURE_2D,
0,
ext.COMPRESSED_RGBA8_ETC2_EAC,
512,
512,
0,
textureData,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
### Compatibility notes
- This extension was named `WEBGL_compressed_texture_es3` from Firefox 46 to Firefox 51 and used to be available on the WebGL 2 context by default – this is not the case anymore. You have to enable it on both, WebGL 1 and WebGL 2 contexts, in order to use it.
## See also
- [Ericsson Texture Compression – Wikipedia](https://en.wikipedia.org/wiki/Ericsson_Texture_Compression)
- {{domxref("WEBGL_compressed_texture_etc1")}} (ETC1)
- {{domxref("WebGLRenderingContext.getExtension()")}}
- {{domxref("WebGLRenderingContext.compressedTexImage2D()")}}
- {{domxref("WebGLRenderingContext.compressedTexSubImage2D()")}}
- {{domxref("WebGLRenderingContext.getParameter()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/midiinputmap/index.md | ---
title: MIDIInputMap
slug: Web/API/MIDIInputMap
page-type: web-api-interface
browser-compat: api.MIDIInputMap
---
{{APIRef("Web MIDI API")}}{{SecureContext_Header}}
The **`MIDIInputMap`** read-only interface of the [Web MIDI API](/en-US/docs/Web/API/Web_MIDI_API) provides the set of MIDI input ports that are currently available.
A `MIDIInputMap` instance is a read-only [`Map`-like object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#map-like_browser_apis), in which each key is the ID string for MIDI input, and the associated value is the corresponding {{domxref("MIDIInput")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmldetailselement/index.md | ---
title: HTMLDetailsElement
slug: Web/API/HTMLDetailsElement
page-type: web-api-interface
browser-compat: api.HTMLDetailsElement
---
{{APIRef("HTML DOM")}}
The **`HTMLDetailsElement`** interface provides special properties (beyond the regular {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating {{HTMLElement("details")}} elements.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLDetailsElement.open")}}
- : A boolean value reflecting the [`open`](/en-US/docs/Web/HTML/Element/details#open) HTML attribute, indicating whether or not the element's contents (not counting the {{HTMLElement("summary")}}) is to be shown to the user.
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._
## Events
Listen to this event using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or by assigning an event listener to the `oneventname` property of this interface.
- [`toggle`](/en-US/docs/Web/API/HTMLDetailsElement/toggle_event)
- : Fired when the `open`/`closed` state of a {{HtmlElement("details")}} element is toggled.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{HTMLElement("details")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmldetailselement | data/mdn-content/files/en-us/web/api/htmldetailselement/toggle_event/index.md | ---
title: "HTMLDetailsElement: toggle event"
short-title: toggle
slug: Web/API/HTMLDetailsElement/toggle_event
page-type: web-api-event
browser-compat: api.HTMLDetailsElement.toggle_event
---
{{APIRef}}
The **`toggle`** event fires when the `open`/`closed` state of a {{HtmlElement("details")}} element is toggled.
This event is not cancelable and does not bubble.
> **Note:** The `toggle` event is also available in a different form on {{domxref("HTMLElement")}}; this version fires on [popover elements](/en-US/docs/Web/API/Popover_API) just after they are shown or hidden. See the `HTMLElement` {{domxref("HTMLElement.toggle_event", "toggle event")}} page for more information.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("toggle", (event) => {});
ontoggle = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
This example logs chapters that are open. Chapters are removed from the log when they are closed.
### HTML
```html
<aside id="log">
<p>Open chapters:</p>
<div data-id="ch1" hidden>I</div>
<div data-id="ch2" hidden>II</div>
<div data-id="ch3" hidden>III</div>
</aside>
<section id="summaries">
<p>Chapter summaries:</p>
<details id="ch1">
<summary>Chapter I</summary>
Philosophy reproves Boethius for the foolishness of his complaints against
Fortune. Her very nature is caprice.
</details>
<details id="ch2">
<summary>Chapter II</summary>
Philosophy in Fortune's name replies to Boethius' reproaches, and proves
that the gifts of Fortune are hers to give and to take away.
</details>
<details id="ch3">
<summary>Chapter III</summary>
Boethius falls back upon his present sense of misery. Philosophy reminds him
of the brilliancy of his former fortunes.
</details>
</section>
```
### CSS
```css
body {
display: flex;
flex-direction: row-reverse;
}
#log {
flex-shrink: 0;
padding-left: 3em;
}
#summaries {
flex-grow: 1;
}
```
### JavaScript
```js
function logItem(e) {
const item = document.querySelector(`[data-id=${e.target.id}]`);
item.toggleAttribute("hidden");
}
const chapters = document.querySelectorAll("details");
chapters.forEach((chapter) => {
chapter.addEventListener("toggle", logItem);
});
```
### Result
{{EmbedLiveSample("Examples", 700, 200)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmldetailselement | data/mdn-content/files/en-us/web/api/htmldetailselement/open/index.md | ---
title: "HTMLDetailsElement: open property"
short-title: open
slug: Web/API/HTMLDetailsElement/open
page-type: web-api-instance-property
browser-compat: api.HTMLDetailsElement.open
---
{{ APIRef("HTML DOM") }}
The **`open`** property of the
{{domxref("HTMLDetailsElement")}} interface is a boolean value reflecting the
[`open`](/en-US/docs/Web/HTML/Element/details#open) HTML attribute, indicating whether the {{htmlelement("details")}}'s contents (not counting the {{htmlelement("summary")}}) is to be shown to the user.
## Value
A boolean value.
The boolean value represents the state of the [`open`](/en-US/docs/Web/HTML/Element/details#open) HTML attribute. The value of `true` means it is set with both the summary and the additional information shown to the user. The `false` value means it not set, with only the summary shown.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{htmlelement("details")}} and {{htmlelement("summary")}} elements
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrsession/index.md | ---
title: XRSession
slug: Web/API/XRSession
page-type: web-api-interface
status:
- experimental
browser-compat: api.XRSession
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}{{SeeCompatTable}}
The {{domxref("WebXR Device API")}}'s **`XRSession`** interface represents an ongoing XR session, providing methods and properties used to interact with and control the session. To open a WebXR session, use the {{domxref("XRSystem")}} interface's {{domxref("XRSystem.requestSession", "requestSession()")}} method.
With `XRSession` methods, you can poll the viewer's position and orientation (the {{domxref("XRViewerPose")}}), gather information about the user's environment, and present imagery to the user. `XRSession` supports both inline and immersive virtual and augmented reality modes.
{{InheritanceDiagram}}
## Instance properties
_In addition to the properties listed below, `XRSession` inherits properties from its parent interface, {{domxref("EventTarget")}}._
- {{DOMxRef("XRSession.depthDataFormat", "depthDataFormat")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns the depth-sensing data format with which the session was configured.
- {{DOMxRef("XRSession.depthUsage", "depthUsage")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns the depth-sensing usage with which the session was configured.
- {{DOMxRef("XRSession.domOverlayState", "domOverlayState")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Provides information about the DOM overlay, if the feature is enabled.
- {{DOMxRef("XRSession.environmentBlendMode", "environmentBlendMode")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns this session's blend mode which denotes how much of the real-world environment is visible through the XR device and how the device will blend the device imagery with it.
- {{DOMxRef("XRSession.inputSources", "inputSources")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns a list of this session's {{DOMxRef("XRInputSource")}}s, each representing an input device used to control the camera and/or scene.
- {{DOMxRef("XRSession.interactionMode", "interactionMode")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns this session's interaction mode, which describes the best space (according to the user agent) for the application to draw interactive UI for the current session.
- {{DOMxRef("XRSession.preferredReflectionFormat", "preferredReflectionFormat")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns this session's preferred reflection format used for lighting estimation texture data.
- {{DOMxRef("XRSession.renderState", "renderState")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : An {{domxref("XRRenderState")}} object which contains options affecting how the imagery is rendered. This includes things such as the near and far clipping planes (distances defining how close and how far away objects can be and still get rendered), as well as field of view information.
- {{DOMxRef("XRSession.visibilityState", "visibilityState")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : A string indicating whether or not the session's imagery is visible to the user, and if so, if it's being visible but not currently the target for user events.
## Instance methods
_`XRSession` provides the following methods in addition to those inherited from its parent interface, {{domxref("EventTarget")}}._
- {{DOMxRef("XRSession.cancelAnimationFrame", "cancelAnimationFrame()")}} {{Experimental_Inline}}
- : Removes a callback from the animation frame painting callback from `XRSession`'s set of animation frame rendering callbacks, given the identifying handle returned by a previous call to {{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}}.
- {{DOMxRef("XRSession.end", "end()")}} {{Experimental_Inline}}
- : Ends the WebXR session. Returns a {{jsxref("promise")}} which resolves when the session has been shut down.
- {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} {{Experimental_Inline}}
- : Schedules the specified method to be called the next time the {{glossary("user agent")}} is working on rendering an animation frame for the WebXR device. Returns an integer value which can be used to identify the request for the purposes of canceling the callback using `cancelAnimationFrame()`. This method is comparable to the {{domxref("Window.requestAnimationFrame()")}} method.
- {{DOMxRef("XRSession.requestHitTestSource", "requestHitTestSource()")}} {{Experimental_Inline}}
- : Requests an {{domxref("XRHitTestSource")}} object that handles hit test subscription.
- {{DOMxRef("XRSession.requestHitTestSourceForTransientInput", "requestHitTestSourceForTransientInput()")}} {{Experimental_Inline}}
- : Requests an {{domxref("XRTransientInputHitTestSource")}} object that handles hit test subscription for a transient input source.
- {{DOMxRef("XRSession.requestLightProbe", "requestLightProbe()")}} {{Experimental_Inline}}
- : Requests an {{domxref("XRLightProbe")}} that estimates lighting information at a given point in the user's environment.
- {{DOMxRef("XRSession.requestReferenceSpace", "requestReferenceSpace()")}} {{Experimental_Inline}}
- : Requests that a new {{domxref("XRReferenceSpace")}} of the specified type be created. Returns a promise which resolves with the `XRReferenceSpace` or {{domxref("XRBoundedReferenceSpace")}} which was requested, or throws a `NotSupportedError` {{domxref("DOMException")}} if the requested space type isn't supported by the device.
- {{DOMxRef("XRSession.updateRenderState", "updateRenderState()")}} {{Experimental_Inline}}
- : Updates the properties of the session's render state.
## Events
_The following events are delivered to `XRSession` objects._
- {{domxref("XRSession.end_event", "end")}} {{Experimental_Inline}}
- : Sent to the `XRSession` object after the WebXR session has ended and all hardware-related functions have completed. The event is represented by an object of type {{domxref("XRSessionEvent")}}. Also available through the `onend` event handler property.
- {{domxref("XRSession.inputsourceschange_event", "inputsourceschange")}} {{Experimental_Inline}}
- : An event of type {{domxref("XRInputSourcesChangeEvent")}} sent to the `XRSession` when the list of active XR input sources has changed. Also available through the `oninputsourceschange` event handler property.
- {{domxref("XRSession.select_event", "select")}} {{Experimental_Inline}}
- : An event of type {{domxref("XRInputSourceEvent")}} which is sent to the session when one of the session's input sources has successfully completed a [primary action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_actions). This generally corresponds to the user pressing a trigger, touchpad, or button, speaks a command, or performs a recognizable gesture. The `select` event is sent after the `selectstart` event is sent and immediately before the `selectend` event is sent. If `select` is _not_ sent, then the select action was aborted before being completed. Also available through the `onselect` event handler property.
- {{domxref("XRSession.selectend_event", "selectend")}} {{Experimental_Inline}}
- : An event of type {{domxref("XRInputSourceEvent")}} which gets sent to the session object when one of its input devices finishes its primary action or gets disconnected while in the process of handling a primary action. For example: for button or trigger actions, this means the button has been released; for spoken commands, it means the user has finished speaking. This is the last of the three `select*` events to be sent. Also available through the `onselectend` event handler property.
- {{domxref("XRSession.selectstart_event", "selectstart")}} {{Experimental_Inline}}
- : An event of type {{domxref("XRInputSourceEvent")}} which is sent to the session object when one of its input devices is first engaged by the user in such a way as to cause the primary action to begin. This is the first of the `session*` event to be sent. Also available through the `onselectstart` event handler property.
- {{domxref("XRSession.squeeze_event", "squeeze")}} {{Experimental_Inline}}
- : An {{domxref("XRInputSourceEvent")}} sent to indicate that a [primary squeeze action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_squeeze_actions) has successfully completed. This indicates that the device being squeezed has been released, and may represent dropping a grabbed object, for example. It is sent immediately before the `squeezeend` event is sent to indicate that the squeeze action is over. Also available through the `onsqueeze` event handler property.
- {{domxref("XRSession.squeezeend_event", "squeezeend")}} {{Experimental_Inline}}
- : An {{domxref("XRInputSourceEvent")}} sent to the `XRSession` when the [primary squeeze action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_squeeze_actions) ends, whether or not the action was successful. Also available using the `onsqueezeend` event handler property.
- {{domxref("XRSession.squeezestart_event", "squeezestart")}} {{Experimental_Inline}}
- : An event of type {{domxref("XRInputSourceEvent")}} which is sent to the `XRSession` when the user initially squeezes a squeezable controller. This may be, for example, a trigger which is used to represent grabbing objects, or might represent actual squeezing when wearing a haptic glove. Also available through the `onsqueezestart` event handler property.
- {{domxref("XRSession.visibilitychange_event", "visibilitychange")}} {{Experimental_Inline}}
- : An {{domxref("XRSessionEvent")}} which is sent to the session when its visibility state as indicated by the {{domxref("XRSession.visibilityState", "visibilityState")}} changes. Also available through the `onvisibilitychange` event handler property.
## Example
This example establishes a new `XRSession` in `inline` mode so that it can be displayed within an HTML element, avoiding the need for a dedicated AR or VR viewing device such as a headset.
```js
const XR = navigator.xr;
if (XR) {
XR.requestSession("inline").then((xrSession) => {
xrSession.requestReferenceSpace("local").then((xrReferenceSpace) => {
xrSession.requestAnimationFrame((time, xrFrame) => {
const viewer = xrFrame.getViewerPose(xrReferenceSpace);
gl.bindFramebuffer(xrWebGLLayer.framebuffer);
for (const xrView of viewer.views) {
const xrViewport = xrWebGLLayer.getViewport(xrView);
gl.viewport(
xrViewport.x,
xrViewport.y,
xrViewport.width,
xrViewport.height,
);
}
});
});
});
} else {
/* WebXR is not available */
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.