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 | data/mdn-content/files/en-us/web/api/xpathexception/index.md | ---
title: XPathException
slug: Web/API/XPathException
page-type: web-api-interface
browser-compat: api.XPathException
---
{{APIRef("DOM XPath")}}{{Deprecated_Header}}
In the [DOM XPath API](/en-US/docs/Web/XPath) the **`XPathException`** interface represents exception conditions that can be encountered while performing XPath operations.
## Instance properties
- {{domxref("XPathException.code")}} {{ReadOnlyInline}}
- : Returns a `short` that contains one of the [error code constants](#error_codes).
## Constants
<table class="no-markdown">
<thead>
<tr>
<th scope="col">Constant</th>
<th scope="col">Value</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>INVALID_EXPRESSION_ERR</code></td>
<td><code>51</code></td>
<td>
If the expression has a syntax error or otherwise is not a legal
expression according to the rules of the specific
{{domxref("XPathEvaluator")}} or contains specialized
extension functions or variables not supported by this implementation.
</td>
</tr>
<tr>
<td><code>TYPE_ERR</code></td>
<td><code>52</code></td>
<td>
If the expression cannot be converted to return the specified type.
</td>
</tr>
</tbody>
</table>
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("Document.createExpression()")}}
- {{DOMxRef("XPathExpression")}}
| 0 |
data/mdn-content/files/en-us/web/api/xpathexception | data/mdn-content/files/en-us/web/api/xpathexception/code/index.md | ---
title: "XPathException: code property"
short-title: code
slug: Web/API/XPathException/code
page-type: web-api-instance-property
browser-compat: api.XPathException.code
---
{{APIRef("DOM XPath")}}{{Deprecated_Header}}
The **`code`** read-only property of the
{{domxref("XPathException")}} interface returns a `short` that contains one
of the [error code constants](/en-US/docs/Web/API/XPathException#constants).
## Value
A `short` number representing the error code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/texttrackcuelist/index.md | ---
title: TextTrackCueList
slug: Web/API/TextTrackCueList
page-type: web-api-interface
browser-compat: api.TextTrackCueList
---
{{APIRef("WebVTT")}}
The **`TextTrackCueList`** array-like object represents a dynamically updating list of {{domxref("TextTrackCue")}} objects.
This interface has no constructor. Retrieve an instance of this object with {{domxref('TextTrack.cues')}} which returns all of the cues in a {{domxref("TextTrack")}} object.
## Instance properties
- {{domxref('TextTrackCueList.length')}} {{ReadOnlyInline}}
- : An `unsigned long` that is the number of cues in the list.
## Instance methods
- {{domxref('TextTrackCueList.getCueById()')}}
- : Returns the first {{domxref('TextTrackCue')}} object with the identifier passed to it.
## Examples
The {{domxref("HTMLMediaElement.textTracks")}} property returns a {{domxref("TextTrackList")}} object listing all of the {{domxref("TextTrack")}} objects, one for each text track linked to the media. The {{domxref("TextTrack.cues")}} property then returns a `TextTrackCueList` containing the cues for that particular track.
```js
const video = document.getElementById("video");
video.onplay = () => {
console.log(video.textTracks[0].cues);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrackcuelist | data/mdn-content/files/en-us/web/api/texttrackcuelist/getcuebyid/index.md | ---
title: "TextTrackCueList: getCueById() method"
short-title: getCueById()
slug: Web/API/TextTrackCueList/getCueById
page-type: web-api-instance-method
browser-compat: api.TextTrackCueList.getCueById
---
{{APIRef("WebVTT")}}
The **`getCueById()`** method of the {{domxref("TextTrackCueList")}} interface returns the first {{domxref("VTTCue")}} in the list represented by the `TextTrackCueList` object whose identifier matches the value of `id`.
## Syntax
```js-nolint
getCueById(id)
```
### Parameters
- `id`
- : A string which is an identifier for the cue.
### Return value
A {{domxref("VTTCue")}} object.
## Examples
The {{domxref("TextTrack.cues")}} property returns a {{domxref("TextTrackCueList")}} containing the current cues for that particular track. Calling `cues.getCueById("second")` returns the {{domxref("VTTCue")}} with an ID of "second".
```plain
WEBVTT
first
00:00:00.000 --> 00:00:00.999 line:80%
Hildy!
second
00:00:01.000 --> 00:00:01.499 line:80%
How are you?
```
```js
const video = document.getElementById("video");
video.onplay = () => {
console.log(video.textTracks[0].cues.getCueById("second")); // a VTTCue object;
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrackcuelist | data/mdn-content/files/en-us/web/api/texttrackcuelist/length/index.md | ---
title: "TextTrackCueList: length property"
short-title: length
slug: Web/API/TextTrackCueList/length
page-type: web-api-instance-property
browser-compat: api.TextTrackCueList.length
---
{{APIRef("WebVTT")}}
The **`length`** read-only property of the {{domxref("TextTrackCueList")}} interface returns the number of cues in the list.
## Value
An `unsigned long` which is the number of cues in the list.
## Examples
The {{domxref("TextTrack.cues")}} property returns a {{domxref("TextTrackCueList")}} containing the current cues for that particular track. Calling `cues.length` returns the number of cues in the list. Using the WebVTT track below, the value of `length` is 5.
```plain
WEBVTT
first
00:00:00.000 --> 00:00:00.999 line:80%
Hildy!
second
00:00:01.000 --> 00:00:01.499 line:80%
How are you?
third
00:00:01.500 --> 00:00:02.999 line:80%
Tell me, is the ruler of the universe in?
fourth
00:00:03.000 --> 00:00:04.299 line:80%
Yes, they're in - in a bad humor
fifth
00:00:04.300 --> 00:00:06.000 line:80%
Somebody must've stolen the crown jewels
```
```js
const video = document.getElementById("video");
video.onplay = () => {
console.log(video.textTracks[0].cues.length); // 5
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/customevent/index.md | ---
title: CustomEvent
slug: Web/API/CustomEvent
page-type: web-api-interface
browser-compat: api.CustomEvent
---
{{APIRef("DOM")}}
The **`CustomEvent`** interface represents events initialized by an application for any purpose.
> **Note:** If used to attempt to communicate between a web extension content script and a web page script, a non-string `detail` property throws with "Permission denied to access property" in Firefox. To avoid this issue clone the object. See [Share objects with page scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Sharing_objects_with_page_scripts) for more information.
{{AvailableInWorkers}}
{{InheritanceDiagram}}
## Constructor
- {{domxref("CustomEvent.CustomEvent", "CustomEvent()")}}
- : Creates a new `CustomEvent`.
## Instance properties
_This interface inherits properties from its parent, {{domxref("Event")}}._
- {{domxref("CustomEvent.detail")}} {{ReadOnlyInline}}
- : Returns any data passed when initializing the event.
## Instance methods
_This interface inherits methods from its parent, {{domxref("Event")}}._
- {{domxref("CustomEvent.initCustomEvent()")}} {{deprecated_inline}}
- : Initializes a `CustomEvent` object. If the event has already been dispatched, this method does nothing.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Window.postMessage()")}}
- [Creating and triggering events](/en-US/docs/Web/Events/Creating_and_triggering_events)
| 0 |
data/mdn-content/files/en-us/web/api/customevent | data/mdn-content/files/en-us/web/api/customevent/detail/index.md | ---
title: "CustomEvent: detail property"
short-title: detail
slug: Web/API/CustomEvent/detail
page-type: web-api-instance-property
browser-compat: api.CustomEvent.detail
---
{{APIRef("DOM")}}
The read-only **`detail`** property of the {{domxref("CustomEvent")}} interface
returns any data passed when initializing the event.
## Value
Whatever data the event was initialized with.
## Example
```js
// create custom events
const catFound = new CustomEvent("animalfound", {
detail: {
name: "cat",
},
});
const dogFound = new CustomEvent("animalfound", {
detail: {
name: "dog",
},
});
// add an appropriate event listener
obj.addEventListener("animalfound", (e) => console.log(e.detail.name));
// dispatch the events
obj.dispatchEvent(catFound);
obj.dispatchEvent(dogFound);
// "cat" and "dog" logged in the console
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CustomEvent")}}
| 0 |
data/mdn-content/files/en-us/web/api/customevent | data/mdn-content/files/en-us/web/api/customevent/initcustomevent/index.md | ---
title: "CustomEvent: initCustomEvent() method"
short-title: initCustomEvent()
slug: Web/API/CustomEvent/initCustomEvent
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.CustomEvent.initCustomEvent
---
{{APIRef("DOM")}}{{Deprecated_header}}
The **`CustomEvent.initCustomEvent()`** method initializes a {{domxref("CustomEvent")}} object.
If the event has already been dispatched, this method does nothing.
Events initialized in this way must have been created with the {{domxref("Document.createEvent()")}} method.
This method must be called to set the event before it is dispatched using {{ domxref("EventTarget.dispatchEvent()") }}.
Once dispatched, it doesn't do anything anymore.
> **Note:** **Do not use this method anymore, as it is deprecated.**
>
> Rather than using the feature, instead use specific event constructors, like {{domxref("CustomEvent.CustomEvent", "CustomEvent()")}}.
> The page on [Creating and triggering events](/en-US/docs/Web/Events/Creating_and_triggering_events) gives more information about the way to use those.
## Syntax
```js-nolint
event.initCustomEvent(type, canBubble, cancelable, detail)
```
### Parameters
- `type`
- : A string containing the name of the event.
- `canBubble`
- : A boolean value indicating whether the event bubbles up through the DOM
or not.
- `cancelable`
- : A boolean value indicating whether the event is cancelable.
- `detail`
- : Any data that will be available to the handler through the {{domxref("CustomEvent.detail")}} property.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CustomEvent")}}
- The constructor to use instead of this deprecated method: {{domxref("CustomEvent.CustomEvent", "CustomEvent()")}}.
| 0 |
data/mdn-content/files/en-us/web/api/customevent | data/mdn-content/files/en-us/web/api/customevent/customevent/index.md | ---
title: "CustomEvent: CustomEvent() constructor"
short-title: CustomEvent()
slug: Web/API/CustomEvent/CustomEvent
page-type: web-api-constructor
browser-compat: api.CustomEvent.CustomEvent
---
{{APIRef("DOM")}}
The **`CustomEvent()`** constructor creates a new {{domxref("CustomEvent")}} object.
## Syntax
```js-nolint
new CustomEvent(type)
new CustomEvent(type, options)
```
### Parameters
- `type`
- : A string providing the name of the event. Event names are case-sensitive.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `detail` {{optional_inline}}
- : An event-dependent value associated with the event. This value is then available to the handler using the {{domxref("CustomEvent.detail")}} property.
It defaults to `null`.
### Return value
A new {{domxref("CustomEvent")}} object.
## Example
```js
// create custom events
const catFound = new CustomEvent("animalfound", {
detail: {
name: "cat",
},
});
const dogFound = new CustomEvent("animalfound", {
detail: {
name: "dog",
},
});
// add an appropriate event listener
obj.addEventListener("animalfound", (e) => console.log(e.detail.name));
// dispatch the events
obj.dispatchEvent(catFound);
obj.dispatchEvent(dogFound);
// "cat" and "dog" logged in the console
```
Additional examples can be found at [Creating and triggering events](/en-US/docs/Web/Events/Creating_and_triggering_events).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CustomEvent")}}
- [Creating and triggering events](/en-US/docs/Web/Events/Creating_and_triggering_events)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/barcode_detection_api/index.md | ---
title: Barcode Detection API
slug: Web/API/Barcode_Detection_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.BarcodeDetector
---
{{securecontext_header}}{{DefaultAPISidebar("Barcode Detection API")}}{{AvailableInWorkers}}{{SeeCompatTable}}
The Barcode Detection API detects linear and two-dimensional barcodes in images.
## Concepts and usage
Support for barcode recognition within web apps unlocks a variety of use cases through supported barcode formats. QR codes can be used for online payments, web navigation or establishing social media connections, Aztec codes can be used to scan boarding passes and shopping apps can use EAN or UPC barcodes to compare prices of physical items.
Detection is achieved through the {{domxref('BarcodeDetector.detect()','detect()')}} method, which takes an image object; it can be one of these objects:
a {{domxref("HTMLImageElement")}},
a {{domxref("SVGImageElement")}},
a {{domxref("HTMLVideoElement")}},
a {{domxref("HTMLCanvasElement")}},
an {{domxref("ImageBitmap")}},
an {{domxref("OffscreenCanvas")}},
a {{domxref("VideoFrame")}},
a {{domxref('Blob')}},
or an {{domxref('ImageData')}}.
Optional parameters can be passed to the {{domxref('BarcodeDetector')}} constructor to provide hints on which barcode formats to detect.
### Supported barcode formats
The Barcode Detection API supports the following barcode formats:
<table class="no-markdown">
<thead>
<tr>
<th>Format</th>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td>aztec</td>
<td>
A square two-dimensional matrix following iso24778 and with a square
bullseye pattern at their center, thus resembling an Aztec pyramid. Does
not require a surrounding blank zone.
</td>
<td>
<img
alt="A sample image of an Aztec barcode. A square with smaller black and white squares inside"
src="aztec.gif"
/>
</td>
</tr>
<tr>
<td>code_128</td>
<td>
A linear (one-dimensional), bidirectionally-decodable, self-checking
barcode following iso15417 and able to encode all 128 characters of
{{Glossary("ASCII")}} (hence the naming).
</td>
<td>
<img
alt="An image of a code-128 barcode. A horizontal distribution of vertical black and white lines"
src="code-128.gif"
/>
</td>
</tr>
<tr>
<td>code_39</td>
<td>
A linear (one-dimensional), self-checking barcode following iso16388. It
is a discrete and variable-length barcode type.
</td>
<td>
<img
alt="An image of a code-39 barcode. A horizontal distribution of vertical black and white lines"
src="code-39.png"
/>
</td>
</tr>
<tr>
<td>code_93</td>
<td>
A linear, continuous symbology with a variable length following bc5. It
offers a larger information density than Code 128 and the visually
similar Code 39. Code 93 is used primarily by Canada Post to encode
supplementary delivery information.
</td>
<td>
<img
alt="An image of a code 93 format barcode. A horizontal distribution of white and black horizontal lines"
src="code-93.png"
/>
</td>
</tr>
<tr>
<td>codabar</td>
<td>
A linear barcode representing characters 0-9, A-D and symbols - . $ / +
</td>
<td>
<img
alt="An image of a codabar format barcode. A horizontal distribution of black and white vertical lines"
src="codabar.png"
/>
</td>
</tr>
<tr>
<td>data_matrix</td>
<td>
An orientation-independent two-dimensional barcode composed of black and
white modules arranged in either a square or rectangular pattern
following iso16022.
</td>
<td>
<img
alt="An example of a data matrix barcode. A square filled with smaller black and white squares"
src="data-matrix.png"
/>
</td>
</tr>
<tr>
<td>ean_13</td>
<td>
A linear barcode based on the UPC-A standard and defined in iso15420.
</td>
<td>
<img
alt="An image of an EAN-13 format barcode. A horizontal distribution of white and black lines"
src="ean-13.png"
/>
</td>
</tr>
<tr>
<td>ean_8</td>
<td>A linear barcode defined in iso15420 and derived from EAN-13.</td>
<td>
<img
alt="An image of an EAN-8 format barcode. A horizontal distribution of vertical black and white lines"
src="ean-8.png"
/>
</td>
</tr>
<tr>
<td>itf</td>
<td>
A continuous, self-checking, bidirectionally decodable barcode. It will
always encode 14 digits.
</td>
<td>
<img
alt="An image of an ITF Barcode. A horizontal distribution of white and black lines"
src="ift.png"
/>
</td>
</tr>
<tr>
<td>pdf417</td>
<td>
A continuous two-dimensional barcode symbology format with multiple rows
and columns. It's bi-directionally decodable and uses the iso15438
standard.
</td>
<td>
<img
alt="An example of a pdf417 barcode format. A rectangle of smaller black and white squares"
src="pdf417.png"
/>
</td>
</tr>
<tr>
<td>qr_code</td>
<td>
A two-dimensional barcode that uses the iso18004 standard. The
information encoded can be text, URL or other data.
</td>
<td>
<img
alt="An example of a QR code. A square of smaller black and white squares"
src="qr-code.png"
/>
</td>
</tr>
<tr>
<td>upc_a</td>
<td>
One of the most common linear barcode types and is widely applied to
retail in the United States. Defined in iso15420, it represents digits
by strips of bars and spaces, each digit being associated to a unique
pattern of 2 bars and 2 spaces, both of variable width. UPC-A can encode
12 digits that are uniquely assigned to each trade item, and it's
technically a subset of EAN-13 (UPC-A codes are represented in EAN-13
with the first character set to 0).
</td>
<td>
<img
alt="An image of a upc-a barcode. A rectangle of black and white vertical lines with numbers underneath"
src="upc-a.png"
/>
</td>
</tr>
<tr>
<td>upc_e</td>
<td>
A variation of UPC-A defined in iso15420, compressing out unnecessary
zeros for a more compact barcode.
</td>
<td>
<img
alt="An image of a upc-e barcode. A rectangle of black and white vertical lines"
src="upc-e.png"
/>
</td>
</tr>
<tr>
<td>unknown</td>
<td>
This value is used by the platform to signify that it does not know or
specify which barcode format is being detected or supported.
</td>
<td></td>
</tr>
</tbody>
</table>
You can check for formats supported by the user agent via the {{domxref('BarcodeDetector/getSupportedFormats_static','getSupportedFormats()')}} method.
## Interfaces
- {{domxref("BarcodeDetector")}} {{Experimental_Inline}}
- : The `BarcodeDetector` interface of the Barcode Detection API allows detection of linear and two dimensional barcodes in images.
## Examples
### Creating A Detector
This example tests for browser compatibility and creates a new barcode detector object, with specified supported formats.
```js
// check compatibility
if (!("BarcodeDetector" in globalThis)) {
console.log("Barcode Detector is not supported by this browser.");
} else {
console.log("Barcode Detector supported!");
// create new detector
const barcodeDetector = new BarcodeDetector({
formats: ["code_39", "codabar", "ean_13"],
});
}
```
### Getting Supported Formats
The following example calls the `getSupportedFormats()` method and logs the results to the console.
```js
// check supported types
BarcodeDetector.getSupportedFormats().then((supportedFormats) => {
supportedFormats.forEach((format) => console.log(format));
});
```
### Detect Barcodes
This example uses the `detect()` method to detect the barcodes within the given image. These are iterated over and the barcode data is logged to the console.
```js
barcodeDetector
.detect(imageEl)
.then((barcodes) => {
barcodes.forEach((barcode) => console.log(barcode.rawValue));
})
.catch((err) => {
console.log(err);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [barcodefaq.com: A website with information about different barcodes and examples of the different types.](https://www.barcodefaq.com/)
- [The Shape Detection API: a picture is worth a thousand words, faces, and barcodes](https://developer.chrome.com/docs/capabilities/shape-detection#barcodedetector)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webtransport/index.md | ---
title: WebTransport
slug: Web/API/WebTransport
page-type: web-api-interface
browser-compat: api.WebTransport
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`WebTransport`** interface of the {{domxref("WebTransport API", "WebTransport API", "", "nocode")}} provides functionality to enable a user agent to connect to an HTTP/3 server, initiate reliable and unreliable transport in either or both directions, and close the connection once it is no longer needed.
{{InheritanceDiagram}}
{{AvailableInWorkers}}
## Constructor
- {{domxref("WebTransport.WebTransport", "WebTransport()")}}
- : Creates a new `WebTransport` object instance.
## Instance properties
- {{domxref("WebTransport.closed", "closed")}} {{ReadOnlyInline}}
- : Returns a promise that resolves when the transport is closed.
- {{domxref("WebTransport.datagrams", "datagrams")}} {{ReadOnlyInline}}
- : Returns a {{domxref("WebTransportDatagramDuplexStream")}} instance that can be used to send and receive datagrams.
- {{domxref("WebTransport.congestionControl", "congestionControl")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a string that indicates the application preference for either high throughput or low-latency when sending data.
- {{domxref("WebTransport.incomingBidirectionalStreams", "incomingBidirectionalStreams")}} {{ReadOnlyInline}}
- : Represents one or more bidirectional streams opened by the server. Returns a {{domxref("ReadableStream")}} of {{domxref("WebTransportBidirectionalStream")}} objects. Each one can be used to read data from the server and write data back to it.
- {{domxref("WebTransport.incomingUnidirectionalStreams", "incomingUnidirectionalStreams")}} {{ReadOnlyInline}}
- : Represents one or more unidirectional streams opened by the server. Returns a {{domxref("ReadableStream")}} of {{domxref("WebTransportReceiveStream")}} objects. Each one can be used to read data from the server.
- {{domxref("WebTransport.ready", "ready")}} {{ReadOnlyInline}}
- : Returns a promise that resolves when the transport is ready to use.
- {{domxref("WebTransport.reliability", "reliability")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a string that indicates whether the connection supports reliable transports only, or whether it also supports unreliable transports (such as UDP).
## Instance methods
- {{domxref("WebTransport.close", "close()")}}
- : Closes an ongoing WebTransport session.
- {{domxref("WebTransport.createBidirectionalStream", "createBidirectionalStream()")}}
- : Asynchronously opens a bidirectional stream ({{domxref("WebTransportBidirectionalStream")}}) that can be used to read from and write to the server.
- {{domxref("WebTransport.createUnidirectionalStream", "createUnidirectionalStream()")}}
- : Asynchronously opens a unidirectional stream ({{domxref("WritableStream")}}) that can be used to write to the server.
- {{domxref("WebTransport.getStats", "getStats()")}} {{Experimental_Inline}}
- : Asynchronously returns a {{jsxref("Promise")}} that fulfills with an object containing HTTP/3 connection statistics.
## Examples
The example code below shows how you'd connect to an HTTP/3 server by passing its URL to the {{domxref("WebTransport.WebTransport", "WebTransport()")}} constructor.
Note that the scheme needs to be HTTPS, and the port number needs to be explicitly specified.
Once the {{domxref("WebTransport.ready")}} promise fulfills, you can start using the connection.
```js
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
return transport;
}
```
You can respond to the connection closing by waiting for the {{domxref("WebTransport.closed")}} promise to fulfill.
Errors returned by `WebTransport` operations are of type {{domxref("WebTransportError")}}, and contain additional data on top of the standard {{domxref("DOMException")}} set.
The `closeTransport()` method below shows a possible implementation.
Within a `try...catch` block it uses `await` to wait for the `closed` promise to fulfill or reject, and then reports whether or not the connection closed intentionally or due to error.
```js
async function closeTransport(transport) {
// Respond to connection closing
try {
await transport.closed;
console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
} catch (error) {
console.error(`The HTTP/3 connection to ${url} closed due to ${error}.`);
}
}
```
We might call the asynchronous functions above in their own asynchronous function, as shown below.
```js
// Use the transport
async function useTransport(url) {
const transport = await initTransport(url);
// Use the transport object to send and receive data
// ...
// When done, close the transport
await closeTransport(transport);
}
const url = "https://example.com:4999/wt";
useTransport(url);
```
For other example code, see the individual property and method pages.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/closed/index.md | ---
title: "WebTransport: closed property"
short-title: closed
slug: Web/API/WebTransport/closed
page-type: web-api-instance-property
browser-compat: api.WebTransport.closed
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`closed`** read-only property of the {{domxref("WebTransport")}} interface returns a promise that resolves when the transport is closed.
{{AvailableInWorkers}}
## Value
A {{jsxref("Promise")}} that resolves to an object containing the following properties:
- `closeCode`
- : A number representing the error code for the error.
- `reason`
- : A string representing the reason for closing the `WebTransport`.
## Examples
```js
const url = "https://example.com:4999/wt";
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
// ...
}
// ...
async function closeTransport(transport) {
// Respond to connection closing
try {
await transport.closed;
console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
} catch (error) {
console.error(`The HTTP/3 connection to ${url} closed due to ${error}.`);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/reliability/index.md | ---
title: "WebTransport: reliability property"
short-title: reliability
slug: Web/API/WebTransport/reliability
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.WebTransport.reliability
---
{{APIRef("WebTransport API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`reliability`** read-only property of the {{domxref("WebTransport")}} interface indicates whether the connection supports reliable transports only, or whether it also supports unreliable transports (such as UDP).
{{AvailableInWorkers}}
## Value
A string with one of the following values:
- `pending`
- : The connection has not yet been established.
The reliability is not yet known.
- `reliable-only`
- : The connection only supports reliable transports.
- `supports-unreliable`
- : The connection supports both unreliable and reliable transports.
## Examples
```js
const url = "https://example.com:4999/wt";
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// Once ready fulfils the connection can be used
// Prior to this the reliability is "pending"
await transport.ready;
if (transport.reliability == "reliable-only") {
// Use connection only with reliable transports
} else {
// Use connection with either reliable or unreliable transports.
}
// ...
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/datagrams/index.md | ---
title: "WebTransport: datagrams property"
short-title: datagrams
slug: Web/API/WebTransport/datagrams
page-type: web-api-instance-property
browser-compat: api.WebTransport.datagrams
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`datagrams`** read-only property of the {{domxref("WebTransport")}} interface returns a {{domxref("WebTransportDatagramDuplexStream")}} instance that can be used to send and receive datagrams — unreliable data transmission.
"Unreliable" means that transmission of data is not guaranteed, nor is arrival in a specific order. This is fine in some situations and provides very fast delivery. For example, you might want to transmit regular game state updates where each message supersedes the last one that arrives, and order is not important.
{{AvailableInWorkers}}
## Value
A {{domxref("WebTransportDatagramDuplexStream")}} object.
## Examples
### Writing an outgoing datagram
The {{domxref("WebTransportDatagramDuplexStream.writable")}} property returns a {{domxref("WritableStream")}} object that you can write data to using a writer, for transmission to the server:
```js
const writer = transport.datagrams.writable.getWriter();
const data1 = new Uint8Array([65, 66, 67]);
const data2 = new Uint8Array([68, 69, 70]);
writer.write(data1);
writer.write(data2);
```
### Reading an incoming datagram
The {{domxref("WebTransportDatagramDuplexStream.readable")}} property returns a {{domxref("ReadableStream")}} object that you can use to receive data from the server:
```js
async function readData() {
const reader = transport.datagrams.readable.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
// value is a Uint8Array.
console.log(value);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/getstats/index.md | ---
title: "WebTransport: getStats() method"
short-title: getStats()
slug: Web/API/WebTransport/getStats
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.WebTransport.getStats
---
{{APIRef("WebTransport API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`getStats()`** method of the {{domxref("WebTransport")}} interface asynchronously returns an object containing HTTP/3 connection statistics.
{{AvailableInWorkers}}
## Syntax
```js-nolint
getStats()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves to a object containing HTTP/3 connection statistics.
The returned object may have the following properties/statistics:
- `timestamp`
- : A {{domxref("DOMHighResTimeStamp")}} indicating the timestamp at which the statistics were gathered, relative to Jan 1, 1970, UTC.
- `bytesSent`
- : A positive integer indicating the number of bytes sent on the QUIC connection, including retransmissions.
Note that this count does not include additional data from protocols used by QUIC, such as UDP, or any other outer framing.
- `packetsSent`
- : A positive integer indicating the number of packets sent on the QUIC connection, including those that are known to have been lost.
- `packetsLost`
- : A positive integer indicating the number of packets lost on the QUIC connection.
This value will increase as packets are declared lost, and decrease if they are subsequently received.
- `numOutgoingStreamsCreated`
- : A positive integer indicating the number of outgoing QUIC streams created on the QUIC connection.
- `numIncomingStreamsCreated`
- : A positive integer indicating the number of incoming QUIC streams created on the QUIC connection.
- `bytesReceived`
- : A positive integer indicating the total number of bytes received on the QUIC connection.
This count includes duplicate data from streams, but does not include additional data for protocols used by QUIC, such as UDP, or any other outer framing.
- `packetsReceived`
- : A positive integer indicating the total number of packets received on the QUIC connection, including packets that were not processable.
- `smoothedRtt`
- : A {{domxref("DOMHighResTimeStamp")}} containing the smoothed [round-trip time (RTT)](/en-US/docs/Glossary/Round_Trip_Time) currently observed on the connection, calculated as an exponentially weighted moving average of an endpoint's RTT samples after taking account of acknowledgement delays.
- `rttVariation`
- : A {{domxref("DOMHighResTimeStamp")}} containing the mean variation in round-trip time samples currently observed on the connection.
- `minRtt`
- : A {{domxref("DOMHighResTimeStamp")}} containing the minimum round-trip time observed on the entire connection.
- `datagrams`
- : An object containing statistics for datagram transmission over the connection.
The object has the following properties:
- `timestamp`
- : A {{domxref("DOMHighResTimeStamp")}} indicating the timestamp at which the statistics were gathered, relative to Jan 1, 1970, UTC.
- `expiredOutgoing`
- : A positive integer indicating the number of datagrams that were dropped from the queue for sending because they expired.
Note that the maximum age before a datagram in the send-queue expires can be found in [`outgoingMaxAge`](/en-US/docs/Web/API/WebTransportDatagramDuplexStream/outgoingMaxAge).
- `droppedIncoming`
- : A positive integer indicating the number incoming datagrams that were dropped.
Incoming datagrams are dropped if the application does not read them before new datagrams overflow the [`readable` stream](/en-US/docs/Web/API/WebTransportDatagramDuplexStream/readable) receive queue.
- `lostOutgoing`
- : A positive integer indicating the number of sent datagrams that were declared lost.
Note that a datagram may be declared lost if, for example, no acknowledgement arrived within a timeout, or an acknowledgement for a later datagram was received first.
<!-- Note, this is not in Firefox IDL, and method not yet implemented by others in https://searchfox.org/mozilla-central/commit/4e6970cd336f1b642c0be6c9b697b4db5f7b6aeb
- `estimatedSendRate`
- : A positive integer indicating the estimated rate at which queued data will be sent by the user agent, in bits per second.
This rate applies to all streams and datagrams that share a `WebTransport` session.
The member is not present when the session is pooled with others in a shared connection (see [`allowPooling`](/en-US/docs/Web/API/WebTransport/WebTransport#allowpooling) in the `WebTransport` constructor), or if the user agent does not yet have an estimate.
-->
## Examples
The example below uses `await` to wait on the {{jsxref("Promise")}} returned by `getStats()`.
When the promise fulfills, the result for the `bytesSent` property in the stats object is logged to the console.
```js
const stats = await transport.getStats();
console.log(`Bytes send: ${stats.bytesSent}`);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/createbidirectionalstream/index.md | ---
title: "WebTransport: createBidirectionalStream() method"
short-title: createBidirectionalStream()
slug: Web/API/WebTransport/createBidirectionalStream
page-type: web-api-instance-method
browser-compat: api.WebTransport.createBidirectionalStream
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`createBidirectionalStream()`** method of the {{domxref("WebTransport")}} interface asynchronously opens and returns a bidirectional stream.
The method returns a {{jsxref("Promise")}} that resolves to a {{domxref("WebTransportBidirectionalStream")}} object, which has `readable` and `writable` properties that can be used to reliably read from and write to the server.
"Reliable" means that transmission and order of data are guaranteed.
This provides slower delivery (albeit faster than with WebSockets) than {{domxref("WebTransport.datagrams", "datagrams")}}, but is needed in situations where reliability and ordering are important, like chat applications.
The relative order in which queued bytes are emptied from created streams can be specified using the `sendOrder` option.
If set, queued bytes in streams with a higher send order are guaranteed to be sent before queued bytes for streams with a lower send order.
If the order number is not set then the order in which bytes are sent is implementation dependent.
Note however that even though bytes from higher send-order streams are sent first, they may not arrive first.
{{AvailableInWorkers}}
## Syntax
```js-nolint
createBidirectionalStream()
createBidirectionalStream(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object that may have the following properties:
- `sendOrder` {{optional_inline}}
- : A integer value specifying the send priority of this stream relative to other streams for which the value has been set.
Queued bytes are sent first for streams that have a higher value.
If not set, the send order depends on the implementation.
### Return value
A {{jsxref("Promise")}} that resolves to a {{domxref("WebTransportBidirectionalStream")}} object.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if `createBidirectionalStream()` is invoked while the `WebTransport` is closed or failed.
## Examples
An initial function is used to get references to the {{domxref("WebTransportBidirectionalStream.readable")}} and {{domxref("WebTransportBidirectionalStream.writable")}} properties. These are references to `WebTransportReceiveStream` and `WebTransportSendStream` instances, which are readable and writable streams that can be used to read from and write to the server.
```js
async function setUpBidirectional() {
const stream = await transport.createBidirectionalStream({
sendOrder: "596996858",
});
// stream is a WebTransportBidirectionalStream
// stream.readable is a ReadableStream
const readable = stream.readable;
// stream.writable is a WritableStream
const writable = stream.writable;
// ...
}
```
Reading from the `WebTransportReceiveStream` can then be done as follows:
```js
async function readData(readable) {
const reader = readable.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
// value is a Uint8Array.
console.log(value);
}
}
```
And writing to the `WebTransportSendStream` can be done like this:
```js
async function writeData(writable) {
const writer = writable.getWriter();
const data1 = new Uint8Array([65, 66, 67]);
const data2 = new Uint8Array([68, 69, 70]);
writer.write(data1);
writer.write(data2);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebTransport.createUnidirectionalStream()")}}
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/createunidirectionalstream/index.md | ---
title: "WebTransport: createUnidirectionalStream() method"
short-title: createUnidirectionalStream()
slug: Web/API/WebTransport/createUnidirectionalStream
page-type: web-api-instance-method
browser-compat: api.WebTransport.createUnidirectionalStream
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`createUnidirectionalStream()`** method of the {{domxref("WebTransport")}} interface asynchronously opens a unidirectional stream.
The method returns a {{jsxref("Promise")}} that resolves to a {{domxref("WritableStream")}} object, which can be used to reliably write data to the server.
<!-- Note, returns a `WebTransportSendStream` according to spec, but not yet implemented -->
"Reliable" means that transmission and order of data are guaranteed. This provides slower delivery (albeit faster than with WebSockets) than {{domxref("WebTransport.datagrams", "datagrams")}}, but is needed in situations where reliability and ordering are important, like chat applications.
The relative order in which queued bytes are emptied from created streams can be specified using the `sendOrder` option.
If set, queued bytes in streams with a higher send order are guaranteed to be sent before queued bytes for streams with a lower send order.
If the order number is not set then the order in which bytes are sent is implementation dependent.
Note however that even though bytes from higher send-order streams are sent first, they may not arrive first.
{{AvailableInWorkers}}
## Syntax
```js-nolint
createUnidirectionalStream()
createUnidirectionalStream(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object that may have the following properties:
- `sendOrder` {{optional_inline}}
- : A integer value specifying the send priority of this stream relative to other streams for which the value has been set.
Queued bytes are sent first for streams that have a higher value.
If not set, the send order depends on the implementation.
### Return value
A {{jsxref("Promise")}} that resolves to a `WebTransportSendStream` object (this is a {{domxref("WritableStream")}}).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if `createUnidirectionalStream()` is invoked while the WebTransport is closed or failed.
## Examples
Use the `createUnidirectionalStream()` method to get a reference to a {{domxref("WritableStream")}}. From this you can {{domxref("WritableStream.getWriter", "get a writer", "", "nocode")}} to allow data to be written to the stream and sent to the server.
Use the {{domxref("WritableStreamDefaultWriter.close", "close()")}} method of the resulting {{domxref("WritableStreamDefaultWriter")}} to close the associated HTTP/3 connection. The browser tries to send all pending data before actually closing the associated connection.
```js
async function writeData() {
const stream = await transport.createUnidirectionalStream({
sendOrder: "596996858",
});
const writer = stream.writable.getWriter();
const data1 = new Uint8Array([65, 66, 67]);
const data2 = new Uint8Array([68, 69, 70]);
writer.write(data1);
writer.write(data2);
try {
await writer.close();
console.log("All data has been sent.");
} catch (error) {
console.error(`An error occurred: ${error}`);
}
}
```
You can also use {{domxref("WritableStreamDefaultWriter.abort()")}} to abruptly terminate the stream. When using `abort()`, the browser may discard any pending data that hasn't yet been sent.
```js
// ...
const stream = await transport.createUnidirectionalStream();
const writer = ws.getWriter();
// ...
writer.write(...);
writer.write(...);
await writer.abort();
// Not all the data may have been written.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebTransport.createBidirectionalStream()")}}
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/incomingbidirectionalstreams/index.md | ---
title: "WebTransport: incomingBidirectionalStreams property"
short-title: incomingBidirectionalStreams
slug: Web/API/WebTransport/incomingBidirectionalStreams
page-type: web-api-instance-property
browser-compat: api.WebTransport.incomingBidirectionalStreams
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`incomingBidirectionalStreams`** read-only property of the {{domxref("WebTransport")}} interface represents one or more bidirectional streams opened by the server. Returns a {{domxref("ReadableStream")}} of {{domxref("WebTransportBidirectionalStream")}} objects. Each one can be used to reliably read data from the server and write data back to it.
"Reliable" means that transmission and order of data are guaranteed. This provides slower delivery (albeit faster than with WebSockets) than {{domxref("WebTransport.datagrams", "datagrams")}}, but is needed in situations where reliability and ordering are important, like chat applications.
{{AvailableInWorkers}}
## Value
A {{domxref("ReadableStream")}} of {{domxref("WebTransportBidirectionalStream")}} objects.
## Examples
An initial function is used to read the {{domxref("WebTransportBidirectionalStream")}} objects from the {{domxref("ReadableStream")}}. For each one, the {{domxref("WebTransportBidirectionalStream.readable")}} and {{domxref("WebTransportBidirectionalStream.writable")}} values are passed to other functions to read from and write to those streams.
```js
async function receiveBidirectional() {
const bds = transport.incomingBidirectionalStreams;
const reader = bds.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
// value is an instance of WebTransportBidirectionalStream
await readData(value.readable);
await writeData(value.writable);
}
}
async function readData(readable) {
const reader = readable.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
// value is a Uint8Array.
console.log(value);
}
}
async function writeData(writable) {
const writer = writable.getWriter();
const data1 = new Uint8Array([65, 66, 67]);
const data2 = new Uint8Array([68, 69, 70]);
writer.write(data1);
writer.write(data2);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/ready/index.md | ---
title: "WebTransport: ready property"
short-title: ready
slug: Web/API/WebTransport/ready
page-type: web-api-instance-property
browser-compat: api.WebTransport.ready
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`ready`** read-only property of the {{domxref("WebTransport")}} interface returns a promise that resolves when the transport is ready to use.
{{AvailableInWorkers}}
## Value
A {{jsxref("Promise")}} that resolves to `undefined`.
## Examples
```js
const url = "https://example.com:4999/wt";
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
// ...
}
// ...
async function closeTransport(transport) {
// Respond to connection closing
try {
await transport.closed;
console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
} catch (error) {
console.error(`The HTTP/3 connection to ${url} closed due to ${error}.`);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/incomingunidirectionalstreams/index.md | ---
title: "WebTransport: incomingUnidirectionalStreams property"
short-title: incomingUnidirectionalStreams
slug: Web/API/WebTransport/incomingUnidirectionalStreams
page-type: web-api-instance-property
browser-compat: api.WebTransport.incomingUnidirectionalStreams
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`incomingUnidirectionalStreams`** read-only property of the {{domxref("WebTransport")}} interface represents one or more unidirectional streams opened by the server. Returns a {{domxref("ReadableStream")}} of {{domxref("WebTransportReceiveStream")}} objects. Each one can be used to reliably read data from the server.
"Reliable" means that transmission and order of data are guaranteed. This provides slower delivery (albeit faster than with WebSockets) than {{domxref("WebTransport.datagrams", "datagrams")}}, but is needed in situations where reliability and ordering are important, like chat applications.
{{AvailableInWorkers}}
## Value
A {{domxref("ReadableStream")}} of {{domxref("WebTransportReceiveStream")}} objects.
## Examples
An initial function is used to read the {{domxref("WebTransportReceiveStream")}} objects from the {{domxref("ReadableStream")}}. Each object is then passed to another function to read from those streams.
```js
async function receiveUnidirectional() {
const uds = transport.incomingUnidirectionalStreams;
const reader = uds.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
// value is an instance of WebTransportReceiveStream
await readData(value);
}
}
async function readData(receiveStream) {
const reader = receiveStream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
// value is a Uint8Array
console.log(value);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/webtransport/index.md | ---
title: "WebTransport: WebTransport() constructor"
short-title: WebTransport()
slug: Web/API/WebTransport/WebTransport
page-type: web-api-constructor
browser-compat: api.WebTransport.WebTransport
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`WebTransport()`** constructor creates a new {{domxref("WebTransport")}} object instance.
{{AvailableInWorkers}}
## Syntax
```js-nolint
new WebTransport(url)
new WebTransport(url, options)
```
### Parameters
- `url`
- : A string representing the URL of the HTTP/3 server to connect to.
The scheme must be HTTPS, and the port number needs to be explicitly specified.
- `options` {{optional_inline}}
- : An object that may have the following properties:
- `allowPooling` {{optional_inline}}
- : A boolean value.
If `true`, the network connection for this {{domxref("WebTransport")}} can be shared with a pool of other HTTP/3 sessions.
By default the value is `false`, and the connection cannot be shared.
- `congestionControl` {{optional_inline}}
- : A string indicating the application's preference that the congestion control algorithm used when sending data over this connection be tuned for either throughput or low-latency.
This is a hint to the user agent.
The allowed values are: `default` (default), `throughput`, and `low-latency`.
- `requireUnreliable` {{optional_inline}}
- : A boolean value.
If `true`, the connection cannot be established over HTTP/2 if an HTTP/3 connection is not possible.
By default the value is `false`.
- `serverCertificateHashes` {{optional_inline}}
- : An array of objects, each defining the hash value of a server certificate along with the name of the algorithm that was used to generate it.
This option is only supported for transports using dedicated connections (`allowPooling` is `false`).
If specified, the browser will attempt to authenticate the certificate provided by the server against the provided certificate hash(es) in order to connect, instead of using the Web public key infrastructure (PKI).
If any hashes match, the browser knows that the server has possession of a trusted certificate and will connect as normal.
If empty the user agent uses the same PKI certificate verification procedures it would use for a normal fetch operation.
This feature allows developers to connect to WebTransport servers that would normally find obtaining a publicly trusted certificate challenging, such as hosts that are not publicly routable, or ephemeral hosts like virtual machines.
> **Note:** The web application might typically fetch the hashes from a trusted intermediary.
> For example, you might use a cloud provider to provision VMs that run your WebTransport servers.
> The provider has trusted access to the server and can request its certificate, generate hashes, and provide these to the application via an API (which is mediated via PKI), or a cloud console.
> The web application can now connect directly to the VM-hosted server using the supplied hashes, even though the VM itself does not have a long-lived TLS certificate.
The certificate must be an X.509v3 certificate that has a validity period of less that 2 weeks, and the current time must be within that validity period.
The format of the public key in the certificate depends on the implementation, but must minimally include ECDSA with the secp256r1 (NIST P-256) named group, and must not include RSA keys.
An ECSDA key is therefore an interoperable default public key format.
A user agent may add further requirements; these will be listed in the [browser compatibility](#browser_compatibility) section if known.
Each object in the array has the following properties:
- `algorithm`
- : A string with the value: `sha-256` (case-insensitive).
Note that this string represents the algorithm to use to verify the hash, and that any hash using an unknown algorithm will be ignored.
At time of writing, `SHA-256` is the only hash algorithm listed in the specification.
- `value`
- : An [`ArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or {{jsxref("TypedArray")}} containing the hash value.
### Exceptions
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if `serverCertificateHashes` is specified but the transport protocol does not support this feature.
- `SyntaxError`
- : Thrown if the specified `url` is invalid, if the scheme is not HTTPS, or if the URL includes a fragment.
- `TypeError`
- : Thrown if a `serverCertificateHashes` is set for a non-dedicated connection (in other words, if `allowPooling` is `true`).
## Examples
### Connecting with default options
This example shows how you might construct a `WebTransport` using just a URL, wait for it to connect, and then monitor the transport and report when it has closed.
First we define an `async` method that takes an URL and uses it to construct the `WebTransport` object.
No constructor options are specified, so the connection uses default options: dedicated connection, support for unreliable transports is not required, default congestion control, and normal Web PKI authentication with the server.
Note that the scheme needs to be HTTPS, and the port number needs to be explicitly specified.
Once the {{domxref("WebTransport.ready")}} promise fulfills, you can start using the connection.
```js
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
return transport;
}
```
You can respond to the connection closing by waiting for the {{domxref("WebTransport.closed")}} promise to fulfill.
Errors returned by `WebTransport` operations are of type {{domxref("WebTransportError")}}, and contain additional data on top of the standard {{domxref("DOMException")}} set.
The `closeTransport()` method below shows how.
Within a `try...catch` block it uses `await` to wait for the `closed` promise to fulfill or reject, and then reports whether or not the connection closed intentionally or due to error.
```js
async function closeTransport(transport) {
// Respond to connection closing
try {
await transport.closed;
console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
} catch (error) {
console.error(`The HTTP/3 connection to ${url} closed due to ${error}.`);
}
}
```
We might call the asynchronous functions above in their own asynchronous function, as shown below.
```js
// Use the transport
async function useTransport(url) {
const transport = await initTransport(url);
// Use the transport object to send and receive data
// ...
// When done, close the transport
await closeTransport(transport);
}
const url = "https://example.com:4999/wt";
useTransport(url);
```
### Connecting with server certificate hashes
The example below shows the code to construct a `WebTransport` that specifies the `serverCertificateHashes` option.
In this case the array contains two hashes, both encoded using the SHA-256 algorithm.
Note that the `allowPooling` option must be `false` (the default).
```js
const transport = new WebTransport(url, {
serverCertificateHashes: [
{
algorithm: "sha-256",
value: "5a155927eba7996228455e4721e6fe5f739ae15db6915d765e5db302b4f8a274",
},
{
algorithm: "sha-256",
value: "7d7094e7a8d3097feff3b5ee84fa5cab58e4de78f38bcfdee5ea8b51f4bfa8fd",
},
],
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/congestioncontrol/index.md | ---
title: "WebTransport: congestionControl property"
short-title: congestionControl
slug: Web/API/WebTransport/congestionControl
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.WebTransport.congestionControl
---
{{APIRef("WebTransport API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`congestionControl`** read-only property of the {{domxref("WebTransport")}} interface indicates the application's preference for either high throughput or low-latency when sending data.
The value is set in the [`WebTransport()` constructor options](/en-US/docs/Web/API/WebTransport/WebTransport#congestioncontrol).
{{AvailableInWorkers}}
## Value
A string with one of the following values:
- `default`
- : The default congestion control tuning for the transport.
This is the default.
- `throughput`
- : The application prefers congestion control to be tuned for throughput.
- `low-latency`
- : The application prefers congestion control to be tuned for low-latency.
## Examples
This example shows how to get the `congestionControl` preference.
As this is not explicitly set in the constructor, the result is `default`.
```js
const url = "https://example.com:4999/wt";
const transport = new WebTransport(url);
console.log(transport.congestionControl); // default
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/webtransport | data/mdn-content/files/en-us/web/api/webtransport/close/index.md | ---
title: "WebTransport: close() method"
short-title: close()
slug: Web/API/WebTransport/close
page-type: web-api-instance-method
browser-compat: api.WebTransport.close
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`close()`** method of the {{domxref("WebTransport")}} interface closes an ongoing WebTransport session.
{{AvailableInWorkers}}
## Syntax
```js-nolint
close(info)
```
### Parameters
- `info` {{optional_inline}}
- : An object containing the following properties:
- `closeCode`
- : A number representing the error code for the error.
- `reason`
- : A string representing the reason for closing the `WebTransport`.
### Return value
`undefined`.
### Exceptions
- {{domxref("WebTransportError")}}
- : Thrown if `close()` is invoked while the WebTransport is in the process of connecting.
## Examples
```js
const url = "https://example.com:4999/wt";
// Initialize transport connection
const transport = new WebTransport(url);
// ...
transport.close({
closeCode: 017,
reason: "CloseButtonPressed",
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/vreyeparameters/index.md | ---
title: VREyeParameters
slug: Web/API/VREyeParameters
page-type: web-api-interface
status:
- deprecated
- non-standard
browser-compat: api.VREyeParameters
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`VREyeParameters`** interface of the [WebVR API](/en-US/docs/Web/API/WebVR_API) represents all the information required to correctly render a scene for a given eye, including field of view information.
> **Note:** This interface 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/).
This interface is accessible through the {{domxref("VRDisplay.getEyeParameters()")}} method.
> **Warning:** The values in this interface should not be used to compute view or projection matrices. In order to ensure the widest possible hardware compatibility use the matrices provided by {{domxref("VRFrameData")}}.
## Instance properties
- {{domxref("VREyeParameters.offset")}} {{Deprecated_Inline}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : Represents the offset from the center point between the user's eyes to the center of the eye, measured in meters.
- {{domxref("VREyeParameters.fieldOfView")}} {{Deprecated_Inline}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : Describes the current field of view for the eye, which can vary as the user adjusts their interpupillary distance (IPD).
- {{domxref("VREyeParameters.renderWidth")}} {{Deprecated_Inline}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : Describes the recommended render target width of each eye viewport, in pixels.
- {{domxref("VREyeParameters.renderHeight")}} {{Deprecated_Inline}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : Describes the recommended render target height of each eye viewport, in pixels.
## Examples
```js
navigator.getVRDisplays().then((displays) => {
// If a display is available, use it to present the scene
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");
// Set the canvas size to the size of the vrDisplay viewport
const leftEye = vrDisplay.getEyeParameters("left");
const rightEye = vrDisplay.getEyeParameters("right");
canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2;
canvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight);
drawVRScene();
});
});
});
```
## Specifications
This interface 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/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vreyeparameters | data/mdn-content/files/en-us/web/api/vreyeparameters/renderwidth/index.md | ---
title: "VREyeParameters: renderWidth property"
short-title: renderWidth
slug: Web/API/VREyeParameters/renderWidth
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VREyeParameters.renderWidth
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`renderWidth`** read-only property of the {{domxref("VREyeParameters")}} interface describes the recommended render target width of each eye viewport, in pixels.
> **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/).
This is already in device pixel units, so there's no need to multiply by [Window.devicePixelRatio](/en-US/docs/Web/API/Window/devicePixelRatio) before setting to [HTMLCanvasElement.width.](/en-US/docs/Web/API/HTMLCanvasElement/width)
## Value
A number, representing the width in pixels.
## Examples
See [`VREyeParameters`](/en-US/docs/Web/API/VREyeParameters#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/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vreyeparameters | data/mdn-content/files/en-us/web/api/vreyeparameters/fieldofview/index.md | ---
title: "VREyeParameters: fieldOfView property"
short-title: fieldOfView
slug: Web/API/VREyeParameters/fieldOfView
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VREyeParameters.fieldOfView
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`fieldOfView`** read-only property of the {{domxref("VREyeParameters")}} interface returns a {{domxref("VRFieldOfView")}} object describing the current field of view for the eye, which can vary as the user adjusts their interpupillary distance (IPD).
> **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
A {{domxref("VRFieldOfView")}} object.
## Examples
See [`VRFieldOfView`](/en-US/docs/Web/API/VRFieldOfView#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/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vreyeparameters | data/mdn-content/files/en-us/web/api/vreyeparameters/renderheight/index.md | ---
title: "VREyeParameters: renderHeight property"
short-title: renderHeight
slug: Web/API/VREyeParameters/renderHeight
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VREyeParameters.renderHeight
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`renderHeight`** read-only property of the {{domxref("VREyeParameters")}} interface describes the recommended render target height of each eye viewport, in pixels.
> **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/).
This is already in device pixel units, so there's no need to multiply by [Window.devicePixelRatio](/en-US/docs/Web/API/Window/devicePixelRatio) before setting to [HTMLCanvasElement.height.](/en-US/docs/Web/API/HTMLCanvasElement/height)
## Value
A number, representing the height in pixels.
## Examples
See [`VREyeParameters`](/en-US/docs/Web/API/VREyeParameters#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/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vreyeparameters | data/mdn-content/files/en-us/web/api/vreyeparameters/maximumfieldofview/index.md | ---
title: "VREyeParameters: maximumFieldOfView property"
short-title: maximumFieldOfView
slug: Web/API/VREyeParameters/maximumFieldOfView
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VREyeParameters.maximumFieldOfView
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`maximumFieldOfView`** read-only property of the {{domxref("VREyeParameters")}} interface describes the maximum supported field of view for the current eye.
> **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
A {{domxref("VRFieldOfView")}} object.
## 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/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- {{domxref("VRFieldOfView")}}
| 0 |
data/mdn-content/files/en-us/web/api/vreyeparameters | data/mdn-content/files/en-us/web/api/vreyeparameters/minimumfieldofview/index.md | ---
title: "VREyeParameters: minimumFieldOfView property"
short-title: minimumFieldOfView
slug: Web/API/VREyeParameters/minimumFieldOfView
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VREyeParameters.minimumFieldOfView
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`minimumFieldOfView`** read-only property of the {{domxref("VREyeParameters")}} interface describes the minimum supported field of view for the current eye.
> **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
A {{domxref("VRFieldOfView")}} object.
## 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/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- {{domxref("VRFieldOfView")}}
| 0 |
data/mdn-content/files/en-us/web/api/vreyeparameters | data/mdn-content/files/en-us/web/api/vreyeparameters/offset/index.md | ---
title: "VREyeParameters: offset property"
short-title: offset
slug: Web/API/VREyeParameters/offset
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VREyeParameters.offset
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`offset`** read-only property of the {{domxref("VREyeParameters")}} interface represents the offset from the center point between the user's eyes to the center of the eye, measured in meters.
> **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/).
This value should represent half the user's interpupillary distance (IPD), but may also represent the distance from the center point of the headset to the center point of the lens for the given eye.
## Value
A {{jsxref("Float32Array")}} representing a vector describing the offset from the center point between the users eyes to the center of the eye in meters.
> **Note:** Values for the left eye will be negative; values for the right eye will be positive.
## Examples
See [`VRFieldOfView`](/en-US/docs/Web/API/VRFieldOfView#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/).
## Browser compatibility
{{Compat}}
## 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/svgnumber/index.md | ---
title: SVGNumber
slug: Web/API/SVGNumber
page-type: web-api-interface
browser-compat: api.SVGNumber
---
{{APIRef("SVG")}}
The **`SVGNumber`** interface corresponds to the {{cssxref("<number>")}} basic data type.
An `SVGNumber` object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown.
## Instance properties
- {{domxref("SVGNumber.value")}}
- : A float representing the number.
Note: If the `SVGNumber` is read-only, a {{domxref("DOMException")}} with the code NO_MODIFICATION_ALLOWED_ERR is raised on an attempt to change the value.
## Instance methods
_This interface doesn't provide any specific methods._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/vrdisplayevent/index.md | ---
title: VRDisplayEvent
slug: Web/API/VRDisplayEvent
page-type: web-api-interface
status:
- deprecated
- non-standard
browser-compat: api.VRDisplayEvent
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`VRDisplayEvent`** interface of the [WebVR API](/en-US/docs/Web/API/WebVR_API) represents the event object of WebVR-related events (see the [list of WebVR window extensions](/en-US/docs/Web/API/WebVR_API#window)).
> **Note:** This interface 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/).
## Constructor
- {{domxref("VRDisplayEvent.VRDisplayEvent", "VRDisplayEvent()")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Creates a `VRDisplayEvent` object instance.
## Instance properties
_`VRDisplayEvent` also inherits properties from its parent object, {{domxref("Event")}}._
- {{domxref("VRDisplayEvent.display")}} {{Deprecated_Inline}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : The {{domxref("VRDisplay")}} associated with this event.
- {{domxref("VRDisplayEvent.reason")}} {{Deprecated_Inline}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : A human-readable reason why the event was fired.
## Examples
```js
window.addEventListener("vrdisplaypresentchange", (e) => {
console.log(
`Display ${e.display.displayId} presentation has changed. Reason given: ${e.reason}.`,
);
});
```
## Specifications
This interface 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/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vrdisplayevent | data/mdn-content/files/en-us/web/api/vrdisplayevent/display/index.md | ---
title: "VRDisplayEvent: display property"
short-title: display
slug: Web/API/VRDisplayEvent/display
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VRDisplayEvent.display
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`display`** read-only property of the {{domxref("VRDisplayEvent")}} interface returns the {{domxref("VRDisplay")}} associated with this event.
> **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
A {{domxref("VRDisplay")}} object.
## Examples
```js
window.addEventListener("vrdisplaypresentchange", (e) => {
console.log(
`Display ${e.display.displayId} presentation has changed. Reason given: ${e.reason}.`,
);
});
```
## 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/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vrdisplayevent | data/mdn-content/files/en-us/web/api/vrdisplayevent/reason/index.md | ---
title: "VRDisplayEvent: reason property"
short-title: reason
slug: Web/API/VRDisplayEvent/reason
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VRDisplayEvent.reason
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`reason`** read-only property of the {{domxref("VRDisplayEvent")}} interface returns a human-readable reason why the event was fired.
> **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
A string representing the reason why the event was fired. The available reasons are defined in the [`VRDisplayEventReason`](https://w3c.github.io/webvr/spec/1.1/#interface-vrdisplayeventreason) enum, and are as follows:
- `mounted` — The {{domxref("VRDisplay")}} has detected that the user has put it on (or it has been otherwise activated).
- `navigation` — The page has been navigated to from a context that allows this page to begin presenting immediately, such as from another site that was already in VR presentation mode.
- `requested` — The user agent has requested that VR presentation mode be started. This allows user agents to include a consistent UI to enter VR across different sites.
- `unmounted` — The {{domxref("VRDisplay")}} has detected that the user has taken it off (or it has been otherwise slept/put on standby).
## Examples
```js
window.addEventListener("vrdisplaypresentchange", (e) => {
console.log(
`Display ${e.display.displayId} presentation has changed. Reason given: ${e.reason}.`,
);
});
```
## 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/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vrdisplayevent | data/mdn-content/files/en-us/web/api/vrdisplayevent/vrdisplayevent/index.md | ---
title: "VRDisplayEvent: VRDisplayEvent() constructor"
short-title: VRDisplayEvent()
slug: Web/API/VRDisplayEvent/VRDisplayEvent
page-type: web-api-constructor
status:
- deprecated
- non-standard
browser-compat: api.VRDisplayEvent.VRDisplayEvent
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`VRDisplayEvent()`** constructor creates a {{domxref("VRDisplayEvent")}} object.
> **Note:** This constructor 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/).
## Syntax
```js-nolint
new VRDisplayEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers set it to `vrdisplayconnect`, `vrdisplaydisconnect`, `vrdisplayactivate`, `vrdisplaydeactivate`, `vrdisplayblur`,
`vrdisplaypointerrestricted`, `vrdisplaypointerunrestricted`, or `vrdisplaypresentchange`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `display`
- : The {{domxref("VRDisplay")}} the event is to be associated with.
- `reason`
- : A string representing the human-readable reason why the event is to be fired (see {{domxref("VRDisplayEvent.reason")}}).
### Return value
A new {{domxref("VRDisplayEvent")}} object.
## Examples
```js
const myEventObject = new VRDisplayEvent("custom", {
display: vrDisplay,
reason: "Custom reason",
});
```
## Specifications
This constructor 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/).
## Browser compatibility
{{Compat}}
## 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/imagebitmaprenderingcontext/index.md | ---
title: ImageBitmapRenderingContext
slug: Web/API/ImageBitmapRenderingContext
page-type: web-api-interface
browser-compat: api.ImageBitmapRenderingContext
---
{{APIRef("Canvas API")}}
The **`ImageBitmapRenderingContext`** interface is a canvas rendering context that provides the functionality to replace the canvas's contents with the given {{domxref("ImageBitmap")}}. Its context id (the first argument to {{domxref("HTMLCanvasElement.getContext()")}} or {{domxref("OffscreenCanvas.getContext()")}}) is `"bitmaprenderer"`.
This interface is available in both the window and the [worker](/en-US/docs/Web/API/Web_Workers_API) context.
## Instance methods
- {{domxref("ImageBitmapRenderingContext.transferFromImageBitmap()")}}
- : Displays the given `ImageBitmap` in the canvas associated with this rendering context. Ownership of the `ImageBitmap` is transferred to the canvas. This was previously named `transferImageBitmap()`, but was renamed in a spec change. The old name is being kept as an alias to avoid code breakage.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("OffscreenCanvas")}}
| 0 |
data/mdn-content/files/en-us/web/api/imagebitmaprenderingcontext | data/mdn-content/files/en-us/web/api/imagebitmaprenderingcontext/transferfromimagebitmap/index.md | ---
title: "ImageBitmapRenderingContext: transferFromImageBitmap() method"
short-title: transferFromImageBitmap()
slug: Web/API/ImageBitmapRenderingContext/transferFromImageBitmap
page-type: web-api-instance-method
browser-compat: api.ImageBitmapRenderingContext.transferFromImageBitmap
---
{{APIRef("Canvas API")}}
The **`ImageBitmapRenderingContext.transferFromImageBitmap()`**
method displays the given {{domxref("ImageBitmap")}} in the canvas associated with this
rendering context. The ownership of the `ImageBitmap` is transferred to the
canvas as well.
This method was previously named `transferImageBitmap()`, but was renamed in
a spec change. The old name is being kept as an alias to avoid code breakage.
## Syntax
```js-nolint
transferFromImageBitmap(bitmap)
```
### Parameters
- `bitmap`
- : An {{domxref("ImageBitmap")}} object to transfer.
### Return value
None ({{jsxref("undefined")}}).
## Examples
### HTML
```html
<canvas id="htmlCanvas"></canvas>
```
### JavaScript
```js
const htmlCanvas = document
.getElementById("htmlCanvas")
.getContext("bitmaprenderer");
// Draw a WebGL scene offscreen
const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");
// Perform some drawing using the gl context
// Transfer the current frame to the visible canvas
const bitmap = offscreen.transferToImageBitmap();
htmlCanvas.transferFromImageBitmap(bitmap);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The interface defining this method, {{domxref("ImageBitmapRenderingContext")}}
- {{domxref("OffscreenCanvas")}}
- {{domxref("OffscreenCanvas.transferToImageBitmap()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlinputelement/index.md | ---
title: HTMLInputElement
slug: Web/API/HTMLInputElement
page-type: web-api-interface
browser-compat: api.HTMLInputElement
---
{{APIRef("HTML DOM")}}
The **`HTMLInputElement`** interface provides special properties and methods for manipulating the options, layout, and presentation of {{HtmlElement("input")}} elements.
{{InheritanceDiagram}}
## Instance properties
_Also inherits properties from its parent interface, {{domxref("HTMLElement")}}._
Some properties only apply to input element types that support the corresponding attributes.
- {{domxref("HTMLInputElement.align", "align")}} {{Deprecated_Inline}}
- : A string that represents the alignment of the element. _Use CSS instead._
- {{domxref("HTMLInputElement.defaultValue", "defaultValue")}}
- : A string that represents the default value as originally specified in the HTML that created this object.
- {{domxref("HTMLInputElement.dirName", "dirName")}}
- : A string that represents the directionality of the element.
- {{domxref("HTMLInputElement.incremental", "incremental")}} {{Non-standard_Inline}}
- : A boolean that represents the search event fire mode, if `true`, fires on every keypress, or on clicking the cancel button; otherwise fires when pressing <kbd>Enter</kbd>.
- {{domxref("HTMLInputElement.labels", "labels")}} {{ReadOnlyInline}}
- : Returns a list of {{ HTMLElement("label") }} elements that are labels for this element.
- {{domxref("HTMLInputElement.list", "list")}} {{ReadOnlyInline}}
- : Returns the element pointed to by the [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute. The property may be `null` if no HTML element is found in the same tree.
- {{domxref("HTMLInputElement.multiple", "multiple")}}
- : A boolean that represents the element's [`multiple`](/en-US/docs/Web/HTML/Element/input#multiple) attribute, indicating whether more than one value is possible (e.g., multiple files).
- {{domxref("HTMLInputElement.name", "name")}}
- : A string that represents the element's [`name`](/en-US/docs/Web/HTML/Element/input#name) attribute, containing a name that identifies the element when submitting the form.
- {{domxref("HTMLInputElement.popoverTargetAction", "popoverTargetAction")}}
- : Gets and sets the action to be performed (`"hide"`, `"show"`, or `"toggle"`) on a popover element being controlled by an {{htmlelement("input")}} element of `type="button"`. It reflects the value of the [`popovertargetaction`](/en-US/docs/Web/HTML/Element/input#popovertargetaction) HTML attribute.
- {{domxref("HTMLInputElement.popoverTargetElement", "popoverTargetElement")}}
- : Gets and sets the popover element to control via an {{htmlelement("input")}} element of `type="button"`. The JavaScript equivalent of the [`popovertarget`](/en-US/docs/Web/HTML/Element/input#popovertarget) HTML attribute.
- {{domxref("HTMLInputElement.step", "step")}}
- : A string that represents the element's [`step`](/en-US/docs/Web/HTML/Element/input#step) attribute, which works with [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) to limit the increments at which a numeric or date-time value can be set. It can be the string `any` or a positive floating point number. If this is not set to `any`, the control accepts only values at multiples of the step value greater than the minimum.
- {{domxref("HTMLInputElement.type", "type")}}
- : A string that represents the element's [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute, indicating the type of control to display. For possible values, see the documentation for the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute.
- {{domxref("HTMLInputElement.useMap", "useMap")}} {{Deprecated_Inline}}
- : A string that represents a client-side image map.
- {{domxref("HTMLInputElement.value", "value")}}
- : A string that represents the current value of the control. If the user enters a value different from the value expected, this may return an empty string.
- {{domxref("HTMLInputElement.valueAsDate", "valueAsDate")}}
- : A {{jsxref("Date")}} that represents the value of the element, interpreted as a date, or `null` if conversion is not possible.
- {{domxref("HTMLInputElement.valueAsNumber", "valueAsNumber")}}
- : A number that represents the value of the element, interpreted as one of the following, in order: A time value, a number, or `NaN` if conversion is impossible.
### Instance properties related to the parent form
- {{domxref("HTMLInputElement.form", "form")}} {{ReadOnlyInline}}
- : Returns a reference to the parent {{HtmlElement("form")}} element.
- {{domxref("HTMLInputElement.formAction", "formAction")}}
- : A string that represents the element's [`formaction`](/en-US/docs/Web/HTML/Element/input#formaction) attribute, containing the URL of a program that processes information submitted by the element. This overrides the [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute of the parent form.
- {{domxref("HTMLInputElement.formEnctype", "formEnctype")}}
- : A string that represents the element's [`formenctype`](/en-US/docs/Web/HTML/Element/input#formenctype) attribute, containing the type of content that is used to submit the form to the server. This overrides the [`enctype`](/en-US/docs/Web/HTML/Element/form#enctype) attribute of the parent form.
- {{domxref("HTMLInputElement.formMethod", "formMethod")}}
- : A string that represents the element's [`formmethod`](/en-US/docs/Web/HTML/Element/input#formmethod) attribute, containing the HTTP method that the browser uses to submit the form. This overrides the [`method`](/en-US/docs/Web/HTML/Element/form#method) attribute of the parent form.
- {{domxref("HTMLInputElement.formNoValidate", "formNoValidate")}}
- : A boolean that represents the element's [`formnovalidate`](/en-US/docs/Web/HTML/Element/input#formnovalidate) attribute, indicating that the form is not to be validated when it is submitted. This overrides the [`novalidate`](/en-US/docs/Web/HTML/Element/form#novalidate) attribute of the parent form.
- {{domxref("HTMLInputElement.formTarget", "formTarget")}}
- : A string that represents the element's [`formtarget`](/en-US/docs/Web/HTML/Element/input#formtarget) attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. This overrides the [`target`](/en-US/docs/Web/HTML/Element/form#target) attribute of the parent form.
### Instance properties that apply to any type of input element that is not hidden
- {{domxref("HTMLInputElement.disabled", "disabled")}}
- : A boolean that represents the element's [`disabled`](/en-US/docs/Web/HTML/Element/input#disabled) attribute, indicating that the control is not available for interaction. The input values will not be submitted with the form. See also [`readonly`](/en-US/docs/Web/HTML/Element/input#readonly).
- {{domxref("HTMLInputElement.required", "required")}}
- : A boolean that represents the element's [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute, indicating that the user must fill in a value before submitting a form.
- {{domxref("HTMLInputElement.validationMessage", "validationMessage")}} {{ReadOnlyInline}}
- : Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ([`willValidate`](/en-US/docs/Web/API/HTMLObjectElement/willValidate) is `false`), or it satisfies its constraints. This value can be set by the {{domxref("HTMLInputElement.setCustomValidity()", "setCustomValidity()")}} method.
- {{domxref("HTMLInputElement.validity", "validity")}} {{ReadOnlyInline}}
- : Returns the element's current validity state.
- {{domxref("HTMLInputElement.willValidate", "willValidate")}} {{ReadOnlyInline}}
- : Returns whether the element is a candidate for constraint validation. It is `false` if any conditions bar it from constraint validation, including: its `type` is one of `hidden`, `reset` or `button`, it has a {{HTMLElement("datalist")}} ancestor or its `disabled` property is `true`.
### Instance properties that apply only to elements of type checkbox or radio
- {{domxref("HTMLInputElement.checked", "checked")}}
- : A boolean that represents the current state of the element.
- {{domxref("HTMLInputElement.defaultChecked", "defaultChecked")}}
- : A boolean that represents the default state of a radio button or checkbox as originally specified in HTML that created this object.
- {{domxref("HTMLInputElement.indeterminate", "indeterminate")}}
- : A boolean that represents whether the checkbox or radio button is in indeterminate state. For checkboxes, the effect is that the appearance of the checkbox is obscured/greyed in some way as to indicate its state is indeterminate (not checked but not unchecked). Does not affect the value of the `checked` attribute, and clicking the checkbox will set the value to false.
### Instance properties that apply only to elements of type image
- {{domxref("HTMLInputElement.alt", "alt")}}
- : A string that represents the element's [`alt`](/en-US/docs/Web/HTML/Element/input#alt) attribute, containing alternative text to use.
- {{domxref("HTMLInputElement.height", "height")}}
- : A string that represents the element's [`height`](/en-US/docs/Web/HTML/Element/input#height) attribute, which defines the height of the image displayed for the button.
- {{domxref("HTMLInputElement.src", "src")}}
- : A string that represents the element's [`src`](/en-US/docs/Web/HTML/Element/input#src) attribute, which specifies a URI for the location of an image to display on the graphical submit button.
- {{domxref("HTMLInputElement.width", "width")}}
- : A string that represents the element's [`width`](/en-US/docs/Web/HTML/Element/input#width) attribute, which defines the width of the image displayed for the button.
### Instance properties that apply only to elements of type file
- {{domxref("HTMLInputElement.accept", "accept")}}
- : A string that represents the element's [`accept`](/en-US/docs/Web/HTML/Element/input#accept) attribute, containing comma-separated list of file types that can be selected.
- {{domxref("HTMLInputElement.files", "files")}}
- : A {{domxref("FileList")}} that represents the files selected for upload.
- {{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}}
- : A boolean that represents the [`webkitdirectory`](/en-US/docs/Web/HTML/Element/input#webkitdirectory) attribute. If `true`, the file-system-picker interface only accepts directories instead of files.
- {{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} {{ReadOnlyInline}}
- : Describes the currently selected files or directories.
### Instance properties that apply only to visible elements containing text or numbers
- {{domxref("HTMLInputElement.autocomplete", "autocomplete")}}
- : A string that represents the element's [`autocomplete`](/en-US/docs/Web/HTML/Element/input#autocomplete) attribute, indicating whether the value of the control can be automatically completed by the browser.
- {{domxref("HTMLInputElement.capture", "capture")}}
- : A string that represents the element's [`capture`](/en-US/docs/Web/HTML/Element/input#capture) attribute, indicating the media capture input method in file upload controls.
- {{domxref("HTMLInputElement.max", "max")}}
- : A string that represents the element's [`max`](/en-US/docs/Web/HTML/Element/input#max) attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum ([`min`](/en-US/docs/Web/HTML/Element/input#min) attribute) value.
- {{domxref("HTMLInputElement.maxLength", "maxLength")}}
- : A number that represents the element's [`maxlength`](/en-US/docs/Web/HTML/Element/input#maxlength) attribute, containing the maximum number of characters (in Unicode code points) that the value can have.
- {{domxref("HTMLInputElement.min", "min")}}
- : A string that represents the element's [`min`](/en-US/docs/Web/HTML/Element/input#min) attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ([`max`](/en-US/docs/Web/HTML/Element/input#max) attribute) value.
- {{domxref("HTMLInputElement.minLength", "minLength")}}
- : A number that represents the element's [`minlength`](/en-US/docs/Web/HTML/Element/input#minlength) attribute, containing the minimum number of characters (in Unicode code points) that the value can have.
- {{domxref("HTMLInputElement.pattern", "pattern")}}
- : A string that represents the element's [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute, containing a regular expression that the control's value is checked against. Use the [`title`](/en-US/docs/Web/HTML/Element/input#title) attribute to describe the pattern to help the user. This attribute only applies when the value of the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute is `text`, `search`, `tel`, `url` or `email`.
- {{domxref("HTMLInputElement.placeholder", "placeholder")}}
- : A string that represents the element's [`placeholder`](/en-US/docs/Web/HTML/Element/input#placeholder) attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute only applies when the value of the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute is `text`, `search`, `tel`, `url` or `email`.
- {{domxref("HTMLInputElement.readOnly", "readOnly")}}
- : A boolean that represents the element's [`readonly`](/en-US/docs/Web/HTML/Element/input#readonly) attribute, indicating that the user cannot modify the value of the control. This is ignored if the [`type`](/en-US/docs/Web/HTML/Element/input#type) is `hidden`, `range`, `color`, `checkbox`, `radio`, `file`, or a button type.
- {{domxref("HTMLInputElement.selectionDirection", "selectionDirection")}}
- : A string that represents the direction in which selection occurred. Possible values are: `forward` (the selection was performed in the start-to-end direction of the current locale), `backward` (the opposite direction) or `none` (the direction is unknown).
- {{domxref("HTMLInputElement.selectionEnd", "selectionEnd")}}
- : A number that represents the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.
- {{domxref("HTMLInputElement.selectionStart", "selectionStart")}}
- : A number that represents the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the {{HTMLElement("input")}} element.
- {{domxref("HTMLInputElement.size", "size")}}
- : A number that represents the element's [`size`](/en-US/docs/Web/HTML/Element/input#size) attribute, containing visual size of the control. This value is in pixels unless the value of [`type`](/en-US/docs/Web/HTML/Element/input#type) is `text` or `password`, in which case, it is an integer number of characters. Applies only when [`type`](/en-US/docs/Web/HTML/Element/input#type) is set to `text`, `search`, `tel`, `url`, `email`, or `password`.
## Instance methods
_Also inherits methods from its parent interface, {{domxref("HTMLElement")}}._
- {{domxref("HTMLInputElement.checkValidity()", "checkValidity()")}}
- : Returns a boolean value that is `false` if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an {{domxref("HTMLInputElement/invalid_event", "invalid")}} event at the element. It returns `true` if the element is not a candidate for constraint validation, or if it satisfies its constraints.
- {{domxref("HTMLInputElement.reportValidity()", "reportValidity()")}}
- : Runs the `checkValidity()` method, and if it returns false (for an invalid input or no pattern attribute provided), then it reports to the user that the input is invalid in the same manner as if you submitted a form.
- {{domxref("HTMLInputElement.select()", "select()")}}
- : Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content.
- {{domxref("HTMLInputElement.setCustomValidity()", "setCustomValidity()")}}
- : Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.
- {{domxref("HTMLInputElement.setRangeText()", "setRangeText()")}}
- : Replaces a range of text in the input element with new text.
- {{domxref("HTMLInputElement.setSelectionRange()", "setSelectionRange()")}}
- : Selects a range of text in the input element (but does not focus it).
- {{domxref("HTMLInputElement.showPicker()", "showPicker()")}}
- : Shows a browser picker for date, time, color, and files.
- {{domxref("HTMLInputElement.stepDown()", "stepDown()")}}
- : Decrements the [`value`](/en-US/docs/Web/HTML/Element/input#value) by ([`step`](/en-US/docs/Web/HTML/Element/input#step) \* n), where n defaults to 1 if not specified.
- {{domxref("HTMLInputElement.stepUp()", "stepUp()")}}
- : Increments the [`value`](/en-US/docs/Web/HTML/Element/input#value) by ([`step`](/en-US/docs/Web/HTML/Element/input#step) \* n), where n defaults to 1 if not specified.
## Events
_Also inherits events from its parent interface, {{domxref("HTMLElement")}}._
Listen to these events using {{domxref("EventTarget.addEventListener", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface:
- {{domxref("HTMLInputElement/invalid_event", "invalid")}} event
- : Fired when an element does not satisfy its constraints during constraint validation.
- {{domxref("HTMLInputElement/search_event", "search")}} event {{Non-standard_Inline}}
- : Fired when a search is initiated on an {{HTMLElement("input")}} of `type="search"`.
- {{domxref("HTMLInputElement/select_event", "select")}} event
- : Fired when some text has been selected.
- {{domxref("HTMLInputElement/selectionchange_event", "selectionchange")}} event {{Experimental_Inline}}
- : Fires when the text selection in a {{HTMLElement("input")}} element has been changed.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- HTML element implementing this interface: {{ HTMLElement("input") }}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/checkvalidity/index.md | ---
title: "HTMLInputElement: checkValidity() method"
short-title: checkValidity()
slug: Web/API/HTMLInputElement/checkValidity
page-type: web-api-instance-method
browser-compat: api.HTMLObjectElement.checkValidity
---
{{APIRef("HTML DOM")}}
The **`HTMLInputElement.checkValidity()`** method returns a boolean value which indicates validity of the value of the element. If the value is invalid, this method also fires the {{domxref("HTMLInputElement/invalid_event", "invalid")}} event on the element.
## Syntax
```js-nolint
checkValidity()
```
### Parameters
None.
### Return value
Returns `true` if the value of the element has no validity problems; otherwise returns `false`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [reportValidity](/en-US/docs/Web/API/HTMLInputElement/reportValidity)
- [Learn: Client-side form validation](/en-US/docs/Learn/Forms/Form_validation)
- [Guide: Constraint validation](/en-US/docs/Web/HTML/Constraint_validation)
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/labels/index.md | ---
title: "HTMLInputElement: labels property"
short-title: labels
slug: Web/API/HTMLInputElement/labels
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.labels
---
{{APIRef("DOM")}}
The **`HTMLInputElement.labels`** read-only property returns a
{{domxref("NodeList")}} of the {{HTMLElement("label")}} elements associated with the
{{HTMLElement("input")}} element, if the element is not hidden. If the element has the
type `hidden`, the property returns `null`.
## Value
A {{domxref("NodeList")}} containing the `<label>` elements associated
with the `<input>` element.
## Examples
### HTML
```html
<label id="label1" for="test">Label 1</label>
<input id="test" />
<label id="label2" for="test">Label 2</label>
```
### JavaScript
```js
window.addEventListener("DOMContentLoaded", () => {
const input = document.getElementById("test");
for (const label of input.labels) {
console.log(label.textContent); // "Label 1" and "Label 2"
}
});
```
{{EmbedLiveSample("Examples", "100%", 30)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/files/index.md | ---
title: "HTMLInputElement: files property"
short-title: files
slug: Web/API/HTMLInputElement/files
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.files
---
{{APIRef("File and Directory Entries API")}}
The **`HTMLInputElement.files`** property allows you to access the {{domxref("FileList")}} selected with the [`<input type="file">`](/en-US/docs/Web/HTML/Element/input/file) element.
## Value
A {{domxref("FileList")}} object listing the selected files, if any, or `null` if the **`HTMLInputElement`** is not of `type="file"`.
## Examples
The example below shows how you can access the **`HTMLInputElement.files`** property and log the name, date modified, size, and type of each file selected by the user.
### HTML
```html
<input id="files" type="file" multiple />
```
### JavaScript
Note that **`HTMLInputElement.files`** still returns an instance of {{domxref("FileList")}} even if no files are
selected.
Therefore it's safe to iterate through it with {{JSxref("Statements/for...of", "for...of")}} without checking if any files are selected.
```js
const fileInput = document.getElementById("files");
console.log(fileInput.files instanceof FileList); // true even if empty
for (const file of fileInput.files) {
console.log(file.name); // prints file name
let fileDate = new Date(file.lastModified);
console.log(fileDate.toLocaleDateString()); // prints legible date
console.log(
file.size < 1000 ? file.size : Math.round(file.size / 1000) + "KB",
);
console.log(file.type); // prints MIME type
}
```
## Specifications
{{ Specifications }}
## Browser compatibility
{{ Compat }}
## See also
- {{domxref("DataTransfer.files")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/setselectionrange/index.md | ---
title: "HTMLInputElement: setSelectionRange() method"
short-title: setSelectionRange()
slug: Web/API/HTMLInputElement/setSelectionRange
page-type: web-api-instance-method
browser-compat: api.HTMLInputElement.setSelectionRange
---
{{APIRef("HTML DOM")}}
The **`HTMLInputElement.setSelectionRange()`** method sets the
start and end positions of the current text selection in an {{HTMLElement("input")}}
or {{HTMLElement("textarea")}} element.
Optionally, in newer browser versions, you can specify the direction in which selection
should be considered to have occurred. This lets you indicate, for example, that the
selection was set by the user clicking and dragging from the end of the selected text
toward the beginning.
This method updates the `HTMLInputElement.selectionStart`,
`selectionEnd`, and `selectionDirection` properties in one call.
Note that according to the [WHATWG forms spec](https://html.spec.whatwg.org/multipage/forms.html#concept-input-apply) `selectionStart`, `selectionEnd` properties and
`setSelectionRange` method apply only to inputs of types text, search, URL,
tel and password. Chrome, starting from version 33, throws an exception while accessing
those properties and method on the rest of input types. For example, on input of type
number: "Failed to read the 'selectionStart' property from 'HTMLInputElement': The input
element's type ('number') does not support selection".
If you wish to select **all** text of an input element, you can use the [HTMLInputElement.select()](/en-US/docs/Web/API/HTMLInputElement/select)
method instead.
## Syntax
```js-nolint
setSelectionRange(selectionStart, selectionEnd)
setSelectionRange(selectionStart, selectionEnd, selectionDirection)
```
### Parameters
If `selectionEnd` is less than `selectionStart`, then both are
treated as the value of `selectionEnd`.
- `selectionStart`
- : The 0-based index of the first selected character. An index greater than the length
of the element's value is treated as pointing to the end of the value.
- `selectionEnd`
- : The 0-based index of the character _after_ the last selected character. An
index greater than the length of the element's value is treated as pointing to the end
of the value.
- `selectionDirection` {{optional_inline}}
- : A string indicating the direction in which the selection is considered to have been
performed. Possible values:
- `"forward"`
- `"backward"`
- `"none"` if the direction is unknown or irrelevant. Default value.
### Return value
None ({{jsxref("undefined")}}).
## Examples
Click the button in this example to select the third, fourth, and fifth characters in
the text box ("zil" in the word "Mozilla").
### HTML
```html
<input type="text" id="text-box" size="20" value="Mozilla" />
<button onclick="selectText()">Select text</button>
```
### JavaScript
```js
function selectText() {
const input = document.getElementById("text-box");
input.focus();
input.setSelectionRange(2, 5);
}
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{HTMLElement("input")}}
- {{HTMLElement("textarea")}}
- {{domxref("HTMLInputElement")}}
- {{domxref("Selection")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/search_event/index.md | ---
title: "HTMLInputElement: search event"
short-title: search
slug: Web/API/HTMLInputElement/search_event
page-type: web-api-event
status:
- non-standard
browser-compat: api.HTMLInputElement.search_event
---
{{APIRef}}{{non-standard_header}}
The **`search`** event is fired when a search is initiated using an {{HTMLElement("input")}} element of `type="search"`.
There are several ways a search can be initiated, such as by pressing <kbd>Enter</kbd> while the {{HTMLElement("input")}} is focused, or, if the [`incremental`](/en-US/docs/Web/HTML/Element/input#incremental) attribute is present, after a UA-defined timeout elapses since the most recent keystroke (with new keystrokes resetting the timeout so the firing of the event is debounced).
Current UA implementations of `<input type="search">` have an additional control to clear the field. Using this control also fires the `search` event. In that case the `value` of the {{HTMLElement("input")}} element will be the empty string.
This event is not cancelable.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("search", (event) => {});
onsearch = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
```js
// addEventListener version
const input = document.querySelector('input[type="search"]');
input.addEventListener("search", () => {
console.log(`The term searched for was ${input.value}`);
});
```
```js
// onsearch version
const input = document.querySelector('input[type="search"]');
input.onsearch = () => {
console.log(`The term searched for was ${input.value}`);
};
```
## Specifications
This event is not part of any specification.
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/webkitentries/index.md | ---
title: "HTMLInputElement: webkitEntries property"
short-title: webkitEntries
slug: Web/API/HTMLInputElement/webkitEntries
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.webkitEntries
---
{{APIRef("File and Directory Entries API")}}
The read-only **`webkitEntries`**
property of the {{domxref("HTMLInputElement")}} interface contains an array of file
system entries (as objects based on {{domxref("FileSystemEntry")}}) representing files
and/or directories selected by the user using an {{HTMLElement("input")}} element of
type `file`, but only if that selection was made using drag-and-drop:
selecting a file in the dialog will leave the property empty.
The array can only contain directories if the
{{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} property is
`true`. This means the `<input>` element was configured to
let the user choose directories.
> **Note:** This property is called `webkitEntries` in the specification due to its
> origins as a Google Chrome-specific API. It's likely to be renamed someday.
## Value
An array of objects based on {{domxref("FileSystemEntry")}}, each representing one file
which is selected in the {{HTMLElement("input")}} element. More specifically, files are
represented by {{domxref("FileSystemFileEntry")}} objects, and, if they're allowed,
directories are represented by {{domxref("FileSystemDirectoryEntry")}} objects.
## Examples
This example shows how to create a file selection `<input>` element
and process the selected files.
### HTML
```html
<input id="files" type="file" multiple />
```
### JavaScript
```js
document.getElementById("files").addEventListener("change", (event) => {
event.target.webkitEntries.forEach((entry) => {
/* do stuff with the entry */
});
});
```
Each time a {{domxref("HTMLElement/change_event", "change")}} event occurs, this code iterates over the selected
files, obtaining their {{domxref("FileSystemEntry")}}-based objects and acting on them.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("HTMLInputElement")}}
- {{domxref("FileSystemEntry")}}
- {{domxref("FileSystem")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/stepup/index.md | ---
title: "HTMLInputElement: stepUp() method"
short-title: stepUp()
slug: Web/API/HTMLInputElement/stepUp
page-type: web-api-instance-method
browser-compat: api.HTMLInputElement.stepUp
---
{{APIRef("HTML DOM")}}
The **`HTMLInputElement.stepUp()`** method increments the value
of a numeric type of {{HTMLElement("input")}} element by the value of the
[`step`](/en-US/docs/Web/HTML/Attributes/step) attribute, or the
default `step` value if the step attribute is not explicitly set. The method,
when invoked, increments the [`value`](/en-US/docs/Web/HTML/Element/input#value) by
([`step`](/en-US/docs/Web/HTML/Element/input#step) \* n), where `n` defaults to
`1` if not specified, and
[`step`](/en-US/docs/Web/HTML/Attributes/step) defaults to the
default value for `step` if not specified.
<table class="no-markdown">
<thead>
<tr>
<th>Input type</th>
<th>Default step value</th>
<th>Example step declaration</th>
</tr>
<tr>
<td>{{HTMLElement("input/date", "date")}}</td>
<td><code>1</code> (day)</td>
<td>
7 day (one week) increments:<br />
<code><input type="date" min="2019-12-25" step="7"></code>
</td>
</tr>
<tr>
<td>{{HTMLElement("input/month", "month")}}</td>
<td><code>1</code> (month)</td>
<td>
12 month (one year) increments:<br />
<code><input type="month" min="2019-12" step="12"></code>
</td>
</tr>
<tr>
<td>{{HTMLElement("input/week", "week")}}</td>
<td><code>1</code> (week)</td>
<td>
Two week increments:<br />
<code><input type="week" min="2019-W23" step="2"></code>
</td>
</tr>
<tr>
<td>{{HTMLElement("input/time", "time")}}</td>
<td><code>60</code> (seconds)</td>
<td>
900 second (15 minute) increments:<br />
<code><input type="time" min="09:00" step="900"></code>
</td>
</tr>
<tr>
<td>
{{HTMLElement("input/datetime-local", "datetime-local")}}
</td>
<td><code>1</code> (day)</td>
<td>
Same day of the week:<br />
<code><input type="datetime-local" min="019-12-25T19:30"
step="7"></code>
</td>
</tr>
<tr>
<td>{{HTMLElement("input/number", "number")}}</td>
<td><code>1</code></td>
<td>
0.1 increments<br />
<code><input type="number" min="0" step="0.1" max="10"></code>
</td>
</tr>
<tr>
<td>{{HTMLElement("input/range", "range")}}</td>
<td><code>1</code></td>
<td>
Increments by 2:<br />
<code><input type="range" min="0" step="2" max="10"></code>
</td>
</tr>
</thead>
</table>
The method, when invoked, changes the form control's value by the value given in the
`step` attribute, multiplied by the parameter, within the constraints set on
the form control. The default value for the parameter, if no value is passed, is
`1`. The method will not cause the value to exceed the
set [`max`](/en-US/docs/Web/HTML/Attributes/max) value, or defy
the constraints set by the
[`step`](/en-US/docs/Web/HTML/Attributes/step) attribute.
If the value before invoking the `stepUp()` method is invalid—for example,
if it doesn't match the constraints set by the step attribute—invoking the
`stepUp()` method will return a value that does match the form controls
constraints.
If the form control is non time, date, or numeric in nature, and therefore does not
support the `step` attribute (see the list of supported input types in the
table above), or if the step value is set to `any`, an
`InvalidStateError` exception is thrown.
## Syntax
```js-nolint
stepUp()
stepUp(stepIncrement)
```
### Parameters
- `stepIncrement` {{optional_inline}}
- : A numeric value. If no parameter is passed, `stepIncrement` defaults to `1`.
### Return value
None ({{jsxref("undefined")}}).
## Examples
Click the button in this example to increment the {{HTMLElement("input/number",
"number")}} input type:
### HTML
```html
<p>
<label for="theNumber">
Enter a number between 0 and 400 that is divisible by 5:
</label>
<input type="number" step="5" id="theNumber" min="0" max="400" />
</p>
<p>
<label>
Enter how many values of step you would like to increment by or leave it
blank:
</label>
<input type="number" step="1" id="incrementInput" min="0" max="25" />
</p>
<input type="button" value="Increment" id="theButton" />
```
### JavaScript
```js
/* make the button call the function */
const button = document.getElementById("theButton");
button.addEventListener("click", () => {
stepOnUp();
});
function stepOnUp() {
let input = document.getElementById("theNumber");
let val = document.getElementById("incrementInput").value;
if (val) {
/* increment with a parameter */
input.stepUp(val);
} else {
/* or without a parameter. Try it with 0 */
input.stepUp();
}
}
```
### CSS
```css
input:invalid {
border: red solid 3px;
}
```
### Result
{{EmbedLiveSample("Examples")}}
Note if you don't pass a parameter to the `stepUp` method, it defaults to
`1`. Any other value is a multiplier of the `step` attribute
value, which in this case is `5`. If you pass `4` as the
`stepIncrement`, the input will `stepUp` by
`4 * 5`, or `20`. If the parameter is `0`, the number
will not be incremented. The stepUp will not allow the input to out of range, in this
case stopping when it reaches `400`, and rounding down any floats that are
passed as a parameter.
Try setting the step increment input to `1.2`. What happens when you invoke the
method?
Try setting the value to `4`, which is not valid. What happens when you
invoke the method?
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{HTMLElement("input")}}
- {{domxref("HTMLInputElement")}}
- {{domxref("HTMLInputElement.stepDown")}}
- [`step`](/en-US/docs/Web/HTML/Attributes/step),
[`min`](/en-US/docs/Web/HTML/Attributes/min) and
[`max`](/en-US/docs/Web/HTML/Attributes/max) attributes
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/select_event/index.md | ---
title: "HTMLInputElement: select event"
short-title: select
slug: Web/API/HTMLInputElement/select_event
page-type: web-api-event
browser-compat: api.HTMLInputElement.select_event
---
{{APIRef}}
The **`select`** event fires when some text has been selected.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("select", (event) => {});
onselect = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
### Selection logger
```html
<input value="Try selecting some text in this element." />
<p id="log"></p>
```
```js
function logSelection(event) {
const log = document.getElementById("log");
const selection = event.target.value.substring(
event.target.selectionStart,
event.target.selectionEnd,
);
log.textContent = `You selected: ${selection}`;
}
const input = document.querySelector("input");
input.addEventListener("select", logSelection);
```
{{EmbedLiveSample("Selection_logger")}}
### onselect equivalent
You can also set up the event handler using the `onselect` property:
```js
input.onselect = logSelection;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/multiple/index.md | ---
title: "HTMLInputElement: multiple property"
short-title: multiple
slug: Web/API/HTMLInputElement/multiple
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.multiple
---
{{ APIRef("HTML DOM") }}
The **`HTMLInputElement.multiple`** property indicates if an input can have more than one value. Firefox currently only supports `multiple` for `<input type="file">`.
## Value
A boolean value.
## Examples
```js
// fileInput is a <input type=file multiple>
let fileInput = document.getElementById("myfileinput");
if (fileInput.multiple) {
// Loop fileInput.files
for (const file of fileInput.files) {
// Perform action on one file
}
// Only one file available
} else {
let [file] = fileInput.files;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [FileList](/en-US/docs/Web/API/FileList)
- [Bug 523771](https://bugzil.la/523771) - Support \<input type=file multiple>
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/popovertargetaction/index.md | ---
title: "HTMLInputElement: popoverTargetAction property"
short-title: popoverTargetAction
slug: Web/API/HTMLInputElement/popoverTargetAction
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.popoverTargetAction
---
{{APIRef("Popover API")}}
The **`popoverTargetAction`** property of the {{domxref("HTMLInputElement")}} interface gets and sets the action to be performed (`"hide"`, `"show"`, or `"toggle"`) on a popover element being controlled by an {{htmlelement("input")}} element of `type="button"`.
It reflects the value of the [`popovertargetaction`](/en-US/docs/Web/HTML/Element/button#popovertargetaction) HTML attribute.
## Value
An enumerated value. Possible values are:
- `"hide"`
- : The button will hide a shown popover. If you try to hide an already hidden popover, no action will be taken.
- `"show"`
- : The button will show a hidden popover. If you try to show an already showing popover, no action will be taken.
- `"toggle"`
- : The button will toggle a popover between showing and hidden. If the popover is hidden, it will be shown; if the popover is showing, it will be hidden. If `popoverTargetAction` is not set, `"toggle"` is the default action that will be performed by the control button.
## Examples
### Toggle popover action with an auto popover
This example shows the basic use of the popover API with a "toggle" value set for the `popoverTargetAction` property.
The `popover` attribute is set to [`"auto"`](/en-US/docs/Web/API/Popover_API/Using#auto_state_and_light_dismiss), so the popover can be closed ("light-dismissed") by clicking outside the popover area.
First we define an [`<input>`](/en-US/docs/Web/HTML/Element/input/button) of `type="button"` that we will use to show and hide the popover, and a `<div>` that will be the popover.
In this case we don't set the [`popovertargetaction`](/en-US/docs/Web/HTML/Element/button#popovertargetaction) HTML attribute on the button or the [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover) attribute on the `<div>`, as we will be doing so programmatically.
```html
<input id="toggleBtn" type="button" value="Toggle popover" />
<div id="mypopover">This is popover content!</div>
```
The JavaScript code first gets a handle to the `<div>` and `<input>` elements.
It then defines a function to check for popover support.
```js
const popover = document.getElementById("mypopover");
const toggleBtn = document.getElementById("toggleBtn");
// Check for popover API support.
function supportsPopover() {
return HTMLElement.prototype.hasOwnProperty("popover");
}
```
If the popover API is supported the code sets the `<div>` element's `popover` attribute to `"auto"` and makes it the popover target of the toggle button.
We then set the `popoverTargetAction` of the button to `"toggle"`.
If the popover API is not supported we change the text content of the `<div>` element to state this, and hide the toggle button.
```js
if (supportsPopover()) {
// Set the <div> element to be an auto popover
popover.popover = "auto";
// Set the button popover target to be the popover
toggleBtn.popoverTargetElement = popover;
// Set that the button toggles popover visibility
toggleBtn.popoverTargetAction = "toggle";
} else {
popover.textContent = "Popover API not supported.";
toggleBtn.hidden = true;
}
```
> **Note:** A popover element is hidden by default, but if the API is not supported your element will display "as usual".
You can try out the example below.
Show and hide the popover by toggling the button.
The "auto" popover can also be dismissed by selecting outside the bounds of the popover text.
{{EmbedLiveSample("Toggle popover action with an auto popover", "100%")}}
### Show/hide popover action with a manual popover
This example shows how to use the `"show"` and `"hide"` values of the `popoverTargetAction` attribute.
The code is near identical to the previous example, except that there are two `<button>` elements, and the popover is set to [`"manual"`](/en-US/docs/Web/API/Popover_API/Using#using_manual_popover_state).
A `manual` popover must be closed explicitly, and not "light dismissed" by selecting outside the popover area.
```html
<input id="showBtn" type="button" value="Show popover" />
<input id="hideBtn" type="button" value="Hide popover" />
<div id="mypopover">This is popover content!</div>
```
```js
function supportsPopover() {
return HTMLElement.prototype.hasOwnProperty("popover");
}
const popover = document.getElementById("mypopover");
const showBtn = document.getElementById("showBtn");
const hideBtn = document.getElementById("hideBtn");
const popoverSupported = supportsPopover();
if (supportsPopover()) {
// Set the <div> element be a manual popover
popover.popover = "manual";
// Set the button targets to be the popover
showBtn.popoverTargetElement = popover;
hideBtn.popoverTargetElement = popover;
// Set the target actions to be show/hide
showBtn.popoverTargetAction = "show";
hideBtn.popoverTargetAction = "hide";
} else {
popover.textContent = "Popover API not supported.";
showBtn.hidden = true;
hideBtn.hidden = true;
}
```
The popover can be displayed by selecting the "Show popover" button, and dismissed using the "Hide popover" button.
{{EmbedLiveSample("Show/hide popover action with a manual popover", "100%")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover) HTML global attribute
- [Popover API](/en-US/docs/Web/API/Popover_API)
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/select/index.md | ---
title: "HTMLInputElement: select() method"
short-title: select()
slug: Web/API/HTMLInputElement/select
page-type: web-api-instance-method
browser-compat: api.HTMLInputElement.select
---
{{ APIRef("HTML DOM") }}
The **`HTMLInputElement.select()`** method selects all the text
in a {{HTMLElement("textarea")}} element or in an {{HTMLElement("input")}} element
that includes a text field.
## Syntax
```js-nolint
select()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
Click the button in this example to select all the text in the
`<input>` element.
### HTML
```html
<input type="text" id="text-box" size="20" value="Hello world!" />
<button onclick="selectText()">Select text</button>
```
### JavaScript
```js
function selectText() {
const input = document.getElementById("text-box");
input.focus();
input.select();
}
```
### Result
{{EmbedLiveSample("Examples")}}
## Notes
Calling `element.select()` will not necessarily focus the input, so it is
often used with {{domxref("HTMLElement.focus")}}.
In browsers where it is not supported, it is possible to replace it with a call to [HTMLInputElement.setSelectionRange()](/en-US/docs/Web/API/HTMLInputElement/setSelectionRange) with
parameters 0 and the input's value length:
```html
<input onClick="this.select();" value="Sample Text" />
<!-- equivalent to -->
<input
onClick="this.setSelectionRange(0, this.value.length);"
value="Sample Text" />
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{ HTMLElement("input") }}
- {{ HTMLElement("textarea") }}
- {{ domxref("HTMLInputElement") }}
- {{ domxref("HTMLInputElement.setSelectionRange") }}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/disabled/index.md | ---
title: "HTMLInputElement: disabled property"
short-title: disabled
slug: Web/API/HTMLInputElement/disabled
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.disabled
---
{{ APIRef("HTML DOM") }}
The **`HTMLInputElement.disabled`** property is a boolean value that reflects the [`disabled`](/en-US/docs/Web/HTML/Element/input#disabled) HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks. A disabled element is unusable and un-clickable.
## Value
A boolean value.
## Examples
### HTML
```html
<p>
<label>
<input id="check-box" name="b" value="1" type="checkbox" disabled /> Check
this box!
</label>
</p>
<p>
<label>
<input id="toggle-box" name="b" value="2" type="checkbox" /> Enable the
other checkbox.
</label>
</p>
```
### JavaScript
```js
const checkBox = document.getElementById("check-box");
const toggleBox = document.getElementById("toggle-box");
toggleBox.addEventListener(
"change",
(event) => {
checkBox.disabled = !event.target.checked;
},
false,
);
```
### Result
{{EmbedLiveSample('Examples')}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/setcustomvalidity/index.md | ---
title: "HTMLInputElement: setCustomValidity() method"
short-title: setCustomValidity()
slug: Web/API/HTMLInputElement/setCustomValidity
page-type: web-api-instance-method
browser-compat: api.HTMLObjectElement.setCustomValidity
---
{{APIRef("HTML DOM")}}
The **`HTMLInputElement.setCustomValidity()`** method sets a custom validity message for the element.
## Syntax
```js-nolint
setCustomValidity(message)
```
### Parameters
- `message`
- : The message to use for validity errors.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
None.
## Examples
In this example, we pass the ID of an input element, and set different error messages
depending on whether the value is missing, too low, or too high. Additionally you
_must_ call the [`reportValidity()`](/en-US/docs/Web/API/HTMLInputElement/reportValidity)
method on the same element or else nothing will happen.
```js
function validate(inputID) {
const input = document.getElementById(inputID);
const validityState = input.validity;
if (validityState.valueMissing) {
input.setCustomValidity("You gotta fill this out, yo!");
} else if (validityState.rangeUnderflow) {
input.setCustomValidity("We need a higher number!");
} else if (validityState.rangeOverflow) {
input.setCustomValidity("That's too high!");
} else {
input.setCustomValidity("");
}
input.reportValidity();
}
```
It's vital to set the message to an empty string if there are no errors. As long as the
error message is not empty, the form will not pass validation and will not be
submitted.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Learn: Client-side form validation](/en-US/docs/Learn/Forms/Form_validation)
- [Guide: Constraint validation](/en-US/docs/Web/HTML/Constraint_validation)
- {{domxref('ValidityState')}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/selectionchange_event/index.md | ---
title: "HTMLInputElement: selectionchange event"
short-title: selectionchange
slug: Web/API/HTMLInputElement/selectionchange_event
page-type: web-api-event
status:
- experimental
browser-compat: api.HTMLInputElement.selectionchange_event
---
{{APIRef}}{{SeeCompatTable}}
The **`selectionchange`** event of the [Selection API](/en-US/docs/Web/API/Selection) is fired when the text selection within an {{HTMLElement("input")}} element is changed.
This includes both changes in the selected range of characters, or if the caret moves.
This event is not cancelable.
The event is usually processed by adding an event listener on the {{HTMLElement("input")}}, and in the handler function read by the {{domxref("HTMLInputElement")}} `selectionStart`, `selectionEnd` and `selectionDirection` properties.
It is also possible to add a listener on the `onselectionchange` event handler, and within the handler function use {{domxref("Document.getSelection()")}} to get the {{domxref("Selection", "Selection")}}. However this is not very useful for getting changes to _text_ selections.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("selectionchange", (event) => {});
onselectionchange = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
The example below shows how to get the text selected in an {{HTMLElement("input")}} element.
### HTML
```html
<div>
Enter and select text here:<br /><input id="mytext" rows="2" cols="20" />
</div>
<div>selectionStart: <span id="start"></span></div>
<div>selectionEnd: <span id="end"></span></div>
<div>selectionDirection: <span id="direction"></span></div>
```
### JavaScript
```js
const myinput = document.getElementById("mytext");
myinput.addEventListener("selectionchange", () => {
document.getElementById("start").textContent = myinput.selectionStart;
document.getElementById("end").textContent = myinput.selectionEnd;
document.getElementById("direction").textContent = myinput.selectionDirection;
});
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/selectionend/index.md | ---
title: "HTMLInputElement: selectionEnd property"
short-title: selectionEnd
slug: Web/API/HTMLInputElement/selectionEnd
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.selectionEnd
---
{{ApiRef("HTML DOM")}}
The **`selectionEnd`** property of the {{domxref("HTMLInputElement")}} interface is a number that represents the end index of the selected text. When there is no selection, this returns the offset of the character immediately following the current text input cursor position.
> **Note:** According to the [WHATWG forms spec](https://html.spec.whatwg.org/multipage/forms.html#concept-input-apply) `selectionEnd` property applies only to inputs of types text, search, URL, tel, and password. In modern browsers, throws an exception while setting `selectionEnd` property on the rest of input types. Additionally, this property returns `null` while accessing `selectionEnd` property on non-text input elements.
If `selectionEnd` is less than `selectionStart`, then both are
treated as the value of `selectionEnd`.
## Value
A non-negative number.
## Examples
### HTML
```html
<!-- using selectionEnd on non text input element -->
<label for="color">selectionStart property on type=color</label>
<input id="color" type="color" />
<!-- using selectionEnd on text input element -->
<fieldset>
<legend>selectionEnd property on type=text</legend>
<label for="pin">Input PIN</label>
<input type="text" id="pin" value="impossible PIN: 102-12-145" />
<button id="pin-btn" type="button">PIN correction</button>
</fieldset>
```
### JavaScript
```js
const colorEnd = document.getElementById("color");
const text = document.querySelector("#pin");
const pinBtn = document.querySelector("#pin-btn");
const validPinChecker = /[^\d{3}-\d{2}-\d{3}]/g;
const selectionEnd = text.value.length;
const selectedText = text.value.substring(text.selectionStart, selectionEnd);
pinBtn.addEventListener("click", () => {
const correctedText = selectedText.replace(validPinChecker, "");
text.value = correctedText;
});
// open browser console to verify output
console.log(colorEnd.selectionEnd); // Output : null
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLTextAreaElement.selectionEnd")}} property
- {{domxref("HTMLInputElement.selectionStart")}} property
- {{domxref("HTMLInputElement.setSelectionRange")}} method
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/selectiondirection/index.md | ---
title: "HTMLInputElement: selectionDirection property"
short-title: selectionDirection
slug: Web/API/HTMLInputElement/selectionDirection
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.selectionDirection
---
{{ApiRef("HTML DOM")}}
The **`selectionDirection`** property of the {{domxref("HTMLInputElement")}} interface is a string that indicates the direction in which the user is selecting the text.
## Value
A string. It can have one of the following values:
- `forward`
- : The user is extending the selection towards the end of the input text.
- `backward`
- : The user is extending the selection towards the start of the input text.
- `none`
- : The user is not extending the selection.
> **Note:** On Windows, the direction indicates the position of the caret relative to the selection: a "forward" selection has the caret at the end of the selection and a "backward" selection has the caret at the start of the selection. Windows has no "none" direction.
> **Note:** On Mac, the direction indicates which end of the selection is affected when the user adjusts the size of the selection using the arrow keys with the Shift modifier: the "forward" direction means the end of the selection is modified, and the "backward" direction means the start of the selection is modified. The "none" direction is the default on Mac, it indicates that no particular direction has yet been selected. The user sets the direction implicitly when first adjusting the selection, based on which directional arrow key was used.
## Examples
### HTML
```html
<label for="selectionDirection">selectionDirection property</label>
<input type="text" id="selectionDirection" value="MDN" />
<p id="direction"></p>
```
### JavaScript
```js
const textSelectionDirection = document.querySelector("#selectionDirection");
const pConsole = document.querySelector("#direction");
pConsole.textContent =
"Selection direction : " + textSelectionDirection.selectionDirection;
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLTextAreaElement.selectionDirection")}} property
- {{domxref("HTMLInputElement.selectionStart")}} property
- {{domxref("HTMLInputElement.selectionEnd")}} property
- {{domxref("HTMLInputElement.setSelectionRange")}} method
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/popovertargetelement/index.md | ---
title: "HTMLInputElement: popoverTargetElement property"
short-title: popoverTargetElement
slug: Web/API/HTMLInputElement/popoverTargetElement
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.popoverTargetElement
---
{{APIRef("Popover API")}}
The **`popoverTargetElement`** property of the {{domxref("HTMLInputElement")}} interface gets and sets the popover element to control via an {{htmlelement("input")}} element of `type="button"`.
It is the JavaScript equivalent of the [`popovertarget`](/en-US/docs/Web/HTML/Element/button#popovertarget) HTML attribute.
## Value
A reference to a popover element in the DOM.
## Examples
```js
function supportsPopover() {
return HTMLElement.prototype.hasOwnProperty("popover");
}
const popover = document.getElementById("mypopover");
const toggleBtn = document.getElementById("toggleBtn");
const popoverSupported = supportsPopover();
if (popoverSupported) {
popover.popover = "auto";
toggleBtn.popoverTargetElement = popover;
toggleBtn.popoverTargetAction = "toggle";
} else {
console.log("Popover API not supported.");
}
```
### Toggle popover action with an auto popover
This example shows the basic use of the popover API, setting a `<div>` element as a popover, and then setting it as the `popoverTargetElement` of an [`<input>`](/en-US/docs/Web/HTML/Element/input/button) of `type="button"`.
The `popover` attribute is set to [`"auto"`](/en-US/docs/Web/API/Popover_API/Using#auto_state_and_light_dismiss), so the popover can be closed ("light-dismissed") by clicking outside the popover area.
First we define an `<input>` that we will use to display and hide the popover, and a `<div>` that will be the popover.
In this case we don't set the [`popovertargetaction`](/en-US/docs/Web/HTML/Element/button#popovertargetaction) HTML attribute on the `<input>` or the [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover) attribute on the `<div>`, as we will be doing so programmatically.
```html
<input id="toggleBtn" type="button" value="Toggle popover" />
<div id="mypopover">This is popover content!</div>
```
The JavaScript code first gets a handle to the `<div>` and `<input>` elements.
It then defines a function to check for popover support.
```js
const popover = document.getElementById("mypopover");
const toggleBtn = document.getElementById("toggleBtn");
// Check for popover API support.
function supportsPopover() {
return HTMLElement.prototype.hasOwnProperty("popover");
}
```
If the popover API is supported the code sets the `<div>` element's `popover` attribute to `"auto"` and makes it the popover target of the toggle button.
We then set the `popoverTargetAction` of the button to `"toggle"`.
If the popover API is not supported we change the text content of the `<div>` element to state this, and hide the input element.
```js
if (supportsPopover()) {
// Set the <div> element to be an auto popover
popover.popover = "auto";
// Set the button popover target to be the popover
toggleBtn.popoverTargetElement = popover;
// Set that the button toggles popover visibility
toggleBtn.popoverTargetAction = "toggle";
} else {
popover.textContent = "Popover API not supported.";
toggleBtn.hidden = true;
}
```
> **Note:** A popover element is hidden by default, but if the API is not supported your element will display "as usual".
You can try out the example below.
Show and hide the popover by toggling the button.
The "auto" popover can also be light dismissed by selecting outside the bounds of the popover text.
{{EmbedLiveSample("Toggle popover action with an auto popover", "100%")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover) HTML global attribute
- [Popover API](/en-US/docs/Web/API/Popover_API)
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/webkitdirectory/index.md | ---
title: "HTMLInputElement: webkitdirectory property"
short-title: webkitdirectory
slug: Web/API/HTMLInputElement/webkitdirectory
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.webkitdirectory
---
{{APIRef("File and Directory Entries API")}}
The **`HTMLInputElement.webkitdirectory`** is a property
that reflects the [`webkitdirectory`](/en-US/docs/Web/HTML/Element/input/file#webkitdirectory) HTML attribute
and indicates that the {{HTMLElement("input")}} element should let the user select directories instead of files.
When a directory is selected, the directory and its entire hierarchy of contents are included in the set of selected items.
The selected file system entries can be obtained using the {{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} property.
> **Note:** This property is called `webkitEntries` in the specification due to its
> origins as a Google Chrome-specific API. It's likely to be renamed someday.
## Value
A Boolean; `true` if the {{HTMLElement("input")}} element should allow
picking only directories or `false` if only files should be selectable.
## Understanding the results
After the user makes a selection, each {{domxref("File")}} object in `files`
has its {{domxref("File.webkitRelativePath")}} property set to the relative path within
the selected directory at which the file is located. For example, consider this file
system:
- PhotoAlbums
- Birthdays
- Jamie's 1st birthday
- PIC1000.jpg
- PIC1004.jpg
- PIC1044.jpg
- Don's 40th birthday
- PIC2343.jpg
- PIC2344.jpg
- PIC2355.jpg
- PIC2356.jpg
- Vacations
- Mars
- PIC5533.jpg
- PIC5534.jpg
- PIC5556.jpg
- PIC5684.jpg
- PIC5712.jpg
If the user chooses `PhotoAlbums`, then the list reported by files will
contain {{domxref("File")}} objects for every file listed above—but not the directories.
The entry for `PIC2343.jpg` will have a `webkitRelativePath` of
`PhotoAlbums/Birthdays/Don's 40th birthday/PIC2343.jpg`. This makes it
possible to know the hierarchy even though the {{domxref("FileList")}} is flat.
> **Note:** The behavior of `webkitRelativePath` is different
> in _Chromium < 72_. See [this bug](https://crbug.com/124187) for
> further details.
## Examples
In this example, a directory picker is presented which lets the user choose one or more
directories. When the {{domxref("HTMLElement/change_event", "change")}} event occurs, a list of all files contained
within the selected directory hierarchies is generated and displayed.
### HTML
```html
<input type="file" id="filepicker" name="fileList" webkitdirectory multiple />
<ul id="listing"></ul>
```
### JavaScript
```js
document.getElementById("filepicker").addEventListener(
"change",
(event) => {
let output = document.getElementById("listing");
for (const file of event.target.files) {
let item = document.createElement("li");
item.textContent = file.webkitRelativePath;
output.appendChild(item);
}
},
false,
);
```
### Result
{{ EmbedLiveSample('Examples') }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- {{domxref("HTMLInputElement.webkitEntries")}}
- {{domxref("File.webkitRelativePath")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/type/index.md | ---
title: "HTMLInputElement: type property"
short-title: type
slug: Web/API/HTMLInputElement/type
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.type
---
{{ApiRef("HTML DOM")}}
The **`type`** property of the {{domxref("HTMLInputElement")}} interface indicates the kind of data allowed in the {{HTMLElement("input")}} element, or example a number, a date, or an email. Browsers will select the appropriate widget and behavior to help users to enter a valid value.
It reflects the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute of the {{HTMLElement("input")}} element.
## Value
A string representing the type.
Its possible values are listed in the attribute's [input types](/en-US/docs/Web/HTML/Element/input#input_types) section.
## Example
### HTML
```html
<input id="input1" type="date" />
```
### JavaScript
```js
const inputElement = document.querySelector("#input1");
console.log(inputElement.type); // Output: "date"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLTextAreaElement.type")}} property
- {{domxref("HTMLButtonElement.type")}} property
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/invalid_event/index.md | ---
title: "HTMLInputElement: invalid event"
short-title: invalid
slug: Web/API/HTMLInputElement/invalid_event
page-type: web-api-event
browser-compat: api.HTMLInputElement.invalid_event
---
{{APIRef}}
The **`invalid`** event fires when a submittable element has been checked for validity and doesn't satisfy its constraints.
This event can be useful for displaying a summary of the problems with a form on submission. When a form is submitted, `invalid` events are fired at each form control that is invalid. The validity of submittable elements is checked before submitting their owner {{HtmlElement("form")}}, or after the [`checkValidity()`](/en-US/docs/Web/API/HTMLInputElement/checkValidity) method of the element or its owner `<form>` is called.
It is not checked on {{domxref("Element/blur_event", "blur")}}.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("invalid", (event) => {});
oninvalid = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
If a form is submitted with an invalid value, the submittable elements are checked and, if an error is found, the `invalid` event will fire on the `invalid` element. In this example, when an invalid event fires because of an invalid value in the input, the invalid value is logged.
### HTML
```html
<form action="#">
<div>
<label>
Enter an integer between 1 and 10:
<input type="number" min="1" max="10" required />
</label>
</div>
<div><input type="submit" value="submit" /></div>
</form>
<hr />
Invalid values:
<ul id="log"></ul>
```
### JavaScript
```js
const input = document.querySelector("input");
const log = document.getElementById("log");
input.addEventListener("invalid", (e) => {
log.appendChild(
Object.assign(document.createElement("li"), {
textContent: JSON.stringify(e.target.value),
}),
);
});
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- HTML {{HtmlElement("form")}} element
- Related event: {{domxref("HTMLFormElement/submit_event", "submit")}}
- CSS {{cssxref(":invalid")}} pseudo class
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/stepdown/index.md | ---
title: "HTMLInputElement: stepDown() method"
short-title: stepDown()
slug: Web/API/HTMLInputElement/stepDown
page-type: web-api-instance-method
browser-compat: api.HTMLInputElement.stepDown
---
{{APIRef("HTML DOM")}}
The
**`HTMLInputElement.stepDown([n])`** method decrements the
value of a numeric type of {{HTMLElement("input")}} element by the value of the
[`step`](/en-US/docs/Web/HTML/Attributes/step) attribute or up
to `n` multiples of the step attribute if a number is passed as the
parameter.
The method, when invoked, decrements the
[`value`](/en-US/docs/Web/HTML/Element/input#value) by ([`step`](/en-US/docs/Web/HTML/Element/input#step) \* n), where n
defaults to 1 if not specified, and
[`step`](/en-US/docs/Web/HTML/Attributes/step) defaults to the
default value for `step` if not specified.
Valid on all numeric, date, and time input types that support the step attribute,
including {{HTMLElement("input/date", "date")}}, {{HTMLElement("input/month", "month")}},
{{HTMLElement("input/week", "week")}}, {{HTMLElement("input/time", "time")}},
{{HTMLElement("input/datetime-local", "datetime-local")}}, {{HTMLElement("input/number",
"number")}}, and {{HTMLElement("input/range", "range")}}.
Given `<input id="myTime" type="time" max="17:00" step="900" value="17:00">`,
invoking `myTime.stepDown(3)` will change the value to 16:15, decrementing the
time by `3 * 900`, or 45 minutes. `myTime.stepDown()`, with no
parameter, would have resulted in `16:45`, as `n` defaults to
`1`.
```html
<!-- decrements by intervals of 900 seconds (15 minute) -->
<input type="time" max="17:00" step="900" />
<!-- decrements by intervals of 7 days (one week) -->
<input type="date" max="2019-12-25" step="7" />
<!-- decrements by intervals of 12 months (one year) -->
<input type="month" max="2019-12" step="12" />
```
However, calling `stepDown` on `<input type="time" max="17:00" step="900">` would not set the value to `17:00`, as one would expect — and as it does for `stepUp` when the input is `<input type="time" min="17:00" step="900">`. Instead, the first call to `stepDown` will set the initial value to `23:45` even though the `max` attribute is set. The second call will set the value to `17:00`. And the third call to will set the value to `16:45`.
```js
let input1 = document.createElement("input");
input1.setAttribute("type", "time");
input1.setAttribute("min", "17:00");
input1.setAttribute("step", 900);
console.log(input1.value); // ""
input1.stepUp();
console.log(input1.value); // "17:00"
// However
let input2 = document.createElement("input");
input2.setAttribute("type", "time");
input2.setAttribute("max", "17:00");
input2.setAttribute("step", 900);
console.log(input2.value); // ""
input2.stepDown();
console.log(input2.value); // "23:45"
input2.stepDown();
console.log(input2.value); // "17:00"
input2.stepDown();
console.log(input2.value); // "16:45"
```
The method, when invoked, changes the form control's value by the value given in the
`step` attribute, multiplied by the parameter, within the constraints set
within the form control. The default value for the parameter, if not is passed, is 1.
The method will not cause the value to go below the
[`min`](/en-US/docs/Web/HTML/Attributes/min) value set or defy the
constraints set by the
[`step`](/en-US/docs/Web/HTML/Attributes/step) attribute. A
negative value for `n` will increment the value, but will not increment
beyond the [`max`](/en-US/docs/Web/HTML/Attributes/max) value.
If the value before invoking the `stepDown()` method is invalid, for
example, if it doesn't match the constraints set by the `step` attribute,
invoking the `stepDown()` method will return a value that does match the form
controls constraints.
If the form control is non time, date, or numeric in nature, and therefore does not
support the `step` attribute (see the list of supported input types above), or if the `step` value is set to `any`, an
`InvalidStateError` exception is thrown.
- {{domxref("HTMLInputElement.stepDown()")}}
- : Decrements the [`value`](/en-US/docs/Web/HTML/Element/input#value) by
([`step`](/en-US/docs/Web/HTML/Element/input#step) \* n), where n defaults to 1 if not specified. Throws
an `InvalidStateError` exception:
- if the method is not applicable to for the current
[`type`](/en-US/docs/Web/HTML/Element/input#type) value,
- if the element has no [`step`](/en-US/docs/Web/HTML/Element/input#step) value,
- if the [`value`](/en-US/docs/Web/HTML/Element/input#value) cannot be converted to a number,
- if the resulting value is above the [`max`](/en-US/docs/Web/HTML/Element/input#max) or below the
[`min`](/en-US/docs/Web/HTML/Element/input#min).
## Syntax
```js-nolint
stepDown()
stepDown(stepDecrement)
```
### Parameters
- `stepDecrement` {{optional_inline}}
- : A numeric value. If no parameter is passed, _stepDecrement_ defaults to 1.
If the value is a float, the value will decrement as if
[`Math.floor(stepDecrement)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor)
was passed. If the value is negative, the value will be incremented instead of
decremented.
### Return value
None ({{jsxref("undefined")}}).
## Examples
Click the button in this example to decrement the {{HTMLElement("input/number",
"number")}} input type:
### HTML
```html
<p>
<label for="theNumber">
Enter a number between 0 and 400 that is divisible by 5:
</label>
<input type="number" step="5" id="theNumber" min="0" max="400" />
</p>
<p>
<label for="decrementButton">
Enter how many values of step you would like to decrement by or leave it
blank:
</label>
<input type="number" step="1" id="decrementInput" min="-2" max="15" />
</p>
<input type="button" value="Decrement" id="theButton" />
```
### JavaScript
```js
/* make the button call the function */
let button = document.getElementById("theButton");
button.addEventListener("click", () => {
stepOnDown();
});
function stepOnDown() {
let input = document.getElementById("theNumber");
let val = document.getElementById("decrementInput").value;
if (val) {
// decrement with a parameter
input.stepDown(val);
} else {
// or without a parameter. Try it with 0, 5, -2, etc.
input.stepDown();
}
}
```
### CSS
```css
input:invalid {
border: red solid 3px;
}
```
### Result
{{EmbedLiveSample("Examples")}}
Note if you don't pass a parameter to the `stepDown()` method, it defaults
to 1. Any other value is a multiplier of the `step` attribute value, which in
this case is 5. If we pass `4` as the `stepDecrement`, the input will `stepDown` by
`4 * 5`, or `20`. If the parameter is `0`, the number will not be
decremented. The `stepDown()` method will not allow the input to go out of range, in this
case stopping when it reaches 0 and rounding down and floats that are passed as a
parameter.
Try setting the step decrement input to `1.2`. What happens when you invoke the
method?
Try setting the value to `44`, which is not valid. What happens when you
invoke the method?
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{HTMLElement("input")}}
- {{domxref("HTMLInputElement")}}
- {{domxref("HTMLInputElement.stepUp", "HTMLInputElement.stepUp()")}}
- [`step`](/en-US/docs/Web/HTML/Attributes/step),
[`min`](/en-US/docs/Web/HTML/Attributes/min) and
[`max`](/en-US/docs/Web/HTML/Attributes/max) attributes
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/showpicker/index.md | ---
title: "HTMLInputElement: showPicker() method"
short-title: showPicker()
slug: Web/API/HTMLInputElement/showPicker
page-type: web-api-instance-method
browser-compat: api.HTMLInputElement.showPicker
---
{{ APIRef("HTML DOM") }}
The **`HTMLInputElement.showPicker()`** method displays the browser picker for an `input` element.
This is the same picker that would normally be displayed when the element is selected, but can be triggered from a button press or other user interaction.
Commonly browsers implement it for inputs of these types: `"date"`, `"month"`, `"week"`, `"time"`, `"datetime-local"`, `"color"`, or `"file"`.
It can also be prepopulated with items from a {{htmlelement("datalist")}} element or [`autocomplete`](/en-US/docs/Web/HTML/Attributes/autocomplete) attribute.
More generally, this method should ideally display the picker for any input element on the platform that has a picker.
## Syntax
```js-nolint
showPicker()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the element is not mutable, meaning that the user cannot modify it and/or that it cannot be automatically prefilled.
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if not explicitly triggered by a user action such as a touch gesture or mouse click (the picker requires {{Glossary("Transient activation")}}).
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if called in a cross-origin iframe, except for file and color pickers (exempt for historical reasons).
## Security
[Transient user activation](/en-US/docs/Web/Security/User_activation) is required. The user has to interact with the page or a UI element in order for this feature to work.
## Examples
### Feature Detection
The code below shows how to check if `showPicker()` is supported:
```js
if ("showPicker" in HTMLInputElement.prototype) {
// showPicker() is supported.
}
```
### Normal input pickers
This example shows how this feature can be used for `color` and `file` input pickers.
> **Note:** Pickers for `date`, `datetime-local`, `month`, `time`, `week` are launched in the same way.
> They cannot be shown here because live examples run in a cross-origin frame, and would cause a [`SecurityError`](#securityerror)
#### HTML
```html
<p>
<input type="color" />
<button id="color">Show the color picker</button>
</p>
<p>
<input type="file" />
<button id="file">Show the file picker</button>
</p>
```
#### JavaScript
The code simply gets the previous element of the selected button and calls `showPicker()` on it.
```js
document.querySelectorAll("button").forEach((button) => {
button.addEventListener("click", (event) => {
const input = event.srcElement.previousElementSibling;
try {
input.showPicker();
} catch (error) {
window.alert(error);
}
});
});
```
#### Result
Click the button next to each input type to show its picker.
{{EmbedLiveSample("Normal input pickers", "100%", "140px")}}
### showPicker() for a datalist input
`showPicker()` can launch the picker for a list of options defined in a [`<datalist>`](/en-US/docs/Web/HTML/Element/datalist).
First we define a `<datalist>` in HTML consisting of a number of internet browsers, an input of type `text` that uses it, and a button.
```html
<datalist id="browsers">
<option value="Chrome"></option>
<option value="Firefox"></option>
<option value="Opera"></option>
<option value="Safari"></option>
<option value="Microsoft Edge"></option>
</datalist>
<input type="text" list="browsers" />
<button>Select browser</button>
```
The code below adds an event listener that calls `showPicker()` when the button is clicked.
```js
const button = document.querySelector("button");
const browserInput = document.querySelector("input");
button.addEventListener("click", () => {
try {
browserInput.showPicker();
} catch (error) {
// Fall back to another picker mechanism
}
});
```
### showPicker() for autocomplete
`showPicker()` can launch a picker for an [`autocomplete`](/en-US/docs/Web/HTML/Attributes/autocomplete) input.
Here we define an input that takes an autocomplete option of "name".
```html
<input autocomplete="name" /> <button>Show autocomplete options</button>
```
The code below shows the picker for the input when the button is clicked.
```js
const button = document.querySelector("button");
const browserInput = document.querySelector("input");
button.addEventListener("click", () => {
try {
browserInput.showPicker();
} catch (error) {
// Fall back to another picker mechanism
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{ HTMLElement("input") }}
- {{ domxref("HTMLInputElement") }}
- {{ domxref("HTMLSelectElement.showPicker()") }}
- {{htmlelement("datalist")}}
- [`autocomplete`](/en-US/docs/Web/HTML/Attributes/autocomplete)
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/setrangetext/index.md | ---
title: "HTMLInputElement: setRangeText() method"
short-title: setRangeText()
slug: Web/API/HTMLInputElement/setRangeText
page-type: web-api-instance-method
browser-compat: api.HTMLInputElement.setRangeText
---
{{APIRef("HTML DOM")}}
The **`HTMLInputElement.setRangeText()`** method replaces a
range of text in an {{HTMLElement("input")}} or {{HTMLElement("textarea")}} element with
a new string.
## Syntax
```js-nolint
setRangeText(replacement)
setRangeText(replacement, start)
setRangeText(replacement, start, end)
setRangeText(replacement, start, end, selectMode)
```
### Parameters
- `replacement`
- : The string to insert.
- `start` {{optional_inline}}
- : The 0-based index of the first character to replace. Defaults to the current
`selectionStart` value (the start of the user's current selection).
- `end` {{optional_inline}}
- : The 0-based index of the character _after_ the last character to replace.
Defaults to the current `selectionEnd` value (the end of the user's current
selection).
- `selectMode` {{optional_inline}}
- : A string defining how the selection should be set after the text has been replaced.
Possible values:
- `"select"` selects the newly inserted text.
- `"start"`moves the selection to just before the inserted text.
- `"end"` moves the selection to just after the inserted text.
- `"preserve"` attempts to preserve the selection. This is the default.
### Return value
None ({{jsxref("undefined")}}).
## Examples
Click the button in this example to replace part of the text in the text box. The newly
inserted text will be highlighted (selected) afterwards.
### HTML
```html
<input
type="text"
id="text-box"
size="30"
value="This text has NOT been updated." />
<button onclick="selectText()">Update text</button>
```
### JavaScript
```js
function selectText() {
const input = document.getElementById("text-box");
input.focus();
input.setRangeText("ALREADY", 14, 17, "select");
}
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{HTMLElement("input")}}
- {{HTMLElement("textarea")}}
- {{domxref("HTMLInputElement")}}
- {{domxref("Selection")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/selectionstart/index.md | ---
title: "HTMLInputElement: selectionStart property"
short-title: selectionStart
slug: Web/API/HTMLInputElement/selectionStart
page-type: web-api-instance-property
browser-compat: api.HTMLInputElement.selectionStart
---
{{ApiRef("HTML DOM")}}
The **`selectionStart`** property of the {{domxref("HTMLInputElement")}} interface is a number that represents the beginning index of the selected text. When nothing is selected, then returns the position of the text input cursor (caret) inside of the `<input>` element.
> **Note:** According to the [WHATWG forms spec](https://html.spec.whatwg.org/multipage/forms.html#concept-input-apply) `selectionStart` property applies only to inputs of types text, search, URL, tel, and password. In modern browsers, throws an exception while setting `selectionStart` property on the rest of input types. Additionally, this property returns `null` while accessing `selectionStart` property on non-text input elements.
If `selectionStart` is greater than `selectionEnd`, then both are
treated as the value of `selectionEnd`.
## Value
A non-negative number.
## Examples
### HTML
```html
<!-- use selectionStart on non text input element -->
<label for="color">selectionStart property on type=color</label>
<input id="color" type="color" />
<!-- use selectionStart on text input element -->
<fieldset>
<legend>selectionStart property on type=text</legend>
<label for="statement">Select 'mdn' word from the text : </label>
<input
type="text"
id="statement"
value="The mdn is a documentation repository." />
<button id="statement-btn">Select mdn text</button>
</fieldset>
```
### JavaScript
```js
const inputElement = document.getElementById("statement");
const statementBtn = document.getElementById("statement-btn");
const colorStart = document.getElementById("color");
statementBtn.addEventListener("click", () => {
inputElement.selectionStart = 4;
inputElement.selectionEnd = 7;
inputElement.focus();
});
// open browser console to verify output
console.log(colorStart.selectionStart); // Output : null
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLTextAreaElement.selectionStart")}} property
- {{domxref("HTMLInputElement.selectionEnd")}} property
- {{domxref("HTMLInputElement.setSelectionRange")}} method
| 0 |
data/mdn-content/files/en-us/web/api/htmlinputelement | data/mdn-content/files/en-us/web/api/htmlinputelement/reportvalidity/index.md | ---
title: "HTMLInputElement: reportValidity() method"
short-title: reportValidity()
slug: Web/API/HTMLInputElement/reportValidity
page-type: web-api-instance-method
browser-compat: api.HTMLInputElement.reportValidity
---
{{APIRef("HTML DOM")}}
The **`reportValidity()`** method of the {{domxref('HTMLInputElement')}} interface performs the same validity checking steps as the {{domxref("HTMLInputElement.checkValidity", "checkValidity()")}} method. If the value is invalid, this method also fires the {{domxref("HTMLInputElement.invalid_event", "invalid")}} event on the element, and (if the event isn't canceled) reports the problem to the user.
## Syntax
```js-nolint
reportValidity()
```
### Parameters
None.
### Return value
Returns `true` if the element's value has no validity problems; otherwise, returns `false`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [checkValidity](/en-US/docs/Web/API/HTMLInputElement/checkValidity)
- [Learn: Client-side form validation](/en-US/docs/Learn/Forms/Form_validation)
- [Guide: Constraint validation](/en-US/docs/Web/HTML/Constraint_validation)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/notification/index.md | ---
title: Notification
slug: Web/API/Notification
page-type: web-api-interface
browser-compat: api.Notification
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`Notification`** interface of the {{domxref("Notifications API", "", "", "nocode")}} is used to configure and display desktop notifications to the user.
These notifications' appearance and specific functionality vary across platforms but generally they provide a way to asynchronously provide information to the user.
{{AvailableInWorkers}}
{{InheritanceDiagram}}
## Constructor
- {{domxref("Notification.Notification", "Notification()")}}
- : Creates a new instance of the `Notification` object.
## Static properties
_Also inherits properties from its parent interface, {{domxref("EventTarget")}}_.
- {{domxref("Notification.permission_static", "Notification.permission")}} {{ReadOnlyInline}}
- : A string representing the current permission to display notifications. Possible values are:
- `denied` — The user refuses to have notifications displayed.
- `granted` — The user accepts having notifications displayed.
- `default` — The user choice is unknown and therefore the browser will act as if the value were denied.
- {{domxref("Notification.maxActions_static", "Notification.maxActions")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The maximum number of actions supported by the device and the User Agent.
## Instance properties
_Also inherits properties from its parent interface, {{domxref("EventTarget")}}_.
- {{domxref("Notification.actions")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The actions array of the notification as specified in the constructor's `options` parameter.
- {{domxref("Notification.badge")}} {{ReadOnlyInline}}
- : A string containing the URL of an image to represent the notification when there is not enough space to display the notification itself such as for example, the Android Notification Bar. On Android devices, the badge should accommodate devices up to 4x resolution, about 96 by 96 px, and the image will be automatically masked.
- {{domxref("Notification.body")}} {{ReadOnlyInline}}
- : The body string of the notification as specified in the constructor's `options` parameter.
- {{domxref("Notification.data")}} {{ReadOnlyInline}}
- : Returns a structured clone of the notification's data.
- {{domxref("Notification.dir")}} {{ReadOnlyInline}}
- : The text direction of the notification as specified in the constructor's `options` parameter.
- {{domxref("Notification.icon")}} {{ReadOnlyInline}}
- : The URL of the image used as an icon of the notification as specified in the constructor's `options` parameter.
- {{domxref("Notification.image")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The URL of an image to be displayed as part of the notification, as specified in the constructor's `options` parameter.
- {{domxref("Notification.lang")}} {{ReadOnlyInline}}
- : The language code of the notification as specified in the constructor's `options` parameter.
- {{domxref("Notification.renotify")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Specifies whether the user should be notified after a new notification replaces an old one.
- {{domxref("Notification.requireInteraction")}} {{ReadOnlyInline}}
- : A boolean value indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automatically.
- {{domxref("Notification.silent")}} {{ReadOnlyInline}}
- : Specifies whether the notification should be silent — i.e., no sounds or vibrations should be issued, regardless of the device settings.
- {{domxref("Notification.tag")}} {{ReadOnlyInline}}
- : The ID of the notification (if any) as specified in the constructor's `options` parameter.
- {{domxref("Notification.timestamp")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Specifies the time at which a notification is created or applicable (past, present, or future).
- {{domxref("Notification.title")}} {{ReadOnlyInline}}
- : The title of the notification as specified in the first parameter of the constructor.
- {{domxref("Notification.vibrate")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Specifies a vibration pattern for devices with vibration hardware to emit.
## Static methods
_Also inherits methods from its parent interface, {{domxref("EventTarget")}}_.
- {{domxref("Notification.requestPermission_static", "Notification.requestPermission()")}}
- : Requests permission from the user to display notifications.
## Instance methods
_Also inherits methods from its parent interface, {{domxref("EventTarget")}}_.
- {{domxref("Notification.close()")}}
- : Programmatically closes a notification instance.
## Events
_Also inherits events from its parent interface, {{domxref("EventTarget")}}_.
- {{domxref("Notification.click_event", "click")}}
- : Fires when the user clicks the notification.
- {{domxref("Notification.close_event", "close")}}
- : Fires when the user closes the notification.
- {{domxref("Notification.error_event", "error")}}
- : Fires when the notification encounters an error.
- {{domxref("Notification.show_event", "show")}}
- : Fires when the notification is displayed.
## Examples
Assume this basic HTML:
```html
<button onclick="notifyMe()">Notify me!</button>
```
It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.
```js
function notifyMe() {
if (!("Notification" in window)) {
// Check if the browser supports notifications
alert("This browser does not support desktop notification");
} else if (Notification.permission === "granted") {
// Check whether notification permissions have already been granted;
// if so, create a notification
const notification = new Notification("Hi there!");
// …
} else if (Notification.permission !== "denied") {
// We need to ask the user for permission
Notification.requestPermission().then((permission) => {
// If the user accepts, let's create a notification
if (permission === "granted") {
const notification = new Notification("Hi there!");
// …
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them anymore.
}
```
We no longer show a live sample on this page, as Chrome and Firefox no longer allow notification permissions to be requested from cross-origin {{htmlelement("iframe")}}s, with other browsers to follow. To see an example in action, check out our [To-do list example](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) (also see [the app running live](https://mdn.github.io/dom-examples/to-do-notifications/)).
> **Note:** In the above example we spawn notifications in response to a user gesture (clicking a button). This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/body/index.md | ---
title: "Notification: body property"
short-title: body
slug: Web/API/Notification/body
page-type: web-api-instance-property
browser-compat: api.Notification.body
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`body`** read-only property of the
{{domxref("Notification")}} interface indicates the body string of the notification, as
specified in the `body` option of the
{{domxref("Notification.Notification","Notification()")}} constructor.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
function spawnNotification(theBody, theIcon, theTitle) {
const options = {
body: theBody,
icon: theIcon,
};
const n = new Notification(theTitle, options);
console.log(n.body);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/icon/index.md | ---
title: "Notification: icon property"
short-title: icon
slug: Web/API/Notification/icon
page-type: web-api-instance-property
browser-compat: api.Notification.icon
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`icon`** read-only property of the
{{domxref("Notification")}} interface contains the URL of an icon to be displayed as
part of the notification, as specified in the `icon` option of the
{{domxref("Notification.Notification","Notification()")}} constructor.
{{AvailableInWorkers}}
## Value
A string.
## Examples
In our [To-do list app](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([view the app running live](https://mdn.github.io/dom-examples/to-do-notifications/)), we use the {{domxref("Notification.Notification","Notification()")}}
constructor to fire a notification, passing it arguments to specify the body, icon and
title we want.
```js
const notification = new Notification("To do list", {
body: text,
icon: img,
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/silent/index.md | ---
title: "Notification: silent property"
short-title: silent
slug: Web/API/Notification/silent
page-type: web-api-instance-property
browser-compat: api.Notification.silent
---
{{APIRef("Web Notifications")}}{{SecureContext_Header}}
The **`silent`** read-only property of the
{{domxref("Notification")}} interface specifies whether the notification should be
silent, i.e., no sounds or vibrations should be issued, regardless of the device
settings. This is specified in the `silent` option of the
{{domxref("Notification.Notification","Notification()")}} constructor.
{{AvailableInWorkers}}
## Value
A boolean value. `false` is the default; `true` makes
the notification silent.
## Examples
The following snippet is intended to fire a silent notification; a simple
`options` object is created, and then the notification is fired using the
{{DOMxRef("Notification.Notification","Notification()")}} constructor.
```js
const options = {
body: "Your code submission has received 3 new review comments.",
silent: true,
};
const n = new Notification("New review activity", options);
console.log(n.silent); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/badge/index.md | ---
title: "Notification: badge property"
short-title: badge
slug: Web/API/Notification/badge
page-type: web-api-instance-property
browser-compat: api.Notification.badge
---
{{APIRef("Web Notifications")}}{{SecureContext_Header}}
The **`badge`** read-only property of the {{domxref("Notification")}} interface returns a string containing the URL of an image to represent the notification when there is not enough space to display the notification itself such as for example, the Android Notification Bar. On Android devices, the badge should accommodate devices up to 4x resolution, about 96 by 96 px, and the image will be automatically masked.
{{AvailableInWorkers}}
## Value
A string containing a URL.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/renotify/index.md | ---
title: "Notification: renotify property"
short-title: renotify
slug: Web/API/Notification/renotify
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.Notification.renotify
---
{{APIRef("Web Notifications")}}{{SecureContext_Header}}{{SeeCompatTable}}
The **`renotify`** read-only property of the
{{domxref("Notification")}} interface specifies whether the user should be notified
after a new notification replaces an old one, as specified in the `renotify`
option of the {{domxref("Notification.Notification","Notification()")}} constructor.
{{AvailableInWorkers}}
## Value
A boolean value. `false` is the default; `true` makes
the notification renotify the user.
## Examples
The following snippet is intended to fire a notification that renotifies the user after
it has been replaced; a simple `options` object is created, and then the
notification is fired using the `Notification()` constructor.
```js
const options = {
body: "Your code submission has received 3 new review comments.",
renotify: true,
};
const n = new Notification("New review activity", options);
console.log(n.renotify); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/dir/index.md | ---
title: "Notification: dir property"
short-title: dir
slug: Web/API/Notification/dir
page-type: web-api-instance-property
browser-compat: api.Notification.dir
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`dir`** read-only property of the {{domxref("Notification")}} interface indicates the text direction of the notification, as specified in the `dir` option of the {{domxref("Notification.Notification","Notification()")}} constructor.
{{AvailableInWorkers}}
## Value
A string specifying the text direction. Possible values are:
- `auto`
- : adopts the browser's language setting behavior (the default.)
- `ltr`
- : left to right.
- `rtl`
- : right to left.
> **Note:** Most browsers seem to ignore explicit ltr and rtl settings, and just go with the browser-wide setting.
## Examples
The following snippet fires a notification; a simple `options` object is created, then the notification is fired using the `Notification()` constructor.
```js
const options = {
body: "Your code submission has received 3 new review comments.",
dir: "rtl",
};
const n = new Notification("New review activity", options);
console.log(n.dir); // "rtl"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/title/index.md | ---
title: "Notification: title property"
short-title: title
slug: Web/API/Notification/title
page-type: web-api-instance-property
browser-compat: api.Notification.title
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`title`** read-only property of the
{{domxref("Notification")}} interface indicates the title of the notification, as
specified in the `title` parameter of the
{{domxref("Notification.Notification","Notification()")}} constructor.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
function spawnNotification(theBody, theIcon, theTitle) {
const options = {
body: theBody,
icon: theIcon,
};
const n = new Notification(theTitle, options);
console.log(n.title);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/vibrate/index.md | ---
title: "Notification: vibrate property"
short-title: vibrate
slug: Web/API/Notification/vibrate
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.Notification.vibrate
---
{{APIRef("Web Notifications")}}{{SecureContext_Header}}{{SeeCompatTable}}
The **`vibrate`** read-only property of the {{domxref("Notification")}}
interface specifies a [vibration pattern](/en-US/docs/Web/API/Vibration_API#vibration_patterns)
for the device's vibration hardware to emit when the notification fires. This is
specified in the `vibrate` option of the
{{domxref("Notification.Notification","Notification()")}} constructor.
{{AvailableInWorkers}}
## Value
A [vibration pattern](/en-US/docs/Web/API/Vibration_API#vibration_patterns), as specified in the [Vibration API spec](https://w3c.github.io/vibration/).
## Examples
The following snippet is intended to create a notification that also triggers a device
vibration; a simple `options` object is created, and then the notification is
fired using the `Notification()` constructor.
```js
const options = {
body: "Your code submission has received 3 new review comments.",
vibrate: [200, 100, 200],
};
const n = new Notification("New review activity", options);
console.log(n.vibrate); // [200, 100, 200]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/data/index.md | ---
title: "Notification: data property"
short-title: data
slug: Web/API/Notification/data
page-type: web-api-instance-property
browser-compat: api.Notification.data
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`data`** read-only property of the
{{domxref("Notification")}} interface returns a structured clone of the notification's
data, as specified in the `data` option of the
{{domxref("Notification.Notification","Notification()")}} constructor.
The notification's data can be any arbitrary data that you want associated with the
notification.
{{AvailableInWorkers}}
## Value
A structured clone.
## Examples
The following snippet fires a notification; a simple `options` object is
created, then the notification is fired using the `Notification()`
constructor.
```js
const options = {
body: "Your code submission has received 3 new review comments.",
data: {
url: "https://example.com/review/12345",
status: "open",
},
};
const n = new Notification("New review activity", options);
console.log(n.data); // Logs the data object
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/tag/index.md | ---
title: "Notification: tag property"
short-title: tag
slug: Web/API/Notification/tag
page-type: web-api-instance-property
browser-compat: api.Notification.tag
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`tag`** read-only property of the
{{domxref("Notification")}} interface signifies an identifying tag for the notification,
as specified in the `tag` option of the
{{domxref("Notification.Notification","Notification()")}} constructor.
The idea of notification tags is that more than one notification can share the same
tag, linking them together. One notification can then be programmatically replaced with
another to avoid the users' screen being filled up with a huge number of similar
notifications.
{{AvailableInWorkers}}
## Value
A string.
## Examples
Our [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API#replacing_existing_notifications) article has a good example of tag usage.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/actions/index.md | ---
title: "Notification: actions property"
short-title: actions
slug: Web/API/Notification/actions
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.Notification.actions
---
{{APIRef("Web Notifications")}}{{SecureContext_Header}}{{SeeCompatTable}}
The **`actions`** read-only property of the {{domxref("Notification")}} interface provides the actions available for users to choose from for interacting with the notification.
The actions are set using the `actions` option of the second argument for the {{DOMxref("ServiceWorkerRegistration.showNotification", "showNotification()")}} method and {{DOMxref("Notification/Notification", "Notification()")}} constructor.
> **Note:** Browsers typically limit the maximum number of actions they will display for a particular notification. Check the static {{DOMxref("Notification.maxActions_static", "Notification.maxActions")}} property to determine the limit.
{{AvailableInWorkers}}
## Value
A read-only array of actions. Each element in the array is an object with the following members:
- `action`
- : A string identifying a user action to be displayed on the notification.
- `title`
- : A string containing action text to be shown to the user.
- `icon`
- : A string containing the URL of an icon to display with the action.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
- {{DOMxref("Notification.maxActions_static", "Notification.maxActions")}}
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/lang/index.md | ---
title: "Notification: lang property"
short-title: lang
slug: Web/API/Notification/lang
page-type: web-api-instance-property
browser-compat: api.Notification.lang
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`lang`** read-only property of the
{{domxref("Notification")}} interface indicates the language used in the notification,
as specified in the `lang` option of the
{{domxref("Notification.Notification","Notification()")}} constructor.
The language itself is specified using a string representing a language tag according to {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}.
See the Sitepoint [ISO 2 letter language codes](https://www.sitepoint.com/iso-2-letter-language-codes/) page for a simple reference.
{{AvailableInWorkers}}
## Value
A string specifying the language tag.
## Examples
The following snippet fires a notification; a simple `options` object is
created, then the notification is fired using the `Notification()`
constructor.
```js
const options = {
body: "Your code submission has received 3 new review comments.",
lang: "en-US",
};
const n = new Notification("New review activity", options);
console.log(n.lang); // "en-US"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/close_event/index.md | ---
title: "Notification: close event"
short-title: close
slug: Web/API/Notification/close_event
page-type: web-api-event
browser-compat: api.Notification.close_event
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`close`** event of the {{domxref("Notification")}} interface fires when a {{domxref("Notification")}} is closed.
{{AvailableInWorkers}}
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("close", (event) => {});
onclose = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/requireinteraction/index.md | ---
title: "Notification: requireInteraction property"
short-title: requireInteraction
slug: Web/API/Notification/requireInteraction
page-type: web-api-instance-property
browser-compat: api.Notification.requireInteraction
---
{{APIRef("Web Notifications")}}{{SecureContext_Header}}
The **`requireInteraction`** read-only property of the {{domxref("Notification")}} interface returns a boolean value indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automatically.
> **Note:** This can be set when the notification is first created by setting the `requireInteraction` option to `true` in the options object of the {{domxref("Notification.Notification", "Notification()")}} constructor.
{{AvailableInWorkers}}
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/image/index.md | ---
title: "Notification: image property"
short-title: image
slug: Web/API/Notification/image
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.Notification.image
---
{{APIRef("Web Notifications")}}{{SecureContext_Header}}{{SeeCompatTable}}
The **`image`** read-only property of the
{{domxref("Notification")}} interface contains the URL of an image to be displayed as
part of the notification, as specified in the `image` option of the
{{domxref("Notification.Notification","Notification()")}} constructor.
{{AvailableInWorkers}}
## Value
A string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/requestpermission_static/index.md | ---
title: "Notification: requestPermission() static method"
short-title: requestPermission()
slug: Web/API/Notification/requestPermission_static
page-type: web-api-static-method
browser-compat: api.Notification.requestPermission_static
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`requestPermission()`** static method of the {{domxref("Notification")}} interface requests permission from the user for the current origin to display notifications.
## Syntax
```js-nolint
// The latest spec has updated this method to a promise-based syntax that works like this:
Notification.requestPermission()
// Previously, the syntax was based on a simple callback; this version is now deprecated:
Notification.requestPermission(callback)
```
### Parameters
- `callback` {{optional_inline}} {{deprecated_inline}}
- : An optional callback function that is called with the permission value. Deprecated in favor of the promise return value.
### Return value
A {{jsxref("Promise")}} that resolves to a string with the permission picked by the user. Possible values for this string are:
- `granted`
- : The user has explicitly granted permission for the current origin to display system notifications.
- `denied`
- : The user has explicitly denied permission for the current origin to display system notifications.
- `default`
- : The user decision is unknown; in this case the application will act as if permission was `denied`.
## Examples
Assume this basic HTML:
```html
<button onclick="notifyMe()">Notify me!</button>
```
It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.
```js
function notifyMe() {
if (!("Notification" in window)) {
// Check if the browser supports notifications
alert("This browser does not support desktop notification");
} else if (Notification.permission === "granted") {
// Check whether notification permissions have already been granted;
// if so, create a notification
const notification = new Notification("Hi there!");
// …
} else if (Notification.permission !== "denied") {
// We need to ask the user for permission
Notification.requestPermission().then((permission) => {
// If the user accepts, let's create a notification
if (permission === "granted") {
const notification = new Notification("Hi there!");
// …
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them anymore.
}
```
We no longer show a live sample on this page, as Chrome and Firefox no longer allow notification permissions to be requested from cross-origin {{htmlelement("iframe")}}s, with other browsers to follow. To see an example in action, check out our [To-do list example](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) (also see [the app running live](https://mdn.github.io/dom-examples/to-do-notifications/)).
> **Note:** In the above example we spawn notifications in response to a user gesture (clicking a button). This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/timestamp/index.md | ---
title: "Notification: timestamp property"
short-title: timestamp
slug: Web/API/Notification/timestamp
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.Notification.timestamp
---
{{APIRef("Web Notifications")}}{{SecureContext_Header}}{{SeeCompatTable}}
The **`timestamp`** read-only property of the
{{domxref("Notification")}} interface returns a number, as
specified in the `timestamp` option of the
{{domxref("Notification.Notification","Notification()")}} constructor.
The notification's timestamp can represent the time, in milliseconds since 00:00:00 UTC
on 1 January 1970, of the event for which the notification was created, or it can be an
arbitrary timestamp that you want associated with the notification. For example, a
timestamp for an upcoming meeting could be set in the future, whereas a timestamp for a
missed message could be set in the past.
{{AvailableInWorkers}}
## Value
A number representing a timestamp, given as {{Glossary("Unix time")}} in milliseconds.
## Examples
The following snippet fires a notification; a simple `options` object is
created, then the notification is fired using the `Notification()`
constructor.
```js
const dts = Math.floor(Date.now());
const options = {
body: "Your code submission has received 3 new review comments.",
timestamp: dts,
};
const n = new Notification("New review activity", options);
console.log(n.timestamp); // Logs the timestamp
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/click_event/index.md | ---
title: "Notification: click event"
short-title: click
slug: Web/API/Notification/click_event
page-type: web-api-event
browser-compat: api.Notification.click_event
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`click`** event of the {{domxref("Notification")}}
interface fires when the user clicks on displayed {{domxref("Notification")}}.
The default behavior is to move the focus to the viewport of the notification's related
[browsing context](https://html.spec.whatwg.org/multipage/browsers.html#browsing-context).
If you don't want that behavior, call {{domxref("Event/preventDefault", "preventDefault()")}} on the event object.
{{AvailableInWorkers}}
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("click", (event) => {});
onclick = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
In the following example, we use an onclick handler to open a webpage in a new tab
(specified by the inclusion of the `'_blank'` parameter) once a notification
is clicked:
```js
notification.onclick = (event) => {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open("http://www.mozilla.org", "_blank");
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/show_event/index.md | ---
title: "Notification: show event"
short-title: show
slug: Web/API/Notification/show_event
page-type: web-api-event
browser-compat: api.Notification.show_event
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`show`** event of the {{domxref("Notification")}} interface fires when a {{domxref("Notification")}} is displayed.
{{AvailableInWorkers}}
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("show", (event) => {});
onshow = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/permission_static/index.md | ---
title: "Notification: permission static property"
short-title: permission
slug: Web/API/Notification/permission_static
page-type: web-api-static-property
browser-compat: api.Notification.permission_static
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`permission`** read-only static property of the {{domxref("Notification")}}
interface indicates the current permission granted by the user for the current origin to
display web notifications.
{{AvailableInWorkers}}
## Value
A string representing the current permission. The value can be:
- `granted`
- : The user has explicitly granted permission for the current
origin to display system notifications.
- `denied`
- : The user has explicitly denied permission for the current
origin to display system notifications.
- `default`
- : The user decision is unknown; in this case the application
will act as if permission was `denied`.
## Examples
The following snippet could be used if you wanted to first check whether notifications
are supported, then check if permission has been granted for the current origin to send
notifications, then request permission if required, before then sending a notification.
```js
function notifyMe() {
if (!("Notification" in window)) {
// Check if the browser supports notifications
alert("This browser does not support desktop notification");
} else if (Notification.permission === "granted") {
// Check whether notification permissions have already been granted;
// if so, create a notification
const notification = new Notification("Hi there!");
// …
} else if (Notification.permission !== "denied") {
// We need to ask the user for permission
Notification.requestPermission().then((permission) => {
// If the user accepts, let's create a notification
if (permission === "granted") {
const notification = new Notification("Hi there!");
// …
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them anymore.
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Notifications API](/en-US/docs/Web/API/Notifications_API)
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
- [Permissions API](/en-US/docs/Web/API/Permissions_API)
- [Using the Permissions API](/en-US/docs/Web/API/Permissions_API/Using_the_Permissions_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/notification/index.md | ---
title: "Notification: Notification() constructor"
short-title: Notification()
slug: Web/API/Notification/Notification
page-type: web-api-constructor
browser-compat: api.Notification.Notification
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`Notification()`** constructor creates a new
{{domxref("Notification")}} object instance, which represents a user notification.
> **Note:** Trying to create a notification inside the {{domxref("ServiceWorkerGlobalScope")}} using the `Notification()` constructor will throw a `TypeError`. Use {{domxref("ServiceWorkerRegistration.showNotification()")}} instead.
{{AvailableInWorkers}}
## Syntax
```js-nolint
new Notification(title)
new Notification(title, options)
```
### Parameters
- `title`
- : Defines a title for the notification, which is shown at the top of the notification
window.
- `options` {{optional_inline}}
- : An options object containing any custom settings that you want to apply to the
notification. The possible options are:
- `dir` {{optional_inline}}
- : The direction in which to display the notification. It
defaults to `auto`, which just adopts the browser's language setting
behavior, but you can override that behavior by setting values of `ltr`
and `rtl` (although most browsers seem to ignore these settings.)
- `lang` {{optional_inline}}
- : The notification's language, as specified using a
string representing a language tag
according to {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}.
See the Sitepoint [ISO 2 letter language codes](https://www.sitepoint.com/iso-2-letter-language-codes/) page for a simple reference. The default is the empty string.
- `badge` {{optional_inline}}
- : A string containing the URL of the image
used to represent the notification when there isn't enough space to display the
notification itself.
- `body` {{optional_inline}}
- : A string representing the body text of the
notification, which is displayed below the title.
The default is the empty string.
- `tag` {{optional_inline}}
- : A string representing an identifying tag for
the notification. The default is the empty string.
- `icon` {{optional_inline}}
- : A string containing the URL of an icon to
be displayed in the notification.
- `image` {{optional_inline}}
- : a string containing the URL of an image to
be displayed in the notification.
- `data` {{optional_inline}}
- : Arbitrary data that you want associated with the
notification. This can be of any data type.
The default is `null`.
- `vibrate` {{optional_inline}}
- : A [vibration pattern](/en-US/docs/Web/API/Vibration_API#vibration_patterns) for the device's vibration hardware to emit with the notification. If specified, `silent` must not be `true`.
- `timestamp` {{optional_inline}}
- : A number representing the time at which a notification is created or applicable (past, present, or future).
- `renotify` {{optional_inline}}
- : A boolean value specifying whether the user should be notified after a new notification replaces an old one. The default is `false`, which means they won't be notified. If `true`, then `tag` also must be set.
- `requireInteraction` {{optional_inline}}
- : Indicates that a notification should remain
active until the user clicks or dismisses it, rather than closing automatically.
The default value is `false`.
- `actions` {{optional_inline}}
- : An array of actions to display in the notification, for which the default is an empty array. Each element in the array can be an object with the following members:
- `action`
- : A string identifying a user action to be displayed on the notification.
- `title`
- : A string containing action text to be shown to the user.
- `icon` {{optional_inline}}
- : A string containing the URL of an icon to display with the action.
Appropriate responses are built using `event.action` within the
{{domxref("ServiceWorkerGlobalScope.notificationclick_event", "notificationclick")}} event.
- `silent` {{optional_inline}}
- : A boolean value specifying whether the
notification is silent (no sounds or vibrations issued), regardless of the device
settings. The default is `null`. If `true`, then `vibrate` must not be present.
### Return value
An instance of the {{domxref("Notification")}} object.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if:
- The constructor is called within the {{domxref("ServiceWorkerGlobalScope")}}.
- The `actions` option is specified and is not empty.
- The `silent` option is `true` and the `vibrate` option is specified.
- The `renotify` option is `true` but the `tag` option is empty.
- `DataCloneError` {{domxref("DOMException")}}
- : Thrown if serializing the `data` option failed for some reason.
## Examples
In our
[`Emogotchi demo`](https://chrisdavidmills.github.io/emogotchi/)
([see source code](https://github.com/chrisdavidmills/emogotchi)), we run a
`spawnNotification()` function when we want to trigger a notification. The
function is passed parameters to specify the body, icon, and title we want, and then it
creates the necessary `options` object and triggers the notification by using
the `Notification()` constructor.
```js
function spawnNotification(body, icon, title) {
const notification = new Notification(title, { body, icon });
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
### Chrome notes
Starting in Chrome 49, notifications don't work in incognito mode.
Chrome for Android will throw a {{jsxref("TypeError")}} when calling the
`Notification` constructor. It only supports creating
notifications from a service worker. See the
[Chromium issue tracker](https://crbug.com/481856) for more details.
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/close/index.md | ---
title: "Notification: close() method"
short-title: close()
slug: Web/API/Notification/close
page-type: web-api-instance-method
browser-compat: api.Notification.close
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`close()`** method of the {{domxref("Notification")}} interface is used to
close/remove a previously displayed notification.
> **Note:** This API shouldn't be used just to have the notification
> removed from the screen after a fixed delay since this method will also remove the
> notification from any notification tray, preventing users from interacting with it
> after it was initially shown. A valid use for this API would be to remove a
> notification that is no longer relevant (e.g. the user already read the notification
> on the webpage in the case of a messaging app or the following song is already playing
> in a music app).
{{AvailableInWorkers}}
## Syntax
```js-nolint
close()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
In the following snippet, we have a simple function that when called creates an
`options` object and then a new notification. At the end of the function, it
also calls `close()` inside a
{{domxref("EventTarget.addEventListener","addEventListener()")}} function to remove the
notification when the relevant content has been read on the webpage.
```js
function spawnNotification(theBody, theIcon, theTitle) {
const options = {
body: theBody,
icon: theIcon,
};
const n = new Notification(theTitle, options);
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
// The tab has become visible so clear the now-stale Notification.
n.close();
}
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/error_event/index.md | ---
title: "Notification: error event"
short-title: error
slug: Web/API/Notification/error_event
page-type: web-api-event
browser-compat: api.Notification.error_event
---
{{APIRef("Web Notifications")}}{{securecontext_header}}
The **`error`** event of the {{domxref("Notification")}} interface fires when something goes wrong with a {{domxref("Notification")}} (in many cases an error preventing the notification from being displayed.)
{{AvailableInWorkers}}
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("error", (event) => {});
onerror = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notification | data/mdn-content/files/en-us/web/api/notification/maxactions_static/index.md | ---
title: "Notification: maxActions static property"
short-title: maxActions
slug: Web/API/Notification/maxActions_static
page-type: web-api-static-property
status:
- experimental
browser-compat: api.Notification.maxActions_static
---
{{APIRef("Web Notifications")}}{{SecureContext_Header}}{{SeeCompatTable}}
The **`maxActions`** read-only static property of the
{{domxref("Notification")}} interface returns the maximum number of actions supported by
the device and the User Agent. Effectively, this is the maximum number of elements in
{{domxref("Notification.actions")}} array which will be respected by the User Agent.
{{AvailableInWorkers}}
## Value
An integer number which indicates the largest number of notification
actions that can be presented to the user by the User Agent and the device.
## Examples
The following snippet logs the maximum number of supported actions.
```js
const maxActions = Notification.maxActions;
console.log(
`This device can display at most ${maxActions} actions on each notification.`,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
- {{domxref("Notification.actions")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediastream_recording_api/index.md | ---
title: MediaStream Recording API
slug: Web/API/MediaStream_Recording_API
page-type: web-api-overview
browser-compat: api.MediaRecorder
spec-urls: https://w3c.github.io/mediacapture-record/
---
{{DefaultAPISidebar("MediaStream Recording")}}
The **MediaStream Recording API**, sometimes referred to as the _Media Recording API_ or the _MediaRecorder API_, is closely affiliated with the [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API) and the [WebRTC API](/en-US/docs/Web/API/WebRTC_API). The MediaStream Recording API makes it possible to capture the data generated by a {{domxref("MediaStream")}} or {{domxref("HTMLMediaElement")}} object for analysis, processing, or saving to disk. It's also surprisingly easy to work with.
## Concepts and usage
The MediaStream Recording API is comprised of a single major interface, {{domxref("MediaRecorder")}}, which does all the work of taking the data from a {{domxref("MediaStream")}} and delivering it to you for processing. The data is delivered by a series of {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} events, already in the format you specify when creating the `MediaRecorder`. You can then process the data further or write it to file as desired.
### Overview of the recording process
The process of recording a stream is simple:
1. Set up a {{domxref("MediaStream")}} or {{domxref("HTMLMediaElement")}} (in the form of an {{HTMLElement("audio")}} or {{HTMLElement("video")}} element) to serve as the source of the media data.
2. Create a {{domxref("MediaRecorder")}} object, specifying the source stream and any desired options (such as the container's MIME type or the desired bit rates of its tracks).
3. Set {{domxref("MediaRecorder.dataavailable_event", "ondataavailable")}} to an event handler for the {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event; this will be called whenever data is available for you.
4. Once the source media is playing and you've reached the point where you're ready to record video, call {{domxref("MediaRecorder.start()")}} to begin recording.
5. Your {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event handler gets called every time there's data ready for you to do with as you will; the event has a `data` attribute whose value is a {{domxref("Blob")}} that contains the media data. You can force a `dataavailable` event to occur, thereby delivering the latest sound to you so you can filter it, save it, or whatever.
6. Recording stops automatically when the source media stops playing.
7. You can stop recording at any time by calling {{domxref("MediaRecorder.stop()")}}.
> **Note:** Individual {{domxref("Blob")}}s containing slices of the recorded media will not necessarily be individually playable. The media needs to be reassembled before playback.
If anything goes wrong during recording, an {{domxref("MediaRecorder/error_event", "error")}} event is sent to the `MediaRecorder`. You can listen for `error` events by setting up a {{domxref("MediaRecorder.error_event", "onerror")}} event handler.
Example here, we use an HTML Canvas as source of the {{domxref("MediaStream")}}, and stop recording after 9 seconds.
```js
const canvas = document.querySelector("canvas");
// Optional frames per second argument.
const stream = canvas.captureStream(25);
const recordedChunks = [];
console.log(stream);
const options = { mimeType: "video/webm; codecs=vp9" };
const mediaRecorder = new MediaRecorder(stream, options);
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start();
function handleDataAvailable(event) {
console.log("data-available");
if (event.data.size > 0) {
recordedChunks.push(event.data);
console.log(recordedChunks);
download();
} else {
// …
}
}
function download() {
const blob = new Blob(recordedChunks, {
type: "video/webm",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = "test.webm";
a.click();
window.URL.revokeObjectURL(url);
}
// demo: to download after 9sec
setTimeout((event) => {
console.log("stopping");
mediaRecorder.stop();
}, 9000);
```
### Examining and controlling the recorder status
You can also use the properties of the `MediaRecorder` object to determine the state of the recording process, and its {{domxref("MediaRecorder.pause", "pause()")}} and {{domxref("MediaRecorder.resume", "resume()")}} methods to pause and resume recording of the source media.
If you need or want to check to see if a specific MIME type is supported, that's possible as well. Just call {{domxref("MediaRecorder.isTypeSupported_static", "MediaRecorder.isTypeSupported()")}}.
### Examining potential input sources
If your goal is to record camera and/or microphone input, you may wish to examine the available input devices before beginning the process of constructing the `MediaRecorder`. To do so, you'll need to call {{domxref("MediaDevices.enumerateDevices", "navigator.mediaDevices.enumerateDevices()")}} to get a list of the available media devices. You can then examine that list and identify the potential input sources, and even filter the list based on desired criteria.
In this code snippet, `enumerateDevices()` is used to examine the available input devices, locate those which are audio input devices, and create {{HTMLElement("option")}} elements that are then added to a {{HTMLElement("select")}} element representing an input source picker.
```js
navigator.mediaDevices.enumerateDevices().then((devices) => {
devices.forEach((device) => {
const menu = document.getElementById("inputdevices");
if (device.kind === "audioinput") {
const item = document.createElement("option");
item.textContent = device.label;
item.value = device.deviceId;
menu.appendChild(item);
}
});
});
```
Code similar to this can be used to let the user restrict the set of devices they wish to use.
### For more information
To learn more about using the MediaStream Recording API, see [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API), which shows how to use the API to record audio clips. A second article, [Recording a media element](/en-US/docs/Web/API/MediaStream_Recording_API/Recording_a_media_element), describes how to receive a stream from an {{HTMLElement("audio")}} or {{HTMLElement("video")}} element and use the captured stream (in this case, recording it and saving it to a local disk).
## Interfaces
- {{domxref("BlobEvent")}}
- : Each time a chunk of media data is finished being recorded, it's delivered to consumers in {{domxref("Blob")}} form using a {{domxref("BlobEvent")}} of type `dataavailable`.
- {{domxref("MediaRecorder")}}
- : The primary interface that implements the MediaStream Recording API.
- {{domxref("MediaRecorderErrorEvent")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : The interface that represents errors thrown by the MediaStream Recording API. Its {{domxref("MediaRecorderErrorEvent.error", "error")}} property is a {{domxref("DOMException")}} that specifies that error occurred.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API) landing page
- {{domxref("MediaDevices.getUserMedia()")}}
- [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton)
- [HTML5's Media Recorder API in Action on Chrome and Firefox](https://blog.addpipe.com/mediarecorder-api/)
- [MediaRecorder polyfill](https://github.com/ai/audio-recorder-polyfill) for Safari and Edge
- [TutorRoom](https://github.com/chrisjohndigital/TutorRoom): HTML video capture/playback/download using getUserMedia and the MediaStream Recording API ([source on GitHub](https://github.com/chrisjohndigital/TutorRoom))
- [Simple video recording demo](https://codepen.io/anon/pen/gpmPzm)
- [Advanced media stream recorder sample](https://quickblox.github.io/javascript-media-recorder/sample/)
- [OpenLang](https://github.com/chrisjohndigital/OpenLang): HTML video language lab web application using MediaDevices and the MediaStream Recording API for video recording ([source on GitHub](https://github.com/chrisjohndigital/OpenLang))
- [MediaStream Recorder API Now Available in Safari Technology Preview 73](https://blog.addpipe.com/safari-technology-preview-73-adds-limited-mediastream-recorder-api-support/)
| 0 |
data/mdn-content/files/en-us/web/api/mediastream_recording_api | data/mdn-content/files/en-us/web/api/mediastream_recording_api/recording_a_media_element/index.md | ---
title: Recording a media element
slug: Web/API/MediaStream_Recording_API/Recording_a_media_element
page-type: guide
---
{{DefaultAPISidebar("MediaStream Recording")}}
While the article Using the MediaStream Recording API demonstrates using the {{domxref("MediaRecorder")}} interface to capture a {{domxref("MediaStream")}} generated by a hardware device, as returned by {{domxref("MediaDevices.getUserMedia()","navigator.mediaDevices.getUserMedia()")}}, you can also use an HTML media element (namely {{HTMLElement("audio")}} or {{HTMLElement("video")}}) as the source of the `MediaStream` to be recorded. In this article, we'll look at an example that does just that.
## Example of recording a media element
### HTML
```html hidden
<p>
Click the "Start Recording" button to begin video recording for a few seconds.
You can stop recording by clicking the "Stop Recording" button. The "Download"
button will download the received data (although it's in a raw, unwrapped form
that isn't very useful).
</p>
<br />
```
Let's start by looking at the key bits of the HTML. There's a little more than this, but it's just informational rather than being part of the core operation of the app.
```html
<div class="left">
<div id="startButton" class="button">Start Recording</div>
<h2>Preview</h2>
<video id="preview" width="160" height="120" autoplay muted></video>
</div>
```
We present our main interface in two columns. On the left is a start button and a {{HTMLElement("video")}} element which displays the video preview; this is the video the user's camera sees. Note that the [`autoplay`](/en-US/docs/Web/HTML/Element/video#autoplay) attribute is used so that as soon as the stream starts to arrive from the camera, it immediately gets displayed, and the [`muted`](/en-US/docs/Web/HTML/Element/video#muted) attribute is specified to ensure that the sound from the user's microphone isn't output to their speakers, causing an ugly feedback loop.
```html
<div class="right">
<div id="stopButton" class="button">Stop Recording</div>
<h2>Recording</h2>
<video id="recording" width="160" height="120" controls></video>
<a id="downloadButton" class="button">Download</a>
</div>
```
On the right we see a stop button and the `<video>` element which will be used to play back the recorded video. Notice that the playback panel doesn't have autoplay set (so the playback doesn't start as soon as media arrives), and it has [`controls`](/en-US/docs/Web/HTML/Element/video#controls) set, which tells it to show the user controls to play, pause, and so forth.
Below the playback element is a button for downloading the recorded video.
```html hidden
<div class="bottom">
<pre id="log"></pre>
</div>
```
```css hidden
body {
font:
14px "Open Sans",
"Arial",
sans-serif;
}
video {
margin-top: 2px;
border: 1px solid black;
}
.button {
cursor: pointer;
display: block;
width: 160px;
border: 1px solid black;
font-size: 16px;
text-align: center;
padding-top: 2px;
padding-bottom: 4px;
color: white;
background-color: darkgreen;
text-decoration: none;
}
h2 {
margin-bottom: 4px;
}
.left {
margin-right: 10px;
float: left;
width: 160px;
padding: 0px;
}
.right {
margin-left: 10px;
float: left;
width: 160px;
padding: 0px;
}
.bottom {
clear: both;
padding-top: 10px;
}
```
Now let's have a look at the JavaScript code; this is where the majority of the action happens, after all!
### Setting up global variables
We start by establishing some global variables we'll need.
```js
let preview = document.getElementById("preview");
let recording = document.getElementById("recording");
let startButton = document.getElementById("startButton");
let stopButton = document.getElementById("stopButton");
let downloadButton = document.getElementById("downloadButton");
let logElement = document.getElementById("log");
let recordingTimeMS = 5000;
```
Most of these are references to elements we need to work with. The last, `recordingTimeMS`, is set to 5000 milliseconds (5 seconds); this specifies the length of the videos we'll record.
### Utility functions
Next, we create some utility functions that will get used later.
```js
function log(msg) {
logElement.innerHTML += `${msg}\n`;
}
```
The `log()` function is used to output text strings to a {{HTMLElement("div")}} so we can share information with the user. Not very pretty but it gets the job done for our purposes.
```js
function wait(delayInMS) {
return new Promise((resolve) => setTimeout(resolve, delayInMS));
}
```
The `wait()` function returns a new {{jsxref("Promise")}} which resolves once the specified number of milliseconds have elapsed. It works by using an [arrow function](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) which calls {{domxref("setTimeout()")}}, specifying the promise's resolution handler as the timeout handler function. That lets us use promise syntax when using timeouts, which can be very handy when chaining promises, as we'll see later.
### Starting media recording
The `startRecording()` function handles starting the recording process:
```js
function startRecording(stream, lengthInMS) {
let recorder = new MediaRecorder(stream);
let data = [];
recorder.ondataavailable = (event) => data.push(event.data);
recorder.start();
log(`${recorder.state} for ${lengthInMS / 1000} seconds…`);
let stopped = new Promise((resolve, reject) => {
recorder.onstop = resolve;
recorder.onerror = (event) => reject(event.name);
});
let recorded = wait(lengthInMS).then(() => {
if (recorder.state === "recording") {
recorder.stop();
}
});
return Promise.all([stopped, recorded]).then(() => data);
}
```
`startRecording()` takes two input parameters: a {{domxref("MediaStream")}} to record from and the length in milliseconds of the recording to make. We always record no more than the specified number of milliseconds of media, although if the media stops before that time is reached, {{domxref("MediaRecorder")}} automatically stops recording as well.
- Line 2
- : Creates the `MediaRecorder` that will handle recording the input `stream`.
- Line 3
- : Creates an empty array, `data`, which will be used to hold the {{domxref("Blob")}}s of media data provided to our {{domxref("MediaRecorder.dataavailable_event", "ondataavailable")}} event handler.
- Line 5
- : Sets up the handler for the {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event. The received event's `data` property is a {{domxref("Blob")}} that contains the media data. The event handler pushes the `Blob` onto the `data` array.
- Lines 6-7
- : Starts the recording process by calling {{domxref("MediaRecorder.start", "recorder.start()")}}, and outputs a message to the log with the updated state of the recorder and the number of seconds it will be recording.
- Lines 9-12
- : Creates a new {{jsxref("Promise")}}, named `stopped`, which is resolved when the `MediaRecorder`'s {{domxref("MediaRecorder.stop_event", "onstop")}} event handler is called, and is rejected if its {{domxref("MediaRecorder.error_event", "onerror")}} event handler is called. The rejection handler receives as input the name of the error that occurred.
- Lines 14-16
- : Creates a new `Promise`, named `recorded`, which is resolved when the specified number of milliseconds have elapsed. Upon resolution, it stops the `MediaRecorder` if it's recording.
- Lines 18-22
- : These lines create a new `Promise` which is fulfilled when both of the two `Promise`s (`stopped` and `recorded`) have resolved. Once that resolves, the array data is returned by `startRecording()` to its caller.
### Stopping the input stream
The `stop()` function stops the input media:
```js
function stop(stream) {
stream.getTracks().forEach((track) => track.stop());
}
```
This works by calling {{domxref("MediaStream.getTracks()")}}, using {{jsxref("Array.forEach", "forEach()")}} to call {{domxref("MediaStreamTrack.stop()")}} on each track in the stream.
### Getting an input stream and setting up the recorder
Now let's look at the most intricate piece of code in this example: our event handler for clicks on the start button:
```js
startButton.addEventListener(
"click",
() => {
navigator.mediaDevices
.getUserMedia({
video: true,
audio: true,
})
.then((stream) => {
preview.srcObject = stream;
downloadButton.href = stream;
preview.captureStream =
preview.captureStream || preview.mozCaptureStream;
return new Promise((resolve) => (preview.onplaying = resolve));
})
.then(() => startRecording(preview.captureStream(), recordingTimeMS))
.then((recordedChunks) => {
let recordedBlob = new Blob(recordedChunks, { type: "video/webm" });
recording.src = URL.createObjectURL(recordedBlob);
downloadButton.href = recording.src;
downloadButton.download = "RecordedVideo.webm";
log(
`Successfully recorded ${recordedBlob.size} bytes of ${recordedBlob.type} media.`,
);
})
.catch((error) => {
if (error.name === "NotFoundError") {
log("Camera or microphone not found. Can't record.");
} else {
log(error);
}
});
},
false,
);
```
When a {{domxref("Element/click_event", "click")}} event occurs, here's what happens:
- Lines 2-4
- : {{domxref("MediaDevices.getUserMedia")}} is called to request a new {{domxref("MediaStream")}} that has both video and audio tracks. This is the stream we'll record.
- Lines 5-9
- : When the Promise returned by `getUserMedia()` is resolved, the preview {{HTMLElement("video")}} element's {{domxref("HTMLMediaElement.srcObject","srcObject")}} property is set to be the input stream, which causes the video being captured by the user's camera to be displayed in the preview box. Since the `<video>` element is muted, the audio won't play. The "Download" button's link is then set to refer to the stream as well. Then, in line 8, we arrange for `preview.captureStream()` to call `preview.mozCaptureStream()` so that our code will work on Firefox, on which the {{domxref("HTMLMediaElement.captureStream()")}} method is prefixed. Then a new {{jsxref("Promise")}} which resolves when the preview video starts to play is created and returned.
- Line 10
- : When the preview video begins to play, we know there's media to record, so we respond by calling the [`startRecording()`](#starting_media_recording) function we created earlier, passing in the preview video stream (as the source media to be recorded) and `recordingTimeMS` as the number of milliseconds of media to record. As mentioned before, `startRecording()` returns a {{jsxref("Promise")}} whose resolution handler is called (receiving as input an array of {{domxref("Blob")}} objects containing the chunks of recorded media data) once recording has completed.
- Lines 11-15
- : The recording process's resolution handler receives as input an array of media data `Blob`s locally known as `recordedChunks`. The first thing we do is merge the chunks into a single {{domxref("Blob")}} whose MIME type is `"video/webm"` by taking advantage of the fact that the {{domxref("Blob.Blob", "Blob()")}} constructor concatenates arrays of objects into one object. Then {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}} is used to create a URL that references the blob; this is then made the value of the recorded video playback element's [`src`](/en-US/docs/Web/HTML/Element/video#src) attribute (so that you can play the video from the blob) as well as the target of the download button's link.
Then the download button's [`download`](/en-US/docs/Web/HTML/Element/a#download) attribute is set. While the `download` attribute can be a Boolean, you can also set it to a string to use as the name for the downloaded file. So by setting the download link's `download` attribute to "RecordedVideo.webm", we tell the browser that clicking the button should download a file named `"RecordedVideo.webm"` whose contents are the recorded video.
- Lines 17-18
- : The size and type of the recorded media are output to the log area below the two videos and the download button.
- Line 20
- : The `catch()` for all the `Promise`s outputs the error to the logging area by calling our `log()` function.
### Handling the stop button
The last bit of code adds a handler for the {{domxref("Element/click_event", "click")}} event on the stop button using {{domxref("EventTarget.addEventListener", "addEventListener()")}}:
```js
stopButton.addEventListener(
"click",
() => {
stop(preview.srcObject);
},
false,
);
```
This calls the [`stop()`](#stopping_the_input_stream) function we covered earlier.
### Result
When put all together with the rest of the HTML and the CSS not shown above, it looks and works like this:
{{ EmbedLiveSample('Example_of_recording_a_media_element', 600, 440) }}
You can {{LiveSampleLink("Example_of_recording_a_media_element", "view the full demo here")}}, and use your browsers developer tools to inspect the page and look at all the code, including the parts hidden above because they aren't critical to the explanation of how the APIs are being used.
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API) landing page
- {{domxref("MediaDevices.getUserMedia()")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastream_recording_api | data/mdn-content/files/en-us/web/api/mediastream_recording_api/using_the_mediastream_recording_api/index.md | ---
title: Using the MediaStream Recording API
slug: Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API
page-type: guide
browser-compat: api.MediaRecorder
---
{{DefaultAPISidebar("MediaStream Recording")}}
The [MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API) makes it easy to record audio and/or video streams. When used with {{domxref("MediaDevices.getUserMedia()","navigator.mediaDevices.getUserMedia()")}}, it provides an easy way to record from the user's input devices and instantly use the result in web apps.
Both audio and video may be recorded, separately or together. This article aims to provide a basic guide on how to use the MediaRecorder interface, which provides this API.
## A sample application: Web Dictaphone

To demonstrate basic usage of the MediaStream Recording API, we have built a web-based dictaphone. It allows you to record snippets of audio and then play them back. It even gives you a visualization of your device's sound input, using the Web Audio API. We'll concentrate on the recording and playback functionality for this article.
You can see this [demo running live](https://mdn.github.io/dom-examples/media/web-dictaphone/), or [grab the source code](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone) on GitHub.
## CSS goodies
The HTML is pretty simple in this app, so we won't go through it here; there are a couple of slightly more interesting bits of CSS worth mentioning, however, so we'll discuss them below. If you are not interested in CSS and want to get straight to the JavaScript, skip to the [Basic app setup](#basic_app_setup) section.
### Keeping the interface constrained to the viewport, regardless of device height, with calc()
The {{cssxref("calc", "calc()")}} function is one of those useful little utility features that's cropped up in CSS that doesn't look like much initially, but soon starts to make you think "Wow, why didn't we have this before? Why was CSS2 layout so awkward?" It allows you do a calculation to determine the computed value of a CSS unit, mixing different units in the process.
For example, in Web Dictaphone we have three main UI areas, stacked vertically. We wanted to give the first two (the header and the controls) fixed heights:
```css
header {
height: 70px;
}
.main-controls {
padding-bottom: 0.7rem;
height: 170px;
}
```
However, we wanted to make the third area (which contains the recorded samples you can play back) take up whatever space is left, regardless of the device height. Flexbox could be the answer here, but it's a bit overkill for such a simple layout. Instead, the problem was solved by making the third container's height equal to 100% of the parent height, minus the heights and padding of the other two:
```css
.sound-clips {
box-shadow: inset 0 3px 4px rgb(0 0 0 / 70%);
background-color: rgb(0 0 0 / 10%);
height: calc(100% - 240px - 0.7rem);
overflow: scroll;
}
```
### Checkbox hack for showing/hiding
This is fairly well documented already, but we thought we'd give a mention to the checkbox hack, which abuses the fact that you can click on the {{htmlelement("label")}} of a checkbox to toggle it checked/unchecked. In Web Dictaphone this powers the Information screen, which is shown/hidden by clicking the question mark icon in the top right-hand corner. First of all, we style the `<label>` how we want it, making sure that it has enough z-index to always sit above the other elements and therefore be focusable/clickable:
```css
label {
font-family: "NotoColorEmoji";
font-size: 3rem;
position: absolute;
top: 2px;
right: 3px;
z-index: 5;
cursor: pointer;
}
```
Then we hide the actual checkbox, because we don't want it cluttering up our UI:
```css
input[type="checkbox"] {
position: absolute;
top: -100px;
}
```
Next, we style the Information screen (wrapped in an {{htmlelement("aside")}} element) how we want it, give it fixed position so that it doesn't appear in the layout flow and affect the main UI, transform it to the position we want it to sit in by default, and give it a transition for smooth showing/hiding:
```css
aside {
position: fixed;
top: 0;
left: 0;
text-shadow: 1px 1px 1px black;
width: 100%;
height: 100%;
transform: translateX(100%);
transition: 0.6s all;
background-color: #999;
background-image: linear-gradient(
to top right,
rgb(0 0 0 / 0%),
rgb(0 0 0 / 50%)
);
}
```
Last, we write a rule to say that when the checkbox is checked (when we click/focus the label), the adjacent `<aside>` element will have its horizontal translation value changed and transition smoothly into view:
```css
input[type="checkbox"]:checked ~ aside {
transform: translateX(0);
}
```
## Basic app setup
To grab the media stream we want to capture, we use `getUserMedia()`. We then use the MediaStream Recording API to record the stream, and output each recorded snippet into the source of a generated {{htmlelement("audio")}} element so it can be played back.
We'll declare some variables for the record and stop buttons, and the {{htmlelement("article")}} that will contain the generated audio players:
```js
const record = document.querySelector(".record");
const stop = document.querySelector(".stop");
const soundClips = document.querySelector(".sound-clips");
```
Finally for this section, we set up the basic `getUserMedia` structure:
```js
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
console.log("getUserMedia supported.");
navigator.mediaDevices
.getUserMedia(
// constraints - only audio needed for this app
{
audio: true,
},
)
// Success callback
.then((stream) => {})
// Error callback
.catch((err) => {
console.error(`The following getUserMedia error occurred: ${err}`);
});
} else {
console.log("getUserMedia not supported on your browser!");
}
```
The whole thing is wrapped in a test that checks whether `getUserMedia` is supported before running anything else. Next, we call `getUserMedia()` and inside it define:
- **The constraints**: Only audio is to be captured for our dictaphone.
- **The success callback**: This code is run once the `getUserMedia` call has been completed successfully.
- **The error/failure callback**: The code is run if the `getUserMedia` call fails for whatever reason.
> **Note:** All of the code below is placed inside the `getUserMedia` success callback.
## Capturing the media stream
Once `getUserMedia` has created a media stream successfully, you create a new Media Recorder instance with the `MediaRecorder()` constructor and pass it the stream directly. This is your entry point into using the MediaStream Recording API — the stream is now ready to be captured into a {{domxref("Blob")}}, in the default encoding format of your browser.
```js
const mediaRecorder = new MediaRecorder(stream);
```
There are a series of methods available in the {{domxref("MediaRecorder")}} interface that allow you to control recording of the media stream; in Web Dictaphone we just make use of two, and listen to some events. First of all, {{domxref("MediaRecorder.start()")}} is used to start recording the stream once the record button is pressed:
```js
record.onclick = () => {
mediaRecorder.start();
console.log(mediaRecorder.state);
console.log("recorder started");
record.style.background = "red";
record.style.color = "black";
};
```
When the `MediaRecorder` is recording, the {{domxref("MediaRecorder.state")}} property will return a value of "recording".
As recording progresses, we need to collect the audio data. We register an event handler to do this using {{domxref("mediaRecorder.dataavailable_event", "ondataavailable")}}:
```js
let chunks = [];
mediaRecorder.ondataavailable = (e) => {
chunks.push(e.data);
};
```
> **Note:** The browser will fire `dataavailable` events as needed, but if you want to intervene you can also include a timeslice when invoking the `start()` method — for example `start(10000)` — to control this interval, or call {{domxref("MediaRecorder.requestData()")}} to trigger an event when you need it.
Lastly, we use the {{domxref("MediaRecorder.stop()")}} method to stop the recording when the stop button is pressed, and finalize the {{domxref("Blob")}} ready for use somewhere else in our application.
```js
stop.onclick = () => {
mediaRecorder.stop();
console.log(mediaRecorder.state);
console.log("recorder stopped");
record.style.background = "";
record.style.color = "";
};
```
Note that the recording may also stop naturally if the media stream ends (e.g. if you were grabbing a song track and the track ended, or the user stopped sharing their microphone).
## Grabbing and using the blob
When recording has stopped, the `state` property returns a value of "inactive", and a stop event is fired. We register an event handler for this using {{domxref("mediaRecorder.stop_event", "onstop")}}, and finalize our blob there from all the chunks we have received:
```js
mediaRecorder.onstop = (e) => {
console.log("recorder stopped");
const clipName = prompt("Enter a name for your sound clip");
const clipContainer = document.createElement("article");
const clipLabel = document.createElement("p");
const audio = document.createElement("audio");
const deleteButton = document.createElement("button");
clipContainer.classList.add("clip");
audio.setAttribute("controls", "");
deleteButton.innerHTML = "Delete";
clipLabel.innerHTML = clipName;
clipContainer.appendChild(audio);
clipContainer.appendChild(clipLabel);
clipContainer.appendChild(deleteButton);
soundClips.appendChild(clipContainer);
const blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
chunks = [];
const audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;
deleteButton.onclick = (e) => {
let evtTgt = e.target;
evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
};
};
```
Let's go through the above code and look at what's happening.
First, we display a prompt asking the user to name their clip.
Next, we create an HTML structure like the following, inserting it into our clip container, which is an {{htmlelement("article")}} element.
```html
<article class="clip">
<audio controls></audio>
<p>your clip name</p>
<button>Delete</button>
</article>
```
After that, we create a combined {{domxref("Blob")}} out of the recorded audio chunks, and create an object URL pointing to it, using `window.URL.createObjectURL(blob)`. We then set the value of the {{HTMLElement("audio")}} element's [`src`](/en-US/docs/Web/HTML/Element/audio#src) attribute to the object URL, so that when the play button is pressed on the audio player, it will play the `Blob`.
Finally, we set an `onclick` handler on the delete button to be a function that deletes the whole clip HTML structure.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API) landing page
- {{domxref("MediaDevices.getUserMedia()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgglyphelement/index.md | ---
title: SVGGlyphElement
slug: Web/API/SVGGlyphElement
page-type: web-api-interface
status:
- deprecated
browser-compat: api.SVGGlyphElement
---
{{APIRef("SVG")}}{{deprecated_header}}
The **`SVGGlyphElement`** interface corresponds to the {{SVGElement("glyph")}} element.
Object-oriented access to the attributes of the `<glyph>` element via the SVG DOM is not possible.
{{InheritanceDiagram}}
> **Warning:** This interface was removed in the SVG 2 specification.
## Instance properties
_This interface doesn't implement any specific properties, but inherits properties from its parent interface, {{domxref("SVGElement")}}._
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("glyph")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/sourcebuffer/index.md | ---
title: SourceBuffer
slug: Web/API/SourceBuffer
page-type: web-api-interface
browser-compat: api.SourceBuffer
---
{{APIRef("Media Source Extensions")}}
The **`SourceBuffer`** interface represents a chunk of media to be passed into an {{domxref("HTMLMediaElement")}} and played, via a {{domxref("MediaSource")}} object. This can be made up of one or several media segments.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("SourceBuffer.appendWindowEnd")}}
- : Controls the timestamp for the end of the append window.
- {{domxref("SourceBuffer.appendWindowStart")}}
- : Controls the timestamp for the start of the [append window](https://w3c.github.io/media-source/#append-window). This is a timestamp range that can be used to filter what media data is appended to the `SourceBuffer`. Coded media frames with timestamps within this range will be appended, whereas those outside the range will be filtered out.
- {{domxref("SourceBuffer.audioTracks")}} {{ReadOnlyInline}}
- : A list of the audio tracks currently contained inside the `SourceBuffer`.
- {{domxref("SourceBuffer.buffered")}} {{ReadOnlyInline}}
- : Returns the time ranges that are currently buffered in the `SourceBuffer`.
- {{domxref("SourceBuffer.mode")}}
- : Controls how the order of media segments in the `SourceBuffer` is handled, in terms of whether they can be appended in any order, or they have to be kept in a strict sequence.
- {{domxref("SourceBuffer.textTracks")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A list of the text tracks currently contained inside the `SourceBuffer`.
- {{domxref("SourceBuffer.timestampOffset")}}
- : Controls the offset applied to timestamps inside media segments that are subsequently appended to the `SourceBuffer`.
- {{domxref("SourceBuffer.updating")}} {{ReadOnlyInline}}
- : A boolean indicating whether the `SourceBuffer` is currently being updated — i.e. whether an {{domxref("SourceBuffer.appendBuffer()")}} or {{domxref("SourceBuffer.remove()")}} operation is currently in progress.
- {{domxref("SourceBuffer.videoTracks")}} {{ReadOnlyInline}}
- : A list of the video tracks currently contained inside the `SourceBuffer`.
## Instance methods
_Inherits methods from its parent interface, {{domxref("EventTarget")}}._
- {{domxref("SourceBuffer.abort()")}}
- : Aborts the current segment and resets the segment parser.
- {{domxref("SourceBuffer.appendBuffer()")}}
- : Appends media segment data from an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}} or a {{jsxref("DataView")}} object to the `SourceBuffer`.
- {{domxref("SourceBuffer.appendBufferAsync()")}} {{Non-standard_Inline}} {{Experimental_Inline}}
- : Starts the process of asynchronously appending the specified buffer to the `SourceBuffer`. Returns a {{jsxref("Promise")}} which is fulfilled once the buffer has been appended.
- {{domxref("SourceBuffer.changeType()")}}
- : Changes the {{Glossary("MIME type")}} that future calls to {{domxref("SourceBuffer.appendBuffer", "appendBuffer()")}} will expect the new data to conform to.
- {{domxref("SourceBuffer.remove()")}}
- : Removes media segments within a specific time range from the `SourceBuffer`.
- {{domxref("SourceBuffer.removeAsync()")}} {{Non-standard_Inline}} {{Experimental_Inline}}
- : Starts the process of asynchronously removing media segments in the specified range from the `SourceBuffer`. Returns a {{jsxref("Promise")}} which is fulfilled once all matching segments have been removed.
## Events
- {{domxref("SourceBuffer.abort_event", "abort")}}
- : Fired whenever {{domxref("SourceBuffer.appendBuffer()")}} is ended by a call to {{domxref("SourceBuffer.abort()")}}. {{domxref("SourceBuffer.updating")}} changes from `true` to `false`.
- {{domxref("SourceBuffer.error_event", "error")}}
- : Fired whenever an error occurs during {{domxref("SourceBuffer.appendBuffer()")}}. {{domxref("SourceBuffer.updating")}} changes from `true` to `false`.
- {{domxref("SourceBuffer.update_event", "update")}}
- : Fired whenever {{domxref("SourceBuffer.appendBuffer()")}} or {{domxref("SourceBuffer.remove()")}} completes. {{domxref("SourceBuffer.updating")}} changes from `true` to `false`. This event is fired before `updateend`.
- {{domxref("SourceBuffer.updateend_event", "updateend")}}
- : Fired after {{domxref("SourceBuffer.appendBuffer()")}} or {{domxref("SourceBuffer.remove()")}} ends. This event is fired after `update`.
- {{domxref("SourceBuffer.updatestart_event", "updatestart")}}
- : Fired whenever the value of {{domxref("SourceBuffer.updating")}} changes from `false` to `true`.
## Examples
### Loading a video chunk by chunk
The following example loads a video chunk by chunk as fast as possible, playing it as soon as it can.
You can see the complete code at <https://github.com/mdn/dom-examples/tree/main/sourcebuffer> and try the demo live at <https://mdn.github.io/dom-examples/sourcebuffer/>.
```js
const video = document.querySelector("video");
const assetURL = "frag_bunny.mp4";
// Need to be specific for Blink regarding codecs
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
function loadVideo() {
if (MediaSource.isTypeSupported(mimeCodec)) {
const mediaSource = new MediaSource();
console.log(mediaSource.readyState); // closed
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
console.error("Unsupported MIME type or codec: ", mimeCodec);
}
}
async function sourceOpen() {
console.log(this.readyState); // open
const mediaSource = this;
const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
const response = await fetch(assetURL);
const buffer = await response.arrayBuffer();
sourceBuffer.addEventListener("updateend", () => {
mediaSource.endOfStream();
video.play();
console.log(mediaSource.readyState); // ended
});
sourceBuffer.appendBuffer(buffer);
}
const load = document.querySelector("#load");
load.addEventListener("click", loadVideo);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaSource")}}
- {{domxref("SourceBufferList")}}
| 0 |
data/mdn-content/files/en-us/web/api/sourcebuffer | data/mdn-content/files/en-us/web/api/sourcebuffer/mode/index.md | ---
title: "SourceBuffer: mode property"
short-title: mode
slug: Web/API/SourceBuffer/mode
page-type: web-api-instance-property
browser-compat: api.SourceBuffer.mode
---
{{APIRef("Media Source Extensions")}}
The **`mode`** property of the {{domxref("SourceBuffer")}}
interface controls whether media segments can be appended to the
`SourceBuffer` in any order, or in a strict sequence.
The two available values are:
- `segments`: The media segment timestamps determine the order in which the
segments are played. The segments can be appended to the `SourceBuffer` in
any order.
- `sequence`: The order in which the segments are appended to the
`SourceBuffer` determines the order in which they are played. Segment
timestamps are generated automatically for the segments that observe this order.
The mode value is initially set when the `SourceBuffer` is created using
`MediaSource.addSourceBuffer()`. If timestamps already exist for the media
segments, then the value will be set to `segments`; if they don't, then the
value will be set to `sequence`.
If you try to set the `mode` property value to `segments` when
the initial value is `sequence`, an exception will be thrown. The existing
segment order must be maintained in `sequence` mode. You can, however, change
the value from `segments` to `sequence`. It just means the play
order will be fixed, and new timestamps generated to reflect this.
This property cannot be changed during while the `SourceBuffer` is
processing either an {{domxref("SourceBuffer.appendBuffer","appendBuffer()")}} or
{{domxref("SourceBuffer.remove","remove()")}} call.
## Value
A string.
### Exceptions
The following exceptions may be thrown when setting a new value for this property:
- `InvalidAccessError` {{domxref("DOMException")}}
- : Thrown if an attempt was made to set the value to `segments` when the
initial value is `sequence`.
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the {{domxref("SourceBuffer")}} object is being updated (i.e.
its {{domxref("SourceBuffer.updating")}} property is
currently `true`), the last media segment appended to this
`SourceBuffer` is incomplete, or this
`SourceBuffer` has been removed from the
{{domxref("MediaSource")}}.
## Examples
This snippet sets the `sourceBuffer` mode to `'sequence'` if it
is currently set to `'segments'`, thus setting the play order to the sequence
in which media segments are appended.
```js
const curMode = sourceBuffer.mode;
if (curMode === "segments") {
sourceBuffer.mode = "sequence";
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaSource")}}
- {{domxref("SourceBufferList")}}
| 0 |
data/mdn-content/files/en-us/web/api/sourcebuffer | data/mdn-content/files/en-us/web/api/sourcebuffer/appendbuffer/index.md | ---
title: "SourceBuffer: appendBuffer() method"
short-title: appendBuffer()
slug: Web/API/SourceBuffer/appendBuffer
page-type: web-api-instance-method
browser-compat: api.SourceBuffer.appendBuffer
---
{{APIRef("Media Source Extensions")}}
The **`appendBuffer()`** method of the
{{domxref("SourceBuffer")}} interface appends media segment data from an
{{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}} or a {{jsxref("DataView")}} object
to the `SourceBuffer`.
## Syntax
```js-nolint
appendBuffer(source)
```
### Parameters
- `source`
- : Either an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}} or a {{jsxref("DataView")}} object
that contains the media segment data you want to add to the `SourceBuffer`.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
None.
## Examples
TBD.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaSource")}}
- {{domxref("SourceBufferList")}}
| 0 |
data/mdn-content/files/en-us/web/api/sourcebuffer | data/mdn-content/files/en-us/web/api/sourcebuffer/remove/index.md | ---
title: "SourceBuffer: remove() method"
short-title: remove()
slug: Web/API/SourceBuffer/remove
page-type: web-api-instance-method
browser-compat: api.SourceBuffer.remove
---
{{APIRef("Media Source Extensions")}}
The **`remove()`** method of the {{domxref("SourceBuffer")}}
interface removes media segments within a specific time range from the
`SourceBuffer`. This method can only be called when
{{domxref("SourceBuffer.updating")}} equals `false`. If
`SourceBuffer.updating` is not equal to `false`, call
{{domxref("SourceBuffer.abort()")}}.
## Syntax
```js-nolint
remove(start, end)
```
### Parameters
- `start`
- : A double representing the start of the time range, in seconds.
- `end`
- : A double representing the end of the time range, in seconds.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `InvalidAccessError` {{domxref("DOMException")}}
- : Thrown if either the {{domxref("MediaSource.duration")}} property is equal to `NaN`, the `start` parameter is negative or greater than {{domxref("MediaSource.duration")}}, or the `end` parameter is less than or equal to `start` or equal to `NaN`.
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the {{domxref("SourceBuffer.updating")}} property is equal
to `true`, or this `SourceBuffer` has been removed
from {{domxref("MediaSource")}}.
## Examples
TBD.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaSource")}}
- {{domxref("SourceBufferList")}}
| 0 |
data/mdn-content/files/en-us/web/api/sourcebuffer | data/mdn-content/files/en-us/web/api/sourcebuffer/texttracks/index.md | ---
title: "SourceBuffer: textTracks property"
short-title: textTracks
slug: Web/API/SourceBuffer/textTracks
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.SourceBuffer.textTracks
---
{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
The **`textTracks`** read-only property of the
{{domxref("SourceBuffer")}} interface returns a list of the text tracks currently
contained inside the `SourceBuffer`.
## Value
An {{domxref("TextTrackList")}} object.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaSource")}}
- {{domxref("SourceBufferList")}}
| 0 |
data/mdn-content/files/en-us/web/api/sourcebuffer | data/mdn-content/files/en-us/web/api/sourcebuffer/buffered/index.md | ---
title: "SourceBuffer: buffered property"
short-title: buffered
slug: Web/API/SourceBuffer/buffered
page-type: web-api-instance-property
browser-compat: api.SourceBuffer.buffered
---
{{APIRef("Media Source Extensions")}}
The **`buffered`** read-only property of the
{{domxref("SourceBuffer")}} interface returns the time ranges that are currently
buffered in the `SourceBuffer` as a normalized {{domxref("TimeRanges")}}
object.
## Value
A {{domxref("TimeRanges")}} object.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaSource")}}
- {{domxref("SourceBufferList")}}
| 0 |
data/mdn-content/files/en-us/web/api/sourcebuffer | data/mdn-content/files/en-us/web/api/sourcebuffer/removeasync/index.md | ---
title: "SourceBuffer: removeAsync() method"
short-title: removeAsync()
slug: Web/API/SourceBuffer/removeAsync
page-type: web-api-instance-method
status:
- experimental
- non-standard
browser-compat: api.SourceBuffer.removeAsync
---
{{APIRef("Media Source Extensions")}}{{Non-standard_Header}}{{SeeCompatTable}}
The **`removeAsync()`** method of the
{{domxref("SourceBuffer")}} interface starts the process of asynchronously removing
from the `SourceBuffer` media segments found within a specific time
range. A {{jsxref("Promise")}} is returned, which is fulfilled when the buffers
in the specified time range have been removed.
This method can only be called when {{domxref("SourceBuffer.updating", "updating")}} is
`false`. If that's not the case, call {{domxref("SourceBuffer.abort",
"abort()")}} instead.
## Syntax
```js-nolint
removeAsync(start, end)
```
### Parameters
- `start`
- : A double representing the start of the time range, in seconds.
- `end`
- : A double representing the end of the time range, in seconds.
### Return value
A {{jsxref("Promise")}} whose fulfillment handler is executed once the buffers in the
specified time range have been removed from the `SourceBuffer`.
## Examples
This example establishes an asynchronous function, `emptySourceBuffer()`,
which clears the contents of the specified `SourceBuffer`.
```js
async function emptySourceBuffer(msBuffer) {
await msBuffer.removeAsync(0, Infinity).catch((e) => {
handleException(e);
});
}
```
## Specifications
This feature is not part of any specification. It is not on track to become a standard.
## Browser compatibility
{{Compat}}
## See also
- [Media Source Extensions API](/en-US/docs/Web/API/Media_Source_Extensions_API)
- {{domxref("SourceBuffer.remove()")}}
- {{domxref("MediaSource")}}
- {{domxref("SourceBufferList")}}
| 0 |
data/mdn-content/files/en-us/web/api/sourcebuffer | data/mdn-content/files/en-us/web/api/sourcebuffer/appendbufferasync/index.md | ---
title: "SourceBuffer: appendBufferAsync() method"
short-title: appendBufferAsync()
slug: Web/API/SourceBuffer/appendBufferAsync
page-type: web-api-instance-method
status:
- experimental
- non-standard
browser-compat: api.SourceBuffer.appendBufferAsync
---
{{APIRef("Media Source Extensions")}}{{Non-standard_Header}}{{SeeCompatTable}}
The **`appendBufferAsync()`** method
of the {{domxref("SourceBuffer")}} interface begins the process of asynchronously
appending media segment data from an {{jsxref("ArrayBuffer")}},
a {{jsxref("TypedArray")}} or a {{jsxref("DataView")}} object to the `SourceBuffer` object.
It returns a {{jsxref("Promise")}} which is fulfilled once the buffer has been appended.
## Syntax
```js-nolint
appendBufferAsync(source)
```
### Parameters
- `source`
- : Either an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}} or a {{jsxref("DataView")}} object that contains the media segment data you want to add to the `SourceBuffer`.
### Return value
A {{jsxref("Promise")}} which is fulfilled when the buffer has been added successfully to the `SourceBuffer` object,
or `null`, if the request could not be initiated.
## Examples
This simplified example async function, `fillSourceBuffer()`, takes as input
parameters `buffer`, an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}}, and a
`SourceBuffer` object to which to append the source media from the buffer.
```js
async function fillSourceBuffer(buffer, msBuffer) {
try {
while (true) {
await msBuffer.appendBufferAsync(buffer);
}
} catch (e) {
handleException(e);
}
}
```
## Specifications
This feature is not part of any specification. It is not on track to become a standard.
## Browser compatibility
{{Compat}}
## See also
- [Media Source Extensions API](/en-US/docs/Web/API/Media_Source_Extensions_API)
- {{domxref("SourceBuffer.appendBuffer()")}}
- {{domxref("MediaSource")}}
- {{domxref("SourceBufferList")}}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.