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/mediarecorder | data/mdn-content/files/en-us/web/api/mediarecorder/dataavailable_event/index.md | ---
title: "MediaRecorder: dataavailable event"
short-title: dataavailable
slug: Web/API/MediaRecorder/dataavailable_event
page-type: web-api-event
browser-compat: api.MediaRecorder.dataavailable_event
---
{{APIRef("MediaStream Recording")}}
The **`dataavailable`** event of the {{domxref("MediaRecorder")}} interface is fired when the MediaRecorder delivers media
data to your application for its use. The data is provided in a {{domxref("Blob")}}
object that contains the data. This occurs in four situations:
- When the media stream ends, any media data not already delivered to your
`ondataavailable` handler is passed in a single {{domxref("Blob")}}.
- When {{domxref("MediaRecorder.stop()")}} is called, all media data which has been
captured since recording began or the last time a `dataavailable` event
occurred is delivered in a {{domxref("Blob")}}; after this, capturing ends.
- When {{domxref("MediaRecorder.requestData()")}} is called, all media data which has
been captured since recording began or the last time a `dataavailable`
event occurred is delivered; then a new `Blob` is created and media capture
continues into that blob.
- If a `timeslice` property was passed into the
{{domxref("MediaRecorder.start()")}} method that started media capture, a
`dataavailable` event is fired every `timeslice` milliseconds.
That means that each blob will have a specific time duration (except the last blob,
which might be shorter, since it would be whatever is left over since the last event).
So if the method call looked like this — `recorder.start(1000);` — the
`dataavailable` event would fire after each second of media capture, and
our event handler would be called every second with a blob of media data that's one
second long. You can use `timeslice` alongside
{{domxref("MediaRecorder.stop()")}} and {{domxref("MediaRecorder.requestData()")}} to
produce multiple same-length blobs plus other shorter blobs as well.
> **Note:** The {{domxref("Blob")}} containing the media data is available in the
> {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event's `data` property.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("dataavailable", (event) => {});
ondataavailable = (event) => {};
```
## Event type
A {{domxref("BlobEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("BlobEvent")}}
## Example
```js
const chunks = [];
mediaRecorder.onstop = (e) => {
console.log("data available after MediaRecorder.stop() called.");
const audio = document.createElement("audio");
audio.controls = true;
const blob = new Blob(chunks, { type: mediaRecorder.mimeType });
const audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;
console.log("recorder stopped");
};
mediaRecorder.ondataavailable = (e) => {
chunks.push(e.data);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API)
- [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder +
getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).)
- [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton).
- {{domxref("Navigator.getUserMedia()")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediarecorder | data/mdn-content/files/en-us/web/api/mediarecorder/state/index.md | ---
title: "MediaRecorder: state property"
short-title: state
slug: Web/API/MediaRecorder/state
page-type: web-api-instance-property
browser-compat: api.MediaRecorder.state
---
{{APIRef("MediaStream Recording")}}
The **`state`** read-only property of the {{domxref("MediaRecorder")}} interface returns the current state of the current `MediaRecorder` object.
## Value
A string containing one of the following values:
- `inactive`
- : Recording is not occurring — it has either not been started yet, or it has been started and then stopped.
- `recording`
- : Recording has been started and the {{glossary("user agent")}} is capturing data.
- `paused`
- : Recording has been started, then paused, but not yet stopped or resumed.
## Examples
```js
record.onclick = () => {
mediaRecorder.start();
console.log(mediaRecorder.state);
// Will return "recording"
console.log("recorder started");
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API)
- [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder +
getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).)
- [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton).
- {{domxref("Navigator.getUserMedia()")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediarecorder | data/mdn-content/files/en-us/web/api/mediarecorder/audiobitspersecond/index.md | ---
title: "MediaRecorder: audioBitsPerSecond property"
short-title: audioBitsPerSecond
slug: Web/API/MediaRecorder/audioBitsPerSecond
page-type: web-api-instance-property
browser-compat: api.MediaRecorder.audioBitsPerSecond
---
{{APIRef("MediaStream Recording")}}
The **`audioBitsPerSecond`** read-only
property of the {{domxref("MediaRecorder")}} interface returns the audio encoding bit
rate in use.
This may differ from the bit rate specified in the constructor (if
it was provided).
## Value
A {{jsxref("Number")}} (unsigned long).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediarecorder | data/mdn-content/files/en-us/web/api/mediarecorder/error_event/index.md | ---
title: "MediaRecorder: error event"
short-title: error
slug: Web/API/MediaRecorder/error_event
page-type: web-api-event
browser-compat: api.MediaRecorder.error_event
---
{{APIRef("MediaStream Recording")}}
The **`error`** event of the {{domxref("MediaRecorder")}} interface is fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec.
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("event", (event) => {});
onevent = (event) => {};
```
## Event type
A {{domxref("MediaRecorderErrorEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MediaRecorderErrorEvent")}}
## Event properties
_Inherits properties from its parent interface, {{domxref("Event")}}_.
- {{domxref("MediaRecorderErrorEvent.error", "error")}} {{ReadOnlyInline}}
- : A {{domxref("DOMException")}} containing information about the error that occurred.
## Description
### Trigger
A function to be called whenever an error occurs during the recorder's lifetime. In
addition to other general errors that might occur, the following errors are specifically
possible when using the MediaStream Recording API; to determine which occurred, check
the value of {{domxref("DOMException.name", "MediaRecorderErrorEvent.error.name")}}.
- `SecurityError`
- : The {{domxref("MediaStream")}} is configured to disallow recording. This may be the
case, for example, with sources obtained using {{domxref("MediaDevices.getUserMedia",
"getUserMedia()")}} when the user denies permission to use an input device.
- `InvalidModificationError`
- : The number of tracks on the stream being recorded has changed. You can't add or
remove tracks while recording media.
- `UnknownError`
- : An non-security related error occurred that cannot otherwise be categorized.
Recording stops, the `MediaRecorder`'s {{domxref("MediaRecorder.state",
"state")}} becomes `inactive`, one last {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event is
sent to the `MediaRecorder` with the remaining received data, and finally a
{{domxref("MediaRecorder/stop_event", "stop")}} event is sent.
## Examples
Using {{domxref("EventTarget.addEventListener", "addEventListener()")}} to listen for `error` events:
```js
async function record() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const recorder = new MediaRecorder(stream);
recorder.addEventListener("error", (event) => {
console.error(`error recording stream: ${event.error.name}`);
});
recorder.start();
}
record();
```
The same, but using the `onerror` event handler property:
```js
async function record() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const recorder = new MediaRecorder(stream);
recorder.onerror = (event) => {
console.error(`error recording stream: ${event.error.name}`);
};
recorder.start();
}
record();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfediffuselightingelement/index.md | ---
title: SVGFEDiffuseLightingElement
slug: Web/API/SVGFEDiffuseLightingElement
page-type: web-api-interface
browser-compat: api.SVGFEDiffuseLightingElement
---
{{APIRef("SVG")}}
The **`SVGFEDiffuseLightingElement`** interface corresponds to the {{SVGElement("feDiffuseLighting")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
- {{domxref("SVGFEDiffuseLightingElement.diffuseConstant")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("diffuseConstant")}} attribute of the given element.
- {{domxref("SVGFEDiffuseLightingElement.height")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element.
- {{domxref("SVGFEDiffuseLightingElement.in1")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element.
- {{domxref("SVGFEDiffuseLightingElement.kernelUnitLengthX")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the X component of the {{SVGAttr("kernelUnitLength")}} attribute of the given element.
- {{domxref("SVGFEDiffuseLightingElement.kernelUnitLengthY")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the Y component of the {{SVGAttr("kernelUnitLength")}} attribute of the given element.
- {{domxref("SVGFEDiffuseLightingElement.result")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element.
- {{domxref("SVGFEDiffuseLightingElement.surfaceScale")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("surfaceScale")}} attribute of the given element.
- {{domxref("SVGFEDiffuseLightingElement.width")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element.
- {{domxref("SVGFEDiffuseLightingElement.x")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element.
- {{domxref("SVGFEDiffuseLightingElement.y")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} 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("feDiffuseLighting")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtccertificatestats/index.md | ---
title: RTCCertificateStats
slug: Web/API/RTCCertificateStats
page-type: web-api-interface
browser-compat: api.RTCStatsReport.type_certificate
---
{{DefaultAPISidebar("WebRTC")}}
The **`RTCCertificateStats`** dictionary of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) is used to report information about a certificate used by an {{domxref("RTCDtlsTransport")}} and its underlying {{domxref("RTCIceTransport")}}.
The report can be obtained by iterating the {{domxref("RTCStatsReport")}} returned by {{domxref("RTCPeerConnection.getStats()")}} until you find an entry with the [`type`](#type) of `certificate`.
## Instance properties
- {{domxref("RTCCertificateStats.fingerprint", "fingerprint")}}
- : A string containing the certificate fingerprint, which is calculated using the hash function specified in [`fingerprintAlgorithm`](#fingerprintalgorithm).
- {{domxref("RTCCertificateStats.fingerprintAlgorithm", "fingerprintAlgorithm")}}
- : A string containing the hash function used to compute the certificate [`fingerprint`](#fingerprint), such as "sha-256".
- {{domxref("RTCCertificateStats.base64Certificate", "base64Certificate")}}
- : A string containing the base-64 representation of the DER-encoded certificate.
### Common instance properties
The following properties are common to all WebRTC statistics objects (See [`RTCStatsReport`](/en-US/docs/Web/API/RTCStatsReport#common_instance_properties) for more information).
<!-- RTCStats -->
- {{domxref("RTCCertificateStats.id", "id")}}
- : A string that uniquely identifies the object that is being monitored to produce this set of statistics.
- {{domxref("RTCCertificateStats.timestamp", "timestamp")}}
- : A {{domxref("DOMHighResTimeStamp")}} object indicating the time at which the sample was taken for this statistics object.
- {{domxref("RTCCertificateStats.type", "type")}}
- : A string with the value `"certificate"`, indicating the type of statistics that the object contains.
## Examples
Given a variable `myPeerConnection`, which is an instance of {{domxref("RTCPeerConnection")}}, the code below uses `await` to wait for the statistics report, and then iterates it using `RTCStatsReport.forEach()`.
It then filters the dictionaries for just those reports that have the type of `certificate` and logs the result.
```js
const stats = await myPeerConnection.getStats();
stats.forEach((report) => {
if (report.type === "certificate") {
// Log the certificate information
console.log(report);
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("RTCStatsReport")}}
- {{domxref("RTCCertificate")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtccertificatestats | data/mdn-content/files/en-us/web/api/rtccertificatestats/base64certificate/index.md | ---
title: "RTCCertificateStats: base64Certificate property"
short-title: base64Certificate
slug: Web/API/RTCCertificateStats/base64Certificate
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_certificate.base64Certificate
---
{{APIRef("WebRTC")}}
The **`base64Certificate`** property of the {{domxref("RTCCertificateStats")}} dictionary is a string containing the base-64 representation of the DER-encoded certificate.
This is essentially an encoding of the original certificate as a string that can safely serialized and deserialized when sent over an IP network.
## Value
A {{glossary("Base64")}} representation of the DER-encoded certificate.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtccertificatestats | data/mdn-content/files/en-us/web/api/rtccertificatestats/id/index.md | ---
title: "RTCCertificateStats: id property"
short-title: id
slug: Web/API/RTCCertificateStats/id
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_certificate.id
---
{{APIRef("WebRTC")}}
The **`id`** property of the {{domxref("RTCCertificateStats")}} dictionary is a string that uniquely identifies the object for which this object provides statistics.
Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an {{domxref("RTCPeerConnection")}}, or an {{domxref("RTCDataChannel")}}.
## Value
A string that uniquely identifies the object for which this `RTCCertificateStats` object provides statistics.
The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtccertificatestats | data/mdn-content/files/en-us/web/api/rtccertificatestats/fingerprint/index.md | ---
title: "RTCCertificateStats: fingerprint property"
short-title: fingerprint
slug: Web/API/RTCCertificateStats/fingerprint
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_certificate.fingerprint
---
{{APIRef("WebRTC")}}
The **`fingerprint`** property of the {{domxref("RTCCertificateStats")}} dictionary is a string containing the fingerprint value of the associated {{domxref("RTCCertificate")}}.
## Value
A string containing the fingerprint of the associated certificate.
This is a lowercase hex string, calculated using the hash function specified in the {{domxref("RTCCertificateStats.fingerprintAlgorithm","fingerprintAlgorithm")}} property.
The format is more precisely defined in [RFC4572, Section 5](https://www.rfc-editor.org/rfc/rfc4572#section-5).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtccertificatestats | data/mdn-content/files/en-us/web/api/rtccertificatestats/type/index.md | ---
title: "RTCCertificateStats: type property"
short-title: type
slug: Web/API/RTCCertificateStats/type
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_certificate.type
---
{{APIRef("WebRTC")}}
The **`type`** property of the {{domxref("RTCCertificateStats")}} dictionary is a string with the value `"certificate"`.
Different statistics are obtained by iterating the {{domxref("RTCStatsReport")}} object returned by a call to {{domxref("RTCPeerConnection.getStats()")}}.
The type indicates the set of statistics available through the object in a particular iteration step.
A value of `"certificate"` indicates that the statistics available in the current step are those defined in {{domxref("RTCCertificateStats")}}.
## Value
A string with the value `"certificate"`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtccertificatestats | data/mdn-content/files/en-us/web/api/rtccertificatestats/fingerprintalgorithm/index.md | ---
title: "RTCCertificateStats: fingerprintAlgorithm property"
short-title: fingerprintAlgorithm
slug: Web/API/RTCCertificateStats/fingerprintAlgorithm
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_certificate.fingerprintAlgorithm
---
{{APIRef("WebRTC")}}
The **`fingerprintAlgorithm`** property of the {{domxref("RTCCertificateStats")}} dictionary is a string containing the name of the hash function used to generate the {{domxref("RTCCertificateStats.fingerprint", "fingerprint")}} value in the associated {{domxref("RTCCertificate")}}.
## Value
A string containing the name of the hash function used to create the fingerprint of the associated certificate.
Allowed values are: `"sha-1"`, `"sha-224"`, `"sha-256"`,`"sha-384"`, `"sha-512"`, `"md5"`, `"md2"`. <!-- from [RFC4572, Section 5](https://www.rfc-editor.org/rfc/rfc4572#section-5) -->
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtccertificatestats | data/mdn-content/files/en-us/web/api/rtccertificatestats/timestamp/index.md | ---
title: "RTCCertificateStats: timestamp property"
short-title: timestamp
slug: Web/API/RTCCertificateStats/timestamp
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_certificate.timestamp
---
{{APIRef("WebRTC")}}
The **`timestamp`** property of the {{domxref("RTCCertificateStats")}} dictionary is a {{domxref("DOMHighResTimeStamp")}} object specifying the time at which the data in the object was sampled.
## Value
A {{domxref("DOMHighResTimeStamp")}} value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC.
The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of [fingerprinting](/en-US/docs/Glossary/Fingerprinting) protection in the form of reduced clock precision or accuracy.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssmatrixcomponent/index.md | ---
title: CSSMatrixComponent
slug: Web/API/CSSMatrixComponent
page-type: web-api-interface
browser-compat: api.CSSMatrixComponent
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSMatrixComponent`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents the [matrix()](/en-US/docs/Web/CSS/transform-function/matrix) and [matrix3d()](/en-US/docs/Web/CSS/transform-function/matrix3d) values of the individual {{CSSXRef('transform')}} property in CSS. It inherits properties and methods from its parent {{domxref('CSSTransformValue')}}.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CSSMatrixComponent.CSSMatrixComponent", "CSSMatrixComponent()")}}
- : Creates a new `CSSMatrixComponent` object.
## Instance properties
- {{domxref('CSSMatrixComponent.matrix','matrix')}}
- : A matrix.
## Examples
To do.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssmatrixcomponent | data/mdn-content/files/en-us/web/api/cssmatrixcomponent/matrix/index.md | ---
title: "CSSMatrixComponent: matrix property"
short-title: matrix
slug: Web/API/CSSMatrixComponent/matrix
page-type: web-api-instance-property
browser-compat: api.CSSMatrixComponent.matrix
---
{{APIRef("CSS Typed Object Model API")}}
The **`matrix`** property of the
{{domxref("CSSMatrixComponent")}} interface gets and sets a 2d or 3d matrix.
See the [matrix()](/en-US/docs/Web/CSS/transform-function/matrix) and [matrix3d()](/en-US/docs/Web/CSS/transform-function/matrix3d) pages for
examples.
## Value
a matrix.
## Examples
To do.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssmatrixcomponent | data/mdn-content/files/en-us/web/api/cssmatrixcomponent/cssmatrixcomponent/index.md | ---
title: "CSSMatrixComponent: CSSMatrixComponent() constructor"
short-title: CSSMatrixComponent()
slug: Web/API/CSSMatrixComponent/CSSMatrixComponent
page-type: web-api-constructor
browser-compat: api.CSSMatrixComponent.CSSMatrixComponent
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSMatrixComponent()`** constructor
creates a new {{domxref("CSSMatrixComponent")}} object representing the [matrix()](/en-US/docs/Web/CSS/transform-function/matrix) and [matrix3d()](/en-US/docs/Web/CSS/transform-function/matrix3d) values of the
individual {{CSSXRef('transform')}} property in CSS.
## Syntax
```js-nolint
new CSSMatrixComponent(matrix)
new CSSMatrixComponent(matrix, options)
```
### Parameters
- {{domxref('CSSMatrixComponent.matrix','matrix')}}
- : A 2d or 3d matrix.
## 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/keyframeeffect/index.md | ---
title: KeyframeEffect
slug: Web/API/KeyframeEffect
page-type: web-api-interface
browser-compat: api.KeyframeEffect
---
{{ APIRef("Web Animations") }}
The **`KeyframeEffect`** interface of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) lets us create sets of animatable properties and values, called **keyframes.** These can then be played using the {{domxref("Animation.Animation", "Animation()")}} constructor.
{{InheritanceDiagram}}
## Constructor
- {{domxref("KeyframeEffect.KeyframeEffect", "KeyframeEffect()")}}
- : Returns a new `KeyframeEffect` object instance, and also allows you to clone an existing keyframe effect object instance.
## Instance properties
- {{domxref("KeyframeEffect.target")}}
- : Gets and sets the element, or originating element of the pseudo-element, being animated by this object. This may be `null` for animations that do not target a specific element or pseudo-element.
- {{domxref("KeyframeEffect.pseudoElement")}}
- : Gets and sets the selector of the pseudo-element being animated by this object. This may be `null` for animations that do not target a pseudo-element.
- {{domxref("KeyframeEffect.iterationComposite")}}
- : Gets and sets the iteration composite operation for resolving the property value changes of this keyframe effect.
- {{domxref("KeyframeEffect.composite")}}
- : Gets and sets the composite operation property for resolving the property value changes between this and other keyframe effects.
## Instance methods
_This interface inherits some of its methods from its parent, {{domxref("AnimationEffect")}}._
- {{domxref("AnimationEffect.getComputedTiming()")}}
- : Returns the calculated, current timing values for this keyframe effect.
- {{domxref("KeyframeEffect.getKeyframes()")}}
- : Returns the computed keyframes that make up this effect along with their computed keyframe offsets.
- {{domxref("AnimationEffect.getTiming()")}}
- : Returns the object associated with the animation containing all the animation's timing values.
- {{domxref("KeyframeEffect.setKeyframes()")}}
- : Replaces the set of keyframes that make up this effect.
- {{domxref("AnimationEffect.updateTiming()")}}
- : Updates the specified timing properties.
## Examples
In the [Follow the White Rabbit example](https://codepen.io/rachelnabors/pen/eJyWzm/?editors=0010), the KeyframeEffect constructor is used to create a set of keyframes that dictate how the White Rabbit should animate down the hole:
```js
const whiteRabbit = document.getElementById("rabbit");
const rabbitDownKeyframes = new KeyframeEffect(
whiteRabbit, // element to animate
[
{ transform: "translateY(0%)" }, // keyframe
{ transform: "translateY(100%)" }, // keyframe
],
{ duration: 3000, fill: "forwards" }, // keyframe options
);
const rabbitDownAnimation = new Animation(
rabbitDownKeyframes,
document.timeline,
);
// Play rabbit animation
rabbitDownAnimation.play();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- {{domxref("Animation")}}
| 0 |
data/mdn-content/files/en-us/web/api/keyframeeffect | data/mdn-content/files/en-us/web/api/keyframeeffect/iterationcomposite/index.md | ---
title: "KeyframeEffect: iterationComposite property"
short-title: iterationComposite
slug: Web/API/KeyframeEffect/iterationComposite
page-type: web-api-instance-property
browser-compat: api.KeyframeEffect.iterationComposite
---
{{ APIRef("Web Animations") }}
The **`iterationComposite`** property of a {{domxref("KeyframeEffect")}} resolves how the animation's property value changes accumulate or override each other upon each of the animation's iterations.
## Value
One of the following:
- `replace`
- : The `keyframeEffect` value produced is independent of the current iteration.
- `accumulate`
- : Subsequent iterations of the `keyframeEffect` build on the final value of the previous iteration.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- Property of both {{domxref("KeyframeEffect")}} objects.
| 0 |
data/mdn-content/files/en-us/web/api/keyframeeffect | data/mdn-content/files/en-us/web/api/keyframeeffect/target/index.md | ---
title: "KeyframeEffect: target property"
short-title: target
slug: Web/API/KeyframeEffect/target
page-type: web-api-instance-property
browser-compat: api.KeyframeEffect.target
---
{{ APIRef("Web Animations") }}
The **`target`** property of a {{domxref("KeyframeEffect")}} interface represents the element or pseudo-element being animated. It may be `null` for animations that do not target a specific element. It performs as both a getter and a setter, except with animations and transitions generated by CSS.
## Value
An {{domxref("Element")}} or `null`.
## Examples
In the [Follow the White Rabbit example](https://codepen.io/rachelnabors/pen/eJyWzm/?editors=0010), `whiteRabbit` sets the `target` element to be animated:
```js
const whiteRabbit = document.getElementById("rabbit");
const rabbitDownKeyframes = new KeyframeEffect(
whiteRabbit,
[{ transform: "translateY(0%)" }, { transform: "translateY(100%)" }],
{ duration: 3000, fill: "forwards" },
);
// returns <div id="rabbit">Click the rabbit's ears!</div>
rabbitDownKeyframes.target;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- Property of {{domxref("KeyframeEffect")}} objects.
| 0 |
data/mdn-content/files/en-us/web/api/keyframeeffect | data/mdn-content/files/en-us/web/api/keyframeeffect/getkeyframes/index.md | ---
title: "KeyframeEffect: getKeyframes() method"
short-title: getKeyframes()
slug: Web/API/KeyframeEffect/getKeyframes
page-type: web-api-instance-method
browser-compat: api.KeyframeEffect.getKeyframes
---
{{ APIRef("Web Animations") }}
The **`getKeyframes()`** method of a {{domxref("KeyframeEffect")}} returns an Array of the computed keyframes that make up this animation along with their computed offsets.
## Syntax
```js-nolint
getKeyframes()
```
### Parameters
None.
### Return value
Returns a sequence of objects with the following format:
- `property value pairs`
- : As many property value pairs as are contained in each keyframe of the animation.
- `offset`
- : The offset of the keyframe specified as a number between `0.0` and `1.0` inclusive or `null`. This is equivalent to specifying start and end states in percentages in CSS stylesheets using `@keyframes`. This will be `null` if the keyframe is automatically spaced using {{domxref("KeyframeEffect.spacing")}}.
- `computedOffset`
- : The computed offset for this keyframe, calculated when the list of computed keyframes was produced according to {{domxref("KeyframeEffect.spacing")}}. Unlike **`offset`,** above, the **`computedOffset`** is never `null`.
- `easing`
- : The [easing function](/en-US/docs/Web/CSS/easing-function) used from this keyframe until the next keyframe in the series.
- `composite`
- : The {{domxref("KeyframeEffect.composite")}} operation used to combine the values specified in this keyframe with the underlying value. This will be absent if the composite operation specified on the effect is being used.
## Examples
In the [Red Queen Race](https://codepen.io/rachelnabors/pen/PNGGaV) example, we can inspect Alice and the RedQueen's animation to see its individual keyframes like so:
```js
// Return the array of keyframes
redQueen_alice.effect.getKeyframes();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- Method of {{domxref("KeyframeEffect")}} objects.
| 0 |
data/mdn-content/files/en-us/web/api/keyframeeffect | data/mdn-content/files/en-us/web/api/keyframeeffect/setkeyframes/index.md | ---
title: "KeyframeEffect: setKeyframes() method"
short-title: setKeyframes()
slug: Web/API/KeyframeEffect/setKeyframes
page-type: web-api-instance-method
browser-compat: api.KeyframeEffect.setKeyframes
---
{{ APIRef("Web Animations") }}
The **`setKeyframes()`** method of the {{domxref("KeyframeEffect")}} interface replaces the keyframes that make up the affected `KeyframeEffect` with a new set of keyframes.
## Syntax
```js-nolint
setKeyframes(keyframes)
```
### Parameters
- `keyframes`
- : A keyframe object or `null`. If set to `null`, the keyframes are replaced with a sequence of empty keyframes.
More information about a keyframe object's [format](/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats#syntax).
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
<table class="no-markdown">
<thead>
<tr>
<th scope="col">Exception</th>
<th scope="col">Explanation</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>TypeError</code></td>
<td>
One or more of the frames were not of the correct type of object, the
keyframes were not
<a href="https://w3c.github.io/web-animations/#loosely-sorted-by-offset"
>loosely sorted by offset</a
>, or a keyframe existed with an offset of less than 0 or more than 1.
</td>
</tr>
</tbody>
</table>
> **Note:** If the keyframes cannot be processed or are malformed, the `KeyframeEffect`'s keyframes are not modified.
## Examples
```js
// passing an array of keyframe objects
existingKeyframeEffect.setKeyframes([
{ color: "blue" },
{ color: "green", left: "10px" },
]);
// passing an object with arrays for values
existingKeyframeEffect.setKeyframes({
color: ["blue", "green"],
left: ["0", "10px"],
});
// passing a single-member object
existingKeyframeEffect.setKeyframes({
color: "blue",
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [KeyframeEffect Interface](/en-US/docs/Web/API/KeyframeEffect)
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
| 0 |
data/mdn-content/files/en-us/web/api/keyframeeffect | data/mdn-content/files/en-us/web/api/keyframeeffect/composite/index.md | ---
title: "KeyframeEffect: composite property"
short-title: composite
slug: Web/API/KeyframeEffect/composite
page-type: web-api-instance-property
browser-compat: api.KeyframeEffect.composite
---
{{ APIRef("Web Animations") }}
The **`composite`** property of a {{domxref("KeyframeEffect")}} resolves how an element's animation impacts its underlying property values.
## Value
To understand these values, take the example of a `keyframeEffect` value of `blur(2)` working on an underlying property value of `blur(3)`.
- `replace`
- : The `keyframeEffect` **overrides** the underlying value it is combined with: `blur(2)` replaces `blur(3)`.
- `add`
- : The `keyframeEffect` is **added** to the underlying value with which it is combined (aka _additive_): `blur(2) blur(3)`.
- `accumulate`
- : The keyframeEffect is **accumulated** on to the underlying value: `blur(5)`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- Property of {{domxref("KeyframeEffect")}} objects
- {{Glossary("Composite operation")}}
| 0 |
data/mdn-content/files/en-us/web/api/keyframeeffect | data/mdn-content/files/en-us/web/api/keyframeeffect/keyframeeffect/index.md | ---
title: "KeyframeEffect: KeyframeEffect() constructor"
short-title: KeyframeEffect()
slug: Web/API/KeyframeEffect/KeyframeEffect
page-type: web-api-constructor
browser-compat: api.KeyframeEffect.KeyframeEffect
---
{{ APIRef("Web Animations") }}
The **`KeyframeEffect()`** constructor of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) returns a new {{domxref("KeyframeEffect")}} object instance, and also allows you to clone an existing keyframe effect object instance.
## Syntax
```js-nolint
new KeyframeEffect(target, keyframes)
new KeyframeEffect(target, keyframes, options)
new KeyframeEffect(sourceKeyFrames)
```
### Parameters
The multi-argument constructor (see above) creates a completely new {{domxref("KeyframeEffect")}} object instance. Its parameters are:
- `target`
- : The DOM element to be animated, or `null`.
- `keyframes`
- : A [keyframes object](/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats) or `null`.
- `options` {{optional_inline}}
- : Either an integer representing the animation's duration (in milliseconds), or an object containing one or more of the following:
- `delay` {{optional_inline}}
- : The number of milliseconds to delay the start of the animation. Defaults to 0.
- `direction` {{optional_inline}}
- : Whether the animation runs forwards (`normal`), backwards (`reverse`), switches direction after each iteration (`alternate`), or runs backwards and switches direction after each iteration (`alternate-reverse`). Defaults to `"normal"`.
- `duration` {{optional_inline}}
- : The number of milliseconds each iteration of the animation takes to complete. Defaults to 0. Although this is technically optional, keep in mind that your animation will not run if this value is 0.
- `easing` {{optional_inline}}
- : The rate of the animation's change over time. Accepts an {{cssxref("easing-function")}}, such as `"linear"`, `"ease-in"`, `"step-end"`, or `"cubic-bezier(0.42, 0, 0.58, 1)"`. Defaults to `"linear"`.
- `endDelay` {{optional_inline}}
- : The number of milliseconds to delay after the end of an animation. This is primarily of use when sequencing animations based on the end time of another animation. Defaults to 0.
- `fill` {{optional_inline}}
- : Dictates whether the animation's effects should be reflected by the element(s) prior to playing (`"backwards"`), retained after the animation has completed playing (`"forwards"`), or `both`. Defaults to `"none"`.
- `iterationStart` {{optional_inline}}
- : Describes at what point in the iteration the animation should start. 0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration. Defaults to 0.0.
- `iterations` {{optional_inline}}
- : The number of times the animation should repeat. Defaults to `1`, and can also take a value of {{jsxref("Infinity")}} to make it repeat for as long as the element exists.
- `composite` {{optional_inline}}
- : Determines how values are combined between this animation and other, separate
animations that do not specify their own specific composite operation. Defaults to
`replace`.
- `add` dictates an additive effect, where each successive iteration
builds on the last. For instance with `transform`, a
`translateX(-200px)` would not override an earlier
`rotate(20deg)` value but result in
`translateX(-200px) rotate(20deg)`.
- `accumulate` is similar but a little smarter: `blur(2)`
and `blur(5)` become `blur(7)`, not
`blur(2) blur(5)`.
- `replace` overwrites the previous value with the new one.
- `iterationComposite` {{optional_inline}}
- : Determines how values build from iteration to iteration in this animation. Can be
set to `accumulate` or `replace` (see above). Defaults
to `replace`.
- `pseudoElement` {{optional_inline}}
- : A `string` containing a {{cssxref("pseudo-elements","pseudo-element")}} selector, such as `"::before"`. If present, the effect is applied to the selected pseudo-element of `target`, rather than to `target` itself.
The single argument constructor (see above) creates a clone of an existing {{domxref("KeyframeEffect")}} object instance. Its parameter is as follows:
- `sourceKeyFrames`
- : A {{domxref("KeyframeEffect")}} object that you want to clone.
## Examples
In the [Follow the White Rabbit example](https://codepen.io/rachelnabors/pen/eJyWzm/?editors=0010), the `KeyframeEffect` constructor is used to create a set of keyframes that dictate how the White Rabbit should animate down the hole:
```js
const whiteRabbit = document.getElementById("rabbit");
const rabbitDownKeyframes = new KeyframeEffect(
whiteRabbit, // element to animate
[
{ transform: "translateY(0%)" }, // keyframe
{ transform: "translateY(100%)" }, // keyframe
],
{ duration: 3000, fill: "forwards" }, // keyframe options
);
const rabbitDownAnimation = new Animation(
rabbitDownKeyframes,
document.timeline,
);
// Play rabbit animation
rabbitDownAnimation.play();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [KeyframeEffect Interface](/en-US/docs/Web/API/KeyframeEffect)
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- {{domxref("Animation")}}
| 0 |
data/mdn-content/files/en-us/web/api/keyframeeffect | data/mdn-content/files/en-us/web/api/keyframeeffect/pseudoelement/index.md | ---
title: "KeyframeEffect: pseudoElement property"
short-title: pseudoElement
slug: Web/API/KeyframeEffect/pseudoElement
page-type: web-api-instance-property
browser-compat: api.KeyframeEffect.pseudoElement
---
{{ APIRef("Web Animations") }}
The **`pseudoElement`** property of a {{domxref("KeyframeEffect")}} interface is a string representing the pseudo-element being animated. It may be `null` for animations that do not target a pseudo-element. It performs as both a getter and a setter, except with animations and transitions generated by CSS.
> **Note:** If set to the legacy single-colon syntax of {{cssxref("::before", ":before")}}, {{cssxref("::after", ":after")}}, {{cssxref("::first-letter", ":first-letter")}}, or {{cssxref("::first-line", ":first-line")}}, the string is transformed into its double-colon modern version ({{cssxref("::before")}}, {{cssxref("::after")}}, {{cssxref("::first-letter")}}, and {{cssxref("::first-line")}}, respectively).
## Value
A string or `null`.
## Exceptions
- `SyntaxError` {{domxref("DOMException")}}
- : Thrown when trying to set this property to an element, an invalid pseudo-element (either non-existent or misspelled). The property is then left unchanged.
## Examples
```html
<div id="text">Some text</div>
<pre id="log"></pre>
```
```css
#text::after {
content: "⭐";
display: inline-block; /* Needed as the `transform` property does not apply to inline elements */
}
#text::before {
content: "😊";
display: inline-block;
}
```
```js
const log = document.getElementById("log");
const text = document.getElementById("text");
// Create the keyframe and launch the animation
const animation = text.animate(
[
{ transform: "rotate(0)" },
{ transform: "rotate(180deg)" },
{ transform: "rotate(360deg)" },
],
{ duration: 3000, iterations: Infinity, pseudoElement: "::after" },
);
// Get the value of KeyframeEffect.pseudoElement
function logPseudoElement() {
const keyframeEffect = animation.effect;
log.textContent = `Value of pseudoElement animated: ${keyframeEffect.pseudoElement}`;
requestAnimationFrame(logPseudoElement);
}
// Every 6 seconds, switch the pseudo-element animated
function switchPseudoElement() {
const keyframeEffect = animation.effect;
keyframeEffect.pseudoElement =
keyframeEffect.pseudoElement === "::after" ? "::before" : "::after";
setTimeout(switchPseudoElement, 6000);
}
switchPseudoElement();
logPseudoElement();
```
{{EmbedLiveSample("Examples", "100", "70")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- {{domxref("KeyframeEffect")}} interface
- {{domxref("KeyframeEffect.KeyframeEffect", "KeyframeEffect()")}} constructor
- {{domxref("KeyframeEffect.target", "target")}} property
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/vrlayerinit/index.md | ---
title: VRLayerInit
slug: Web/API/VRLayerInit
page-type: web-api-interface
status:
- deprecated
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}
The **`VRLayerInit`** dictionary of the [WebVR API](/en-US/docs/Web/API/WebVR_API) represents a content layer (an {{domxref("HTMLCanvasElement")}} or {{domxref("OffscreenCanvas")}}) that you want to present in a VR display.
> **Note:** This dictionary was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/).
You can retrieve `VRLayerInit` objects using {{domxref("VRDisplay.getLayers()")}}, and present them using the {{domxref("VRDisplay.requestPresent()")}} method.
## Instance properties
- {{domxref("VRLayerInit.leftBounds")}} {{deprecated_inline}}
- : Defines the left texture bounds of the canvas whose contents will be presented by the {{domxref("VRDisplay")}}.
- {{domxref("VRLayerInit.rightBounds")}} {{deprecated_inline}}
- : Defines the right texture bounds of the canvas whose contents will be presented by the {{domxref("VRDisplay")}}.
- {{domxref("VRLayerInit.source")}} {{deprecated_inline}}
- : Defines the canvas whose contents will be presented by the {{domxref("VRDisplay")}} when {{domxref("VRDisplay.submitFrame()")}} is called.
## Examples
```js
// currently returns an empty array
let layers = vrDisplay.getLayers();
if (navigator.getVRDisplays) {
console.log("WebVR 1.1 supported");
// Then get the displays attached to the computer
navigator.getVRDisplays().then((displays) => {
// If a display is available, use it to present the scene
if (displays.length > 0) {
vrDisplay = displays[0];
console.log("Display found");
// Starting the presentation when the button is clicked: It can only be called in response to a user gesture
btn.addEventListener("click", () => {
vrDisplay.requestPresent([{ source: canvas }]).then(() => {
console.log("Presenting to WebVR display");
// Here it returns an array of VRLayerInit objects
layers = vrDisplay.getLayers();
// …
});
});
}
});
}
```
{{domxref("VRLayerInit")}} objects look something like this:
```js
{
leftBounds : [/* … */],
rightBounds: [/* … */],
source: canvasReference
}
```
> **Note:** The `canvasReference` refers to the {{htmlelement("canvas")}} element itself, not the WebGL context associated with the canvas. The other two members are arrays
## Specifications
This dictionary was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard.
Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/).
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vrlayerinit | data/mdn-content/files/en-us/web/api/vrlayerinit/source/index.md | ---
title: "VRLayerInit: source property"
short-title: source
slug: Web/API/VRLayerInit/source
page-type: web-api-instance-property
status:
- deprecated
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}
The **`source`** property of the {{domxref("VRLayerInit")}} interface (dictionary) defines the canvas whose contents will be presented by the {{domxref("VRDisplay")}}.
> **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/).
## Value
An {{domxref("HTMLCanvasElement")}} or {{domxref("OffscreenCanvas")}} object.
## Examples
See [`VRLayerInit`](/en-US/docs/Web/API/VRLayerInit#examples) for example code.
## Specifications
This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard.
Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/).
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vrlayerinit | data/mdn-content/files/en-us/web/api/vrlayerinit/leftbounds/index.md | ---
title: "VRLayerInit: leftBounds property"
short-title: leftBounds
slug: Web/API/VRLayerInit/leftBounds
page-type: web-api-instance-property
status:
- deprecated
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}
The **`leftBounds`** property of the {{domxref("VRLayerInit")}} interface (dictionary) defines the left texture bounds of the canvas whose contents will be presented by the {{domxref("VRDisplay")}}.
> **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/).
## Value
An array of four floating point values, which can take values from 0.0–1.0.
- The left offset of the bounds.
- The top offset of the bounds.
- The width of the bounds.
- The height of the bounds.
If `leftBounds` is not specified in the dictionary, the default value used is `[0.0, 0.0, 0.5, 1.0]`.
## Examples
See [`VRLayerInit`](/en-US/docs/Web/API/VRLayerInit#examples) for example code.
## Specifications
This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard.
Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/).
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vrlayerinit | data/mdn-content/files/en-us/web/api/vrlayerinit/rightbounds/index.md | ---
title: "VRLayerInit: rightBounds property"
short-title: rightBounds
slug: Web/API/VRLayerInit/rightBounds
page-type: web-api-instance-property
status:
- deprecated
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}
The **`rightBounds`** property of the {{domxref("VRLayerInit")}} interface (dictionary) defines the right texture bounds of the canvas whose contents will be presented by the {{domxref("VRDisplay")}}.
> **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/).
## Value
An array of four floating point values, which can take values from 0.0–1.0:
1. The left offset of the bounds.
2. The top offset of the bounds.
3. The width of the bounds.
4. The height of the bounds.
If `leftBounds` is not specified in the dictionary, the default value used is `[0.5, 0.0, 0.5, 1.0]`.
## Examples
See [`VRLayerInit`](/en-US/docs/Web/API/VRLayerInit#examples) for example code.
## Specifications
This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard.
Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/).
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediastream_image_capture_api/index.md | ---
title: MediaStream Image Capture API
slug: Web/API/MediaStream_Image_Capture_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.ImageCapture
---
{{DefaultAPISidebar("Image Capture API")}}{{SeeCompatTable}}
The **MediaStream Image Capture API** is an API for capturing images or videos from a photographic device. In addition to capturing data, it also allows you to retrieve information about device capabilities such as image size, red-eye reduction and whether or not there is a flash and what they are currently set to. Conversely, the API allows the capabilities to be configured within the constraints what the device allows.
## MediaStream image capture concepts and usage
The process of retrieving an image or video stream happens as described below. The example code is adapted from [Chrome's Image Capture examples](https://googlechrome.github.io/samples/image-capture/).
First, get a reference to a device by calling {{domxref("MediaDevices.getUserMedia()")}}. The example below says give me whatever video device is available, though the `getUserMedia()` method allows more specific capabilities to be requested. This method returns a {{jsxref("Promise")}} that resolves with a {{domxref("MediaStream")}} object.
```js
navigator.mediaDevices.getUserMedia({ video: true }).then((mediaStream) => {
// Do something with the stream.
});
```
Next, isolate the visual part of the media stream. Do this by calling {{domxref("MediaStream.getVideoTracks()")}}. This returns an array of {{domxref("MediaStreamTrack")}} objects. The code below assumes that the first item in the `MediaStreamTrack` array is the one to use. You can use the properties of the `MediaStreamTrack` objects to select the one you need.
```js
const track = mediaStream.getVideoTracks()[0];
```
At this point, you might want to configure the device capabilities before capturing an image. You can do this by calling {{domxref("MediaStreamTrack.applyConstraints","applyConstraints()")}} on the track object before doing anything else.
```js
let zoom = document.querySelector("#zoom");
const capabilities = track.getCapabilities();
// Check whether zoom is supported or not.
if (!capabilities.zoom) {
return;
}
track.applyConstraints({ advanced: [{ zoom: zoom.value }] });
```
Finally, pass the `MediaStreamTrack` object to the {{domxref("ImageCapture.ImageCapture()", "ImageCapture()")}} constructor. Though a `MediaStream` holds several types of tracks and provides multiple methods for retrieving them, the ImageCapture constructor will throw a {{domxref("DOMException")}} of type `NotSupportedError` if {{domxref("MediaStreamTrack.kind")}} is not `"video"`.
```js
let imageCapture = new ImageCapture(track);
```
## Interfaces
- {{domxref("ImageCapture")}} {{Experimental_Inline}}
- : An interface for capturing images from a photographic device referenced through a valid {{domxref("MediaStreamTrack")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaStream")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcdtmfsender/index.md | ---
title: RTCDTMFSender
slug: Web/API/RTCDTMFSender
page-type: web-api-interface
browser-compat: api.RTCDTMFSender
---
{{APIRef("WebRTC")}}
The **`RTCDTMFSender`** interface provides a mechanism for transmitting {{Glossary("DTMF")}} codes on a [WebRTC](/en-US/docs/Web/API/WebRTC_API) {{domxref("RTCPeerConnection")}}. You gain access to the connection's `RTCDTMFSender` through the {{domxref("RTCRtpSender.dtmf")}} property on the audio track you wish to send DTMF with.
The primary purpose for WebRTC's DTMF support is to allow WebRTC-based communication clients to be connected to a [public-switched telephone network (PSTN)](https://en.wikipedia.org/wiki/Public_switched_telephone_network) or other legacy telephone service, including extant voice over IP (VoIP) services. For that reason, DTMF can't be used between two WebRTC-based devices, because there is no mechanism provided by WebRTC for receiving DTMF codes.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("RTCDTMFSender.toneBuffer")}} {{ReadOnlyInline}}
- : A string which contains the list of DTMF tones currently in the queue to be transmitted (tones which have already been played are no longer included in the string). See {{domxref("RTCDTMFSender.toneBuffer", "toneBuffer")}} for details on the format of the tone buffer.
## Instance methods
- {{domxref("RTCDTMFSender.insertDTMF()")}}
- : Given a string describing a set of DTMF codes and, optionally, the duration of and inter-tone gap between the tones, `insertDTMF()` starts sending the specified tones. Calling `insertDTMF()` replaces any already-pending tones from the `toneBuffer`. You can abort sending queued tones by specifying an empty string (`""`) as the set of tones to play.
## Events
Listen to these events using {{domxref("EventTarget.addEventListener", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface.
- {{domxref("RTCDTMFSender.tonechange_event", "tonechange")}}
- : The `tonechange` event is sent to the `RTCDTMFSender` instance's event handler to indicate that a tone has either started or stopped playing.
## Example
See the article [Using DTMF with WebRTC](/en-US/docs/Web/API/WebRTC_API/Using_DTMF) for a full example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
- [Using DTMF with WebRTC](/en-US/docs/Web/API/WebRTC_API/Using_DTMF)
- {{domxref("RTCRtpSender.dtmf")}}
- {{domxref("RTCPeerConnection")}}
- {{domxref("RTCRtpSender")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcdtmfsender | data/mdn-content/files/en-us/web/api/rtcdtmfsender/tonechange_event/index.md | ---
title: "RTCDTMFSender: tonechange event"
short-title: tonechange
slug: Web/API/RTCDTMFSender/tonechange_event
page-type: web-api-event
browser-compat: api.RTCDTMFSender.tonechange_event
---
{{APIRef("WebRTC")}}
The **`tonechange`** event is sent to an {{domxref("RTCDTMFSender")}} by the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) to indicate when {{Glossary("DTMF")}} tones previously queued for sending (by calling {{domxref("RTCDTMFSender.insertDTMF()")}}) begin and end.
To determine what tone started playing, or if a tone stopped playing, check the value of the event's {{domxref("RTCDTMFToneChangeEvent.tone", "tone")}} property.
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("tonechange", (event) => {});
ontonechange = (event) => {};
```
## Event type
An {{domxref("RTCDTMFToneChangeEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("RTCDTMFToneChangeEvent")}}
## Event properties
_In addition to the properties of {{domxref("Event")}}, this interface offers the following:_
- {{domxref("RTCDTMFToneChangeEvent.tone")}} {{ReadOnlyInline}}
- : A string specifying the tone which has begun playing, or an empty string (`""`) if the previous tone has finished playing.
## Examples
This example establishes a handler for the `tonechange` event which updates an element to display the currently playing tone in its content, or, if all tones have played, the string "\<none>".
This can be done using {{domxref("EventTarget.addEventListener", "addEventListener()")}}:
```js
dtmfSender.addEventListener(
"tonechange",
(ev) => {
let tone = ev.tone;
if (tone === "") {
tone = "<none>";
}
document.getElementById("playingTone").innerText = tone;
},
false,
);
```
You can also just set the `ontonechange` event handler property directly:
```js
dtmfSender.ontonechange = (ev) => {
let tone = ev.tone;
if (tone === "") {
tone = "<none>";
}
document.getElementById("playingTone").innerText = tone;
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcdtmfsender | data/mdn-content/files/en-us/web/api/rtcdtmfsender/tonebuffer/index.md | ---
title: "RTCDTMFSender: toneBuffer property"
short-title: toneBuffer
slug: Web/API/RTCDTMFSender/toneBuffer
page-type: web-api-instance-property
browser-compat: api.RTCDTMFSender.toneBuffer
---
{{APIRef("WebRTC")}}
The {{domxref("RTCDTMFSender")}} interface's toneBuffer property returns a string
containing a list of the {{Glossary("DTMF")}} tones currently queued for sending to the
remote peer over the {{domxref("RTCPeerConnection")}}. To place tones into the buffer,
call {{domxref("RTCDTMFSender.insertDTMF", "insertDTMF()")}}.
Tones are removed from the string as they're played, so only upcoming tones are listed.
## Value
A string listing the tones to be played. If the string is empty,
there are no tones pending.
### Exceptions
- `InvalidCharacterError` {{domxref("DOMException")}}
- : Thrown if a character is not a DTMF tone character (0-9, A-D, # or ,).
### Tone buffer format
The tone buffer is a string which can contain any combination of the characters that
are permitted by the DTMF standard.
#### DTMF tone characters
- The digits 0-9
- : These characters represent the digit keys on a telephone keypad.
- The letters A-D
- : These characters represent the "A" through "D" keys which are part of the DTMF
standard but not included on most telephones. These are _not_ interpreted as
digits. Lower-case "a"-"d" automatically gets converted to upper-case.
- The pound/hash sign ("#") and the asterisk ("\*")
- : These correspond to the similarly-labeled keys which are typically on the bottom row
of the telephone keypad.
- The comma (",")
- : This character instructs the dialing process to pause for two seconds before sending
the next character in the buffer.
> **Note:** All other characters are unrecognized and will cause
> {{domxref("RTCDTMFSender.insertDTMF", "insertDTMF()")}} to throw an
> `InvalidCharacterError` {{domxref("DOMException")}}.
#### Using tone buffer strings
For example, if you're writing code to control a voicemail system by sending DTMF
codes, you might use a string such as "\*,1,5555". In this example, we would send "\*" to
request access to the VM system, then, after a pause, send a "1" to start playback of
voicemail messages, then after a pause, dial "5555" as a PIN number to open the
messages.
Setting the tone buffer to an empty string (`""`) cancels any pending DTMF
codes.
## Example
tbd
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
- [Using DTMF with WebRTC](/en-US/docs/Web/API/WebRTC_API/Using_DTMF)
- {{domxref("RTCDTMFSender.insertDTMF()")}}
- {{domxref("RTCPeerConnection")}}
- {{domxref("RTCDTMFSender")}}
- {{domxref("RTCRtpSender")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcdtmfsender | data/mdn-content/files/en-us/web/api/rtcdtmfsender/insertdtmf/index.md | ---
title: "RTCDTMFSender: insertDTMF() method"
short-title: insertDTMF()
slug: Web/API/RTCDTMFSender/insertDTMF
page-type: web-api-instance-method
browser-compat: api.RTCDTMFSender.insertDTMF
---
{{APIRef("WebRTC")}}
The **`insertDTMF()`** method on the {{domxref("RTCDTMFSender")}} interface
starts sending {{Glossary("DTMF")}} tones to the remote peer over the
{{domxref("RTCPeerConnection")}}.
Sending of the tones is performed asynchronously,
with [`tonechange`](/en-US/docs/Web/API/RTCDTMFSender/tonechange_event) events sent to the `RTCDTMFSender` every time
a tone starts or ends.
As long as the connection is active, you can send tones at any time. Calling
`insertDTMF()` replaces any already-pending tones from the `toneBuffer`.
You can abort sending queued tones by specifying an empty string (`""`) as the set of tones to play.
Since `insertDTMF()` replaces the tone buffer, in order to add to the DTMF tones being played, it is necessary to call
`insertDTMF` with a string containing both the remaining tones (stored in the `toneBuffer`) and the new tones appended together.
## Syntax
```js-nolint
insertDTMF(tones)
insertDTMF(tones, duration)
insertDTMF(tones, duration, interToneGap)
```
### Parameters
- `tones`
- : A string containing the DTMF codes to be transmitted to the
recipient. Specifying an empty string as the `tones` parameter clears the
tone buffer, aborting any currently queued tones. A "," character inserts a two second
delay.
- `duration` {{optional_inline}}
- : The amount of time, in milliseconds, that each DTMF tone should last. This value
must be between 40 ms and 6000 ms (6 seconds), inclusive. The default is 100 ms.
- `interToneGap` {{optional_inline}}
- : The length of time, in milliseconds, to wait between tones. The browser will enforce
a minimum value of 30 ms (that is, if you specify a lower value, 30 ms will be used
instead); the default is 70 ms.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the DTMF tones couldn't be sent because the track has been stopped or is in a
read-only or inactive state.
- `InvalidCharacterError` {{domxref("DOMException")}}
- : Thrown if one or more of the characters in `tones` is not valid DTMF (0-9, A-Z, # or ,).
## Examples
tbd
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
- [Using DTMF with WebRTC](/en-US/docs/Web/API/WebRTC_API/Using_DTMF)
- {{domxref("RTCPeerConnection")}}
- {{domxref("RTCDTMFSender")}}
- {{domxref("RTCRtpSender")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssmathnegate/index.md | ---
title: CSSMathNegate
slug: Web/API/CSSMathNegate
page-type: web-api-interface
browser-compat: api.CSSMathNegate
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSMathNegate`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} negates the value passed into it. It inherits properties and methods from its parent {{domxref('CSSNumericValue')}}.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CSSMathNegate.CSSMathNegate", "CSSMathNegate()")}}
- : Creates a new `CSSMathNegate` object.
## Instance properties
- {{domxref('CSSMathNegate.value')}} {{ReadOnlyInline}}
- : Returns a {{domxref('CSSNumericValue')}} object.
## Static methods
_The interface may also inherit methods from its parent interface, {{domxref("CSSMathValue")}}._
## Instance methods
_The interface may also inherit methods from its parent interface, {{domxref("CSSMathValue")}}._
## Examples
To do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssmathnegate | data/mdn-content/files/en-us/web/api/cssmathnegate/cssmathnegate/index.md | ---
title: "CSSMathNegate: CSSMathNegate() constructor"
short-title: CSSMathNegate()
slug: Web/API/CSSMathNegate/CSSMathNegate
page-type: web-api-constructor
browser-compat: api.CSSMathNegate.CSSMathNegate
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSMathNegate()`** constructor creates a
new {{domxref("CSSMathNegate")}} object which negates the value passed into it.
## Syntax
```js-nolint
new CSSMathNegate(arg)
```
### Parameters
- `arg`
- : A {{domxref('CSSNumericValue')}}.
## Examples
To do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssmathnegate | data/mdn-content/files/en-us/web/api/cssmathnegate/value/index.md | ---
title: "CSSMathNegate: value property"
short-title: value
slug: Web/API/CSSMathNegate/value
page-type: web-api-instance-property
browser-compat: api.CSSMathNegate.value
---
{{APIRef("CSS Typed Object Model API")}}
The CSSMathNegate.value read-only property of the
{{domxref("CSSMathNegate")}} interface returns a {{domxref('CSSNumericValue')}} object.
## Value
A {{domxref('CSSNumericValue')}}.
## 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/htmlformelement/index.md | ---
title: HTMLFormElement
slug: Web/API/HTMLFormElement
page-type: web-api-interface
browser-compat: api.HTMLFormElement
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement`** interface represents a {{HTMLElement("form")}} element in the DOM. It allows access to—and, in some cases, modification of—aspects of the form, as well as access to its component elements.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLFormElement.elements")}} {{ReadOnlyInline}}
- : A {{domxref("HTMLFormControlsCollection")}} holding all form controls belonging to this form element.
- {{domxref("HTMLFormElement.length")}} {{ReadOnlyInline}}
- : A `long` reflecting the number of controls in the form.
- {{domxref("HTMLFormElement.name")}}
- : A string reflecting the value of the form's [`name`](/en-US/docs/Web/HTML/Element/form#name) HTML attribute, containing the name of the form.
- {{domxref("HTMLFormElement.method")}}
- : A string reflecting the value of the form's [`method`](/en-US/docs/Web/HTML/Element/form#method) HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set.
- {{domxref("HTMLFormElement.target")}}
- : A string reflecting the value of the form's [`target`](/en-US/docs/Web/HTML/Element/form#target) HTML attribute, indicating where to display the results received from submitting the form.
- {{domxref("HTMLFormElement.action")}}
- : A string reflecting the value of the form's [`action`](/en-US/docs/Web/HTML/Element/form#action) HTML attribute, containing the URI of a program that processes the information submitted by the form.
- {{domxref("HTMLFormElement.encoding")}} or {{domxref("HTMLFormElement.enctype")}}
- : A string reflecting the value of the form's [`enctype`](/en-US/docs/Web/HTML/Element/form#enctype) HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two properties are synonyms.
- {{domxref("HTMLFormElement.acceptCharset")}}
- : A string reflecting the value of the form's [`accept-charset`](/en-US/docs/Web/HTML/Element/form#accept-charset) HTML attribute, representing the character encoding that the server accepts.
- {{domxref("HTMLFormElement.autocomplete")}}
- : A string reflecting the value of the form's [`autocomplete`](/en-US/docs/Web/HTML/Element/form#autocomplete) HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser.
- {{domxref("HTMLFormElement.noValidate")}}
- : A boolean value reflecting the value of the form's [`novalidate`](/en-US/docs/Web/HTML/Element/form#novalidate) HTML attribute, indicating whether the form should not be validated.
Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (e.g. a form with an input named `action` will have its `action` property return that input instead of the form's [`action`](/en-US/docs/Web/HTML/Element/form#action) HTML attribute).
## Instance methods
_This interface also inherits methods from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLFormElement.checkValidity", "checkValidity()")}}
- : Returns `true` if the element's child controls are subject to [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) and satisfy those constraints; returns `false` if some controls do not satisfy their constraints. Fires an event named {{domxref("HTMLInputElement/invalid_event", "invalid")}} at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to `false`.
- {{domxref("HTMLFormElement.reportValidity", "reportValidity()")}}
- : Returns `true` if the element's child controls satisfy their [validation constraints](/en-US/docs/Web/HTML/Constraint_validation). When `false` is returned, cancelable {{domxref("HTMLInputElement/invalid_event", "invalid")}} events are fired for each invalid child and validation problems are reported to the user.
- {{domxref("HTMLFormElement.requestSubmit", "requestSubmit()")}}
- : Requests that the form be submitted using the specified submit button and its corresponding configuration.
- {{domxref("HTMLFormElement.reset", "reset()")}}
- : Resets the form to its initial state.
- {{domxref("HTMLFormElement.submit", "submit()")}}
- : Submits the form to the server.
### Deprecated methods
- {{domxref("HTMLFormElement.requestAutocomplete()")}} {{deprecated_inline}}
- : Triggers a native browser interface to assist the user in completing the fields which have an [autofill field name](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill-field-name) value that is not `off` or `on`. The form will receive an event once the user has finished with the interface, the event will either be `autocomplete` when the fields have been filled or `autocompleteerror` when there was a problem.
## Events
Listen to these events using `addEventListener()`, or by assigning an event listener to the `oneventname` property of this interface.
- {{domxref("HTMLFormElement/formdata_event", "formdata")}}
- : The `formdata` event fires after the entry list representing the form's data is constructed.
- {{domxref("HTMLFormElement/reset_event", "reset")}}
- : The `reset` event fires when a form is reset.
- {{domxref("HTMLFormElement/submit_event", "submit")}}
- : The `submit` event fires when a form is submitted.
## Usage notes
### Obtaining a form element object
To obtain an `HTMLFormElement` object, you can use a [CSS selector](/en-US/docs/Web/CSS/CSS_selectors) with {{domxref("Document.querySelector", "querySelector()")}}, or you can get a list of all of the forms in the document using its {{domxref("Document.forms", "forms")}} property.
{{domxref("Document.forms")}} returns an array of `HTMLFormElement` objects listing each of the forms on the page. You can then use any of the following syntaxes to get an individual form:
- `document.forms[index]`
- : Returns the form at the specified `index` into the array of forms.
- `document.forms[id]`
- : Returns the form whose ID is `id`.
- `document.forms[name]`
- : Returns the form whose `name` attribute's value is `name`.
### Accessing the form's elements
You can access the list of the form's data-containing elements by examining the form's {{domxref("HTMLFormElement.elements", "elements")}} property. This returns an {{domxref("HTMLFormControlsCollection")}} listing all of the form's user data entry elements, both those which are descendants of the `<form>` and those which are made members of the form using their `form` attributes.
You can also get the form's element by using its `name` attribute as a key of the `form`, but using `elements` is a better approach—it contains _only_ the form's elements, and it cannot be mixed with other attributes of the `form`.
### Issues with Naming Elements
Some names will interfere with JavaScript access to the form's properties and elements.
For example:
- `<input name="id">` will take precedence over `<form id="…">`. This means that `form.id` will not refer to the form's id, but to the element whose name is "`id`". This will be the case with any other form properties, such as `<input name="action">` or `<input name="post">`.
- `<input name="elements">` will render the form's `elements` collection inaccessible. The reference `form.elements` will now refer to the individual element.
To avoid such problems with element names:
- _Always_ use the `elements` collection to avoid ambiguity between an element name and a form property.
- _Never_ use "`elements`" as an element name.
If you are not using JavaScript, this will not cause a problem.
### Elements that are considered form controls
The elements included by `HTMLFormElement.elements` and `HTMLFormElement.length` are the following:
- {{HTMLElement("button")}}
- {{HTMLElement("fieldset")}}
- {{HTMLElement("input")}} (with the exception that any whose [`type`](/en-US/docs/Web/HTML/Element/input#type) is `"image"` are omitted for historical reasons)
- {{HTMLElement("object")}}
- {{HTMLElement("output")}}
- {{HTMLElement("select")}}
- {{HTMLElement("textarea")}}
No other elements are included in the list returned by `elements`, which makes it an excellent way to get at the elements most important when processing forms.
## Examples
Creating a new form element, modifying its attributes, then submitting it:
```js
const f = document.createElement("form"); // Create a form
document.body.appendChild(f); // Add it to the document body
f.action = "/cgi-bin/some.cgi"; // Add action and method attributes
f.method = "POST";
f.submit(); // Call the form's submit() method
```
Extract information from a `<form>` element and set some of its attributes:
```html
<form name="formA" action="/cgi-bin/test" method="post">
<p>Press "Info" for form details, or "Set" to change those details.</p>
<p>
<button type="button" onclick="getFormInfo();">Info</button>
<button type="button" onclick="setFormInfo(this.form);">Set</button>
<button type="reset">Reset</button>
</p>
<textarea id="form-info" rows="15" cols="20"></textarea>
</form>
<script>
function getFormInfo() {
// Get a reference to the form via its name
const f = document.forms["formA"];
// The form properties we're interested in
const properties = [
"elements",
"length",
"name",
"charset",
"action",
"acceptCharset",
"action",
"enctype",
"method",
"target",
];
// Iterate over the properties, turning them into a string that we can display to the user
const info = properties
.map((property) => `${property}: ${f[property]}`)
.join("\n");
// Set the form's <textarea> to display the form's properties
document.forms["formA"].elements["form-info"].value = info; // document.forms["formA"]['form-info'].value would also work
}
function setFormInfo(f) {
// Argument should be a form element reference.
f.action = "a-different-url.cgi";
f.name = "a-different-name";
}
</script>
```
Submit a `<form>` into a new window:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Example new-window form submission</title>
</head>
<body>
<form action="test.php" target="_blank">
<p>
<label>First name: <input type="text" name="firstname" /></label>
</p>
<p>
<label>Last name: <input type="text" name="lastname" /></label>
</p>
<p>
<label><input type="password" name="pwd" /></label>
</p>
<fieldset>
<legend>Pet preference</legend>
<p>
<label><input type="radio" name="pet" value="cat" /> Cat</label>
</p>
<p>
<label><input type="radio" name="pet" value="dog" /> Dog</label>
</p>
</fieldset>
<fieldset>
<legend>Owned vehicles</legend>
<p>
<label
><input type="checkbox" name="vehicle" value="Bike" />I have a
bike</label
>
</p>
<p>
<label
><input type="checkbox" name="vehicle" value="Car" />I have a
car</label
>
</p>
</fieldset>
<p><button>Submit</button></p>
</form>
</body>
</html>
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{HTMLElement("form")}}.
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/formdata_event/index.md | ---
title: "HTMLFormElement: formdata event"
short-title: formdata
slug: Web/API/HTMLFormElement/formdata_event
page-type: web-api-event
browser-compat: api.HTMLFormElement.formdata_event
---
{{APIRef}}
The **`formdata`** event fires after the entry list representing the form's data is constructed. This happens when the form is submitted, but can also be triggered by the invocation of a {{domxref("FormData.FormData", "FormData()")}} constructor.
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("formdata", (event) => {});
onformdata = (event) => {};
```
## Event type
A {{domxref("FormDataEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("FormDataEvent")}}
## Event properties
_Inherits properties from its parent interface, {{domxref("Event")}}._
- {{domxref("FormDataEvent.formData")}}
- : Contains the {{domxref("FormData")}} object representing the data contained in the form when the event was fired.
## Examples
```js
// grab reference to form
const formElem = document.querySelector("form");
// submit handler
formElem.addEventListener("submit", (e) => {
// on form submission, prevent default
e.preventDefault();
console.log(formElem.querySelector('input[name="field1"]')); // FOO
console.log(formElem.querySelector('input[name="field2"]')); // BAR
// construct a FormData object, which fires the formdata event
const formData = new FormData(formElem);
// formdata gets modified by the formdata event
console.log(formData.get("field1")); // foo
console.log(formData.get("field2")); // bar
});
// formdata handler to retrieve data
formElem.addEventListener("formdata", (e) => {
console.log("formdata fired");
// modifies the form data
const formData = e.formData;
// formdata gets modified by the formdata event
formData.set("field1", formData.get("field1").toLowerCase());
formData.set("field2", formData.get("field2").toLowerCase());
});
```
The `onformdata` version would look like this:
```js
formElem.onformdata = (e) => {
console.log("formdata fired");
// modifies the form data
const formData = e.formData;
formData.set("field1", formData.get("field1").toLowerCase());
formData.set("field2", formData.get("field2").toLowerCase());
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- HTML {{htmlElement("form")}} element
- {{domxref("FormDataEvent")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/name/index.md | ---
title: "HTMLFormElement: name property"
short-title: name
slug: Web/API/HTMLFormElement/name
page-type: web-api-instance-property
browser-compat: api.HTMLFormElement.name
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement.name`** property represents the name of
the current {{HtmlElement("form")}} element as a string.
If your {{HTMLElement("Form")}} element contains an element named _name_ then
that element overrides the `form.name` property, so that you can't access it.
## Value
A string.
## Examples
```js
const form1name = document.getElementById("form1").name;
if (form1name !== document.form.form1) {
// Browser doesn't support this form of reference
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/elements/index.md | ---
title: "HTMLFormElement: elements property"
short-title: elements
slug: Web/API/HTMLFormElement/elements
page-type: web-api-instance-property
browser-compat: api.HTMLFormElement.elements
---
{{APIRef("HTML DOM")}}
The {{domxref("HTMLFormElement")}} property
**`elements`** returns an
{{domxref("HTMLFormControlsCollection")}} listing all the form controls contained in
the {{HTMLElement("form")}} element.
Independently, you can obtain just the
number of form controls using the {{domxref("HTMLFormElement.length", "length")}}
property.
You can access a particular form control in the returned collection by using either an
index or the element's `name` or `id` attributes.
Prior to HTML 5, the returned object was an {{domxref("HTMLCollection")}}, on which
`HTMLFormControlsCollection` is based.
> **Note:** Similarly, you can get a list of all of the forms contained within a given document using the document's {{domxref("Document.forms", "forms")}} property.
## Value
An {{domxref("HTMLFormControlsCollection")}} containing all non-image controls in the form.
This is a live collection; if form controls are added to or removed from the form, this collection will update to reflect the change.
The form controls in the returned collection are in the same order in which they appear in the form by following a preorder, depth-first traversal of the tree.
This is called **tree order**.
Only the following elements are returned:
- {{HTMLElement("button")}}
- {{HTMLElement("fieldset")}}
- {{HTMLElement("input")}} (with the exception that any whose [`type`](/en-US/docs/Web/HTML/Element/input#type) is `"image"` are omitted for historical reasons)
- {{HTMLElement("object")}}
- {{HTMLElement("output")}}
- {{HTMLElement("select")}}
- {{HTMLElement("textarea")}}
## Examples
### Quick syntax example
In this example, we see how to obtain the list of form controls as well as how to access its members by index and by name or ID.
```html
<form id="my-form">
<label>
Username:
<input type="text" name="username" />
</label>
<label>
Full name:
<input type="text" name="full-name" />
</label>
<label>
Password:
<input type="password" name="password" />
</label>
</form>
```
```js
const inputs = document.getElementById("my-form").elements;
const inputByIndex = inputs[0];
const inputByName = inputs["username"];
```
### Accessing form controls
This example gets the form's element list, then iterates over the list, looking for
{{HTMLElement("input")}} elements of type
[`"text"`](/en-US/docs/Web/HTML/Element/input/text) so that some
form of processing can be performed on them.
```js
const inputs = document.getElementById("my-form").elements;
// Iterate over the form controls
for (let i = 0; i < inputs.length; i++) {
if (inputs[i].nodeName === "INPUT" && inputs[i].type === "text") {
// Update text input
inputs[i].value.toLocaleUpperCase();
}
}
```
### Disabling form controls
```js
const inputs = document.getElementById("my-form").elements;
// Iterate over the form controls
for (let i = 0; i < inputs.length; i++) {
// Disable all form controls
inputs[i].setAttribute("disabled", "");
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/acceptcharset/index.md | ---
title: "HTMLFormElement: acceptCharset property"
short-title: acceptCharset
slug: Web/API/HTMLFormElement/acceptCharset
page-type: web-api-instance-property
browser-compat: api.HTMLFormElement.acceptCharset
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement.acceptCharset`** property represents a
list of the supported [character encodings](/en-US/docs/Glossary/Character_encoding) for the given {{htmlelement("form")}} element. This list can be
comma-separated or space-separated.
## Value
A string.
## Examples
```js
let inputs = document.forms["myform"].acceptCharset;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/method/index.md | ---
title: "HTMLFormElement: method property"
short-title: method
slug: Web/API/HTMLFormElement/method
page-type: web-api-instance-property
browser-compat: api.HTMLFormElement.method
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement.method`** property represents the
{{Glossary("HTTP")}} method used to submit the {{HtmlElement("form")}}.
Unless explicitly specified, the default method is 'get'.
## Value
A string.
## Examples
```js
document.forms["myform"].method = "post";
const formElement = document.createElement("form"); // Create a form
document.body.appendChild(formElement);
console.log(formElement.method); // 'get'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/requestsubmit/index.md | ---
title: "HTMLFormElement: requestSubmit() method"
short-title: requestSubmit()
slug: Web/API/HTMLFormElement/requestSubmit
page-type: web-api-instance-method
browser-compat: api.HTMLFormElement.requestSubmit
---
{{APIRef("HTML DOM")}}
The {{domxref("HTMLFormElement")}} method **`requestSubmit()`** requests
that the form be submitted using a specific submit button.
## Syntax
```js-nolint
requestSubmit()
requestSubmit(submitter)
```
### Parameters
- `submitter` {{optional_inline}}
- : A {{Glossary("submit button")}} that is a member of the form.
If the `submitter` specifies `form*` attributes, they [will override](/en-US/docs/Glossary/Submit_button#overriding_the_forms_behavior) the form's submission behavior (e.g. `formmethod="POST"`).
If the `submitter` has a `name` attribute or is an `{{HtmlElement('input/image', '<input type="image">')}}`, its data [will be included](/en-US/docs/Glossary/Submit_button#form_data_entries) in the form submission (e.g. `btnName=btnValue`).
If you omit the `submitter` parameter, the form element itself is used as the submitter.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the specified `submitter` is not a {{Glossary("submit button")}}.
- `NotFoundError` {{domxref("DOMException")}}
- : Thrown if the specified `submitter` isn't a member of the form on
which `requestSubmit()` was called. The submitter must be either a
descendant of the form element or must have a [`form`](/en-US/docs/Web/HTML/Element/input#form)
attribute referring to the form.
## Usage notes
The obvious question is: Why does this method exist, when we've had the
{{domxref("HTMLFormElement.submit", "submit()")}} method since the dawn of time?
The answer is simple. `submit()` submits the form, but that's all it
does. `requestSubmit()`, on the other hand, acts as if a submit button were
clicked. The form's content is validated, and the form is submitted only if validation
succeeds. Once the form has been submitted, the
{{domxref("HTMLFormElement.submit_event", "submit")}} event is sent back to the form
object.
## Examples
In the example below, the form is submitted by attempting to send the request using
`requestSubmit()` if it's available. If a submit button with the
ID `main-submit` is found, that's used to submit the form. Otherwise, the
form is submitted with no `submitter` parameter, so it's submitted directly
by the form itself.
If, on the other hand, `requestSubmit()` isn't available, this code falls
back to calling the form's {{domxref("HTMLFormElement.submit", "submit()")}} method.
```js
let myForm = document.querySelector("form");
let submitButton = myForm.querySelector("#main-submit");
if (myForm.requestSubmit) {
if (submitButton) {
myForm.requestSubmit(submitButton);
} else {
myForm.requestSubmit();
}
} else {
myForm.submit();
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/target/index.md | ---
title: "HTMLFormElement: target property"
short-title: target
slug: Web/API/HTMLFormElement/target
page-type: web-api-instance-property
browser-compat: api.HTMLFormElement.target
---
{{APIRef("HTML DOM")}}
The **`target`** property of the {{domxref("HTMLFormElement")}}
interface represents the target of the form's action (i.e., the frame in which to render
its output).
## Value
A string.
## Examples
```js
myForm.target = document.frames[1].name;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/submit_event/index.md | ---
title: "HTMLFormElement: submit event"
short-title: submit
slug: Web/API/HTMLFormElement/submit_event
page-type: web-api-event
browser-compat: api.HTMLFormElement.submit_event
---
{{APIRef}}
The **`submit`** event fires when a {{HtmlElement("form")}} is submitted.
Note that the `submit` event fires on the `<form>` element itself, and not on any {{HtmlElement("button")}} or `{{HtmlElement('input/submit', '<input type="submit">')}}` inside it. However, the {{domxref("SubmitEvent")}} which is sent to indicate the form's submit action has been triggered includes a {{domxref("SubmitEvent.submitter", "submitter")}} property, which is the button that was invoked to trigger the submit request.
The `submit` event fires when:
- the user clicks a {{Glossary("submit button")}},
- the user presses <kbd>Enter</kbd> while editing a field (e.g. {{HtmlElement('input/text', '<input type="text">')}}) in a form,
- a script calls the {{domxref("HTMLFormElement.requestSubmit()", "form.requestSubmit()")}} method
However, the event is _not_ sent to the form when a script calls the {{domxref("HTMLFormElement.submit()", "form.submit()")}} method directly.
> **Note:** Trying to submit a form that does not pass [validation](/en-US/docs/Learn/Forms/Form_validation) triggers an {{domxref("HTMLInputElement/invalid_event", "invalid")}} event. In this case, the validation prevents form submission, and thus there is no `submit` event.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("submit", (event) => {});
onsubmit = (event) => {};
```
## Event type
A {{domxref("SubmitEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("SubmitEvent")}}
## Event properties
_In addition to the properties listed below, this interface inherits the properties of its parent interface, {{domxref("Event")}}._
- {{domxref("SubmitEvent.submitter", "submitter")}} {{ReadOnlyInline}}
- : An {{domxref("HTMLElement")}} object which identifies the button or other element which was invoked to trigger the form being submitted.
## Examples
This example uses {{domxref("EventTarget.addEventListener()")}} to listen for form submit, and logs the current {{domxref("Event.timeStamp")}} whenever that occurs, then prevents the default action of submitting the form.
### HTML
```html
<form id="form">
<label>Test field: <input type="text" /></label>
<br /><br />
<button type="submit">Submit form</button>
</form>
<p id="log"></p>
```
### JavaScript
```js
function logSubmit(event) {
log.textContent = `Form Submitted! Timestamp: ${event.timeStamp}`;
event.preventDefault();
}
const form = document.getElementById("form");
const log = document.getElementById("log");
form.addEventListener("submit", logSubmit);
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- HTML {{HtmlElement("form")}} element
- Related event: {{domxref("HTMLInputElement/invalid_event", "invalid")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/length/index.md | ---
title: "HTMLFormElement: length property"
short-title: length
slug: Web/API/HTMLFormElement/length
page-type: web-api-instance-property
browser-compat: api.HTMLFormElement.length
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement.length`**
read-only property returns the number of controls in the {{HTMLElement("form")}}
element.
You can access the list of the form's controls using the
{{domxref("HTMLFormElement.elements", "elements")}} property.
This includes both elements that are descendants of the `<form>`
element as well as elements that are made members of the form using their
`form` property.
Elements that are considered for this property are: {{HTMLElement("button")}},
{{HTMLElement("fieldset")}}, {{HTMLElement("input")}} (with the exception
that any whose type is "image" are omitted for historical reasons),
{{HTMLElement("object")}}, {{HTMLElement("output")}}, {{HTMLElement("select")}},
and {{HTMLElement("textarea")}}.
## Value
A number.
## Examples
```js
if (document.getElementById("form1").length > 1) {
// more than one form control here
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/action/index.md | ---
title: "HTMLFormElement: action property"
short-title: action
slug: Web/API/HTMLFormElement/action
page-type: web-api-instance-property
browser-compat: api.HTMLFormElement.action
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement.action`** property represents the action
of the {{HTMLElement("form")}} element.
The action of a form is the program that is executed on the server when the form is
submitted. This property can be retrieved or set.
## Value
A string.
## Examples
```js
form.action = "/cgi-bin/publish";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/encoding/index.md | ---
title: "HTMLFormElement: encoding property"
short-title: encoding
slug: Web/API/HTMLFormElement/encoding
page-type: web-api-instance-property
browser-compat: api.HTMLFormElement.encoding
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement.encoding`** property is an alternative name for the {{domxref("HTMLFormElement.enctype","enctype")}} element on the DOM {{domxref("HTMLFormElement")}} object.
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/enctype/index.md | ---
title: "HTMLFormElement: enctype property"
short-title: enctype
slug: Web/API/HTMLFormElement/enctype
page-type: web-api-instance-property
browser-compat: api.HTMLFormElement.enctype
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement.enctype`** property is the [MIME type](https://en.wikipedia.org/wiki/Mime_type) of content that is used
to submit the form to the server. Possible values are:
- `application/x-www-form-urlencoded`: The initial default type.
- `multipart/form-data`: The type that allows file {{HTMLElement("input")}}
element(s) to upload file data.
- `text/plain`: Ambiguous format, human-readable content not reliably interpretable by computer.
This value can be overridden by a [`formenctype`](/en-US/docs/Web/HTML/Element/button#formenctype) attribute
on a {{HTMLElement("button")}} or {{HTMLElement("input")}} element.
## Value
A string.
## Examples
```js
form.enctype = "application/x-www-form-urlencoded";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/reset/index.md | ---
title: "HTMLFormElement: reset() method"
short-title: reset()
slug: Web/API/HTMLFormElement/reset
page-type: web-api-instance-method
browser-compat: api.HTMLFormElement.reset
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement.reset()`** method restores a form
element's default values. This method does the same thing as clicking the form's
[`<input type="reset">`](/en-US/docs/Web/HTML/Element/input/reset) control.
If a form control (such as a reset button) has a name or id of _reset_ it will
mask the form's reset method. It does not reset other attributes in the input, such as
`disabled`.
Note that if {{domxref("Element.setAttribute", "setAttribute()")}} is called to set
the value of a particular attribute, a subsequent call to `reset()` won't
reset the attribute to its default value, but instead will keep the attribute at
whatever value the {{domxref("Element.setAttribute", "setAttribute()")}} call set it to.
## Syntax
```js-nolint
reset()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
document.getElementById("myform").reset();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/reset_event/index.md | ---
title: "HTMLFormElement: reset event"
short-title: reset
slug: Web/API/HTMLFormElement/reset_event
page-type: web-api-event
browser-compat: api.HTMLFormElement.reset_event
---
{{APIRef}}
The **`reset`** event fires when a {{HTMLElement("form")}} is reset.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("reset", (event) => {});
onreset = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
This example uses {{domxref("EventTarget.addEventListener()")}} to listen for form resets, and logs the current {{domxref("Event.timeStamp")}} whenever that occurs.
### HTML
```html
<form id="form">
<label>Test field: <input type="text" /></label>
<br /><br />
<button type="reset">Reset form</button>
</form>
<p id="log"></p>
```
### JavaScript
```js
function logReset(event) {
log.textContent = `Form reset! Timestamp: ${event.timeStamp}`;
}
const form = document.getElementById("form");
const log = document.getElementById("log");
form.addEventListener("reset", logReset);
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- HTML {{HTMLElement("form")}} element
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/submit/index.md | ---
title: "HTMLFormElement: submit() method"
short-title: submit()
slug: Web/API/HTMLFormElement/submit
page-type: web-api-instance-method
browser-compat: api.HTMLFormElement.submit
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement.submit()`** method submits a given
{{HtmlElement("form")}}.
This method is similar, but not identical to, activating a form's submit
{{HtmlElement("button")}}. When invoking this method directly, however:
- No {{domxref("HTMLFormElement/submit_event", "submit")}} event is raised. In particular, the form's `onsubmit` event handler is not run.
- [Constraint validation](/en-US/docs/Web/HTML/Constraint_validation) is not triggered.
The {{domxref("HTMLFormElement.requestSubmit()")}} method is identical to activating a
form's submit {{HtmlElement("button")}} and does not have these differences.
A form control (such as a submit button) with a `name` or `id` of `submit` will mask the form's `submit` method. Trying to call `myForm.submit();` throws an error "submit is not a function" because in this case `submit` refers to the form control which has a `name` or `id` of `submit`.
{{HtmlElement("input")}} with attribute type="submit" will not be submitted with the
form when using **`HTMLFormElement.submit()`**, but it would be
submitted when you do it with original HTML form submit.
## Syntax
```js-nolint
submit()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
document.forms["myform"].submit();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlformelement | data/mdn-content/files/en-us/web/api/htmlformelement/reportvalidity/index.md | ---
title: "HTMLFormElement: reportValidity() method"
short-title: reportValidity()
slug: Web/API/HTMLFormElement/reportValidity
page-type: web-api-instance-method
browser-compat: api.HTMLFormElement.reportValidity
---
{{APIRef("HTML DOM")}}
The **`HTMLFormElement.reportValidity()`** method returns
`true` if the element's child controls satisfy their validation constraints.
When `false` is returned, cancelable
[`invalid`](/en-US/docs/Web/API/HTMLInputElement/invalid_event) events are fired for
each invalid child and validation problems are reported to the user.
## Syntax
```js-nolint
reportValidity()
```
### Return value
`true` or `false`
## Example
```js
document.forms["myform"].addEventListener(
"submit",
() => {
document.forms["myform"].reportValidity();
},
false,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/server-sent_events/index.md | ---
title: Server-sent events
slug: Web/API/Server-sent_events
page-type: web-api-overview
spec-urls: https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
---
{{DefaultAPISidebar("Server Sent Events")}}
Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as _[Events](/en-US/docs/Web/API/Event) + data_ inside the web page.
{{AvailableInWorkers}}
> **Note:** Firefox does not currently support the use of server-sent events in service workers (it does support them in dedicated and shared workers). See [Firefox bug 1681218](https://bugzil.la/1681218).
## Concepts and usage
To learn how to use server-sent events, see our article [Using server-sent events](/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events).
## Interfaces
- {{domxref("EventSource")}}
- : Defines all the features that handle connecting to a server, receiving events/data, errors, closing a connection, etc.
## Examples
- [Simple SSE demo using PHP](https://github.com/mdn/dom-examples/tree/main/server-sent-events)
## Specifications
{{Specifications}}
## See also
### Tools
- [Mercure: a real-time communication protocol (publish-subscribe) built on top of SSE](https://mercure.rocks)
- [EventSource polyfill for Node.js](https://github.com/EventSource/eventsource)
- Remy Sharp's [EventSource polyfill](https://github.com/remy/polyfills/blob/master/EventSource.js)
- Yaffle's [EventSource polyfill](https://github.com/Yaffle/EventSource)
- Rick Waldron's [jquery plugin](https://github.com/rwaldron/jquery.eventsource)
- intercooler.js [declarative SSE support](https://intercoolerjs.org/docs.html#sse)
### Related Topics
- [Fetching data from the server](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data)
- [JavaScript](/en-US/docs/Web/JavaScript)
- [WebSockets](/en-US/docs/Web/API/WebSockets_API)
### Other resources
- [Creating a wall/feed social application](https://hacks.mozilla.org/2011/06/a-wall-powered-by-eventsource-and-server-sent-events/) powered by server-sent events and [its code on GitHub](https://github.com/mozilla/webowonder-demos/tree/master/demos/friends%20timeline).
| 0 |
data/mdn-content/files/en-us/web/api/server-sent_events | data/mdn-content/files/en-us/web/api/server-sent_events/using_server-sent_events/index.md | ---
title: Using server-sent events
slug: Web/API/Server-sent_events/Using_server-sent_events
page-type: guide
browser-compat: api.EventSource
---
{{DefaultAPISidebar("Server Sent Events")}}
Developing a web application that uses [server-sent events](/en-US/docs/Web/API/Server-sent_events) is straightforward. You'll need a bit of code on the server to stream events to the front-end, but the client side code works almost identically to [websockets](/en-US/docs/Web/API/WebSockets_API) in part of handling incoming events. This is a one-way connection, so you can't send events from a client to a server.
## Receiving events from the server
The server-sent event API is contained in the {{domxref("EventSource")}} interface.
### Creating an `EventSource` instance
To open a connection to the server to begin receiving events from it, create a new `EventSource` object with the URL of a script that generates the events. For example:
```js
const evtSource = new EventSource("ssedemo.php");
```
If the event generator script is hosted on a different origin, a new `EventSource` object should be created with both the URL and an options dictionary. For example, assuming the client script is on `example.com`:
```js
const evtSource = new EventSource("//api.example.com/ssedemo.php", {
withCredentials: true,
});
```
### Listening for `message` events
Messages sent from the server that don't have an [`event`](#event) field are received as `message` events. To receive message events, attach a handler for the {{domxref("EventSource.message_event", "message")}} event:
```js
evtSource.onmessage = (event) => {
const newElement = document.createElement("li");
const eventList = document.getElementById("list");
newElement.textContent = `message: ${event.data}`;
eventList.appendChild(newElement);
};
```
This code listens for incoming message events and appends the message text to a list in the document's HTML.
### Listening for custom events
Messages from the server that do have an `event` field defined are received as events with the name given in `event`. For example:
```js
evtSource.addEventListener("ping", (event) => {
const newElement = document.createElement("li");
const eventList = document.getElementById("list");
const time = JSON.parse(event.data).time;
newElement.textContent = `ping at ${time}`;
eventList.appendChild(newElement);
});
```
This code will be called whenever the server sends a message with the `event` field set to `ping`; it then parses the JSON in the `data` field and outputs that information.
> **Warning:** When **not used over HTTP/2**, SSE suffers from a limitation to the maximum number of open connections, which can be especially painful when opening multiple tabs, as the limit is _per browser_ and is set to a very low number (6). The issue has been marked as "Won't fix" in [Chrome](https://crbug.com/275955) and [Firefox](https://bugzil.la/906896). This limit is per browser + domain, which means that you can open 6 SSE connections across all of the tabs to `www.example1.com` and another 6 SSE connections to `www.example2.com` (per [Stackoverflow](https://stackoverflow.com/questions/5195452/websockets-vs-server-sent-events-eventsource/5326159)). When using HTTP/2, the maximum number of simultaneous _HTTP streams_ is negotiated between the server and the client (defaults to 100).
## Sending events from the server
The server-side script that sends events needs to respond using the MIME type `text/event-stream`. Each notification is sent as a block of text terminated by a pair of newlines. For details on the format of the event stream, see [Event stream format](#event_stream_format).
The {{Glossary("PHP")}} code for the example we're using here follows:
```php
date_default_timezone_set("America/New_York");
header("Cache-Control: no-store");
header("Content-Type: text/event-stream");
$counter = rand(1, 10);
while (true) {
// Every second, send a "ping" event.
echo "event: ping\n";
$curDate = date(DATE_ISO8601);
echo 'data: {"time": "' . $curDate . '"}';
echo "\n\n";
// Send a simple message at random intervals.
$counter--;
if (!$counter) {
echo 'data: This is a message at time ' . $curDate . "\n\n";
$counter = rand(1, 10);
}
ob_end_flush();
flush();
// Break the loop if the client aborted the connection (closed the page)
if (connection_aborted()) break;
sleep(1);
}
```
The code above generates an event every second, with the event type "ping". Each event's data is a JSON object containing the ISO 8601 timestamp corresponding to the time at which the event was generated. At random intervals, a simple message (with no event type) is sent.
The loop will keep running independent of the connection status, so a check is included
to break the loop if the connection has been closed (e.g. client closes the page).
> **Note:** You can find a full example that uses the code shown in this article on GitHub — see [Simple SSE demo using PHP](https://github.com/mdn/dom-examples/tree/main/server-sent-events).
## Error handling
When problems occur (such as a network timeout or issues pertaining to [access control](/en-US/docs/Web/HTTP/CORS)), an error event is generated. You can take action on this programmatically by implementing the `onerror` callback on the `EventSource` object:
```js
evtSource.onerror = (err) => {
console.error("EventSource failed:", err);
};
```
## Closing event streams
By default, if the connection between the client and server closes, the connection is restarted. The connection is terminated with the `.close()` method.
```js
evtSource.close();
```
## Event stream format
The event stream is a simple stream of text data which must be encoded using [UTF-8](/en-US/docs/Glossary/UTF-8). Messages in the event stream are separated by a pair of newline characters. A colon as the first character of a line is in essence a comment, and is ignored.
> **Note:** The comment line can be used to prevent connections from timing out; a server can send a comment periodically to keep the connection alive.
Each message consists of one or more lines of text listing the fields for that message. Each field is represented by the field name, followed by a colon, followed by the text data for that field's value.
### Fields
Each message received has some combination of the following fields, one per line:
- `event`
- : A string identifying the type of event described. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use `addEventListener()` to listen for named events. The `onmessage` handler is called if no event name is specified for a message.
- `data`
- : The data field for the message. When the `EventSource` receives multiple consecutive lines that begin with `data:`, [it concatenates them](https://html.spec.whatwg.org/multipage/#dispatchMessage), inserting a newline character between each one. Trailing newlines are removed.
- `id`
- : The event ID to set the [`EventSource`](/en-US/docs/Web/API/EventSource) object's last event ID value.
- `retry`
- : The reconnection time. If the connection to the server is lost, the browser will wait for the specified time before attempting to reconnect. This must be an integer, specifying the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored.
All other field names are ignored.
> **Note:** If a line doesn't contain a colon, the entire line is treated as the field name with an empty value string.
### Examples
#### Data-only messages
In the following example, there are three messages sent. The first is just a comment, since it starts with a colon character. As mentioned previously, this can be useful as a keep-alive mechanism if messages might not be sent regularly.
The second message contains a data field with the value "some text". The third message contains a data field with the value "another message\nwith two lines". Note the newline special character in the value.
```bash
: this is a test stream
data: some text
data: another message
data: with two lines
```
#### Named events
This example sends named events. Each has an event name specified by the `event` field, and a `data` field whose value is an appropriate JSON string with the data needed for the client to act on the event. The `data` field could, of course, have any string data; it doesn't have to be JSON.
```bash
event: userconnect
data: {"username": "bobby", "time": "02:33:48"}
event: usermessage
data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."}
event: userdisconnect
data: {"username": "bobby", "time": "02:34:23"}
event: usermessage
data: {"username": "sean", "time": "02:34:36", "text": "Bye, bobby."}
```
#### Mixing and matching
You don't have to use just unnamed messages or typed events; you can mix them together in a single event stream.
```bash
event: userconnect
data: {"username": "bobby", "time": "02:33:48"}
data: Here's a system message of some kind that will get used
data: to accomplish some task.
event: usermessage
data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."}
```
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor/index.md | ---
title: BluetoothRemoteGATTDescriptor
slug: Web/API/BluetoothRemoteGATTDescriptor
page-type: web-api-interface
status:
- experimental
browser-compat: api.BluetoothRemoteGATTDescriptor
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The `BluetoothRemoteGATTDescriptor` interface of the [Web Bluetooth API](/en-US/docs/Web/API/Web_Bluetooth_API) provides a GATT Descriptor,
which provides further information about a characteristic's value.
## Instance properties
- {{DOMxRef("BluetoothRemoteGATTDescriptor.characteristic")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the {{DOMxRef("BluetoothRemoteGATTCharacteristic")}} this descriptor belongs
to.
- {{DOMxRef("BluetoothRemoteGATTDescriptor.uuid")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the UUID of the characteristic descriptor, for
example '`00002902-0000-1000-8000-00805f9b34fb`' for theClient
Characteristic Configuration descriptor.
- {{DOMxRef("BluetoothRemoteGATTDescriptor.value")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the currently cached descriptor value. This value gets updated when the
value of the descriptor is read.
## Instance methods
- {{DOMxRef("BluetoothRemoteGATTDescriptor.readValue()")}} {{Experimental_Inline}}
- : Returns a {{JSxRef("Promise")}} that resolves to
an {{JSxRef("ArrayBuffer")}} holding a duplicate of the `value` property
if it is available and supported. Otherwise it throws an error.
- {{DOMxRef("BluetoothRemoteGATTDescriptor.writeValue()")}} {{Experimental_Inline}}
- : Sets the value property to the bytes contained in an {{JSxRef("ArrayBuffer")}} and
returns a {{JSxRef("Promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor | data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor/characteristic/index.md | ---
title: "BluetoothRemoteGATTDescriptor: characteristic property"
short-title: characteristic
slug: Web/API/BluetoothRemoteGATTDescriptor/characteristic
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothRemoteGATTDescriptor.characteristic
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`BluetoothRemoteGATTDescriptor.characteristic`**
read-only property returns the {{domxref("BluetoothRemoteGATTCharacteristic")}} this
descriptor belongs to.
## Value
An instance of {{domxref("BluetoothRemoteGATTCharacteristic")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor | data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor/writevalue/index.md | ---
title: "BluetoothRemoteGATTDescriptor: writeValue() method"
short-title: writeValue()
slug: Web/API/BluetoothRemoteGATTDescriptor/writeValue
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.BluetoothRemoteGATTDescriptor.writeValue
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`BluetoothRemoteGATTDescriptor.writeValue()`**
method sets the value property to the bytes contained in
an {{jsxref("ArrayBuffer")}} and returns a {{jsxref("Promise")}}.
## Syntax
```js-nolint
writeValue(array)
```
### Parameters
- `array`
- : Sets the value with the bytes contained in the array.
### Return value
A {{jsxref("Promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor | data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor/value/index.md | ---
title: "BluetoothRemoteGATTDescriptor: value property"
short-title: value
slug: Web/API/BluetoothRemoteGATTDescriptor/value
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothRemoteGATTDescriptor.value
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`BluetoothRemoteGATTDescriptor.value`**
read-only property returns an {{jsxref("ArrayBuffer")}} containing the currently cached
descriptor value. This value gets updated when the value of the descriptor is read.
## Value
An {{jsxref("ArrayBuffer")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor | data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor/readvalue/index.md | ---
title: "BluetoothRemoteGATTDescriptor: readValue() method"
short-title: readValue()
slug: Web/API/BluetoothRemoteGATTDescriptor/readValue
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.BluetoothRemoteGATTDescriptor.readValue
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The
**`BluetoothRemoteGATTDescriptor.readValue()`**
method returns a {{jsxref("Promise")}} that resolves to
an {{jsxref("ArrayBuffer")}} holding a duplicate of the `value` property if
it is available and supported. Otherwise it throws an error.
## Syntax
```js-nolint
readValue()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves to an {{jsxref("ArrayBuffer")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor | data/mdn-content/files/en-us/web/api/bluetoothremotegattdescriptor/uuid/index.md | ---
title: "BluetoothRemoteGATTDescriptor: uuid property"
short-title: uuid
slug: Web/API/BluetoothRemoteGATTDescriptor/uuid
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothRemoteGATTDescriptor.uuid
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`BluetoothRemoteGATTDescriptor.uuid`** read-only property returns the {{Glossary("UUID")}} of the characteristic descriptor.
For example '`00002902-0000-1000-8000-00805f9b34fb`' for theClient Characteristic Configuration descriptor.
## Value
A UUID.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webglobject/index.md | ---
title: WebGLObject
slug: Web/API/WebGLObject
page-type: web-api-interface
browser-compat: api.WebGLObject
---
{{APIRef("WebGL")}}
The **`WebGLObject`** is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and is the parent interface for all WebGL objects.
This object has no public properties or methods on its own.
If the WebGL context is lost, the internal _invalidated_ flag of all `WebGLObject` instances is set to `true`.
## Objects inheriting from `WebGLObject`
WebGL 1:
- {{domxref("WebGLBuffer")}}
- {{domxref("WebGLFramebuffer")}}
- {{domxref("WebGLProgram")}}
- {{domxref("WebGLRenderbuffer")}}
- {{domxref("WebGLShader")}}
- {{domxref("WebGLTexture")}}
WebGL 2:
- {{domxref("WebGLQuery")}} (and `WebGLTimerQueryEXT`)
- {{domxref("WebGLSampler")}}
- {{domxref("WebGLSync")}}
- {{domxref("WebGLTransformFeedback")}}
- {{domxref("WebGLVertexArrayObject")}} (and `WebGLVertexArrayObjectOES`)
## See also
- [`WebGLRenderingContext.isContextLost()`](/en-US/docs/Web/API/WebGLRenderingContext/isContextLost)
- [`WEBGL_lose_context`](/en-US/docs/Web/API/WEBGL_lose_context)
- [`webglcontextlost` event](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrrigidtransform/index.md | ---
title: XRRigidTransform
slug: Web/API/XRRigidTransform
page-type: web-api-interface
browser-compat: api.XRRigidTransform
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The **`XRRigidTransform`** is a [WebXR API](/en-US/docs/Web/API/WebXR_Device_API) interface that represents the 3D geometric transform described by a position and orientation.
`XRRigidTransform` is used to specify transforms throughout the WebXR APIs, including:
- The offset and orientation relative to the parent reference space to use when creating a new reference space with {{domxref("XRReferenceSpace.getOffsetReferenceSpace", "getOffsetReferenceSpace()")}}.
- The {{domxref("XRView.transform", "transform")}} of an {{domxref("XRView")}}.
- The {{domxref("XRPose.transform", "transform")}} of an {{domxref("XRPose")}}.
- The {{domxref("XRReferenceSpaceEvent")}} event's {{domxref("XRReferenceSpaceEvent.transform", "transform")}} property, as found in the {{domxref("XRReferenceSpace.reset_event", "reset")}} event received by an {{domxref("XRReferenceSpace")}}.
Using `XRRigidTransform` in these places rather than bare arrays that provide the matrix data has an advantage. It automatically computes the inverse of the transform and even caches it making subsequent requests significantly faster.
## Constructor
- {{domxref("XRRigidTransform.XRRigidTransform", "new XRRigidTransform()")}}
- : Creates a new `XRRigidTransform` object which represents a transform that applies a specified position and/or orientation.
## Instance properties
- {{DOMxRef("XRRigidTransform.position")}} {{ReadOnlyInline}}
- : A {{DOMxRef("DOMPointReadOnly")}} specifying a 3-dimensional point, expressed in meters, describing the translation component of the transform. The {{DOMxRef("DOMPointReadonly.w", "w")}} property is always `1.0`.
- {{DOMxRef("XRRigidTransform.orientation")}} {{ReadOnlyInline}}
- : A {{DOMxRef("DOMPointReadOnly")}} which contains a unit quaternion describing the rotational component of the transform. As a unit quaternion, its length is always normalized to `1.0`.
- {{DOMxRef("XRRigidTransform.matrix")}} {{ReadOnlyInline}}
- : Returns the transform matrix in the form of a 16-member {{jsxref("Float32Array")}}. See the section [Matrix format](/en-US/docs/Web/API/XRRigidTransform/matrix#matrix_format) for how the array is used to represent a matrix.
- {{DOMxRef("XRRigidTransform.inverse")}} {{ReadOnlyInline}}
- : Returns a `XRRigidTransform` which is the inverse of this transform. That is, if applied to an object that had been previously transformed by the original transform, it will undo the transform and return the original object.
## Usage notes
When an `XRRigidTransform` is interpreted, the orientation is always applied to the affected object before the position is applied.
## Example
This code snippet creates an `XRRigidTransform` to specify the offset and orientation in relation to the current reference space to use when creating a new reference space. It then requests the first animation frame callback by calling the session's {{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} method.
```js
xrSession.requestReferenceSpace(refSpaceType).then((refSpace) => {
xrReferenceSpace = refSpace;
xrReferenceSpace = xrReferenceSpace.getOffsetReferenceSpace(
new XRRigidTransform(viewerStartPosition, cubeOrientation),
);
animationFrameRequestID = xrSession.requestAnimationFrame(drawFrame);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrrigidtransform | data/mdn-content/files/en-us/web/api/xrrigidtransform/position/index.md | ---
title: "XRRigidTransform: position property"
short-title: position
slug: Web/API/XRRigidTransform/position
page-type: web-api-instance-property
browser-compat: api.XRRigidTransform.position
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The read-only {{domxref("XRRigidTransform")}} property
**`position`** is a {{domxref("DOMPointReadOnly")}} object which
provides the 3D point, specified in meters, describing the translation component of the
transform.
## Value
A read-only {{domxref("DOMPointReadOnly")}} indicating the 3D position component of the
transform matrix. The units are meters.
> **Note:** The `w` component of the point is always 1.0.
## Examples
To create a reference space which can be used to place an object at eye level (assuming
eye level is 1.5 meters):
```js
function onSessionStarted(xrSession) {
xrSession.addEventListener("end", onSessionEnded);
gl = initGraphics(xrSession);
const glLayer = new XRWebGLLayer(xrSession, gl);
xrSession.updateRenderState({ baseLayer: glLayer });
if (immersiveSession) {
xrSession
.requestReferenceSpace("bounded-floor")
.then((refSpace) => {
refSpaceCreated(refSpace);
})
.catch(() => {
session.requestReferenceSpace("local-floor").then(refSpaceCreated);
});
} else {
session.requestReferenceSpace("viewer").then(refSpaceCreated);
}
}
function refSpaceCreated(refSpace) {
xrReferenceSpace = immersiveSession
? refSpace
: refSpace.getOffsetReferenceSpace(new XRRigidTransform({ y: -1.5 }));
xrSession.requestAnimationFrame(onFrame);
}
```
After setting up the graphics context for WebXR use, this begins by looking to see if a
variable `immersiveSession` is `true`; if so, we first request a
`bounded-floor` reference space. If that fails (probably because
`bounded-floor` isn't supported), we try requesting a
`local-floor` reference space.
If we're not in an immersive session, we instead request a `viewer`
reference space.
In all cases, once the space has been obtained, it gets passed into the
`refSpaceCreated()` function. For immersive spaces, the specified space is
saved for future use. However, for inline sessions, we know we're in a space not
automatically adjusted for floor level, so we request an offset reference space to shift
the viewer's height to 1.5 meters above the presumed floor level of 0 meters. That new
reference space is used instead of the one initially received.
Finally, an animation frame request is submitted.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrrigidtransform | data/mdn-content/files/en-us/web/api/xrrigidtransform/orientation/index.md | ---
title: "XRRigidTransform: orientation property"
short-title: orientation
slug: Web/API/XRRigidTransform/orientation
page-type: web-api-instance-property
browser-compat: api.XRRigidTransform.orientation
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The read-only {{domxref("XRRigidTransform")}} property
**`orientation`** is a {{domxref("DOMPointReadOnly")}}
containing a normalized {{Glossary("quaternion")}} (also called a **unit
quaternion** or **[versor](https://en.wikipedia.org/wiki/Versor)**)
specifying the rotational component of the transform represented by the object.
If you specify a quaternion whose length is not exactly 1.0 meters, it will be
normalized for you.
## Value
A {{domxref("DOMPointReadOnly")}} object which contains a unit quaternion providing the
orientation component of the transform. As a unit quaternion, the length of the returned
quaternion is always 1.0 meters.
## Examples
To create a reference space which is oriented to look straight up, positioned 2 meters
off of ground level:
```js
xrReferenceSpace = refSpace.getOffsetReferenceSpace(
new XRRigidTransform({ y: -2 }, { x: 0.0, y: 1.0, z: 0.0, w: 1.0 }),
);
```
The unit quaternion specified here is \[0.0, 1.0, 0.0, 1.0] to indicate that the object
should be facing directly along the _y_ axis.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Movement, orientation, and motion](/en-US/docs/Web/API/WebXR_Device_API/Movement_and_motion)
- [Unit quaternions](https://en.wikipedia.org/wiki/Versor)
- [Quaternions and spatial rotation](https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation)
| 0 |
data/mdn-content/files/en-us/web/api/xrrigidtransform | data/mdn-content/files/en-us/web/api/xrrigidtransform/matrix/index.md | ---
title: "XRRigidTransform: matrix property"
short-title: matrix
slug: Web/API/XRRigidTransform/matrix
page-type: web-api-instance-property
browser-compat: api.XRRigidTransform.matrix
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The read-only {{domxref("XRRigidTransform")}} property
**`matrix`** returns the transform
matrix represented by the object. The returned matrix can then be premultiplied with a
column vector to rotate the
vector by the 3D rotation specified by the {{domxref("XRRigidTransform.orientation",
"orientation")}}, then translate
it by the {{domxref("XRRigidTransform.position", "position")}}.
## Value
A {{jsxref("Float32Array")}} containing 16 entries which represents the 4x4 transform
matrix which is described by
the {{domxref("XRRigidTransform.position", "position")}} and
{{domxref("XRRigidTransform.orientation",
"orientation")}} properties.
## Usage notes
### Matrix format
All 4x4 transform matrices used in WebGL are stored in 16-element
{{jsxref("Float32Array")}}s. The values are stored
into the array in column-major order; that is, each column is written into the array
top-down before moving to the
right one column and writing the next column into the array. Thus, for an array \[a0, a1,
a2, …, a13, a14, a15], the
matrix looks like this:
<math display="block"><semantics><mrow><mo>[</mo>
<mtable rowspacing="0.5ex"><mtr><mtd><mi>a0</mi>
</mtd><mtd><mi>a4</mi>
</mtd><mtd><mi>a8</mi>
</mtd><mtd><mi>a12</mi>
</mtd></mtr><mtr><mtd><mi>a1</mi>
</mtd><mtd><mi>a5</mi>
</mtd><mtd><mi>a9</mi>
</mtd><mtd><mi>a13</mi>
</mtd></mtr><mtr><mtd><mi>a2</mi>
</mtd><mtd><mi>a6</mi>
</mtd><mtd><mi>a10</mi>
</mtd><mtd><mi>a14</mi>
</mtd></mtr><mtr><mtd><mi>a3</mi>
</mtd><mtd><mi>a7</mi>
</mtd><mtd><mi>a11</mi>
</mtd><mtd><mi>a15</mi>
</mtd></mtr></mtable><mo>]</mo>
</mrow><annotation encoding="TeX">\begin{bmatrix} a[0] & a[4] & a[8] & a[12]\\
a[1] & a[5] & a[9]
& a[13]\\ a[2] & a[6] & a[10] & a[14]\\ a[3] & a[7] &
a[11] & a[15]\\ \end{bmatrix}</annotation></semantics></math>
On the first request, the `matrix` gets computed. After that, it should be cached for performance reasons.
### Creating the matrix
In this section, intended for more advanced readers, we cover how the API calculates
the matrix for the specified
transform. It begins by allocating a new matrix and writing a 4x4 identity matrix into
it:
<math display="block"><semantics><mrow><mo>[</mo>
<mtable rowspacing="0.5ex"><mtr><mtd><mn>1</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd></mtr><mtr><mtd><mn>0</mn>
</mtd><mtd><mn>1</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd></mtr><mtr><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>1</mn>
</mtd><mtd><mn>0</mn>
</mtd></mtr><mtr><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>1</mn>
</mtd></mtr></mtable><mo>]</mo>
</mrow><annotation encoding="TeX">\begin{bmatrix} 1 & 0 & 0 & 0\\ 0 & 1
& 0 & 0\\ 0 & 0 &
1 & 0\\ 0 & 0 & 0 & 1 \end{bmatrix}</annotation></semantics></math>
This is a transform that will not change either the orientation or position of any
point, vector, or object to which
it's applied.
Next, the `position` is placed into the right-hand column, like this,
resulting in a translation matrix
that will transform a coordinate system by the specified distance in each dimension,
with no rotational change. Here
_p<sub>x</sub>_, _p<sub>y</sub>_, and _p<sub>z</sub>_
are the values of the
`x`, `y`, and `z` members of the
{{domxref("DOMPointReadOnly")}}
`position`.
<math display="block"><semantics><mrow><mo>[</mo>
<mtable rowspacing="0.5ex"><mtr><mtd><mn>1</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><msub><mi>p</mi>
<mi>x</mi>
</msub></mtd></mtr><mtr><mtd><mn>0</mn>
</mtd><mtd><mn>1</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><msub><mi>p</mi>
<mi>y</mi>
</msub></mtd></mtr><mtr><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>1</mn>
</mtd><mtd><msub><mi>p</mi>
<mi>z</mi>
</msub></mtd></mtr><mtr><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>1</mn>
</mtd></mtr></mtable><mo>]</mo>
</mrow><annotation encoding="TeX">\begin{bmatrix} 1 & 0 & 0 & x\\ 0 & 1
& 0 & y\\ 0 & 0 &
1 & z\\ 0 & 0 & 0 & 1 \end{bmatrix}</annotation></semantics></math>
Then a rotation matrix is created by computing a column-vector rotation matrix from the
unit quaternion specified by
`orientation`:
<math display="block"><semantics><mrow><mo>[</mo>
<mtable rowspacing="0.5ex"><mtr><mtd><mn>1</mn>
<mo>-</mo>
<mn>2</mn>
<mo stretchy="false">(</mo>
<msubsup><mi>q</mi>
<mi>y</mi>
<mn>2</mn>
</msubsup><mo>+</mo>
<msubsup><mi>q</mi>
<mi>z</mi>
<mn>2</mn>
</msubsup><mo stretchy="false">)</mo>
</mtd><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>y</mi>
</msub><mo>-</mo>
<msub><mi>q</mi>
<mi>z</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>z</mi>
</msub><mo>+</mo>
<msub><mi>q</mi>
<mi>y</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><mn>0</mn>
</mtd></mtr><mtr><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>y</mi>
</msub><mo>+</mo>
<msub><mi>q</mi>
<mi>z</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><mn>1</mn>
<mo>-</mo>
<mn>2</mn>
<mo stretchy="false">(</mo>
<msubsup><mi>q</mi>
<mi>x</mi>
<mn>2</mn>
</msubsup><mo>+</mo>
<msubsup><mi>q</mi>
<mi>z</mi>
<mn>2</mn>
</msubsup><mo stretchy="false">)</mo>
</mtd><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>y</mi>
</msub><msub><mi>q</mi>
<mi>z</mi>
</msub><mo>-</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><mn>0</mn>
</mtd></mtr><mtr><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>z</mi>
</msub><mo>-</mo>
<msub><mi>q</mi>
<mi>y</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>y</mi>
</msub><msub><mi>q</mi>
<mi>z</mi>
</msub><mo>+</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><mn>1</mn>
<mo>-</mo>
<mn>2</mn>
<mo stretchy="false">(</mo>
<msubsup><mi>q</mi>
<mi>x</mi>
<mn>2</mn>
</msubsup><mo>+</mo>
<msubsup><mi>q</mi>
<mi>y</mi>
<mn>2</mn>
</msubsup><mo stretchy="false">)</mo>
</mtd><mtd><mn>0</mn>
</mtd></mtr><mtr><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>1</mn>
</mtd></mtr></mtable><mo>]</mo>
</mrow><annotation encoding="TeX">\begin{bmatrix} 1 - 2(q_y^2 + q_z^2) & 2(q_xq_y -
q_zq_w) & 2(q_xq_z + q_yq_w)
& p_x\\ 2(q_xq_y + q_zq_w) & 1 - 2(q_x^2 + q_z^2) & 2(q_yq_z - q_xq_w)
& p_y\\ 2(q_xq_z -
q_yq_w) & 2(q_yq_z + q_xq_w) & 1 - 2(q_x^2 + q_y^2) & p_z\\ 0 & 0
& 0 & 1 \end{bmatrix}</annotation></semantics></math>
The final transform `matrix` is calculated by multiplying the translation
matrix by the rotation matrix,
in the order `(translation * rotation)`. This yields the final transform
matrix as returned by
`matrix`:
<math display="block"><semantics><mrow><mo>[</mo>
<mtable rowspacing="0.5ex"><mtr><mtd><mn>1</mn>
<mo>-</mo>
<mn>2</mn>
<mo stretchy="false">(</mo>
<msubsup><mi>q</mi>
<mi>y</mi>
<mn>2</mn>
</msubsup><mo>+</mo>
<msubsup><mi>q</mi>
<mi>z</mi>
<mn>2</mn>
</msubsup><mo stretchy="false">)</mo>
</mtd><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>y</mi>
</msub><mo>-</mo>
<msub><mi>q</mi>
<mi>z</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>z</mi>
</msub><mo>+</mo>
<msub><mi>q</mi>
<mi>y</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><msub><mi>p</mi>
<mi>x</mi>
</msub></mtd></mtr><mtr><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>y</mi>
</msub><mo>+</mo>
<msub><mi>q</mi>
<mi>z</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><mn>1</mn>
<mo>-</mo>
<mn>2</mn>
<mo stretchy="false">(</mo>
<msubsup><mi>q</mi>
<mi>x</mi>
<mn>2</mn>
</msubsup><mo>+</mo>
<msubsup><mi>q</mi>
<mi>z</mi>
<mn>2</mn>
</msubsup><mo stretchy="false">)</mo>
</mtd><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>y</mi>
</msub><msub><mi>q</mi>
<mi>z</mi>
</msub><mo>-</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><msub><mi>p</mi>
<mi>y</mi>
</msub></mtd></mtr><mtr><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>z</mi>
</msub><mo>-</mo>
<msub><mi>q</mi>
<mi>y</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><mn>2</mn>
<mo stretchy="false">(</mo>
<msub><mi>q</mi>
<mi>y</mi>
</msub><msub><mi>q</mi>
<mi>z</mi>
</msub><mo>+</mo>
<msub><mi>q</mi>
<mi>x</mi>
</msub><msub><mi>q</mi>
<mi>w</mi>
</msub><mo stretchy="false">)</mo>
</mtd><mtd><mn>1</mn>
<mo>-</mo>
<mn>2</mn>
<mo stretchy="false">(</mo>
<msubsup><mi>q</mi>
<mi>x</mi>
<mn>2</mn>
</msubsup><mo>+</mo>
<msubsup><mi>q</mi>
<mi>y</mi>
<mn>2</mn>
</msubsup><mo stretchy="false">)</mo>
</mtd><mtd><msub><mi>p</mi>
<mi>z</mi>
</msub></mtd></mtr><mtr><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>0</mn>
</mtd><mtd><mn>1</mn>
</mtd></mtr></mtable><mo>]</mo>
</mrow><annotation encoding="TeX">\begin{bmatrix} 1 - 2(q_y^2 + q_z^2) & 2(q_xq_y -
q_zq_w) & 2(q_xq_z + q_yq_w)
& p_x\\ 2(q_xq_y + q_zq_w) & 1 - 2(q_x^2 + q_z^2) & 2(q_yq_z - q_xq_w)
& p_y\\ 2(q_xq_z -
q_yq_w) & 2(q_yq_z + q_xq_w) & 1 - 2(q_x^2 + q_y^2) & p_z\\ 0 & 0
& 0 & 1 \end{bmatrix}</annotation></semantics></math>
## Examples
In this example, a transform is created to create a matrix which can be used as a
transform during rendering of WebGL
objects, in order to place objects to match a given offset and orientation. The
`matrix` is then passed
into a library function that uses WebGL to render an object matching a given name using
the transform matrix specified
to position and orient it.
```js
let transform = new XRRigidTransform(
{ x: 0, y: 0.5, z: 0.5 },
{ x: 0, y: -0.5, z: -0.5, w: 1 },
);
drawGLObject("magic-lamp", transform.matrix);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrrigidtransform | data/mdn-content/files/en-us/web/api/xrrigidtransform/xrrigidtransform/index.md | ---
title: "XRRigidTransform: XRRigidTransform() constructor"
short-title: XRRigidTransform()
slug: Web/API/XRRigidTransform/XRRigidTransform
page-type: web-api-constructor
browser-compat: api.XRRigidTransform.XRRigidTransform
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The
**`XRRigidTransform()`** constructor creates
a new {{domxref("XRRigidTransform")}} object, representing the position and
orientation of a point or object. Among other things,
`XRRigidTransform` is used when providing a transform to translate between
coordinate systems across spaces.
## Syntax
```js-nolint
new XRRigidTransform()
new XRRigidTransform(position)
new XRRigidTransform(position, orientation)
```
### Parameters
- `position` {{optional_inline}}
- : An object which specifies the coordinates
at which the point or object is located. These dimensions are specified in meters. If
this parameter is left out or is invalid, the
position used is assumed to be `{x: 0, y: 0, z: 0, w: 1}`. `w`
must _always_ be 1.
- `orientation` {{optional_inline}}
- : An object which specifies the direction in
which the object is facing. The default value for `orientation` is
`{x: 0, y: 0, z: 0, w: 1}`. The specified orientation gets normalized if
it's not already.
### Return value
A new {{domxref("XRRigidTransform")}} object which has been initialized to represent a
transform matrix that would adjust the position and orientation of an object from the
origin to the specified `position` and facing in the direction indicated by
`orientation`.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the value of the `w` coordinate in the specified `position` is
not 1.0.
## Examples
In this example, the beginning of the animation of a scene is shown, starting with a
request for a reference space of a given type, then shifting the coordinate system based
on a transform before requesting the first animation frame.
```js
let animationFrameRequestID = 0;
xrSession.requestReferenceSpace("local-floor").then((refSpace) => {
xrReferenceSpace = refSpace.getOffsetReferenceSpace(
new XRRigidTransform(viewerPosition, viewerOrientation),
);
animationFrameRequestID = xrSession.requestAnimationFrame(drawFrame);
});
```
After requesting a reference space of type `local-floor`, the returned
promise is eventually resolved, at which time we receive a new reference space object,
`refSpace`. After creating an `XRRigidTransform` from the viewer's
initial position and orientation, we pass the new transform into
{{domxref("XRReferenceSpace.getOffsetReferenceSpace", "getOffsetReferenceSpace()")}} to
create _another_ reference space, now offset so that its origin is located at the
same place in space as the coordinates given by `viewerPosition`, with the
orientation also revised in the same fashion.
Then {{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} is
called to ask for a new animation frame to draw into. The `drawFrame()`
callback will be executed when the system is ready to draw the next frame.
You can find more examples in [Movement, orientation, and motion](/en-US/docs/Web/API/WebXR_Device_API/Movement_and_motion).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrrigidtransform | data/mdn-content/files/en-us/web/api/xrrigidtransform/inverse/index.md | ---
title: "XRRigidTransform: inverse property"
short-title: inverse
slug: Web/API/XRRigidTransform/inverse
page-type: web-api-instance-property
browser-compat: api.XRRigidTransform.inverse
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The read-only **`inverse`** property
of the {{domxref("XRRigidTransform")}} interface returns another
{{domxref("XRRigidTransform")}} object which is the inverse of its owning
transform. That is, you can always get the inverse of any
`XRRigidTransform` using its `inverse` property, instead of having
to explicitly generate it.
## Value
An {{domxref("XRRigidTransform")}} which contains the inverse of the
`XRRigidTransform` on which it's accessed.
Applying the inverse of a transform to any object previously transformed by the parent
`XRRigidTransform` always undoes the transformation, resulting in the object
returning to its previous pose. In other words, its position and orientation both return
to their prior configurations.
## Examples
In this example, the model view matrix for an object is computed by taking the view
matrix and multiplying it by the object's pose matrix.
```js
const modelViewMatrix = mat4.create();
for (const view of pose.view) {
const viewport = glLayer.getViewport(view);
gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
// …
mat4.multiply(modelViewMatrix, view.transform.inverse.matrix, objectMatrix);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix,
);
// …
}
```
This outline of a renderer's core code shows how the pose's view gets represented by
taking its transform's inverse's matrix as the model view matrix used to transform
objects based on the viewer's position and orientation. The inverse's matrix is
multiplied by the object's matrix to get the model view matrix, which is then passed
into the shader program by setting a uniform to contain that information.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/web_nfc_api/index.md | ---
title: Web NFC API
slug: Web/API/Web_NFC_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.NDEFReader
---
{{DefaultAPISidebar("Web NFC API")}}{{SeeCompatTable}}
The Web NFC API allows exchanging data over NFC via light-weight NFC Data Exchange Format (NDEF) messages.
> **Note:** Devices and tags have to be formatted and recorded specifically to support NDEF record format to be used with Web NFC. Low-level operations are currently not supported by the API, however there is a public discussion about API that would add such functionality.
## Interfaces
- {{DOMxRef("NDEFMessage")}}
- : Interface that represents NDEF messages that can be received from or sent to a compatible tag via a `NDEFReader` object. A message is composed of metadata and NDEF Records.
- {{DOMxRef("NDEFReader")}} {{Experimental_Inline}}
- : Interface that enables reading and writing messages from compatible NFC tags. The messages are represented as `NDEFMessage` objects.
- {{DOMxRef("NDEFRecord")}}
- : Interface that represents NDEF records that can be included in an NDEF message.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/relativeorientationsensor/index.md | ---
title: RelativeOrientationSensor
slug: Web/API/RelativeOrientationSensor
page-type: web-api-interface
browser-compat: api.RelativeOrientationSensor
---
{{securecontext_header}}{{APIRef("Sensor API")}}
The **`RelativeOrientationSensor`** interface of the [Sensor APIs](/en-US/docs/Web/API/Sensor_APIs) describes the device's physical orientation without regard to the Earth's reference coordinate system.
To use this sensor, the user must grant permission to the `'accelerometer'`, and `'gyroscope'` device sensors 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("RelativeOrientationSensor.RelativeOrientationSensor", "RelativeOrientationSensor()")}}
- : Creates a new `RelativeOrientationSensor` object.
## Instance properties
_No specific properties; inherits properties from its ancestors {{domxref('OrientationSensor')}} and {{domxref('Sensor')}}._
## Instance methods
_No specific methods; inherits methods from its ancestors {{domxref('OrientationSensor')}} and {{domxref('Sensor')}}._
## Events
_No specific events; inherits events from its ancestor, {{domxref('Sensor')}}._
## Examples
### Basic Example
The following example, which is loosely based on [Intel's Orientation Phone demo](https://intel.github.io/generic-sensor-demos/orientation-phone/), instantiates an `RelativeOrientationSensor` with a frequency of 60 times a second.
> **Note:** The Intel demo this is based on uses the `AbsoluteOrientationSensor`. On each reading it uses {{domxref('OrientationSensor.quaternion')}} to rotate a visual model of a phone.
```js
const options = { frequency: 60, referenceFrame: "device" };
const sensor = new RelativeOrientationSensor(options);
sensor.addEventListener("reading", () => {
// model is a Three.js object instantiated elsewhere.
model.quaternion.fromArray(sensor.quaternion).inverse();
});
sensor.addEventListener("error", (error) => {
if (event.error.name === "NotReadableError") {
console.log("Sensor is not available.");
}
});
sensor.start();
```
### Permissions Example
Using orientation sensors requires requesting permissions for multiple device sensors. Because the {{domxref('Permissions')}} interface uses promises, a good way to request permissions is to use {{jsxref('Promise.all')}}.
```js
const sensor = new RelativeOrientationSensor();
Promise.all([
navigator.permissions.query({ name: "accelerometer" }),
navigator.permissions.query({ name: "gyroscope" }),
]).then((results) => {
if (results.every((result) => result.state === "granted")) {
sensor.start();
// ...
} else {
console.log("No permissions to use RelativeOrientationSensor.");
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/relativeorientationsensor | data/mdn-content/files/en-us/web/api/relativeorientationsensor/relativeorientationsensor/index.md | ---
title: "RelativeOrientationSensor: RelativeOrientationSensor() constructor"
short-title: RelativeOrientationSensor()
slug: Web/API/RelativeOrientationSensor/RelativeOrientationSensor
page-type: web-api-constructor
browser-compat: api.RelativeOrientationSensor.RelativeOrientationSensor
---
{{securecontext_header}}{{APIRef("Sensor API")}}
The **`RelativeOrientationSensor()`**
constructor creates a new {{domxref("RelativeOrientationSensor")}} object which
describes the device's physical orientation.
## Syntax
```js-nolint
new RelativeOrientationSensor()
new RelativeOrientationSensor(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/file_api/index.md | ---
title: File API
slug: Web/API/File_API
page-type: web-api-overview
spec-urls: https://w3c.github.io/FileAPI/
---
{{DefaultAPISidebar("File API")}}{{AvailableInWorkers}}
## Concepts and Usage
The File API enables web applications to access files and their contents.
Web applications can access files when the user makes them available, either using a [file `<input>` element](/en-US/docs/Web/HTML/Element/input/file) or [via drag and drop](/en-US/docs/Web/API/DataTransfer/files).
Sets of files made available in this way are represented as {{domxref("FileList")}} objects, which enable a web application to retrieve individual {{domxref("File")}} objects. In turn {{domxref("File")}} objects provide access to metadata such as the file's name, size, type, and last modified date.
{{domxref("File")}} objects can be passed to {{domxref("FileReader")}} objects to access the contents of the file. The {{domxref("FileReader")}} interface is asynchronous, but a synchronous version, available only in [web workers](/en-US/docs/Web/API/Web_Workers_API), is provided by the {{domxref("FileReaderSync")}} interface.
## Interfaces
- {{domxref("Blob")}}
- : Represents a "Binary Large Object", meaning a file-like object of immutable, raw data; a {{domxref("Blob")}} can be read as text or binary data, or converted into a {{domxref("ReadableStream")}} so its methods can be used for processing the data.
- {{domxref("File")}}
- : Provides information about a file and allows JavaScript in a web page to access its content.
- {{domxref("FileList")}}
- : Returned by the `files` property of the HTML {{HTMLElement("input")}} element; this lets you access the list of files selected with the `<input type="file">` element. It's also used for a list of files dropped into web content when using the drag and drop API; see the {{domxref("DataTransfer")}} object for details on this usage.
- {{domxref("FileReader")}}
- : Enables web applications to asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using {{domxref("File")}} or {{domxref("Blob")}} objects to specify the file or data to read.
- {{domxref("FileReaderSync")}}
- : Enables web applications to synchronously read the contents of files (or raw data buffers) stored on the user's computer, using {{domxref("File")}} or {{domxref("Blob")}} objects to specify the file or data to read.
### Extensions to other interfaces
- {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}
- : Creates a URL that can be used to fetch a {{domxref("File")}} or {{domxref("Blob")}} object.
- {{domxref("URL.revokeObjectURL_static", "URL.revokeObjectURL()")}}
- : Releases an existing object URL which was previously created by calling {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}.
## Examples
### Reading a file
In this example, we provide a [file `<input>` element](/en-US/docs/Web/HTML/Element/input/file), and when the user selects a file, we read the contents of the first file selected as text, and display the result in a {{HTMLElement("div")}}.
#### HTML
```html
<input type="file" />
<div class="output"></div>
```
#### CSS
```css
.output {
overflow: scroll;
margin: 1rem 0;
height: 200px;
}
```
#### JavaScript
```js
const fileInput = document.querySelector("input[type=file]");
const output = document.querySelector(".output");
fileInput.addEventListener("change", async () => {
const [file] = fileInput.files;
if (file) {
output.innerText = await file.text();
}
});
```
### Result
{{EmbedLiveSample("Reading a file", "", "300")}}
## Specifications
{{Specifications}}
## See also
- [`<input type="file">`](/en-US/docs/Web/HTML/Element/input/file): the file input element
- [`text() method`](/en-US/docs/Web/API/Blob/text): .text()
- The {{domxref("DataTransfer")}} interface
| 0 |
data/mdn-content/files/en-us/web/api/file_api | data/mdn-content/files/en-us/web/api/file_api/using_files_from_web_applications/index.md | ---
title: Using files from web applications
slug: Web/API/File_API/Using_files_from_web_applications
page-type: guide
---
{{DefaultAPISidebar("File API")}}{{AvailableInWorkers}}
Using the File API, web content can ask the user to select local files and then read the contents of those files. This selection can be done by either using an HTML `{{HTMLElement("input/file", '<input type="file">')}}` element or by drag and drop.
## Accessing selected file(s)
Consider this HTML:
```html
<input type="file" id="input" multiple />
```
The File API makes it possible to access a {{DOMxRef("FileList")}} containing {{DOMxRef("File")}} objects representing the files selected by the user.
The `multiple` attribute on the `input` element allows the user to select multiple files.
Accessing the first selected file using a classical DOM selector:
```js
const selectedFile = document.getElementById("input").files[0];
```
### Accessing selected file(s) on a change event
It is also possible (but not mandatory) to access the {{DOMxRef("FileList")}} through the `change` event. You need to use {{DOMxRef("EventTarget.addEventListener()")}} to add the `change` event listener, like this:
```js
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
const fileList = this.files; /* now you can work with the file list */
}
```
## Getting information about selected file(s)
The {{DOMxRef("FileList")}} object provided by the DOM lists all of the files selected by the user, each specified as a {{DOMxRef("File")}} object. You can determine how many files the user selected by checking the value of the file list's `length` attribute:
```js
const numFiles = fileList.length;
```
Individual {{DOMxRef("File")}} objects can be retrieved by accessing the list as an array.
There are three attributes provided by the {{DOMxRef("File")}} object that contain useful information about the file.
- `name`
- : The file's name as a read-only string. This is just the file name, and does not include any path information.
- `size`
- : The size of the file in bytes as a read-only 64-bit integer.
- `type`
- : The MIME type of the file as a read-only string or `""` if the type couldn't be determined.
### Example: Showing file(s) size
The following example shows a possible use of the `size` property:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>File(s) size</title>
</head>
<body>
<form name="uploadForm">
<div>
<input id="uploadInput" type="file" multiple />
<label for="fileNum">Selected files:</label>
<output id="fileNum">0</output>;
<label for="fileSize">Total size:</label>
<output id="fileSize">0</output>
</div>
<div><input type="submit" value="Send file" /></div>
</form>
<script>
const uploadInput = document.getElementById("uploadInput");
uploadInput.addEventListener(
"change",
() => {
// Calculate total size
let numberOfBytes = 0;
for (const file of uploadInput.files) {
numberOfBytes += file.size;
}
// Approximate to the closest prefixed unit
const units = [
"B",
"KiB",
"MiB",
"GiB",
"TiB",
"PiB",
"EiB",
"ZiB",
"YiB",
];
const exponent = Math.min(
Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
units.length - 1,
);
const approx = numberOfBytes / 1024 ** exponent;
const output =
exponent === 0
? `${numberOfBytes} bytes`
: `${approx.toFixed(3)} ${
units[exponent]
} (${numberOfBytes} bytes)`;
document.getElementById("fileNum").textContent =
uploadInput.files.length;
document.getElementById("fileSize").textContent = output;
},
false,
);
</script>
</body>
</html>
```
## Using hidden file input elements using the click() method
You can hide the admittedly ugly file {{HTMLElement("input")}} element and present your own interface for opening the file picker and displaying which file or files the user has selected. You can do this by styling the input element with `display:none` and calling the {{DOMxRef("HTMLElement.click","click()")}} method on the {{HTMLElement("input")}} element.
Consider this HTML:
```html
<input
type="file"
id="fileElem"
multiple
accept="image/*"
style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
```
The code that handles the `click` event can look like this:
```js
const fileSelect = document.getElementById("fileSelect");
const fileElem = document.getElementById("fileElem");
fileSelect.addEventListener(
"click",
(e) => {
if (fileElem) {
fileElem.click();
}
},
false,
);
```
You can style the {{HTMLElement("button")}} however you wish.
## Using a label element to trigger a hidden file input element
To allow opening the file picker without using JavaScript (the click() method), a {{HTMLElement("label")}} element can be used. Note that in this case the input element must not be hidden using `display: none` (nor `visibility: hidden`), otherwise the label would not be keyboard-accessible. Use the [visually-hidden technique](https://www.a11yproject.com/posts/how-to-hide-content/) instead.
Consider this HTML:
```html
<input
type="file"
id="fileElem"
multiple
accept="image/*"
class="visually-hidden" />
<label for="fileElem">Select some files</label>
```
and this CSS:
```css
.visually-hidden {
position: absolute !important;
height: 1px;
width: 1px;
overflow: hidden;
clip: rect(1px, 1px, 1px, 1px);
}
input.visually-hidden:is(:focus, :focus-within) + label {
outline: thin dotted;
}
```
There is no need to add JavaScript code to call `fileElem.click()`. Also in this case you can style the label element as you wish. You need to provide a visual cue for the focus status of the hidden input field on its label, be it an outline as shown above, or background-color or box-shadow. (As of time of writing, Firefox doesn't show this visual cue for `<input type="file">` elements.)
## Selecting files using drag and drop
You can also let the user drag and drop files into your web application.
The first step is to establish a drop zone. Exactly what part of your content will accept drops may vary depending on the design of your application, but making an element receive drop events is easy:
```js
let dropbox;
dropbox = document.getElementById("dropbox");
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);
```
In this example, we're turning the element with the ID `dropbox` into our drop zone. This is done by adding listeners for the {{domxref("HTMLElement/dragenter_event", "dragenter")}}, {{domxref("HTMLElement/dragover_event", "dragover")}}, and {{domxref("HTMLElement/drop_event", "drop")}} events.
We don't actually need to do anything with the `dragenter` and `dragover` events in our case, so these functions are both simple. They just stop propagation of the event and prevent the default action from occurring:
```js
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
```
The real magic happens in the `drop()` function:
```js
function drop(e) {
e.stopPropagation();
e.preventDefault();
const dt = e.dataTransfer;
const files = dt.files;
handleFiles(files);
}
```
Here, we retrieve the `dataTransfer` field from the event, pull the file list out of it, and then pass that to `handleFiles()`. From this point on, handling the files is the same whether the user used the `input` element or drag and drop.
## Example: Showing thumbnails of user-selected images
Let's say you're developing the next great photo-sharing website and want to use HTML to display thumbnail previews of images before the user actually uploads them. You can establish your input element or drop zone as discussed previously and have them call a function such as the `handleFiles()` function below.
```js
function handleFiles(files) {
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!file.type.startsWith("image/")) {
continue;
}
const img = document.createElement("img");
img.classList.add("obj");
img.file = file;
preview.appendChild(img); // Assuming that "preview" is the div output where the content will be displayed.
const reader = new FileReader();
reader.onload = (e) => {
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
}
```
Here our loop handling the user-selected files looks at each file's `type` attribute to see if its MIME type begins with the string "`image/`"). For each file that is an image, we create a new `img` element. CSS can be used to establish any pretty borders or shadows and to specify the size of the image, so that doesn't need to be done here.
Each image has the CSS class `obj` added to it, making it easy to find in the DOM tree. We also add a `file` attribute to each image specifying the {{DOMxRef("File")}} for the image; this will let us fetch the images for actual upload later. We use {{DOMxRef("Node.appendChild()")}} to add the new thumbnail to the preview area of our document.
Next, we establish the {{DOMxRef("FileReader")}} to handle asynchronously loading the image and attaching it to the `img` element. After creating the new `FileReader` object, we set up its `onload` function and then call `readAsDataURL()` to start the read operation in the background. When the entire contents of the image file are loaded, they are converted into a `data:` URL which is passed to the `onload` callback. Our implementation of this routine sets the `img` element's `src` attribute to the loaded image which results in the image appearing in the thumbnail on the user's screen.
## Using object URLs
The DOM {{DOMxref("URL.createObjectURL_static", "URL.createObjectURL()")}} and {{DOMxref("URL.revokeObjectURL_static", "URL.revokeObjectURL()")}} methods let you create simple URL strings that can be used to reference any data that can be referred to using a DOM {{DOMxRef("File")}} object, including local files on the user's computer.
When you have a {{DOMxRef("File")}} object you'd like to reference by URL from HTML, you can create an object URL for it like this:
```js
const objectURL = window.URL.createObjectURL(fileObj);
```
The object URL is a string identifying the {{DOMxRef("File")}} object. Each time you call {{DOMxref("URL.createObjectURL_static", "URL.createObjectURL()")}}, a unique object URL is created even if you've created an object URL for that file already. Each of these must be released. While they are released automatically when the document is unloaded, if your page uses them dynamically you should release them explicitly by calling {{DOMxref("URL.revokeObjectURL_static", "URL.revokeObjectURL()")}}:
```js
URL.revokeObjectURL(objectURL);
```
## Example: Using object URLs to display images
This example uses object URLs to display image thumbnails. In addition, it displays other file information including their names and sizes.
The HTML that presents the interface looks like this:
```html
<input
type="file"
id="fileElem"
multiple
accept="image/*"
style="display:none" />
<a href="#" id="fileSelect">Select some files</a>
<div id="fileList">
<p>No files selected!</p>
</div>
```
This establishes our file {{HTMLElement("input")}} element as well as a link that invokes the file picker (since we keep the file input hidden to prevent that less-than-attractive user interface from being displayed). This is explained in the section [Using hidden file input elements using the click() method](#using_hidden_file_input_elements_using_the_click_method), as is the method that invokes the file picker.
The `handleFiles()` method follows:
```js
const fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener(
"click",
(e) => {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
},
false,
);
fileElem.addEventListener("change", handleFiles, false);
function handleFiles() {
if (!this.files.length) {
fileList.innerHTML = "<p>No files selected!</p>";
} else {
fileList.innerHTML = "";
const list = document.createElement("ul");
fileList.appendChild(list);
for (let i = 0; i < this.files.length; i++) {
const li = document.createElement("li");
list.appendChild(li);
const img = document.createElement("img");
img.src = URL.createObjectURL(this.files[i]);
img.height = 60;
img.onload = () => {
URL.revokeObjectURL(img.src);
};
li.appendChild(img);
const info = document.createElement("span");
info.innerHTML = `${this.files[i].name}: ${this.files[i].size} bytes`;
li.appendChild(info);
}
}
}
```
This starts by fetching the URL of the {{HTMLElement("div")}} with the ID `fileList`. This is the block into which we'll insert our file list, including thumbnails.
If the {{DOMxRef("FileList")}} object passed to `handleFiles()` is `null`, we set the inner HTML of the block to display "No files selected!". Otherwise, we start building our file list, as follows:
1. A new unordered list ({{HTMLElement("ul")}}) element is created.
2. The new list element is inserted into the {{HTMLElement("div")}} block by calling its {{DOMxRef("Node.appendChild()")}} method.
3. For each {{DOMxRef("File")}} in the {{DOMxRef("FileList")}} represented by `files`:
1. Create a new list item ({{HTMLElement("li")}}) element and insert it into the list.
2. Create a new image ({{HTMLElement("img")}}) element.
3. Set the image's source to a new object URL representing the file, using {{DOMxref("URL.createObjectURL_static", "URL.createObjectURL()")}} to create the blob URL.
4. Set the image's height to 60 pixels.
5. Set up the image's load event handler to release the object URL since it's no longer needed once the image has been loaded. This is done by calling the {{DOMxref("URL.revokeObjectURL_static", "URL.revokeObjectURL()")}} method and passing in the object URL string as specified by `img.src`.
6. Append the new list item to the list.
Here is a live demo of the code above:
{{EmbedLiveSample('Example_Using_object_URLs_to_display_images', '100%', '300px')}}
## Example: Uploading a user-selected file
This example shows how to let the user upload files (such as the images selected using the previous example) to a server.
> **Note:** It's usually preferable to make HTTP requests using the [Fetch API](/en-US/docs/Web/API/Fetch_API) instead of {{domxref("XMLHttpRequest")}}. However, in this case we want to show the user the upload progress, and this feature is still not supported by the Fetch API, so the example uses `XMLHttpRequest`.
>
> Work to track standardization of progress notifications using the Fetch API is at <https://github.com/whatwg/fetch/issues/607>.
### Creating the upload tasks
Continuing with the code that built the thumbnails in the previous example, recall that every thumbnail image is in the CSS class `obj` with the corresponding {{DOMxRef("File")}} attached in a `file` attribute. This allows us to select all of the images the user has chosen for uploading using {{DOMxRef("Document.querySelectorAll()")}}, like this:
```js
function sendFiles() {
const imgs = document.querySelectorAll(".obj");
for (let i = 0; i < imgs.length; i++) {
new FileUpload(imgs[i], imgs[i].file);
}
}
```
Line 2 fetches a {{DOMxRef("NodeList")}}, called `imgs`, of all the elements in the document with the CSS class `obj`. In our case, these will be all of the image thumbnails. Once we have that list, it's trivial to go through it and create a new `FileUpload` instance for each. Each of these handles uploading the corresponding file.
### Handling the upload process for a file
The `FileUpload` function accepts two inputs: an image element and a file from which to read the image data.
```js
function FileUpload(img, file) {
const reader = new FileReader();
this.ctrl = createThrobber(img);
const xhr = new XMLHttpRequest();
this.xhr = xhr;
const self = this;
this.xhr.upload.addEventListener(
"progress",
(e) => {
if (e.lengthComputable) {
const percentage = Math.round((e.loaded * 100) / e.total);
self.ctrl.update(percentage);
}
},
false,
);
xhr.upload.addEventListener(
"load",
(e) => {
self.ctrl.update(100);
const canvas = self.ctrl.ctx.canvas;
canvas.parentNode.removeChild(canvas);
},
false,
);
xhr.open(
"POST",
"http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php",
);
xhr.overrideMimeType("text/plain; charset=x-user-defined-binary");
reader.onload = (evt) => {
xhr.send(evt.target.result);
};
reader.readAsBinaryString(file);
}
function createThrobber(img) {
const throbberWidth = 64;
const throbberHeight = 6;
const throbber = document.createElement("canvas");
throbber.classList.add("upload-progress");
throbber.setAttribute("width", throbberWidth);
throbber.setAttribute("height", throbberHeight);
img.parentNode.appendChild(throbber);
throbber.ctx = throbber.getContext("2d");
throbber.ctx.fillStyle = "orange";
throbber.update = (percent) => {
throbber.ctx.fillRect(
0,
0,
(throbberWidth * percent) / 100,
throbberHeight,
);
if (percent === 100) {
throbber.ctx.fillStyle = "green";
}
};
throbber.update(0);
return throbber;
}
```
The `FileUpload()` function shown above creates a throbber, which is used to display progress information, and then creates an {{DOMxRef("XMLHttpRequest")}} to handle uploading the data.
Before actually transferring the data, several preparatory steps are taken:
1. The `XMLHttpRequest`'s upload `progress` listener is set to update the throbber with new percentage information so that as the upload progresses the throbber will be updated based on the latest information.
2. The `XMLHttpRequest`'s upload `load` event handler is set to update the throbber progress information to 100% to ensure the progress indicator actually reaches 100% (in case of granularity quirks during the process). It then removes the throbber since it's no longer needed. This causes the throbber to disappear once the upload is complete.
3. The request to upload the image file is opened by calling `XMLHttpRequest`'s `open()` method to start generating a POST request.
4. The MIME type for the upload is set by calling the `XMLHttpRequest` function `overrideMimeType()`. In this case, we're using a generic MIME type; you may or may not need to set the MIME type at all depending on your use case.
5. The `FileReader` object is used to convert the file to a binary string.
6. Finally, when the content is loaded the `XMLHttpRequest` function `send()` is called to upload the file's content.
### Asynchronously handling the file upload process
This example, which uses PHP on the server side and JavaScript on the client side, demonstrates asynchronous uploading of a file.
```php
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
exit;
}
?><!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>dnd binary upload</title>
<script type="application/javascript">
function sendFile(file) {
const uri = "/index.php";
const xhr = new XMLHttpRequest();
const fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
window.onload = () => {
const dropzone = document.getElementById("dropzone");
dropzone.ondragover = dropzone.ondragenter = (event) => {
event.stopPropagation();
event.preventDefault();
}
dropzone.ondrop = (event) => {
event.stopPropagation();
event.preventDefault();
const filesArray = event.dataTransfer.files;
for (let i=0; i<filesArray.length; i++) {
sendFile(filesArray[i]);
}
}
}
</script>
</head>
<body>
<div>
<div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here</div>
</div>
</body>
</html>
```
## Example: Using object URLs to display PDF
Object URLs can be used for other things than just images! They can be used to display embedded PDF files or any other resources that can be displayed by the browser.
In Firefox, to have the PDF appear embedded in the iframe (rather than proposed as a downloaded file), the preference `pdfjs.disabled` must be set to `false` {{non-standard_inline()}}.
```html
<iframe id="viewer"></iframe>
```
And here is the change of the `src` attribute:
```js
const obj_url = URL.createObjectURL(blob);
const iframe = document.getElementById("viewer");
iframe.setAttribute("src", obj_url);
URL.revokeObjectURL(obj_url);
```
## Example: Using object URLs with other file types
You can manipulate files of other formats the same way. Here is how to preview uploaded video:
```js
const video = document.getElementById("video");
const obj_url = URL.createObjectURL(blob);
video.src = obj_url;
video.play();
URL.revokeObjectURL(obj_url);
```
## See also
- {{DOMxRef("File")}}
- {{DOMxRef("FileList")}}
- {{DOMxRef("FileReader")}}
- {{DOMxRef("URL")}}
- {{DOMxRef("XMLHttpRequest")}}
- [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webglactiveinfo/index.md | ---
title: WebGLActiveInfo
slug: Web/API/WebGLActiveInfo
page-type: web-api-interface
browser-compat: api.WebGLActiveInfo
---
{{APIRef("WebGL")}}
The **WebGLActiveInfo** interface is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and represents the information returned by calling the {{domxref("WebGLRenderingContext.getActiveAttrib()")}} and {{domxref("WebGLRenderingContext.getActiveUniform()")}} methods.
## Instance properties
- {{domxref("WebGLActiveInfo.name")}}
- : The read-only name of the requested variable.
- {{domxref("WebGLActiveInfo.size")}}
- : The read-only size of the requested variable.
- {{domxref("WebGLActiveInfo.type")}}
- : The read-only type of the requested variable.
## Examples
A `WebGLActiveInfo` object is returned by:
- {{domxref("WebGLRenderingContext.getActiveAttrib()")}}
- {{domxref("WebGLRenderingContext.getActiveUniform()")}} or
- {{domxref("WebGL2RenderingContext.getTransformFeedbackVarying()")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.getActiveAttrib()")}}
- {{domxref("WebGLRenderingContext.getActiveUniform()")}}
| 0 |
data/mdn-content/files/en-us/web/api/webglactiveinfo | data/mdn-content/files/en-us/web/api/webglactiveinfo/name/index.md | ---
title: "WebGLActiveInfo: name property"
short-title: name
slug: Web/API/WebGLActiveInfo/name
page-type: web-api-instance-property
browser-compat: api.WebGLActiveInfo.name
---
{{APIRef("WebGL")}}
The read-only **`WebGLActiveInfo.name`** property represents the name of the requested data returned by calling the {{domxref("WebGLRenderingContext.getActiveAttrib()", "getActiveAttrib()")}} or {{domxref("WebGLRenderingContext.getActiveUniform()", "getActiveUniform()")}} methods.
## Examples
```js
const activeAttrib = gl.getActiveAttrib(program, index);
activeAttrib.name;
const activeUniform = gl.getActiveUniform(program, index);
activeUniform.name;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLActiveInfo")}}
| 0 |
data/mdn-content/files/en-us/web/api/webglactiveinfo | data/mdn-content/files/en-us/web/api/webglactiveinfo/size/index.md | ---
title: "WebGLActiveInfo: size property"
short-title: size
slug: Web/API/WebGLActiveInfo/size
page-type: web-api-instance-property
browser-compat: api.WebGLActiveInfo.size
---
{{APIRef("WebGL")}}
The read-only **`WebGLActiveInfo.size`** property is a {{jsxref("Number")}} representing the size of the requested data returned by calling the {{domxref("WebGLRenderingContext.getActiveAttrib()", "getActiveAttrib()")}} or {{domxref("WebGLRenderingContext.getActiveUniform()", "getActiveUniform()")}} methods.
## Examples
```js
const activeAttrib = gl.getActiveAttrib(program, index);
activeAttrib.size;
const activeUniform = gl.getActiveUniform(program, index);
activeUniform.size;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLActiveInfo")}}
| 0 |
data/mdn-content/files/en-us/web/api/webglactiveinfo | data/mdn-content/files/en-us/web/api/webglactiveinfo/type/index.md | ---
title: "WebGLActiveInfo: type property"
short-title: type
slug: Web/API/WebGLActiveInfo/type
page-type: web-api-instance-property
browser-compat: api.WebGLActiveInfo.type
---
{{APIRef("WebGL")}}
The read-only **`WebGLActiveInfo.type`** property represents the type of the requested data returned by calling the {{domxref("WebGLRenderingContext.getActiveAttrib()", "getActiveAttrib()")}} or {{domxref("WebGLRenderingContext.getActiveUniform()", "getActiveUniform()")}} methods.
## Examples
```js
const activeAttrib = gl.getActiveAttrib(program, index);
activeAttrib.type;
const activeUniform = gl.getActiveUniform(program, index);
activeUniform.type;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLActiveInfo")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrsessionevent/index.md | ---
title: XRSessionEvent
slug: Web/API/XRSessionEvent
page-type: web-api-interface
browser-compat: api.XRSessionEvent
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API)'s **`XRSessionEvent`** interface describes an event which indicates the change of the state of an {{domxref("XRSession")}}. These events occur, for example, when the session ends or the visibility of its context changes.
{{InheritanceDiagram}}
## Constructor
- {{domxref("XRSessionEvent.XRSessionEvent", "XRSessionEvent()")}}
- : Creates and returns a new `XRSessionEvent` object.
## Instance properties
_In addition to properties inherited from its parent interface, {{domxref("Event")}}, `XRSessionEvent` provides the following:_
- {{domxref("XRSessionEvent.session", "session")}} {{ReadOnlyInline}}
- : The {{domxref("XRSession")}} to which the event refers.
## Instance methods
_While `XRSessionEvent` defines no methods, it inherits methods from its parent interface, {{domxref("Event")}}._
## Session event types
_The following events are represented using the `XRSessionEvent` interface, and are permitted values for its `type` property._
- {{domxref("XRSession.end_event", "end")}}
- : Fired at the session when it has ended, after being terminated by the application or the {{Glossary("user agent")}}.
- {{domxref("XRSession.visibilitychange_event", "visibilitychange")}}
- : Fired at the session whenever its visibility state changes.
## Examples
This example creates a listener that watches for the visibility state of the session to change. It reacts by calling a function `mySessionVisible()` with a Boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfigure a worker that handles rendering the scene.
```js
xrSession.addEventListener("visibilitystate", (e) => {
switch (e.session.visibilitystate) {
case "visible":
case "visible-blurred":
mySessionVisible(true);
break;
case "hidden":
mySessionVisible(false);
break;
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsessionevent | data/mdn-content/files/en-us/web/api/xrsessionevent/xrsessionevent/index.md | ---
title: "XRSessionEvent: XRSessionEvent() constructor"
short-title: XRSessionEvent()
slug: Web/API/XRSessionEvent/XRSessionEvent
page-type: web-api-constructor
browser-compat: api.XRSessionEvent.XRSessionEvent
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The WebXR Device API's
**`XRSessionEvent()`** constructor creates and returns a new
{{domxref("XRSessionEvent")}} object. These objects represent events announcing
state changes in an {{domxref("XRSession")}} representing an augmented or virtual
reality session.
## Syntax
```js-nolint
new XRSessionEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers set it to `end` or `visibilitychange`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `session`
- : The {{domxref("XRSession")}} to which the event is to be delivered.
### Return value
A new {{domxref("XRSessionEvent")}} object representing an object of the
specified type and configured as described by the `options` parameter.
## Examples
See [`XRSessionEvent`](/en-US/docs/Web/API/XRSessionEvent#examples) for example code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsessionevent | data/mdn-content/files/en-us/web/api/xrsessionevent/session/index.md | ---
title: "XRSessionEvent: session property"
short-title: session
slug: Web/API/XRSessionEvent/session
page-type: web-api-instance-property
browser-compat: api.XRSessionEvent.session
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The read-only {{domxref("XRSessionEvent")}} interface's
**`session`** property indicates which
{{domxref("XRSession")}} the event is about.
## Value
An {{domxref("XRSession")}} object indicating which WebXR session the event refers to.
## Examples
In this example, the `session` property is used to obtain the session object
to manage when an event is received.
```js
xrSession.addEventListener("visibilitychange", (e) => {
switch (e.session.visibilityState) {
case "hidden":
myEnableRendering(true);
break;
case "visible":
case "visible-blurred":
myEnableRendering(false);
break;
}
});
```
This calls a function that reacts to the session's visibility state change.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/extendableevent/index.md | ---
title: ExtendableEvent
slug: Web/API/ExtendableEvent
page-type: web-api-interface
browser-compat: api.ExtendableEvent
---
{{APIRef("Service Workers API")}}
The **`ExtendableEvent`** interface extends the lifetime of the [`install`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/install_event) and [`activate`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/activate_event) events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like {{domxref("FetchEvent")}}) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.
If {{domxref("ExtendableEvent.waitUntil","waitUntil()")}} is called outside of the `ExtendableEvent` handler, the browser should throw an `InvalidStateError`; note also that multiple calls will stack up, and the resulting promises will be added to the list of [extend lifetime promises](https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises).
This interface inherits from the {{domxref("Event")}} interface.
{{InheritanceDiagram}}
> **Note:** This interface is only available when the global scope is a {{domxref("ServiceWorkerGlobalScope")}}. It is not available when it is a {{domxref("Window")}}, or the scope of another kind of worker.
## Constructor
- {{domxref("ExtendableEvent.ExtendableEvent()", "ExtendableEvent()")}}
- : Creates a new `ExtendableEvent` object.
## Instance properties
_Doesn't implement any specific properties, but inherits properties from its parent, {{domxref("Event")}}._
## Instance methods
_Inherits methods from its parent, {{domxref("Event")}}_.
- {{domxref("ExtendableEvent.waitUntil", "ExtendableEvent.waitUntil()")}}
- : Extends the lifetime of the event. It is intended to be called in the [`install`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/install_event) [event handler](/en-US/docs/Web/Events/Event_handlers) for the {{domxref("ServiceWorkerRegistration.installing", "installing")}} worker and on the [`activate`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/activate_event) [event handler](/en-US/docs/Web/Events/Event_handlers) for the {{domxref("ServiceWorkerRegistration.active", "active")}} worker.
## Examples
This code snippet is from the [service worker prefetch sample](https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/prefetch/service-worker.js) (see [prefetch example live](https://googlechrome.github.io/samples/service-worker/prefetch/).) The code calls {{domxref("ExtendableEvent.waitUntil()")}} in {{domxref("ServiceWorkerGlobalScope.install_event", "oninstall")}}, delaying treating the {{domxref("ServiceWorkerRegistration.installing")}} worker as installed until the passed promise resolves successfully. The promise resolves when all resources have been fetched and cached, or else when any exception occurs.
The code snippet also shows a best practice for versioning caches used by the service worker. Though there's only one cache in this example, the same approach can be used for multiple caches. It maps a shorthand identifier for a cache to a specific, versioned cache name.
> **Note:** In Chrome, logging statements are visible via the "Inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals.
```js
const CACHE_VERSION = 1;
const CURRENT_CACHES = {
prefetch: `prefetch-cache-v${CACHE_VERSION}`,
};
self.addEventListener("install", (event) => {
const urlsToPrefetch = [
"./static/pre_fetched.txt",
"./static/pre_fetched.html",
"https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif",
];
console.log(
"Handling install event. Resources to pre-fetch:",
urlsToPrefetch,
);
event.waitUntil(
caches
.open(CURRENT_CACHES["prefetch"])
.then((cache) => {
return cache
.addAll(
urlsToPrefetch.map((urlToPrefetch) => {
return new Request(urlToPrefetch, { mode: "no-cors" });
}),
)
.then(() => {
console.log("All resources have been fetched and cached.");
});
})
.catch((error) => {
console.error("Pre-fetching failed:", error);
}),
);
});
```
> **Note:** When fetching resources, it's very important to use `{mode: 'no-cors'}` if there is any chance that the resources are served off of a server that doesn't support {{glossary("CORS")}}. In this example, [www.chromium.org](https://www.chromium.org/) doesn't support CORS.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
- [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
- [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
| 0 |
data/mdn-content/files/en-us/web/api/extendableevent | data/mdn-content/files/en-us/web/api/extendableevent/waituntil/index.md | ---
title: "ExtendableEvent: waitUntil() method"
short-title: waitUntil()
slug: Web/API/ExtendableEvent/waitUntil
page-type: web-api-instance-method
browser-compat: api.ExtendableEvent.waitUntil
---
{{APIRef("Service Workers API")}}
The **`ExtendableEvent.waitUntil()`**
method tells the event dispatcher that work is ongoing. It can also be used to detect
whether that work was successful. In service workers, `waitUntil()` tells
the browser that work is ongoing until the promise settles, and it shouldn't terminate
the service worker if it wants that work to complete.
The {{domxref("ServiceWorkerGlobalScope/install_event", "install")}} events in [service workers](/en-US/docs/Web/API/ServiceWorkerGlobalScope) use
`waitUntil()` to hold the service worker in
the {{domxref("ServiceWorkerRegistration.installing", "installing")}} phase until tasks
complete. If the promise passed to `waitUntil()` rejects, the install is
considered a failure, and the installing service worker is discarded. This is primarily
used to ensure that a service worker is not considered installed until all of the core
caches it depends on are successfully populated.
The {{domxref("ServiceWorkerGlobalScope/activate_event", "activate")}} events in [service workers](/en-US/docs/Web/API/ServiceWorkerGlobalScope) use
`waitUntil()` to buffer functional events such as `fetch` and
`push` until the promise passed to `waitUntil()` settles. This
gives the service worker time to update database schemas and delete outdated
{{domxref("Cache", "caches")}}, so other events can rely on a completely upgraded state.
The `waitUntil()` method must be initially called within the event callback,
but after that it can be called multiple times, until all the promises passed to it
settle.
## Syntax
```js-nolint
waitUntil(promise)
```
### Parameters
A {{jsxref("Promise")}}.
### Return value
None ({{jsxref("undefined")}}).
## Examples
Using `waitUntil()` within a service worker's `install` event:
```js
addEventListener("install", (event) => {
const preCache = async () => {
const cache = await caches.open("static-v1");
return cache.addAll(["/", "/about/", "/static/styles.css"]);
};
event.waitUntil(preCache());
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
| 0 |
data/mdn-content/files/en-us/web/api/extendableevent | data/mdn-content/files/en-us/web/api/extendableevent/extendableevent/index.md | ---
title: "ExtendableEvent: ExtendableEvent() constructor"
short-title: ExtendableEvent()
slug: Web/API/ExtendableEvent/ExtendableEvent
page-type: web-api-constructor
browser-compat: api.ExtendableEvent.ExtendableEvent
---
{{APIRef("Service Workers API")}}
The **`ExtendableEvent()`** constructor creates a new {{domxref("ExtendableEvent")}} object.
## Syntax
```js-nolint
new ExtendableEvent(type)
new ExtendableEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event. It is case-sensitive.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can contain any custom settings
that you want to apply to the event object.
Currently no possible options are mandatory,
but this has been defined for forward compatibility across the different derived events.
### Return value
A new {{domxref("ExtendableEvent")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
- [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
- [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/serialport/index.md | ---
title: SerialPort
slug: Web/API/SerialPort
page-type: web-api-interface
status:
- experimental
browser-compat: api.SerialPort
---
{{securecontext_header}}{{APIRef("Web Serial API")}}{{SeeCompatTable}}
The `SerialPort` interface of the {{domxref("Web_Serial_API", "Web Serial API")}} provides access to a serial port on the host device.
{{InheritanceDiagram}}
## Constructor
Instances of this interface may be obtained by calling methods of the {{domxref("Serial")}} interface, therefore it has no constructor of its own.
## Instance properties
- {{domxref("SerialPort.readable")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("ReadableStream")}} for receiving data from the device connected to the port.
- {{domxref("SerialPort.writable")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("WritableStream")}} for sending data to the device connected to the port.
## Instance methods
- {{domxref("SerialPort.forget()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when the port closes and is forgotten.
- {{domxref("SerialPort.getInfo()")}} {{Experimental_Inline}}
- : Returns an object containing properties of the port.
- {{domxref("SerialPort.open()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when the port is opened. By default the port is opened with 8 data bits, 1 stop bit and no parity checking.
- {{domxref("SerialPort.setSignals()")}} {{Experimental_Inline}}
- : Sets control signals on the port and returns a {{jsxref("Promise")}} that resolves when they are set.
- {{domxref("SerialPort.getSignals()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves with an object containing the current state of the port's control signals.
- {{domxref("SerialPort.close()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when the port closes.
## Events
- {{domxref("SerialPort.connect_event", "connect")}} {{Experimental_Inline}}
- : An event fired when the port has connected to the device.
- {{domxref("SerialPort.disconnect_event", "disconnect")}} {{Experimental_Inline}}
- : An event fired when the port has disconnected from the device.
## Examples
### Opening a port
Before communicating on a serial port it must be opened. Opening the port allows the site to specify the necessary parameters that control how data is transmitted and received. Developers should check the documentation for the device they are connecting to for the appropriate parameters.
```js
await port.open({ baudRate: 9600 /* pick your baud rate */ });
```
Once the `Promise` returned by `open()` resolves the `readable` and `writable` attributes can be accessed to get the {{domxref("ReadableStream")}} and {{domxref("WritableStream")}} instances for receiving data from and sending data to the connected device.
### Reading data from a port
The following example shows how to read data from a port. The outer loop handles non-fatal errors, creating a new reader until a fatal error is encountered and `readable` becomes `null`.
```js
while (port.readable) {
const reader = port.readable.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
// |reader| has been canceled.
break;
}
// Do something with |value|…
}
} catch (error) {
// Handle |error|…
} finally {
reader.releaseLock();
}
}
```
### Writing data to a port
The following example shows how to write a string to a port. A {{domxref("TextEncoder")}} converts the string to a `Uint8Array` before transmission.
```js
const encoder = new TextEncoder();
const writer = port.writable.getWriter();
await writer.write(encoder.encode("PING"));
writer.releaseLock();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serialport | data/mdn-content/files/en-us/web/api/serialport/disconnect_event/index.md | ---
title: "SerialPort: disconnect event"
short-title: disconnect
slug: Web/API/SerialPort/disconnect_event
page-type: web-api-event
status:
- experimental
browser-compat: api.SerialPort.disconnect_event
---
{{SecureContext_Header}}{{APIRef("Web Serial API")}}{{SeeCompatTable}}
The **`disconnect`** event of the {{domxref("SerialPort")}} interface is fired when the port has disconnected from the device. This event is only fired for ports associated with removable devices such as those connected via USB.
This event bubbles to the instance of {{domxref("Serial")}} that returned this interface.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("disconnect", (event) => {});
ondisconnect = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Bubbling
This event bubbles to {{domxref("Serial")}}. The `event.target` property refers to the {{domxref('SerialPort')}} object that bubbles up.
For more information, see [Event bubbling](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling).
## Examples
### Notify when a specific port disconnects
Here the event listener is installed on a specific {{domxref("SerialPort")}} object.
```js
port.addEventListener("disconnect", (event) => {
// notify that the port has become unavailable
});
```
### Listening for any ports that become unavailable
The `disconnect` event bubbles up to the {{domxref("Serial")}} object where you can listen for any ports that become unavailable.
```js
navigator.serial.addEventListener("disconnect", (event) => {
// notify that a port has become unavailable
// use `event.target` to refer to the unavailable port
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("SerialPort.connect_event", "connect")}} event
| 0 |
data/mdn-content/files/en-us/web/api/serialport | data/mdn-content/files/en-us/web/api/serialport/forget/index.md | ---
title: "SerialPort: forget() method"
short-title: forget()
slug: Web/API/SerialPort/forget
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SerialPort.forget
---
{{securecontext_header}}{{APIRef("Web Serial API")}}{{SeeCompatTable}}
The **`SerialPort.forget()`** method of the {{domxref("SerialPort")}} interface returns a {{jsxref("Promise")}} that resolves when the serial port is closed and is forgotten.
## Syntax
```js-nolint
forget()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves with `undefined` once the connection is closed, the device is forgotten, and the permission is reset.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serialport | data/mdn-content/files/en-us/web/api/serialport/readable/index.md | ---
title: "SerialPort: readable property"
short-title: readable
slug: Web/API/SerialPort/readable
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.SerialPort.readable
---
{{SecureContext_Header}}{{APIRef("Web Serial API")}}{{SeeCompatTable}}
The **`readable`** read-only property of the {{domxref("SerialPort")}} interface returns a {{domxref("ReadableStream")}} for receiving data from the device connected to the port. Chunks read from this stream are instances of {{jsxref("Uint8Array")}}. This property is non-null as long as the port is open and has not encountered a fatal error.
## Value
A {{domxref("ReadableStream")}}.
## Examples
The following example shows how to read data from a port. The outer loop handles non-fatal errors, creating a new reader until a fatal error is encountered and `readable` becomes `null`.
```js
while (port.readable) {
const reader = port.readable.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
// |reader| has been canceled.
break;
}
// Do something with |value|…
}
} catch (error) {
// Handle |error|…
} finally {
reader.releaseLock();
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serialport | data/mdn-content/files/en-us/web/api/serialport/connect_event/index.md | ---
title: "SerialPort: connect event"
short-title: connect
slug: Web/API/SerialPort/connect_event
page-type: web-api-event
status:
- experimental
browser-compat: api.SerialPort.connect_event
---
{{APIRef("Web Serial API")}}{{SecureContext_Header}}{{SeeCompatTable}}
The **`connect`** event of the {{domxref("SerialPort")}} interface is fired when a port has connected to the device. This event is only fired for ports associated with removable devices such as those connected via USB.
This event bubbles to the instance of {{domxref("Serial")}} that returned this interface.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("connect", (event) => {});
onconnect = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Bubbling
This event bubbles to {{domxref("Serial")}}. The `event.target` property refers to the {{domxref('SerialPort')}} object that bubbles up.
For more information, see [Event bubbling](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling).
## Examples
### Notify when a specific port connects
The {{domxref("Serial.requestPort()")}} method returns a {{jsxref("Promise")}} that resolves with a {{domxref("SerialPort")}} chosen by the user.
```js
// Prompt user to choose a serial port
const port = await navigator.serial.requestPort();
port.addEventListener("connect", (event) => {
// notify that the chosen port is connected
});
```
### Listening for any newly-connected ports
The `connect` event bubbles up to the {{domxref("Serial")}} object where you can listen for any newly-connected ports.
```js
navigator.serial.addEventListener("connect", (event) => {
// notify that a new port is available
// use `event.target` to refer to the newly-added port
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("SerialPort.disconnect_event", "disconnect")}} event
| 0 |
data/mdn-content/files/en-us/web/api/serialport | data/mdn-content/files/en-us/web/api/serialport/getinfo/index.md | ---
title: "SerialPort: getInfo() method"
short-title: getInfo()
slug: Web/API/SerialPort/getInfo
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SerialPort.getInfo
---
{{SecureContext_Header}}{{APIRef("Web Serial API")}}{{SeeCompatTable}}
The **`getInfo()`** method of the {{domxref("SerialPort")}} interface returns an object whose properties are the vendor ID and product ID of the device.
## Syntax
```js-nolint
getInfo()
```
### Parameters
None.
### Return value
An object containing the following values.
- `usbVendorId`
- : If the port is part of a USB device, an unsigned short integer that identifies a USB device vendor, otherwise `undefined`.
- `usbProductId`
- : If the port is part of a USB device, an unsigned short integer that identifies a USB device, otherwise `undefined`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serialport | data/mdn-content/files/en-us/web/api/serialport/writable/index.md | ---
title: "SerialPort: writable property"
short-title: writable
slug: Web/API/SerialPort/writable
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.SerialPort.writable
---
{{SecureContext_Header}}{{APIRef("Web Serial API")}}{{SeeCompatTable}}
The **`writable`** read-only property of the {{domxref("SerialPort")}} interface returns a {{domxref("WritableStream")}} for sending data to the device connected to the port. Chunks written to this stream must be instances of {{jsxref("ArrayBuffer")}}, {{jsxref("TypedArray")}}, or {{jsxref("DataView")}}. This property is non-null as long as the port is open and has not encountered a fatal error.
## Value
A {{domxref("WritableStream")}}
## Examples
The following example shows how to write a string to a port. A {{domxref("TextEncoder")}} converts the string to a `Uint8Array` before transmission.
```js
const encoder = new TextEncoder();
const writer = port.writable.getWriter();
await writer.write(encoder.encode("PING"));
writer.releaseLock();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serialport | data/mdn-content/files/en-us/web/api/serialport/setsignals/index.md | ---
title: "SerialPort: setSignals() method"
short-title: setSignals()
slug: Web/API/SerialPort/setSignals
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SerialPort.setSignals
---
{{SecureContext_Header}}{{APIRef("Web Serial API")}}{{SeeCompatTable}}
The **`setSignals()`** method of the {{domxref("SerialPort")}} interface sets control signals on the port and returns a {{jsxref("Promise")}} that resolves when they are set.
## Syntax
```js-nolint
setSignals()
setSignals(options)
```
### Parameters
- `options` {{Optional_Inline}}
- : An object with any of the following values:
- `dataTerminalReady`
- : A boolean indicating whether to invoke the operating system to either assert (if true) or de-assert (if false) the "data terminal ready" or "DTR" signal on the serial port.
- `requestToSend`
- : A boolean indicating whether to invoke the operating system to either assert (if true) or de-assert (if false) the "request to send" or "RTS" signal on the serial port.
- `break`
- : A boolean indicating whether to invoke the operating system to either assert (if true) or de-assert (if false) the "break" signal on the serial port.
### Return value
A {{jsxref("Promise")}}.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Returned if the port is not open. Call {{domxref("SerialPort.open()")}} to avoid this error.
- `NetworkError` {{domxref("DOMException")}}
- : Returned if the signals on the device could not be set.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serialport | data/mdn-content/files/en-us/web/api/serialport/getsignals/index.md | ---
title: "SerialPort: getSignals() method"
short-title: getSignals()
slug: Web/API/SerialPort/getSignals
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SerialPort.getSignals
---
{{SecureContext_Header}}{{APIRef("Web Serial API")}}{{SeeCompatTable}}
The **`SerialPort.getSignals()`** method of the {{domxref("SerialPort")}} interface returns a {{jsxref("Promise")}} that resolves with an object containing the current state of the port's control signals.
## Syntax
```js-nolint
getSignals()
```
### Parameters
None.
### Return value
Returns a {{jsxref("Promise")}} that resolves with an object containing the following members:
- `clearToSend`
- : A boolean indicating to the other end of a serial connection that is clear to send data.
- `dataCarrierDetect`
- : A boolean that toggles the control signal needed to communicate over a serial connection.
- `dataSetReady`
- : A boolean indicating whether the device is ready to send and receive data.
- `ringIndicator`
- : A boolean indicating whether a ring signal should be sent down the serial connection.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Returned if the port is not open. Call {{domxref("SerialPort.open()")}} to avoid this error.
- `NetworkError` {{domxref("DOMException")}}
- : Returned if the signals on the device could not be read.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serialport | data/mdn-content/files/en-us/web/api/serialport/close/index.md | ---
title: "SerialPort: close() method"
short-title: close()
slug: Web/API/SerialPort/close
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SerialPort.close
---
{{APIRef("Web Serial API")}}{{SecureContext_Header}}{{SeeCompatTable}}
The **`SerialPort.close()`** method of the {{domxref("SerialPort")}} interface returns a {{jsxref("Promise")}} that resolves when the port closes.
## Syntax
```js-nolint
close()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serialport | data/mdn-content/files/en-us/web/api/serialport/open/index.md | ---
title: "SerialPort: open() method"
short-title: open()
slug: Web/API/SerialPort/open
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SerialPort.open
---
{{SecureContext_Header}}{{APIRef("Web Serial API")}}{{SeeCompatTable}}
The **`open()`** method of the {{domxref("SerialPort")}} interface returns a {{jsxref("Promise")}} that resolves when the port is opened. By default the port is opened with 8 data bits, 1 stop bit and no parity checking. The `baudRate` parameter is required.
## Syntax
```js-nolint
open(options)
```
### Parameters
- `options`
- : An object with any of the following values:
- `baudRate`
- : A positive, non-zero value indicating the baud rate at which serial communication should be established.
- `bufferSize` {{Optional_Inline}}
- : An unsigned long integer indicating the size of the read and write buffers that are to be established. If not passed, defaults to 255.
- `dataBits` {{Optional_Inline}}
- : An integer value of 7 or 8 indicating the number of data bits per frame. If not passed, defaults to 8.
- `flowControl` {{Optional_Inline}}
- : The flow control type, either `"none"` or `"hardware"`. The default value is `"none"`.
- `parity` {{Optional_Inline}}
- : The parity mode, either `"none"`, `"even"`, or `"odd"`. The default value is `"none"`.
- `stopBits` {{Optional_Inline}}
- : An integer value of 1 or 2 indicating the number of stop bits at the end of the frame. If not passed, defaults to 1.
### Return value
A {{jsxref("Promise")}}.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Returned if the port is already open.
- `NetworkError` {{domxref("DOMException")}}
- : Returned if the attempt to open the port failed.
## Examples
Before communicating on a serial port it must be opened. Opening the port allows the site to specify the necessary parameters that control how data is transmitted and received. Developers should check the documentation for the device they are connecting to for the appropriate parameters.
```js
await port.open({ baudRate: 9600 /* pick your baud rate */ });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/clients/index.md | ---
title: Clients
slug: Web/API/Clients
page-type: web-api-interface
browser-compat: api.Clients
---
{{APIRef("Service Workers API")}}
The `Clients` interface provides access to {{domxref("Client")}} objects. Access it via `{{domxref("ServiceWorkerGlobalScope", "self")}}.clients` within a [service worker](/en-US/docs/Web/API/Service_Worker_API).
## Instance methods
- {{domxref("Clients.get()")}}
- : Returns a {{jsxref("Promise")}} for a {{domxref("Client")}} matching a given {{domxref("Client.id", "id")}}.
- {{domxref("Clients.matchAll()")}}
- : Returns a {{jsxref("Promise")}} for an array of {{domxref("Client")}} objects. An options argument allows you to control the types of clients returned.
- {{domxref("Clients.openWindow()")}}
- : Opens a new browser window for a given URL and returns a {{jsxref("Promise")}} for the new {{domxref("WindowClient")}}.
- {{domxref("Clients.claim()")}}
- : Allows an active service worker to set itself as the {{domxref("ServiceWorkerContainer.controller", "controller")}} for all clients within its {{domxref("ServiceWorkerRegistration.scope", "scope")}}.
## Examples
The following example shows an existing chat window or creates a new one when the user clicks a notification.
```js
addEventListener("notificationclick", (event) => {
event.waitUntil(
(async () => {
const allClients = await clients.matchAll({
includeUncontrolled: true,
});
let chatClient;
// Let's see if we already have a chat window open:
for (const client of allClients) {
const url = new URL(client.url);
if (url.pathname === "/chat/") {
// Excellent, let's use it!
client.focus();
chatClient = client;
break;
}
}
// If we didn't find an existing chat window,
// open a new one:
if (!chatClient) {
chatClient = await clients.openWindow("/chat/");
}
// Message the client:
chatClient.postMessage("New chat messages!");
})(),
);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
| 0 |
data/mdn-content/files/en-us/web/api/clients | data/mdn-content/files/en-us/web/api/clients/matchall/index.md | ---
title: "Clients: matchAll() method"
short-title: matchAll()
slug: Web/API/Clients/matchAll
page-type: web-api-instance-method
browser-compat: api.Clients.matchAll
---
{{APIRef("Service Workers API")}}
The **`matchAll()`** method of the {{domxref("Clients")}}
interface returns a {{jsxref("Promise")}} for a list of service worker
{{domxref("Client")}} objects. Include the `options` parameter to return all service worker
clients whose origin is the same as the associated service worker's origin. If options
are not included, the method returns only the service worker clients controlled by the
service worker.
## Syntax
```js-nolint
matchAll()
matchAll(options)
```
### Parameters
- `options` {{optional_inline}}
- : An options object allowing you to set options for the matching operation. Available
options are:
- `includeUncontrolled`
- : A boolean value — if set to
`true`, the matching operation will return all service worker clients
who share the same origin as the current service worker. Otherwise, it returns
only the service worker clients controlled by the current service worker. The
default is `false`.
- `type`
- : Sets the type of clients you want matched. Available values
are `"window"`, `"worker"`, `"sharedworker"`, and
`"all"`. The default is `"window"`.
### Return value
A {{jsxref("Promise")}} that resolves to an array of {{domxref("Client")}} objects. In
Chrome 46/Firefox 54 and later, this method returns clients in most recently focused
order, correct as per spec.
## Examples
```js
clients.matchAll(options).then((clientList) => {
for (const client of clientList) {
if (client.url === "index.html") {
clients.openWindow(client);
// or do something else involving the matching client
}
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/clients | data/mdn-content/files/en-us/web/api/clients/get/index.md | ---
title: "Clients: get() method"
short-title: get()
slug: Web/API/Clients/get
page-type: web-api-instance-method
browser-compat: api.Clients.get
---
{{APIRef("Service Workers API")}}
The **`get()`** method of the
{{domxref("Clients")}} interface gets a service worker client matching a given
`id` and returns it in a {{jsxref("Promise")}}.
## Syntax
```js-nolint
get(id)
```
### Parameters
- `id`
- : A string representing the id of the client you want to get.
### Return value
A {{jsxref("Promise")}} that resolves to a {{domxref("Client")}} object or
`undefined`.
## Examples
```js
self.clients.get(id).then((client) => {
self.clients.openWindow(client.url);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/clients | data/mdn-content/files/en-us/web/api/clients/claim/index.md | ---
title: "Clients: claim() method"
short-title: claim()
slug: Web/API/Clients/claim
page-type: web-api-instance-method
browser-compat: api.Clients.claim
---
{{APIRef("Service Worker Clients")}}
The **`claim()`** method of the {{domxref("Clients")}} interface allows an active service worker to set itself as the {{domxref("ServiceWorkerContainer.controller", "controller")}} for all clients within its {{domxref("ServiceWorkerRegistration.scope", "scope")}}.
This triggers a "`controllerchange`" event on {{domxref("ServiceWorkerContainer","navigator.serviceWorker")}} in any clients that become controlled by this service worker.
When a service worker is initially registered, pages won't use it until they next
load. The `claim()` method causes those pages to be controlled immediately.
Be aware that this results in your service worker controlling pages that loaded
regularly over the network, or possibly via a different service worker.
## Syntax
```js-nolint
claim()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves to `undefined`.
## Examples
The following example uses `claim()` inside service worker's "`activate`" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker.
```js
self.addEventListener("activate", (event) => {
event.waitUntil(clients.claim());
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
- [The service worker lifecycle](https://web.dev/articles/service-worker-lifecycle)
- {{domxref("ServiceWorkerGlobalScope.skipWaiting()", "self.skipWaiting()")}} - skip the service worker's waiting phase
| 0 |
data/mdn-content/files/en-us/web/api/clients | data/mdn-content/files/en-us/web/api/clients/openwindow/index.md | ---
title: "Clients: openWindow() method"
short-title: openWindow()
slug: Web/API/Clients/openWindow
page-type: web-api-instance-method
browser-compat: api.Clients.openWindow
---
{{APIRef("Service Workers API")}}
The **`openWindow()`** method of the {{domxref("Clients")}}
interface creates a new top level browsing context and loads a given URL. If the calling
script doesn't have permission to show popups, `openWindow()` will throw an
`InvalidAccessError`.
In Firefox, the method is allowed to show popups only when called as the result of a
notification click event.
In Chrome for Android, the method may instead open the URL in an existing browsing
context provided by a [standalone web app](/en-US/docs/Web/Progressive_web_apps) previously added to the user's home screen. As of recently, this also works on
Chrome for Windows.
## Syntax
```js-nolint
openWindow(url)
```
### Parameters
- `url`
- : A string representing the URL of the client you want to open in
the window. Generally this value must be a URL from the same origin as the calling
script.
### Return value
A {{jsxref("Promise")}} that resolves to a {{domxref("WindowClient")}} object if the
URL is from the same origin as the service worker or a {{Glossary("null", "null
value")}} otherwise.
### Exceptions
- `InvalidAccessError` {{domxref("DOMException")}}
- : The promise is rejected with this exception if none of the windows in the app's origin have [transient activation](/en-US/docs/Web/Security/User_activation).
## Security requirements
- At least one window in the app's origin must have [transient activation](/en-US/docs/Web/Security/User_activation).
## Examples
```js
// Send notification to OS if applicable
if (self.Notification.permission === "granted") {
const notificationObject = {
body: "Click here to view your messages.",
data: { url: `${self.location.origin}/some/path` },
// data: { url: 'http://example.com' },
};
self.registration.showNotification(
"You've got messages!",
notificationObject,
);
}
// Notification click event listener
self.addEventListener("notificationclick", (e) => {
// Close the notification popout
e.notification.close();
// Get all the Window clients
e.waitUntil(
clients.matchAll({ type: "window" }).then((clientsArr) => {
// If a Window tab matching the targeted URL already exists, focus that;
const hadWindowToFocus = clientsArr.some((windowClient) =>
windowClient.url === e.notification.data.url
? (windowClient.focus(), true)
: false,
);
// Otherwise, open a new tab to the applicable URL and focus it.
if (!hadWindowToFocus)
clients
.openWindow(e.notification.data.url)
.then((windowClient) => (windowClient ? windowClient.focus() : null));
}),
);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtctransformevent/index.md | ---
title: RTCTransformEvent
slug: Web/API/RTCTransformEvent
page-type: web-api-interface
browser-compat: api.RTCTransformEvent
---
{{APIRef("WebRTC")}}
The **`RTCTransformEvent`** of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) represent an event that is fired in a dedicated worker when an encoded frame has been queued for processing by a [WebRTC Encoded Transform](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms).
The interface has a {{domxref("RTCTransformEvent.transformer","transformer")}} property that exposes a readable stream and a writable stream.
A worker should read encoded frames from `transformer.readable`, modify them as needed, and write them to `transformer.writable` in the same order and without any duplication.
At time of writing there is just one event based on `RTCTransformEvent`: {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}}.
{{InheritanceDiagram}}
## Instance properties
_Since `RTCTransformEvent` is based on {{domxref("Event")}}, its properties are also available._
- {{domxref("RTCTransformEvent.transformer")}} {{ReadOnlyInline}}
- : Returns the {{domxref("RTCRtpScriptTransformer")}} associated with the event.
## Transform event types
There is only one type of transform event.
### `rtctransform`
The {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}} event is fired at the worker global scope on construction of an associated {{domxref("RTCRtpScriptTransform")}}, and whenever a new encoded video or audio frame is enqueued for processing.
You can add a `rtctransform` event listener to be notified when the new frame is available using either {{domxref("EventTarget.addEventListener", "DedicatedWorkerGlobalScope.addEventListener()")}} or the `onrtctransform` event handler property.
## Example
This example creates an event listener for the {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}} event.
The example assumes we have a {{domxref("TransformStream")}} with an `options` object passed from a {{domxref("RTCRtpScriptTransform")}} constructor in the main-thread.
The code at the end shows how the stream is piped through the transform stream from the `readable` to the `writable`.
```js
addEventListener("rtctransform", (event) => {
let transform;
// Select a transform based on passed options
if (event.transformer.options.name == "senderTransform") {
transform = createSenderTransform(); // A TransformStream (not shown)
} else if (event.transformer.options.name == "receiverTransform") {
transform = createReceiverTransform(); // A TransformStream (not shown)
}
// Pipe frames from the readable to writeable through TransformStream
event.transformer.readable
.pipeThrough(transform)
.pipeTo(event.transformer.writable);
});
```
Note that this code is part of a more complete example provided in [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
- [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms)
- {{domxref("TransformStream")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtctransformevent | data/mdn-content/files/en-us/web/api/rtctransformevent/transformer/index.md | ---
title: "RTCTransformEvent: transformer property"
short-title: transformer
slug: Web/API/RTCTransformEvent/transformer
page-type: web-api-instance-property
browser-compat: api.RTCTransformEvent.transformer
---
{{APIRef("WebRTC")}}
The read-only **`transformer`** property of the {{domxref("RTCTransformEvent")}} interface returns the {{domxref("RTCRtpScriptTransformer")}} associated with the event.
The property exposes the WebRTC sender or receiver pipeline as a readable and writable stream of encoded media frames, which a [WebRTC Encoded Transform](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms) can insert itself into in order to modify frames.
## Value
A {{domxref("RTCRtpScriptTransformer")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms)
| 0 |
Subsets and Splits