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/serviceworkerregistration | data/mdn-content/files/en-us/web/api/serviceworkerregistration/navigationpreload/index.md | ---
title: "ServiceWorkerRegistration: navigationPreload property"
short-title: navigationPreload
slug: Web/API/ServiceWorkerRegistration/navigationPreload
page-type: web-api-instance-property
browser-compat: api.ServiceWorkerRegistration.navigationPreload
---
{{APIRef("Service Workers API")}}{{SecureContext_Header}}
The **`navigationPreload`** read-only property of the {{domxref("ServiceWorkerRegistration")}} interface returns the {{domxref("NavigationPreloadManager")}} associated with the current service worker registration.
The returned object allows resources managed by a service worker to be preemptively downloaded in parallel with service worker boot up.
{{AvailableInWorkers}}
## Value
An instance of {{domxref("NavigationPreloadManager")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serviceworkerregistration | data/mdn-content/files/en-us/web/api/serviceworkerregistration/periodicsync/index.md | ---
title: "ServiceWorkerRegistration: periodicSync property"
short-title: periodicSync
slug: Web/API/ServiceWorkerRegistration/periodicSync
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ServiceWorkerRegistration.periodicSync
---
{{APIRef("Service Workers API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`periodicSync`** read-only property of
the {{domxref("ServiceWorkerRegistration")}} interface returns a reference to the
{{domxref('PeriodicSyncManager')}} interface, which allows for registering of tasks to
run at specific intervals.
{{AvailableInWorkers}}
## Value
A {{domxref('PeriodicSyncManager')}} object.
## Examples
You can access the property from either your main script or the registered service
worker.
Here is an example from the main script:
```js
// reference registration
const registration = await navigator.serviceWorker.ready;
// feature detection
if ("periodicSync" in registration) {
// Background Periodic Sync functionality
const periodicSync = registration.periodicSync;
}
```
From the [service worker](/en-US/docs/Web/API/Service_Worker_API):
```js
// service worker script
const periodicSync = self.registration.periodicSync;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Richer offline experiences with the Periodic Background Sync API](https://developer.chrome.com/docs/capabilities/periodic-background-sync)
- [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)
| 0 |
data/mdn-content/files/en-us/web/api/serviceworkerregistration | data/mdn-content/files/en-us/web/api/serviceworkerregistration/index/index.md | ---
title: "ServiceWorkerRegistration: index property"
short-title: index
slug: Web/API/ServiceWorkerRegistration/index
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ServiceWorkerRegistration.index
---
{{APIRef("Service Workers API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`index`** read-only property of the
{{domxref("ServiceWorkerRegistration")}} interface returns a reference to the
{{domxref('ContentIndex')}} interface, which allows for indexing of offline content.
{{AvailableInWorkers}}
## Value
A {{domxref('ContentIndex')}} object.
## Examples
You can access the property from either your main script or the registered service
worker.
Here is an example from the main script:
```js
// reference registration
const registration = await navigator.serviceWorker.ready;
// feature detection
if ("index" in registration) {
// Content Index API functionality
const contentIndex = registration.index;
}
```
From the [service worker](/en-US/docs/Web/API/ServiceWorker):
```js
// service worker script
const contentIndex = self.registration.index;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Content Index API")}}
- [An introductory article on the Content Index API](https://developer.chrome.com/docs/capabilities/web-apis/content-indexing-api)
- [An app which uses the Content Index API to list and remove 'save for later' content](https://contentindex.dev/)
| 0 |
data/mdn-content/files/en-us/web/api/serviceworkerregistration | data/mdn-content/files/en-us/web/api/serviceworkerregistration/sync/index.md | ---
title: "ServiceWorkerRegistration: sync property"
short-title: sync
slug: Web/API/ServiceWorkerRegistration/sync
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ServiceWorkerRegistration.sync
---
{{APIRef("Background Sync")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`sync`** read-only property of the
{{domxref("ServiceWorkerRegistration")}} interface returns a reference to the
{{domxref("SyncManager")}} interface, which manages background synchronization
processes.
{{AvailableInWorkers}}
## Value
A {{domxref("SyncManager")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serviceworkerregistration | data/mdn-content/files/en-us/web/api/serviceworkerregistration/shownotification/index.md | ---
title: "ServiceWorkerRegistration: showNotification() method"
short-title: showNotification()
slug: Web/API/ServiceWorkerRegistration/showNotification
page-type: web-api-instance-method
browser-compat: api.ServiceWorkerRegistration.showNotification
---
{{APIRef("Web Notifications")}}{{SecureContext_Header}}
The **`showNotification()`** method of the
{{domxref("ServiceWorkerRegistration")}} interface creates a notification on an active
service worker.
{{AvailableInWorkers}}
## Syntax
```js-nolint
showNotification(title)
showNotification(title, options)
```
### Parameters
- `title`
- : The title that must be shown within the notification.
- `options` {{optional_inline}}
- : An object that allows configuring the notification. It can have the following
properties:
- `actions` {{optional_inline}} {{experimental_inline}}
- : An array of actions to display in the notification. 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` {{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.
- `badge` {{optional_inline}} {{experimental_inline}}
- : 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.
- `body` {{optional_inline}}
- : A string representing an extra content to display within the
notification.
- `data` {{optional_inline}} {{experimental_inline}}
- : Arbitrary data that you want to be associated with the
notification. This can be of any data type.
- `dir` {{optional_inline}}
- : The direction of the notification; it can be `auto`, `ltr` or `rtl`.
- `icon` {{optional_inline}}
- : A string containing the URL of an image to
be used as an icon by the notification.
- `image` {{optional_inline}} {{experimental_inline}}
- : A string containing the URL of an image to
be displayed in the notification.
- `lang` {{optional_inline}}
- : Specify the lang used within the notification. This string
must be a valid language tag according to
{{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}.
- `renotify` {{optional_inline}} {{experimental_inline}}
- : A boolean that indicates whether to suppress vibrations
and audible alerts when reusing a `tag` value.
If _options_'s `renotify` is `true`
and _options_'s `tag` is the empty string a `TypeError` will be
thrown. The default is `false`.
- `requireInteraction` {{optional_inline}} {{experimental_inline}}
- : Indicates that on devices with sufficiently
large screens, a notification should remain active until the user clicks or
dismisses it. If this value is absent or `false`, the desktop version of Chrome will
auto-minimize notifications after approximately twenty seconds. The default value
is `false`.
- `silent` {{optional_inline}}
- : When set indicates that no sounds or vibrations should be
made. If _options_'s `silent` is `true`
and _options_'s `vibrate` is present a `TypeError` exception
will be thrown. The default value is `false`.
- `tag` {{optional_inline}}
- : An ID for a given notification that allows you to find,
replace, or remove the notification using a script if necessary.
- `timestamp` {{optional_inline}}
- : A timestamp, given as {{glossary("Unix time")}} in milliseconds, representing the time associated with the notification. This could be in the past when a notification is used for a message that couldn't immediately be delivered because the device was offline, or in the future for a meeting that is about to start.
- `vibrate` {{optional_inline}} {{experimental_inline}}
- : A vibration pattern to run with the display of the
notification. A vibration pattern can be an array with as few as one member. The
values are times in milliseconds where the even indices (0, 2, 4, etc.) indicate
how long to vibrate and the odd indices indicate how long to pause. For
example, `[300, 100, 400]` would vibrate 300ms, pause 100ms, then
vibrate 400ms.
### Return value
A {{jsxref('Promise')}} that resolves to `undefined`.
### Exceptions
- `TypeError`
- : Thrown if current service worker's state is not `activating` or `activated`, or if the user has explicitly denied the browser's permission request to use the API.
## Examples
```js
navigator.serviceWorker.register("sw.js");
function showNotification() {
Notification.requestPermission().then((result) => {
if (result === "granted") {
navigator.serviceWorker.ready.then((registration) => {
registration.showNotification("Vibration Sample", {
body: "Buzz! Buzz!",
icon: "../images/touch/chrome-touch-icon-192x192.png",
vibrate: [200, 100, 200, 100, 200, 100, 200],
tag: "vibration-sample",
});
});
}
});
}
```
To invoke the above function at an appropriate time, you could listen to the
{{domxref("ServiceWorkerGlobalScope.notificationclick_event", "notificationclick")}} event.
You can also retrieve details of the {{domxref("Notification")}}s that have been fired
from the current service worker using
{{domxref("ServiceWorkerRegistration.getNotifications()")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/serviceworkerregistration | data/mdn-content/files/en-us/web/api/serviceworkerregistration/active/index.md | ---
title: "ServiceWorkerRegistration: active property"
short-title: active
slug: Web/API/ServiceWorkerRegistration/active
page-type: web-api-instance-property
browser-compat: api.ServiceWorkerRegistration.active
---
{{APIRef("Service Workers API")}}{{SecureContext_Header}}
The **`active`** read-only property of the
{{domxref("ServiceWorkerRegistration")}} interface returns a service worker whose
{{domxref("ServiceWorker.state")}} is `activating` or `activated`.
This property is initially set to `null`.
An active worker controls a {{domxref("Client")}} if the client's URL
falls within the scope of the registration (the `scope` option set when
{{domxref("ServiceWorkerContainer.register")}} is first called.)
> **Note:** Once an active worker is `activating`, neither a
> runtime script error nor a force termination of the active worker prevents the active
> worker from getting `activated`.
{{AvailableInWorkers}}
## Value
A {{domxref("ServiceWorker")}} object's property, if it is currently in an
`activating` or `activated` state.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
- [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
- [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/usbisochronousouttransferresult/index.md | ---
title: USBIsochronousOutTransferResult
slug: Web/API/USBIsochronousOutTransferResult
page-type: web-api-interface
status:
- experimental
browser-compat: api.USBIsochronousOutTransferResult
---
{{securecontext_header}}{{APIRef("WebUSB API")}}{{SeeCompatTable}}
The `USBIsochronousOutTransferResult` interface of the [WebUSB API](/en-US/docs/Web/API/WebUSB_API) provides the result from a call to the `isochronousTransferOut()` method of the `USBDevice` interface. It represents the result from requesting a transfer of data from the USB host to the USB device.
## Constructor
- {{domxref("USBIsochronousOutTransferResult.USBIsochronousOutTransferResult", "USBIsochronousOutTransferResult()")}} {{Experimental_Inline}}
- : Creates a new `USBIsochronousOutTransferResult` object with the provided `packet` field.
## Instance properties
- {{domxref("USBIsochronousOutTransferResult.packets")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns an array of `USBIsochronousOutTransferPacket` objects containing the result of each request to send a packet to the device.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/css_custom_highlight_api/index.md | ---
title: CSS Custom Highlight API
slug: Web/API/CSS_Custom_Highlight_API
page-type: web-api-overview
browser-compat:
- api.Highlight
- api.HighlightRegistry
- css.selectors.highlight
spec-urls: https://drafts.csswg.org/css-highlight-api-1/
---
{{DefaultAPISidebar("CSS Custom Highlight API")}}
The CSS Custom Highlight API provides a mechanism for styling arbitrary text ranges on a document by using JavaScript to create the ranges, and CSS to style them.
## Concepts and usage
Styling text ranges on a webpage can be very useful. For example, text editing web apps highlight spelling or grammar errors, and code editors highlight syntax errors.
The CSS Custom Highlight API extends the concept of other highlight pseudo-elements such as {{cssxref('::selection')}}, {{cssxref('::spelling-error')}}, {{cssxref('::grammar-error')}}, and {{cssxref('::target-text')}} by providing a way to create and style arbitrary {{domxref('Range')}} objects, rather than being limited to browser-defined ranges.
Using the CSS Custom Highlight API, you can programmatically create text ranges and highlight them without affecting the DOM structure in the page.
There are four steps to style text ranges on a webpage using the CSS Custom Highlight API:
1. Creating {{domxref("Range")}} objects.
2. Creating {{domxref("Highlight")}} objects for these ranges.
3. Registering the highlights using the {{domxref("HighlightRegistry")}}.
4. Styling the highlights using the {{cssxref("::highlight", "::highlight()")}} pseudo-element.
### Create ranges
The first step is to define the text ranges that you want to style by creating {{domxref("Range")}} objects in JavaScript. For example:
```js
const parentNode = document.getElementById("foo");
const range1 = new Range();
range1.setStart(parentNode, 10);
range1.setEnd(parentNode, 20);
const range2 = new Range();
range2.setStart(parentNode, 40);
range2.setEnd(parentNode, 60);
```
### Create highlights
The second step is to instantiate {{domxref("Highlight")}} objects for your text ranges.
Multiple ranges can be associated to one highlight. If you want to highlight multiple pieces of text the same way, you need to create a single highlight and initialize it with the corresponding ranges.
```js
const highlight = new Highlight(range1, range2);
```
But you can also create as many highlights as you need. For example, if you are building a collaborative text editor where each user gets a different text color, then you can create one highlight per user, as seen in the code snippet below:
```js
const user1Highlight = new Highlight(user1Range1, user1Range2);
const user2Highlight = new Highlight(user2Range1, user2Range2, user2Range3);
```
Each highlight can be styled differently.
### Register highlights
Once highlights have been created, register them by using the {{domxref("HighlightRegistry")}} available as {{domxref("CSS/highlights_static", "CSS.highlights")}}.
The registry is a {{jsxref("Map")}}-like object used to register highlights by names, as seen below:
```js
CSS.highlights.set("user-1-highlight", user1Highlight);
CSS.highlights.set("user-2-highlight", user2Highlight);
```
In the above code snippet, the `user-1-highlight` and `user-2-highlight` strings are custom identifiers that can be used in CSS to apply styles to the registered highlights.
You can register as many highlights as you need in the registry, as well as remove highlights and clear the entire registry.
```js
// Remove a single highlight from the registry.
CSS.highlights.delete("user-1-highlight");
// Clear the registry.
CSS.highlights.clear();
```
### Style highlights
The final step is to style the registered highlights. This is done by using the {{cssxref("::highlight", "::highlight()")}} pseudo-element. For example, to style the `user-1-highlight` highlight registered in the previous step:
```css
::highlight(user-1-highlight) {
background-color: yellow;
color: black;
}
```
## Interfaces
- {{domxref("Highlight")}}
- : This interface is used to represent a collection of ranges to be styled on a document.
- {{domxref("HighlightRegistry")}}
- : Accessible via {{domxref("CSS/highlights_static", "CSS.highlights")}}, this {{jsxref("Map")}}-like object is used to register highlights with custom identifiers.
## Examples
### Highlighting search results
This example shows how to use the CSS Custom Highlight API to highlight search results.
#### HTML
The HTML code snippet below defines a search field and an article with a few paragraphs of text:
```html
<label>Search within text <input id="query" type="text" /></label>
<article>
<p>
Maxime debitis hic, delectus perspiciatis laborum molestiae labore,
deleniti, quam consequatur iure veniam alias voluptas nisi quo. Dolorem
eaque alias, quo vel quas repudiandae architecto deserunt quidem, sapiente
laudantium nulla.
</p>
<p>
Maiores odit molestias, necessitatibus doloremque dolor illum reprehenderit
provident nostrum laboriosam iste, tempore perferendis! Ab porro neque esse
voluptas libero necessitatibus fugiat, ex, minus atque deserunt veniam
molestiae tempora? Vitae.
</p>
<p>
Dolorum facilis voluptate eaque eius similique ducimus dignissimos assumenda
quos architecto. Doloremque deleniti non exercitationem rerum quam alias
harum, nisi obcaecati corporis temporibus vero sapiente voluptatum est
quibusdam id ipsa.
</p>
</article>
```
#### JavaScript
JavaScript is used to listen to the `input` event on the search field. When the event is fired, the code locates matches for the input text in the article text. It then creates ranges for the matches, and uses the CSS Custom Highlight API to create and register a `search-results` highlight object:
```js
const query = document.getElementById("query");
const article = document.querySelector("article");
// Find all text nodes in the article. We'll search within
// these text nodes.
const treeWalker = document.createTreeWalker(article, NodeFilter.SHOW_TEXT);
const allTextNodes = [];
let currentNode = treeWalker.nextNode();
while (currentNode) {
allTextNodes.push(currentNode);
currentNode = treeWalker.nextNode();
}
// Listen to the input event to run the search.
query.addEventListener("input", () => {
// If the CSS Custom Highlight API is not supported,
// display a message and bail-out.
if (!CSS.highlights) {
article.textContent = "CSS Custom Highlight API not supported.";
return;
}
// Clear the HighlightRegistry to remove the
// previous search results.
CSS.highlights.clear();
// Clean-up the search query and bail-out if
// if it's empty.
const str = query.value.trim().toLowerCase();
if (!str) {
return;
}
// Iterate over all text nodes and find matches.
const ranges = allTextNodes
.map((el) => {
return { el, text: el.textContent.toLowerCase() };
})
.map(({ text, el }) => {
const indices = [];
let startPos = 0;
while (startPos < text.length) {
const index = text.indexOf(str, startPos);
if (index === -1) break;
indices.push(index);
startPos = index + str.length;
}
// Create a range object for each instance of
// str we found in the text node.
return indices.map((index) => {
const range = new Range();
range.setStart(el, index);
range.setEnd(el, index + str.length);
return range;
});
});
// Create a Highlight object for the ranges.
const searchResultsHighlight = new Highlight(...ranges.flat());
// Register the Highlight object in the registry.
CSS.highlights.set("search-results", searchResultsHighlight);
});
```
#### CSS
Finally, the `::highlight()` pseudo-element is used in CSS to style the highlights:
```css
::highlight(search-results) {
background-color: #f06;
color: white;
}
```
#### Result
The result is shown below. Type text within the search field to highlight matches in the article:
{{ EmbedLiveSample('Highlighting search results', 700, 300) }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediametadata/index.md | ---
title: MediaMetadata
slug: Web/API/MediaMetadata
page-type: web-api-interface
browser-compat: api.MediaMetadata
---
{{APIRef("Media Session API")}}
The **`MediaMetadata`** interface of the {{domxref("Media Session API", "", "", "nocode")}} allows a web page to provide rich media metadata for display in a platform UI.
## Constructor
- {{domxref("MediaMetadata.MediaMetadata", "MediaMetadata()")}}
- : Creates a new `MediaMetaData` object.
## Instance properties
- {{domxref("MediaMetadata.title")}}
- : Returns or sets the title of the media to be played.
- {{domxref("MediaMetadata.artist")}}
- : Returns or sets the name of the artist, group, creator, etc. of the media to be played.
- {{domxref("MediaMetadata.album")}}
- : Returns or sets the name of the album or collection containing the media to be played.
- {{domxref("MediaMetadata.artwork")}}
- : Returns or sets an array of images associated with playing media.
## Examples
The following example checks for browser compatibility and sets the current metadata for the media session.
```js
if ("mediaSession" in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: "Unforgettable",
artist: "Nat King Cole",
album: "The Ultimate Collection (Remastered)",
artwork: [
{
src: "https://dummyimage.com/96x96",
sizes: "96x96",
type: "image/png",
},
{
src: "https://dummyimage.com/128x128",
sizes: "128x128",
type: "image/png",
},
{
src: "https://dummyimage.com/192x192",
sizes: "192x192",
type: "image/png",
},
{
src: "https://dummyimage.com/256x256",
sizes: "256x256",
type: "image/png",
},
{
src: "https://dummyimage.com/384x384",
sizes: "384x384",
type: "image/png",
},
{
src: "https://dummyimage.com/512x512",
sizes: "512x512",
type: "image/png",
},
],
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediametadata | data/mdn-content/files/en-us/web/api/mediametadata/title/index.md | ---
title: "MediaMetadata: title property"
short-title: title
slug: Web/API/MediaMetadata/title
page-type: web-api-instance-property
browser-compat: api.MediaMetadata.title
---
{{APIRef("Media Session API")}}
The **`title`** property of the
{{domxref("MediaMetaData")}} interface returns or sets the title of the media to be
played.
## Value
A {{jsxref("String")}} containing the title of the media.
## Examples
The following example checks for browser compatibility and sets the current metadata
for the media session.
```js
if ("mediaSession" in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: "Unforgettable",
artist: "Nat King Cole",
album: "The Ultimate Collection (Remastered)",
artwork: [
{
src: "https://dummyimage.com/96x96",
sizes: "96x96",
type: "image/png",
},
{
src: "https://dummyimage.com/128x128",
sizes: "128x128",
type: "image/png",
},
{
src: "https://dummyimage.com/192x192",
sizes: "192x192",
type: "image/png",
},
{
src: "https://dummyimage.com/256x256",
sizes: "256x256",
type: "image/png",
},
{
src: "https://dummyimage.com/384x384",
sizes: "384x384",
type: "image/png",
},
{
src: "https://dummyimage.com/512x512",
sizes: "512x512",
type: "image/png",
},
],
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediametadata | data/mdn-content/files/en-us/web/api/mediametadata/artist/index.md | ---
title: "MediaMetadata: artist property"
short-title: artist
slug: Web/API/MediaMetadata/artist
page-type: web-api-instance-property
browser-compat: api.MediaMetadata.artist
---
{{APIRef("Media Session API")}}
The **`artist`** property of the
{{domxref("MediaMetaData")}} interface returns or sets the name of the artist, group,
creator, etc., of the media to be played.
## Value
A {{jsxref("String")}} containing the name of the artist.
## Examples
The following example checks for browser compatibility and sets the current metadata
for the media session.
```js
if ("mediaSession" in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: "Unforgettable",
artist: "Nat King Cole",
album: "The Ultimate Collection (Remastered)",
artwork: [
{
src: "https://dummyimage.com/96x96",
sizes: "96x96",
type: "image/png",
},
{
src: "https://dummyimage.com/128x128",
sizes: "128x128",
type: "image/png",
},
{
src: "https://dummyimage.com/192x192",
sizes: "192x192",
type: "image/png",
},
{
src: "https://dummyimage.com/256x256",
sizes: "256x256",
type: "image/png",
},
{
src: "https://dummyimage.com/384x384",
sizes: "384x384",
type: "image/png",
},
{
src: "https://dummyimage.com/512x512",
sizes: "512x512",
type: "image/png",
},
],
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediametadata | data/mdn-content/files/en-us/web/api/mediametadata/mediametadata/index.md | ---
title: "MediaMetadata: MediaMetadata() constructor"
short-title: MediaMetadata()
slug: Web/API/MediaMetadata/MediaMetadata
page-type: web-api-constructor
browser-compat: api.MediaMetadata.MediaMetadata
---
{{APIRef("Media Session API")}}
The **`MediaMetadata()`** constructor creates a new
{{domxref("MediaMetadata")}} object.
## Syntax
```js-nolint
new MediaMetadata()
new MediaMetadata(metadata)
```
### Parameters
- `metadata` {{optional_inline}}
- : The metadata parameters are as follows:
- `title` {{optional_inline}}
- : The title of the media to be played. It defaults to the empty string (`""`).
- `artist` {{optional_inline}}
- : The name of the artist, group, creator, etc. of the media to be played. It defaults to the empty string (`""`).
- `album` {{optional_inline}}
- : The name of the album, or collection, containing the media to be played. It defaults to the empty string (`""`).
- `artwork` {{optional_inline}}
- : An {{jsxref("Array")}} of objects that represent images associated with the playing media that defaults to be an empty array. The object structure is:
- `src`
- : The URL from which the user agent fetches the image's data.
- `sizes` {{optional_inline}}
- : Specifies the resource in multiple sizes so the user agent doesn't have to scale a single image. It defaults to the empty string (`""`).
- `type` {{optional_inline}}
- : The {{Glossary("MIME type")}} hint for the user agent that allows it to ignore images of types that it doesn't support. However, the user agent may still use MIME type sniffing after downloading the image to determine its type. It defaults to the empty string (`""`).
## Example
The following example creates a new {{domxref("MediaMetadata")}} object using the
correct format of metadata.
```js
if ("mediaSession" in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: "Unforgettable",
artist: "Nat King Cole",
album: "The Ultimate Collection (Remastered)",
artwork: [
{
src: "https://dummyimage.com/96x96",
sizes: "96x96",
type: "image/png",
},
{
src: "https://dummyimage.com/128x128",
sizes: "128x128",
type: "image/png",
},
{
src: "https://dummyimage.com/192x192",
sizes: "192x192",
type: "image/png",
},
{
src: "https://dummyimage.com/256x256",
sizes: "256x256",
type: "image/png",
},
{
src: "https://dummyimage.com/384x384",
sizes: "384x384",
type: "image/png",
},
{
src: "https://dummyimage.com/512x512",
sizes: "512x512",
type: "image/png",
},
],
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediametadata | data/mdn-content/files/en-us/web/api/mediametadata/album/index.md | ---
title: "MediaMetadata: album property"
short-title: album
slug: Web/API/MediaMetadata/album
page-type: web-api-instance-property
browser-compat: api.MediaMetadata.album
---
{{APIRef("Media Session API")}}
The **`album`** property of the
{{domxref("MediaMetaData")}} interface returns or sets the name of the album or
collection containing the media to be played.
## Value
A {{jsxref("String")}} containing the name of the album.
## Examples
The following example checks for browser compatibility and sets the current metadata
for the media session.
```js
if ("mediaSession" in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: "Unforgettable",
artist: "Nat King Cole",
album: "The Ultimate Collection (Remastered)",
artwork: [
{
src: "https://dummyimage.com/96x96",
sizes: "96x96",
type: "image/png",
},
{
src: "https://dummyimage.com/128x128",
sizes: "128x128",
type: "image/png",
},
{
src: "https://dummyimage.com/192x192",
sizes: "192x192",
type: "image/png",
},
{
src: "https://dummyimage.com/256x256",
sizes: "256x256",
type: "image/png",
},
{
src: "https://dummyimage.com/384x384",
sizes: "384x384",
type: "image/png",
},
{
src: "https://dummyimage.com/512x512",
sizes: "512x512",
type: "image/png",
},
],
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediametadata | data/mdn-content/files/en-us/web/api/mediametadata/artwork/index.md | ---
title: "MediaMetadata: artwork property"
short-title: artwork
slug: Web/API/MediaMetadata/artwork
page-type: web-api-instance-property
browser-compat: api.MediaMetadata.artwork
---
{{APIRef("Media Session API")}}
The **`artwork`** property of the
{{domxref("MediaMetaData")}} interface returns or sets an array of
objects representing images associated with playing
media.
## Value
An {{jsxref("Array")}} of objects, each containing the following fields:
- `src`
- : The URL from which the user agent fetches the image's data.
- `sizes` {{optional_inline}}
- : Specifies the resource in multiple sizes so the user agent doesn't have to scale a single image. It defaults to the empty string (`""`).
- `type` {{optional_inline}}
- : The {{Glossary("MIME type")}} hint for the user agent that allows it to ignore images of types that it doesn't support. However, the user agent may still use MIME type sniffing after downloading the image to determine its type. It defaults to the empty string (`""`).
## Examples
The following example checks for browser compatibility and sets the current metadata
for the media session.
```js
if ("mediaSession" in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: "Unforgettable",
artist: "Nat King Cole",
album: "The Ultimate Collection (Remastered)",
artwork: [
{
src: "https://dummyimage.com/96x96",
sizes: "96x96",
type: "image/png",
},
{
src: "https://dummyimage.com/128x128",
sizes: "128x128",
type: "image/png",
},
{
src: "https://dummyimage.com/192x192",
sizes: "192x192",
type: "image/png",
},
{
src: "https://dummyimage.com/256x256",
sizes: "256x256",
type: "image/png",
},
{
src: "https://dummyimage.com/384x384",
sizes: "384x384",
type: "image/png",
},
{
src: "https://dummyimage.com/512x512",
sizes: "512x512",
type: "image/png",
},
],
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediakeys/index.md | ---
title: MediaKeys
slug: Web/API/MediaKeys
page-type: web-api-interface
browser-compat: api.MediaKeys
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The **`MediaKeys`** interface of [Encrypted Media Extensions API](/en-US/docs/Web/API/Encrypted_Media_Extensions_API) represents a set of keys that an associated {{domxref("HTMLMediaElement")}} can use for decryption of media data during playback.
## Instance properties
None.
## Instance methods
- {{domxref("MediaKeys.createSession()")}}
- : Returns a new {{domxref("MediaKeySession")}} object, which represents a context for message exchange with a content decryption module (CDM).
- {{domxref("MediaKeys.setServerCertificate()")}}
- : Returns a {{jsxref("Promise")}} to a server certificate to be used to encrypt messages to the license server.
## Examples
```js
//TBD
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeys | data/mdn-content/files/en-us/web/api/mediakeys/createsession/index.md | ---
title: "MediaKeys: createSession() method"
short-title: createSession()
slug: Web/API/MediaKeys/createSession
page-type: web-api-instance-method
browser-compat: api.MediaKeys.createSession
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The `MediaKeys.createSession()` method returns a new
{{domxref("MediaKeySession")}} object, which represents a context for message exchange
with a content decryption module (CDM).
## Syntax
```js-nolint
createSession()
createSession(mediaKeySessionType)
```
### Parameters
- `mediaKeySessionType` {{optional_inline}}
- : A string. Either "temporary" or "persistent-license". The default value is "temporary".
### Return value
A new {{domxref("MediaKeySession")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeys | data/mdn-content/files/en-us/web/api/mediakeys/setservercertificate/index.md | ---
title: "MediaKeys: setServerCertificate() method"
short-title: setServerCertificate()
slug: Web/API/MediaKeys/setServerCertificate
page-type: web-api-instance-method
browser-compat: api.MediaKeys.setServerCertificate
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The **`MediaKeys.setServerCertificate()`** method provides a
server certificate to be used to encrypt messages to the license server.
## Syntax
```js-nolint
setServerCertificate(serverCertificate)
```
### Parameters
- `serverCertificate`
- : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}} object containing the server certificate. The contents are Key System-specific. It MUST NOT contain executable code.
### Return value
A {{jsxref('Promise')}} that resolves to a boolean. If the Key System implementation represented by this object's content decryption module's implementation value does not support server certificates, return a promise resolved with false.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/index.md | ---
title: RTCIceCandidateStats
slug: Web/API/RTCIceCandidateStats
page-type: web-api-interface
browser-compat: api.RTCStatsReport.type_local-candidate
---
{{APIRef("WebRTC")}}
The **`RTCIceCandidateStats`** dictionary of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) is used to report statistics related to an {{domxref("RTCIceCandidate")}}.
The statistics can be obtained by iterating the {{domxref("RTCStatsReport")}} returned by {{domxref("RTCPeerConnection.getStats()")}} until you find a report with the [`type`](#type) of `local-candidate`.
## Instance properties
- {{domxref("RTCIceCandidateStats.address", "address")}} {{optional_inline}}
- : A string containing the address of the candidate. This value may be an IPv4 address, an IPv6 address, or a fully-qualified domain name. This property was previously named `ip` and only accepted IP addresses.
- {{domxref("RTCIceCandidateStats.candidateType", "candidateType")}}
- : A string matching one of the values in [`RTCIceCandidate.type`](/en-US/docs/Web/API/RTCIceCandidate/type#values), indicating what kind of candidate the object provides statistics for.
- {{domxref("RTCIceCandidateStats.deleted", "deleted")}} {{optional_inline}}
- : A Boolean value indicating whether or not the candidate has been released or deleted; the default value is `false`. For local candidates, its value is `true` if the candidate has been deleted or released. For host candidates, `true` means that any network resources (usually a network socket) associated with the candidate have already been released. For {{Glossary("TURN")}} candidates, the TURN allocation is no longer active for deleted candidates. This property is not present for remote candidates.
- {{domxref("RTCIceCandidateStats.port", "port")}} {{optional_inline}}
- : The network port number used by the candidate.
- {{domxref("RTCIceCandidateStats.priority", "priority")}} {{optional_inline}}
- : The candidate's priority, corresponding to {{domxref("RTCIceCandidate.priority")}}.
- {{domxref("RTCIceCandidateStats.protocol", "protocol")}} {{optional_inline}}
- : A string specifying the protocol (`tcp` or `udp`) used to transmit data on the `port`.
- {{domxref("RTCIceCandidateStats.relayProtocol", "relayProtocol")}} {{optional_inline}}
- : A string identifying the protocol used by the endpoint for communicating with the {{Glossary("TURN")}} server; valid values are `tcp`, `udp`, and `tls`.
Only present for local candidates.
- {{domxref("RTCIceCandidateStats.transportId", "transportId")}}
- : A string uniquely identifying the transport object that was inspected in order to obtain the {{domxref("RTCTransportStats")}} associated with the candidate corresponding to these statistics.
- {{domxref("RTCIceCandidateStats.url", "url")}} {{optional_inline}}
- : For local candidates, the `url` property is the {{Glossary("URL")}} of the {{Glossary("ICE")}} server from which the candidate was received.
This URL matches the one included in the {{domxref("RTCPeerConnectionIceEvent")}} object representing the {{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}} event that delivered the candidate to the local peer.
### Common instance properties
The following properties are common to all WebRTC statistics objects.
<!-- RTCStats -->
- {{domxref("RTCIceCandidateStats.id", "id")}}
- : A string that uniquely identifies the object that is being monitored to produce this set of statistics.
- {{domxref("RTCIceCandidateStats.timestamp", "timestamp")}}
- : A {{domxref("DOMHighResTimeStamp")}} object indicating the time at which the sample was taken for this statistics object.
- {{domxref("RTCIceCandidateStats.type", "type")}}
- : A string with the value `"local-candidate"`, indicating the type of statistics that the object contains.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/transportid/index.md | ---
title: "RTCIceCandidateStats: transportId property"
short-title: transportId
slug: Web/API/RTCIceCandidateStats/transportId
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_local-candidate.transportId
---
{{APIRef("WebRTC")}}
The {{domxref("RTCIceCandidateStats")}} dictionary's
**`transportId`** property is a string that uniquely
identifies the transport that produced the {{domxref("RTCTransportStats")}} from which
information about this candidate was taken.
## Value
A string whose value uniquely identifies the transport from which any
transport-related information accumulated in the {{domxref("RTCIceCandidateStats")}} was
taken. This can be used to compare candidates that would use the same transport, for
example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/relayprotocol/index.md | ---
title: "RTCIceCandidateStats: relayProtocol property"
short-title: relayProtocol
slug: Web/API/RTCIceCandidateStats/relayProtocol
page-type: web-api-instance-property
browser-compat: api.RTCIceCandidateStats.relayProtocol
---
{{APIRef("WebRTC")}}
The {{domxref("RTCIceCandidateStats")}} dictionary's
**`relayProtocol`** property specifies the protocol being used
by a local {{Glossary("ICE")}} candidate to communicate with the {{Glossary("TURN")}}
server.
The ICE protocol being used by the candidate otherwise can be obtained from the
{{domxref("RTCIceCandidateStats.protocol", "protocol")}} property.
## Value
A string identifying the protocol being used by the endpoint to
communicate with the TURN server. The possible values are:
- `tcp`
- : TCP (Transport Control Protocol) is being used to communicate with the TURN server.
- `tls`
- : TLS (Transport Layer Security) is being used to communicate with the TURN server.
- `udp`
- : UDP (User Datagram Protocol) is being used to communicate with the TURN server.
> **Note:** This property is only present on
> {{domxref("RTCIceCandidateStats")}} objects that represent local candidates.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/port/index.md | ---
title: "RTCIceCandidateStats: port property"
short-title: port
slug: Web/API/RTCIceCandidateStats/port
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_local-candidate.port
---
{{APIRef("WebRTC")}}
The {{domxref("RTCIceCandidateStats")}} dictionary's **`port`**
property specifies the network port used by the candidate.
## Value
An integer value indicating the network port used by the {{domxref("RTCIceCandidate")}}
described by the `RTCIceCandidateStats` object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/url/index.md | ---
title: "RTCIceCandidateStats: url property"
short-title: url
slug: Web/API/RTCIceCandidateStats/url
page-type: web-api-instance-property
browser-compat: api.RTCIceCandidateStats.url
---
{{APIRef("WebRTC")}}
The {{domxref("RTCIceCandidateStats")}} dictionary's
**`url`** property specifies the URL of the
{{Glossary("ICE")}} server from which the described candidate was obtained. This
property is _only_ available for local candidates.
## Value
A string specifying the URL of the ICE server from which the
candidate described by the `RTCIceCandidateStats` was obtained. This is the
same URL that would be received in the {{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}} event's
{{domxref("RTCPeerConnectionIceEvent.url", "url")}} property.
> **Note:** This property does not exist for remote candidates.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/address/index.md | ---
title: "RTCIceCandidateStats: address property"
short-title: address
slug: Web/API/RTCIceCandidateStats/address
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_local-candidate.address
---
{{APIRef("WebRTC")}}
The **`address`** property of the
{{domxref("RTCIceCandidateStats")}} dictionary indicates the address of the
{{Glossary("ICE")}} candidate. While it's preferred that the address be specified as
an IPv4 or IPv6 numeric address, a fully-qualified domain name can be used as
well.
When a domain name is specified, the first IP address selected for that
address is used, even if the domain name maps to multiple IP addresses.
## Value
Either an IPv4 or IPv6 address or a fully-qualified domain name, which corresponds to
the candidate.
- If the value of `address` is comprised entirely of digits from 0-9 with
periods as separators, the value is interpreted as an IPv4 address.
- If the value is entirely comprised of hexadecimal digits and colon (":")
characters, it is interpreted as an IPv6 address.
- Otherwise, the `address` is presumed to be a fully-qualified domain name,
which is resolved first using an AAAA record (assuming IPv6 is available), then using
an A record (if no result is found or the device only supports IPv4). If multiple IP
addresses are returned in response to the query, the {{Glossary("user agent")}}
selects one, which is then used for the duration of ICE processing.
## Usage notes
The `address` property was previously known as `ip`, and only
permitted IPv4 and IPv6 addresses to be used. The addition of support for
fully-qualified domain names to be used for the address brought about the renaming of
the property.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/id/index.md | ---
title: "RTCIceCandidateStats: id property"
short-title: id
slug: Web/API/RTCIceCandidateStats/id
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_local-candidate.id
---
{{APIRef("WebRTC")}}
The **`id`** property of the {{domxref("RTCIceCandidateStats")}} dictionary is a string that uniquely identifies the object for which this object provides statistics.
Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an {{domxref("RTCPeerConnection")}}, or an {{domxref("RTCDataChannel")}}.
## Value
A string that uniquely identifies the object for which this `RTCIceCandidateStats` object provides statistics.
The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/candidatetype/index.md | ---
title: "RTCIceCandidateStats: candidateType property"
short-title: candidateType
slug: Web/API/RTCIceCandidateStats/candidateType
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_local-candidate.candidateType
---
{{APIRef("WebRTC")}}
The {{domxref("RTCIceCandidateStats")}} interface's
**`candidateType`** property is a string that indicates the
type of {{Glossary("ICE")}} candidate the object represents.
## Syntax
```js-nolint
rtcIceCandidateStats.candidateType
```
### Value
A string whose value is one of the strings found in [`RTCIceCandidate.type`](/en-US/docs/Web/API/RTCIceCandidate/type#values).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/type/index.md | ---
title: "RTCIceCandidateStats: type property"
short-title: type
slug: Web/API/RTCIceCandidateStats/type
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_local-candidate.type
---
{{APIRef("WebRTC")}}
The **`type`** property of the {{domxref("RTCIceCandidateStats")}} dictionary is a string with the value `"local-candidate"`.
Different statistics are obtained by iterating the {{domxref("RTCStatsReport")}} object returned by a call to {{domxref("RTCPeerConnection.getStats()")}}.
The type indicates the set of statistics available through the object in a particular iteration step.
A value of `"local-candidate"` indicates that the statistics available in the current step are those defined in {{domxref("RTCIceCandidateStats")}}.
## Value
A string with the value `"local-candidate"`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/priority/index.md | ---
title: "RTCIceCandidateStats: priority property"
short-title: priority
slug: Web/API/RTCIceCandidateStats/priority
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_local-candidate.priority
---
{{APIRef("WebRTC")}}
The {{domxref("RTCIceCandidateStats")}} dictionary's
**`priority`** property is a positive integer value
indicating the priority (or desirability) of the described candidate.
During {{Glossary("ICE")}} negotiation while setting up a WebRTC peer connection, the
priority values reported to the remote peer by a {{Glossary("user agent")}} are used
to determine which candidates are considered "more desirable". The higher the value,
the more desirable the candidate is.
## Syntax
```js-nolint
priority = rtcIceCandidateStats.priority
```
### Value
A positive integer indicating the priority of the {{domxref("RTCIceCandidate")}}
described by the `RTCIceCandidateStats` object. The value may be anywhere
from 1 to 2,147,483,647.
## Determining priority
The ICE specification describes how user agents and other software using WebRTC should
calculate the priority. The priority of a candidate is calculated using the following
variables as inputs:
- The preferability of the candidate type (local, server reflexive, peer reflexive,
or relayed)
- The preferability of the candidate's specific IP address (for multihomed agents)
- The candidate's component ID (1 for RTP, 2 for RTCP)
The candidate's priority is computed using the formula (_p<sub>type</sub>_ is
the priority of the candidate's type and _p<sub>local</sub>_ is the priority of
the IP address):
<math display="block"><semantics><mrow><mi mathvariant="italic">priority</mi>
<mo>=</mo>
<msup><mn>2</mn>
<mn>24</mn>
</msup><mo>×</mo>
<msub><mi>p</mi>
<mrow><mi>type</mi>
</mrow></msub><mo>+</mo>
<msup><mn>2</mn>
<mn>8</mn>
</msup><mo>×</mo>
<msub><mi>p</mi>
<mrow><mi>local</mi>
</mrow></msub><mo>+</mo>
<mo stretchy="false">(</mo>
<mn>256</mn>
<mo>-</mo>
<mi mathvariant="italic">componentID</mi>
<mo stretchy="false">)</mo>
</mrow><annotation encoding="TeX">priority\quad =\quad { 2 }^{ 24 }\times { p }_{
type }\quad +\quad { 2 }^{ 8 }\times { p }_{ local }\quad +\quad (256\quad
-\quad componentID)</annotation></semantics></math>
This is equivalent to mapping the priorities of the candidate type, the local IP, and
the component ID into various bit ranges within the 32-bit `priority`
value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{RFC(5245, "", "4.1.2.1")}}: Recommended Formula section in the ICE specification
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/timestamp/index.md | ---
title: "RTCIceCandidateStats: timestamp property"
short-title: timestamp
slug: Web/API/RTCIceCandidateStats/timestamp
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_local-candidate.timestamp
---
{{APIRef("WebRTC")}}
The **`timestamp`** property of the {{domxref("RTCIceCandidateStats")}} dictionary is a {{domxref("DOMHighResTimeStamp")}} object specifying the time at which the data in the object was sampled.
## Value
A {{domxref("DOMHighResTimeStamp")}} value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC.
The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of [fingerprinting](/en-US/docs/Glossary/Fingerprinting) protection in the form of reduced clock precision or accuracy.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/protocol/index.md | ---
title: "RTCIceCandidateStats: protocol property"
short-title: protocol
slug: Web/API/RTCIceCandidateStats/protocol
page-type: web-api-instance-property
browser-compat: api.RTCIceCandidateStats.protocol
---
{{APIRef("WebRTC")}}
The {{domxref("RTCIceCandidateStats")}} dictionary's
**`protocol`** property specifies the protocol the specified
candidate would use for communication with the remote peer.
## Value
The value is one of the following string:
- `tcp`
- : The candidate, if selected, would use {{Glossary("TCP")}} as the transport protocol for its data. The {{domxref("RTCIceCandidate.tcpType", "tcpType")}} property provides additional information about the kind of TCP candidate represented by the object.
- `udp`
- : The candidate will use the {{Glossary("UDP")}} transport protocol for its data. This is the preferred protocol for media interactions because of its better performance profile.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcicecandidatestats | data/mdn-content/files/en-us/web/api/rtcicecandidatestats/deleted/index.md | ---
title: "RTCIceCandidateStats: deleted property"
short-title: deleted
slug: Web/API/RTCIceCandidateStats/deleted
page-type: web-api-instance-property
browser-compat: api.RTCIceCandidateStats.deleted
---
{{APIRef("WebRTC")}}
The {{domxref("RTCIceCandidateStats")}} dictionary's
**`deleted`** property indicates whether or not the candidate
has been deleted or released.
## Value
A Boolean value indicating whether or not the candidate has been deleted or released.
If this value is `true`, the candidate described by the
{{domxref("RTCIceCandidateStats")}} object is no longer under consideration. The exact
meaning varies depending on the type of candidate:
- `Local candidate`
- : A value of `true` means the candidate has been deleted as described by
{{RFC(5245, "", "8.3")}}.
- `Host candidate`
- : A value of `true` indicates that the candidate's network resources have
been released. This generally mean that any associated socket(s) have been closed and
released.
- `Remote (TURN) candidate`
- : A value of `true` means the candidate's {{Glossary("TURN")}} allocation
is no longer active.
The net result is the same; the candidate is no longer under consideration if this
value is `true`.
## Examples
In this example, {{domxref("setInterval()")}}
is used to set up a function that runs periodically to display the latest statistics for
candidates. Only candidates which have not been deleted are included in the output.
```js
setInterval(() => {
myPeerConnection.getStats(null).then((stats) => {
let statsOutput = "";
stats.forEach((report) => {
if (
(stats.type === "local-candidate" ||
stats.type === "remote.candidate") &&
!stats.deleted
) {
statsOutput +=
`<h2>Report: ${report.type}</h3>\n<strong>ID:</strong> ${report.id}<br>\n` +
`<strong>Timestamp:</strong> ${report.timestamp}<br>\n`;
// Now the statistics for this report; we intentionally drop the ones we
// sorted to the top above
Object.keys(report).forEach((statName) => {
if (
statName !== "id" &&
statName !== "timestamp" &&
statName !== "type"
) {
statsOutput += `<strong>${statName}:</strong> ${report[statName]}<br>\n`;
}
});
}
});
document.querySelector(".stats-box").innerHTML = statsOutput;
});
}, 1000);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats/index.md | ---
title: RTCPeerConnectionStats
slug: Web/API/RTCPeerConnectionStats
page-type: web-api-interface
browser-compat: api.RTCStatsReport.type_peer-connection
---
{{APIRef("WebRTC")}}
The **`RTCPeerConnectionStats`** dictionary of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) provides information about the high level peer connection ({{domxref("RTCPeerConnection")}}).
In particular, it provides the number of unique data channels that have been opened, and the number of opened channels that have been closed.
This allows the current number of open channels to be calculated.
These statistics can be obtained by iterating the {{domxref("RTCStatsReport")}} returned by {{domxref("RTCPeerConnection.getStats()")}} until you find a report with the [`type`](#type) of `peer-connection`.
## Instance properties
- {{domxref("RTCPeerConnectionStats.dataChannelsOpened", "dataChannelsOpened")}}
- : A positive integer value indicating the number of unique {{domxref("RTCDataChannel")}} objects that have entered the [`open`](/en-US/docs/Web/API/RTCDataChannel/readyState#open) state during their lifetime.
- {{domxref("RTCPeerConnectionStats.dataChannelsClosed", "dataChannelsClosed")}}
- : A positive integer value indicating the number of unique {{domxref("RTCDataChannel")}} objects that have left the [`open`](/en-US/docs/Web/API/RTCDataChannel/readyState#open) state during their lifetime (channels that transition to [`closing`](/en-US/docs/Web/API/RTCDataChannel/readyState#closing) or [`closed`](/en-US/docs/Web/API/RTCDataChannel/readyState#closed) without ever being `open` are not counted in this number).
A channel will leave the `open` state if either end of the connection or the underlying transport is closed.
### Common instance properties
The following properties are common to all WebRTC statistics objects.
<!-- RTCStats -->
- {{domxref("RTCPeerConnectionStats.id", "id")}}
- : A string that uniquely identifies the object that is being monitored to produce this set of statistics.
- {{domxref("RTCPeerConnectionStats.timestamp", "timestamp")}}
- : A {{domxref("DOMHighResTimeStamp")}} object indicating the time at which the sample was taken for this statistics object.
- {{domxref("RTCPeerConnectionStats.type", "type")}}
- : A string with the value `"peer-connection"`, indicating the type of statistics that the object contains.
## Examples
This example shows a function to return the total number of open connections, or `null` if no statistics are provided.
This might be called in a loop, similar to the approach used in [`RTCPeerConnection.getStats()` example](/en-US/docs/Web/API/RTCPeerConnection/getStats#examples)
The function waits for the result of a call to {{domxref("RTCPeerConnection.getStats()")}} and then iterates the returned {{domxref("RTCStatsReport")}} to get just the stats of type `"peer-connection"`.
It then returns the total number of open channels, or `null`, using the data in the report.
```js
async function numberOpenConnections (peerConnection) {
const stats = await peerConnection.getStats();
let peerConnectionStats = null;
stats.forEach((report) => {
if (report.type === "peer-connection") {
peerConnectionStats = report;
break;
}
});
result = (typeof peerConnectionStats.dataChannelsOpened === 'undefined' || typeof peerConnectionStats.dataChannelsClosed=== 'undefined') ? null : peerConnectionStats.dataChannelsOpened - peerConnectionStats.dataChannelsClosed;
return result
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats | data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats/datachannelsopened/index.md | ---
title: "RTCPeerConnectionStats: dataChannelsOpened property"
short-title: dataChannelsOpened
slug: Web/API/RTCPeerConnectionStats/dataChannelsOpened
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_peer-connection.dataChannelsOpened
---
{{APIRef("WebRTC")}}
The **`dataChannelsOpened`** property of the {{domxref("RTCPeerConnectionStats")}} dictionary indicates the number of unique {{domxref("RTCDataChannel")}} objects that have entered the [`open`](/en-US/docs/Web/API/RTCDataChannel/readyState#open) state during their lifetime.
## Value
A positive integer that indicates the number of unique {{domxref("RTCDataChannel")}} objects that have entered the [`open`](/en-US/docs/Web/API/RTCDataChannel/readyState#open) state during their lifetime.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats | data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats/datachannelsclosed/index.md | ---
title: "RTCPeerConnectionStats: dataChannelsClosed property"
short-title: dataChannelsClosed
slug: Web/API/RTCPeerConnectionStats/dataChannelsClosed
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_peer-connection.dataChannelsClosed
---
{{APIRef("WebRTC")}}
The **`dataChannelsClosed`** property of the {{domxref("RTCPeerConnectionStats")}} dictionary indicates the number of unique {{domxref("RTCDataChannel")}} objects that have left the [`open`](/en-US/docs/Web/API/RTCDataChannel/readyState#open) state during their lifetime.
A channel will leave the `open` state if either end of the connection or the underlying transport is closed.
Note that channels that transition to [`closing`](/en-US/docs/Web/API/RTCDataChannel/readyState#closing) or [`closed`](/en-US/docs/Web/API/RTCDataChannel/readyState#closed) without ever being `open` are not counted in this number.
## Value
A positive integer that indicates the number of unique {{domxref("RTCDataChannel")}} objects that have left the [`open`](/en-US/docs/Web/API/RTCDataChannel/readyState#open) state during their lifetime.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats | data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats/id/index.md | ---
title: "RTCPeerConnectionStats: id property"
short-title: id
slug: Web/API/RTCPeerConnectionStats/id
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_peer-connection.id
---
{{APIRef("WebRTC")}}
The **`id`** property of the {{domxref("RTCPeerConnectionStats")}} dictionary is a string which uniquely identifies the object for which this object provides statistics.
Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an {{domxref("RTCPeerConnection")}}, or an {{domxref("RTCDataChannel")}}.
## Value
A string that uniquely identifies the object for which this `RTCPeerConnectionStats` object provides statistics.
The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats | data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats/type/index.md | ---
title: "RTCPeerConnectionStats: type property"
short-title: type
slug: Web/API/RTCPeerConnectionStats/type
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_peer-connection.type
---
{{APIRef("WebRTC")}}
The **`type`** property of the {{domxref("RTCPeerConnectionStats")}} dictionary is a string with the value `"peer-connection"`.
Different statistics are obtained by iterating the {{domxref("RTCStatsReport")}} object returned by a call to {{domxref("RTCPeerConnection.getStats()")}}.
The type indicates the set of statistics available through the object in a particular iteration step.
A value of `"peer-connection"` indicates that the statistics available in the current step are those defined in {{domxref("RTCPeerConnectionStats")}}.
## Value
A string with the value `"peer-connection"`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats | data/mdn-content/files/en-us/web/api/rtcpeerconnectionstats/timestamp/index.md | ---
title: "RTCPeerConnectionStats: timestamp property"
short-title: timestamp
slug: Web/API/RTCPeerConnectionStats/timestamp
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_peer-connection.timestamp
---
{{APIRef("WebRTC")}}
The **`timestamp`** property of the {{domxref("RTCPeerConnectionStats")}} dictionary is a {{domxref("DOMHighResTimeStamp")}} object specifying the time at which the data in the object was sampled.
## Value
A {{domxref("DOMHighResTimeStamp")}} value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC.
The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of [fingerprinting](/en-US/docs/Glossary/Fingerprinting) protection in the form of reduced clock precision or accuracy.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/animationeffect/index.md | ---
title: AnimationEffect
slug: Web/API/AnimationEffect
page-type: web-api-interface
browser-compat: api.AnimationEffect
---
{{ APIRef("Web Animations") }}
The `AnimationEffect` interface of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) is an interface representing animation effects.
`AnimationEffect` is an abstract interface and so isn't directly instantiable. However, concrete interfaces such as {{domxref("KeyframeEffect")}} inherit from it, and instances of these interfaces can be passed to {{domxref("Animation")}} objects for playing, and may also be used by [CSS Animations](/en-US/docs/Web/CSS/CSS_animations) and [Transitions](/en-US/docs/Web/CSS/CSS_transitions).
## Instance methods
- {{domxref("AnimationEffect.getTiming()")}}
- : Returns the object associated with the animation containing all the animation's timing values.
- {{domxref("AnimationEffect.getComputedTiming()")}}
- : Returns the calculated timing properties for this `AnimationEffect`.
- {{domxref("AnimationEffect.updateTiming()")}}
- : Updates the specified timing properties of this `AnimationEffect`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- {{domxref("Animation.effect")}}
| 0 |
data/mdn-content/files/en-us/web/api/animationeffect | data/mdn-content/files/en-us/web/api/animationeffect/gettiming/index.md | ---
title: "AnimationEffect: getTiming() method"
short-title: getTiming()
slug: Web/API/AnimationEffect/getTiming
page-type: web-api-instance-method
browser-compat: api.AnimationEffect.getTiming
---
{{ APIRef("Web Animations") }}
The `AnimationEffect.getTiming()` method of the {{domxref("AnimationEffect")}} interface returns an object containing the timing properties for the Animation Effect.
> **Note:** Several of the timing properties returned by `getTiming()` may take on the placeholder value `"auto"`. To obtain resolved values for use in timing computations, instead use {{domxref("AnimationEffect.getComputedTiming()")}}.
>
> In the future, `"auto"` or similar values might be added to the types of more timing properties, and new types of {{domxref("AnimationEffect")}} might resolve `"auto"` to different values.
## Syntax
```js-nolint
getTiming()
```
### Parameters
None.
### Return value
An object containing the following properties:
- `delay`
- : The `number` of milliseconds of delay before the start of the effect.
(See also {{cssxref("animation-delay")}}.)
- `direction`
- : `"normal"`, `"reverse"`, `"alternate"`, or `"alternate-reverse"`.
Indicates whether the effect runs forwards (`"normal"`), backwards (`"reverse"`), switches direction
after each iteration (`"alternate"`), or runs backwards and switches direction after each iteration
(`"alternate-reverse"`).
(See also {{cssxref("animation-direction")}}.)
- `duration`
- : A `number` of milliseconds or the `string` `"auto"`.
Indicates the time one iteration of the animation takes to complete.
The meaning of `"auto"` may differ depending on the type of effect; for {{domxref("KeyframeEffect")}}, `"auto"` is the same as `0`.
(See also {{cssxref("animation-duration")}}.)
- `easing`
- : A `string` representing an {{cssxref("easing-function")}} describing the rate of change of the effect over time.
(See also {{cssxref("animation-timing-function")}}.)
- `endDelay`
- : The `number` of milliseconds of delay after the end of the effect.
This is primarily of use when sequencing animations based on the end time of another animation.
- `fill`
- : `"none"`, `"forwards"`, `"backwards"`, "`both`", or `"auto"`.
Indicates whether the effect is reflected by its target(s) prior to playing
(`"backwards"`), retained after the effect has completed (`"forwards"`), `"both"`, or
neither (`"none"`).
The meaning of `"auto"` may differ depending on the type of effect; for
{{domxref("KeyframeEffect")}}, `"auto"` is the same as `"none"`.
(See also {{cssxref("animation-fill-mode")}}.)
- `iterations`
- : The `number` of times the effect will repeat. A value of {{jsxref("Infinity")}} indicates that
the effect repeats indefinitely.
(See also {{cssxref("animation-iteration-count")}}.)
- `iterationStart`
- : A `number` indicating at what point in the iteration the effect starts. For example, an effect with
an `iterationStart` of 0.5 and 2 `iterations` would start halfway through its first iteration
and end halfway through a third iteration.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- {{domxref("AnimationEffect")}}
| 0 |
data/mdn-content/files/en-us/web/api/animationeffect | data/mdn-content/files/en-us/web/api/animationeffect/updatetiming/index.md | ---
title: "AnimationEffect: updateTiming() method"
short-title: updateTiming()
slug: Web/API/AnimationEffect/updateTiming
page-type: web-api-instance-method
browser-compat: api.AnimationEffect.updateTiming
---
{{ APIRef("Web Animations") }}
The `updateTiming()` method of the {{domxref("AnimationEffect")}} interface updates the specified timing properties for an animation effect.
## Syntax
```js-nolint
updateTiming(timing)
```
### Parameters
- `timing` {{optional_inline}}
- : An object containing zero or more of the properties from the return value of {{domxref("AnimationEffect.getTiming()")}}, representing the timing properties to update.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if invalid values are provided for any of the timing properties.
### Examples
#### Side effects
`updateTiming()` may cause any associated {{domxref("Animation")}} to start or stop playing, if for example the effect of a running animation is shortened such that its end time is before {{domxref("Animation.currentTime")}} or the effect of a finished animation is lengthened such that its end time is after {{domxref("Animation.currentTime")}}.
```js
const animation = document.body.animate([], { duration: 1000 });
animation.finish();
console.log(animation.playState); // finished
animation.effect.updateTiming({ duration: 2000 });
console.log(animation.playState); // running
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- {{domxref("AnimationEffect")}}
- {{domxref("Animation")}}
- {{domxref("AnimationEffect.getTiming()")}}
- {{domxref("AnimationEffect.getComputedTiming()")}}
| 0 |
data/mdn-content/files/en-us/web/api/animationeffect | data/mdn-content/files/en-us/web/api/animationeffect/getcomputedtiming/index.md | ---
title: "AnimationEffect: getComputedTiming() method"
short-title: getComputedTiming()
slug: Web/API/AnimationEffect/getComputedTiming
page-type: web-api-instance-method
browser-compat: api.AnimationEffect.getComputedTiming
---
{{ APIRef("Web Animations") }}
The `getComputedTiming()` method of the {{domxref("AnimationEffect")}} interface returns the calculated timing properties for this animation effect.
> **Note:** These values are comparable to the computed styles of an Element returned using `window.getComputedStyle(elem)`.
## Syntax
```js-nolint
getComputedTiming()
```
### Parameters
None.
### Return value
An object which contains:
- all of the properties of the object returned by {{domxref("AnimationEffect.getTiming()")}}, except that any `"auto"` values are replaced by computed values that may depend on the type of {{domxref("AnimationEffect")}}.
- the following additional properties:
- `endTime`
- : A `number` indicating the end time of the effect in milliseconds from the effect's start. This is equal to `activeDuration` plus `delay` and `endDelay`.
- `activeDuration`
- : A `number` indicating the total duration in milliseconds of all iterations of the effect. This is equal to `duration` multiplied by `iterations` (or zero if that product would be {{jsxref("NaN")}}).
- `localTime`
- : A `number` or `null`.
Indicates the length of time in milliseconds that the effect has run. This is equal to the {{domxref("Animation.currentTime","currentTime")}} of the associated animation, or `null` if the effect is not associated with an animation.
- `progress`
- : `null` or a `number` at least `0` and less than `1`.
Indicates the effect's progress through its current iteration. At the start of the `activeDuration`, this equals the fractional part of `iterationStart`.
Returns `null` if the effect isn't mid-iteration, for example because the effect is in the `delay` or `endDelay` periods, the effect is finished, or `localTime` is `null`.
- `currentIteration`
- : `null` or an integer `number`.
Indicates the index of the current iteration. At the start of the `activeDuration`, this equals the integer part of `iterationStart`.
Returns `null` whenever `progress` is `null`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- {{domxref("AnimationEffect")}}
- {{domxref("Animation")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/filesystemfilehandle/index.md | ---
title: FileSystemFileHandle
slug: Web/API/FileSystemFileHandle
page-type: web-api-interface
browser-compat: api.FileSystemFileHandle
---
{{securecontext_header}}{{APIRef("File System API")}}
The **`FileSystemFileHandle`** interface of the {{domxref("File System API", "File System API", "", "nocode")}} represents a handle to a file system entry. The interface is accessed through the {{domxref('window.showOpenFilePicker()')}} method.
Note that read and write operations depend on file-access permissions that do not persist after a page refresh if no other tabs for that origin remain open. The {{domxref("FileSystemHandle.queryPermission()", "queryPermission")}} method of the {{domxref("FileSystemHandle")}} interface can be used to verify permission state before accessing a file.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{DOMxRef("FileSystemHandle")}}._
## Instance methods
_Inherits methods from its parent, {{DOMxRef("FileSystemHandle")}}._
- {{domxref('FileSystemFileHandle.getFile', 'getFile()')}}
- : Returns a {{jsxref('Promise')}} which resolves to a {{domxref('File')}} object
representing the state on disk of the entry represented by the handle.
- {{domxref('FileSystemFileHandle.createSyncAccessHandle', 'createSyncAccessHandle()')}}
- : Returns a {{jsxref('Promise')}} which resolves to a {{domxref('FileSystemSyncAccessHandle')}} object
that can be used to synchronously read from and write to a file. The synchronous nature of this method brings performance advantages,
but it is only usable inside dedicated [Web Workers](/en-US/docs/Web/API/Web_Workers_API).
- {{domxref('FileSystemFileHandle.createWritable', 'createWritable()')}}
- : Returns a {{jsxref('Promise')}} which resolves to a newly created {{domxref('FileSystemWritableFileStream')}}
object that can be used to write to a file.
## Examples
### Reading a File
The following asynchronous function presents a file picker and once a file is chosen, uses the `getFile()` method to retrieve the contents.
```js
async function getTheFile() {
const pickerOpts = {
types: [
{
description: "Images",
accept: {
"image/*": [".png", ".gif", ".jpeg", ".jpg"],
},
},
],
excludeAcceptAllOption: true,
multiple: false,
};
// open file picker
const [fileHandle] = await window.showOpenFilePicker(pickerOpts);
// get file contents
const fileData = await fileHandle.getFile();
return fileData;
}
```
### Writing a File
The following asynchronous function writes the given contents to the file handle, and thus to disk.
```js
async function writeFile(fileHandle, contents) {
// Create a FileSystemWritableFileStream to write to.
const writable = await fileHandle.createWritable();
// Write the contents of the file to the stream.
await writable.write(contents);
// Close the file and write the contents to disk.
await writable.close();
}
```
### Synchronously reading and writing a file
The following asynchronous event handler function is contained inside a Web Worker. On receiving a message from the main thread it:
- Creates a synchronous file access handle.
- Gets the size of the file and creates an {{jsxref("ArrayBuffer")}} to contain it.
- Reads the file contents into the buffer.
- Encodes the message and writes it to the end of the file.
- Persists the changes to disk and closes the access handle.
```js
onmessage = async (e) => {
// Retrieve message sent to work from main script
const message = e.data;
// Get handle to draft file
const root = await navigator.storage.getDirectory();
const draftHandle = await root.getFileHandle("draft.txt", { create: true });
// Get sync access handle
const accessHandle = await draftHandle.createSyncAccessHandle();
// Get size of the file.
const fileSize = accessHandle.getSize();
// Read file content to a buffer.
const buffer = new DataView(new ArrayBuffer(fileSize));
const readBuffer = accessHandle.read(buffer, { at: 0 });
// Write the message to the end of the file.
const encoder = new TextEncoder();
const encodedMessage = encoder.encode(message);
const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });
// Persist changes to disk.
accessHandle.flush();
// Always close FileSystemSyncAccessHandle if done.
accessHandle.close();
};
```
> **Note:** In earlier versions of the spec, {{domxref("FileSystemSyncAccessHandle.close()", "close()")}}, {{domxref("FileSystemSyncAccessHandle.flush()", "flush()")}}, {{domxref("FileSystemSyncAccessHandle.getSize()", "getSize()")}}, and {{domxref("FileSystemSyncAccessHandle.truncate()", "truncate()")}} were wrongly specified as asynchronous methods, and older versions of some browsers implement them in this way. However, all current browsers that support these methods implement them as synchronous methods.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File System API](/en-US/docs/Web/API/File_System_API)
- [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
| 0 |
data/mdn-content/files/en-us/web/api/filesystemfilehandle | data/mdn-content/files/en-us/web/api/filesystemfilehandle/createwritable/index.md | ---
title: "FileSystemFileHandle: createWritable() method"
short-title: createWritable()
slug: Web/API/FileSystemFileHandle/createWritable
page-type: web-api-instance-method
browser-compat: api.FileSystemFileHandle.createWritable
---
{{securecontext_header}}{{APIRef("File System API")}}
The **`createWritable()`** method of the {{domxref("FileSystemFileHandle")}} interface creates a {{domxref('FileSystemWritableFileStream')}} that can be used to write to a file.
The method returns a {{jsxref('Promise')}} which resolves to this created stream.
Any changes made through the stream won't be reflected in the file represented by the file handle until the stream has been closed.
This is typically implemented by writing data to a temporary file, and only replacing the file represented by file handle with the temporary file when the writable filestream is closed.
## Syntax
```js-nolint
createWritable()
createWritable(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object with the following properties:
- `keepExistingData` {{optional_inline}}
- : A {{jsxref('Boolean')}}. Default `false`.
When set to `true` if the file exists, the existing file is first copied to the temporary file.
Otherwise the temporary file starts out empty.
### Return value
A {{jsxref('Promise')}} which resolves to a {{domxref('FileSystemWritableFileStream')}} object.
### Exceptions
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if the {{domxref('PermissionStatus.state')}} for the handle is not `'granted'` in `readwrite` mode.
- `NotFoundError` {{domxref("DOMException")}}
- : Thrown if current entry is not found.
- `NoModificationAllowedError` {{domxref("DOMException")}}
- : Thrown if the browser is not able to acquire a lock on the file associated with the file handle.
- `AbortError` {{domxref("DOMException")}}
- : Thrown if implementation-defined malware scans and safe-browsing checks fails.
## Examples
The following asynchronous function writes the given contents to the file handle, and thus to disk.
```js
async function writeFile(fileHandle, contents) {
// Create a FileSystemWritableFileStream to write to.
const writable = await fileHandle.createWritable();
// Write the contents of the file to the stream.
await writable.write(contents);
// Close the file and write the contents to disk.
await writable.close();
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File System API](/en-US/docs/Web/API/File_System_API)
- [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
| 0 |
data/mdn-content/files/en-us/web/api/filesystemfilehandle | data/mdn-content/files/en-us/web/api/filesystemfilehandle/getfile/index.md | ---
title: "FileSystemFileHandle: getFile() method"
short-title: getFile()
slug: Web/API/FileSystemFileHandle/getFile
page-type: web-api-instance-method
browser-compat: api.FileSystemFileHandle.getFile
---
{{securecontext_header}}{{APIRef("File System API")}}
The **`getFile()`** method of the
{{domxref("FileSystemFileHandle")}} interface returns a {{jsxref('Promise')}} which resolves to a
{{domxref('File')}} object representing the state on disk of the entry represented by the handle.
If the file on disk changes or is removed after this method is called, the returned
{{domxref('File')}} object will likely be no longer readable.
## Syntax
```js-nolint
getFile()
```
### Parameters
None.
### Return value
A {{jsxref('Promise')}} which resolves to a {{domxref('File')}} object.
### Exceptions
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if the {{domxref('PermissionStatus.state')}} is not `granted` in `read` mode.
- `NotFoundError` {{domxref("DOMException")}}
- : Thrown if current entry is not found.
## Examples
The following asynchronous function presents a file picker and once a file is chosen,
uses the `getFile()` method to retrieve the contents.
```js
async function getTheFile() {
// open file picker
[fileHandle] = await window.showOpenFilePicker(pickerOpts);
// get file contents
const fileData = await fileHandle.getFile();
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File System API](/en-US/docs/Web/API/File_System_API)
- [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
| 0 |
data/mdn-content/files/en-us/web/api/filesystemfilehandle | data/mdn-content/files/en-us/web/api/filesystemfilehandle/createsyncaccesshandle/index.md | ---
title: "FileSystemFileHandle: createSyncAccessHandle() method"
short-title: createSyncAccessHandle()
slug: Web/API/FileSystemFileHandle/createSyncAccessHandle
page-type: web-api-instance-method
browser-compat: api.FileSystemFileHandle.createSyncAccessHandle
---
{{securecontext_header}}{{APIRef("File System API")}}
The **`createSyncAccessHandle()`** method of the
{{domxref("FileSystemFileHandle")}} interface returns a {{jsxref('Promise')}} which resolves to a {{domxref('FileSystemSyncAccessHandle')}} object
that can be used to synchronously read from and write to a file. The synchronous nature of this method brings performance advantages,
but it is only usable inside dedicated [Web Workers](/en-US/docs/Web/API/Web_Workers_API) for files within the [origin private file system](/en-US/docs/Web/API/File_System_API/Origin_private_file_system).
Creating a {{domxref('FileSystemSyncAccessHandle')}} takes an exclusive lock on the file associated with the file handle. This prevents the creation of further {{domxref('FileSystemSyncAccessHandle')}}s or {{domxref('FileSystemWritableFileStream')}}s for the file until the existing access handle is closed.
## Syntax
```js-nolint
createSyncAccessHandle()
```
### Parameters
None.
### Return value
A {{jsxref('Promise')}} which resolves to a {{domxref('FileSystemSyncAccessHandle')}} object.
### Exceptions
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if the {{domxref('PermissionStatus.state')}} for the handle is not `granted` in `readwrite` mode.
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the {{domxref('FileSystemSyncAccessHandle')}} object does not represent a file in the [origin private file system](/en-US/docs/Web/API/File_System_API/Origin_private_file_system).
- `NotFoundError` {{domxref("DOMException")}}
- : Thrown if current entry is not found.
- `NoModificationAllowedError` {{domxref("DOMException")}}
- : Thrown if the browser is not able to acquire a lock on the file associated with the file handle.
## Examples
The following asynchronous event handler function is contained inside a Web Worker. The snippet inside it creates a synchronous file access handle.
```js
onmessage = async (e) => {
// Retrieve message sent to work from main script
const message = e.data;
// Get handle to draft file
const root = await navigator.storage.getDirectory();
const draftHandle = await root.getFileHandle("draft.txt", { create: true });
// Get sync access handle
const accessHandle = await draftHandle.createSyncAccessHandle();
// …
// Always close FileSystemSyncAccessHandle if done.
accessHandle.close();
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File System API](/en-US/docs/Web/API/File_System_API)
- [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/insertable_streams_for_mediastreamtrack_api/index.md | ---
title: Insertable Streams for MediaStreamTrack API
slug: Web/API/Insertable_Streams_for_MediaStreamTrack_API
page-type: web-api-overview
---
{{DefaultAPISidebar("Insertable Streams for MediaStreamTrack API")}}
The **Insertable Streams for MediaStreamTrack API** provides a method of adding new components to a {{domxref("MediaStreamTrack")}}.
## Concepts and Usage
When processing video or audio, you sometimes want to insert additional elements or otherwise process the stream. For example, an application might include two tracks that need to be combined, such as a weather map and video of a presenter explaining the map. Or, you may want to do processing on a track to blur backgrounds, remove background noise, or introduce other elements (such as adding funny hats to people, and so on). This API provides a method to do this by giving direct access to the stream, thus allowing it to be manipulated.
## Interfaces
- {{domxref("MediaStreamTrackGenerator")}}
- : Creates a {{domxref("WritableStream")}} that acts as a {{domxref("MediaStreamTrack")}} source.
- {{domxref("MediaStreamTrackProcessor")}}
- : Consumes a {{domxref("MediaStreamTrack")}} object's source and generates a stream of media frames.
## Examples
The following example is from the article [Insertable streams for MediaStreamTrack](https://developer.chrome.com/docs/capabilities/web-apis/mediastreamtrack-insertable-media-processing), and demonstrates a barcode scanner application that highlights a barcode in a video stream. This transforms the stream accessed via {{domxref("MediaStreamTrackProcessor.readable")}}.
```js
const stream = await getUserMedia({ video: true });
const videoTrack = stream.getVideoTracks()[0];
const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });
const transformer = new TransformStream({
async transform(videoFrame, controller) {
const barcodes = await detectBarcodes(videoFrame);
const newFrame = highlightBarcodes(videoFrame, barcodes);
videoFrame.close();
controller.enqueue(newFrame);
},
});
trackProcessor.readable
.pipeThrough(transformer)
.pipeTo(trackGenerator.writable);
```
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/launchqueue/index.md | ---
title: LaunchQueue
slug: Web/API/LaunchQueue
page-type: web-api-interface
status:
- experimental
browser-compat: api.LaunchQueue
---
{{APIRef("Launch Handler API")}}{{SeeCompatTable}}
The **`LaunchQueue`** interface of the {{domxref("Launch Handler API", "Launch Handler API", "", "nocode")}} is available via the {{domxref("Window.launchQueue")}} property. When a [progressive web app](/en-US/docs/Web/Progressive_web_apps) (PWA) is launched with a [`launch_handler`](/en-US/docs/Web/Manifest/launch_handler) `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`, {{domxref("LaunchQueue")}} provides access to functionality that allows custom launch navigation handling to be implemented in the PWA. This functionality is controlled by the properties of the {{domxref("LaunchParams")}} object passed into the {{domxref("LaunchQueue.setConsumer", "setConsumer()")}} callback function.
{{InheritanceDiagram}}
## Instance Methods
- {{domxref("LaunchQueue.setConsumer", "setConsumer()")}} {{Experimental_Inline}}
- : Contains a callback function that handles custom launch navigation for a PWA.
## Examples
```js
if ("launchQueue" in window) {
window.launchQueue.setConsumer((launchParams) => {
if (launchParams.targetURL) {
const params = new URL(launchParams.targetURL).searchParams;
// Assuming a music player app that gets a track passed to it to be played
const track = params.get("track");
if (track) {
audio.src = track;
title.textContent = new URL(track).pathname.substr(1);
audio.play();
}
}
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Launch Handler API: Control how your app is launched](https://developer.chrome.com/docs/web-platform/launch-handler/)
- {{domxref("Window.launchQueue")}}
- [Musicr 2.0](https://launch-handler.glitch.me/) demo app
| 0 |
data/mdn-content/files/en-us/web/api/launchqueue | data/mdn-content/files/en-us/web/api/launchqueue/setconsumer/index.md | ---
title: "LaunchQueue: setConsumer() method"
short-title: setConsumer()
slug: Web/API/LaunchQueue/setConsumer
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.LaunchQueue.setConsumer
---
{{APIRef("Launch Handler API")}}{{SeeCompatTable}}
The **`setConsumer()`** method of the {{domxref("LaunchQueue")}} interface is used to declare the callback that will handle custom launch navigation handling in a [progressive web app](/en-US/docs/Web/Progressive_web_apps) (PWA). Such custom navigation is initiated via {{domxref("Window.launchQueue")}} when a PWA has been launched with a [`launch_handler`](/en-US/docs/Web/Manifest/launch_handler) `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`.
## Syntax
```js-nolint
setConsumer(callback)
```
### Parameters
- `callback`
- : A callback function that handles custom navigation for the PWA. The callback is passed a {{domxref("LaunchParams")}} object instance as a parameter.
### Return value
`undefined`.
## Examples
```js
if ("launchQueue" in window) {
window.launchQueue.setConsumer((launchParams) => {
if (launchParams.targetURL) {
const params = new URL(launchParams.targetURL).searchParams;
// Assuming a music player app that gets a track passed to it to be played
const track = params.get("track");
if (track) {
audio.src = track;
title.textContent = new URL(track).pathname.substr(1);
audio.play();
}
}
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Launch Handler API: Control how your app is launched](https://developer.chrome.com/docs/web-platform/launch-handler/)
- {{domxref("Window.launchQueue")}}
- [Musicr 2.0](https://launch-handler.glitch.me/) demo app
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpubindgroup/index.md | ---
title: GPUBindGroup
slug: Web/API/GPUBindGroup
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPUBindGroup
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUBindGroup`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} is based on a {{domxref("GPUBindGroupLayout")}} and defines a set of resources to be bound together in a group and how those resources are used in shader stages.
A `GPUBindGroup` object instance is created using the {{domxref("GPUDevice.createBindGroup()")}} method.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("GPUBindGroup.label", "label")}} {{Experimental_Inline}}
- : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings.
## Examples
> **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples.
### Basic example
Our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/) shows an example of creating a bind group layout and then using that as a template when creating a bind group.
```js
// ...
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: "storage",
},
},
],
});
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: output,
},
},
],
});
// ...
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpubindgroup | data/mdn-content/files/en-us/web/api/gpubindgroup/label/index.md | ---
title: "GPUBindGroup: label property"
short-title: label
slug: Web/API/GPUBindGroup/label
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUBindGroup.label
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`label`** property of the
{{domxref("GPUBindGroup")}} interface provides a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings.
This can be set by providing a `label` property in the descriptor object passed into the originating {{domxref("GPUDevice.createBindGroup()")}} call, or you can get and set it directly on the `GPUBindGroup` object.
## Value
A string. If this has not been previously set as described above, it will be an empty string.
## Examples
Setting and getting a label via `GPUBindGroup.label`:
```js
// ...
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: output,
},
},
],
});
bindGroup.label = "mybindgroup";
console.log(bindGroup.label); // "mybindgroup";
```
Setting a label via the originating {{domxref("GPUDevice.createBindGroup()")}} call, and then getting it via `GPUBindGroup.label`:
```js
// ...
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: output,
},
},
],
label: "mybindgroup",
});
console.log(bindGroup.label); // "mybindgroup";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfecomponenttransferelement/index.md | ---
title: SVGFEComponentTransferElement
slug: Web/API/SVGFEComponentTransferElement
page-type: web-api-interface
browser-compat: api.SVGFEComponentTransferElement
---
{{APIRef("SVG")}}
The **`SVGFEComponentTransferElement`** interface corresponds to the {{SVGElement("feComponentTransfer")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
- {{domxref("SVGFEComponentTransferElement.height")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element.
- {{domxref("SVGFEComponentTransferElement.in1")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element.
- {{domxref("SVGFEComponentTransferElement.result")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element.
- {{domxref("SVGFEComponentTransferElement.width")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element.
- {{domxref("SVGFEComponentTransferElement.x")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element.
- {{domxref("SVGFEComponentTransferElement.y")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element.
## Instance methods
_This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("feComponentTransfer")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/scheduling/index.md | ---
title: Scheduling
slug: Web/API/Scheduling
page-type: web-api-interface
status:
- experimental
browser-compat: api.Scheduling
---
{{SeeCompatTable}}{{APIRef("Prioritized Task Scheduling API")}}
The **`Scheduling`** object provides methods and properties to control scheduling tasks within the current document.
## Instance methods
- {{domxref("Scheduling.isInputPending", "isInputPending()")}} {{Experimental_Inline}}
- : Returns a boolean that indicates whether there are pending input events in the event queue, meaning that the user is attempting to interact with the page.
## Example
See the {{domxref("Scheduling.isInputPending()")}} page for a full example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Faster input events with Facebook's first browser API contribution](https://engineering.fb.com/2019/04/22/developer-tools/isinputpending-api/) on engineering.fb.com (2019)
- [Better JS scheduling with isInputPending()](https://developer.chrome.com/docs/capabilities/web-apis/isinputpending) on developer.chrome.com (2020)
- [Optimizing long tasks](https://web.dev/articles/optimize-long-tasks#yield_only_when_necessary) on web.dev (2022)
| 0 |
data/mdn-content/files/en-us/web/api/scheduling | data/mdn-content/files/en-us/web/api/scheduling/isinputpending/index.md | ---
title: "Scheduling: isInputPending() method"
short-title: isInputPending()
slug: Web/API/Scheduling/isInputPending
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.Scheduling.isInputPending
---
{{SeeCompatTable}}{{APIRef("Prioritized Task Scheduling API")}}
The **`isInputPending()`** method of the {{domxref("Scheduling")}} interface allows you to check whether there are pending input events in the event queue, indicating that the user is attempting to interact with the page.
This feature is useful in situations where you have a queue of tasks to run, and you want to yield to the main thread regularly to allow user interaction to occur so that the app is kept as responsive and performant as possible. `isInputPending()` allows you to yield only when there is input pending, rather than having to do it at arbitrary intervals.
`isInputPending()` is called using `navigator.scheduling.isInputPending()`.
## Syntax
```js-nolint
isInputPending()
isInputPending(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object providing options. Currently, the only option is:
- `includeContinuous` {{optional_inline}}
- : A boolean, which is `false` by default. If set to `true`, it indicates that continuous events should be considered when checking for pending input. Continuous events are trusted events (events dispatched by the browser) that are fired successively, such as {{domxref("Element/mousemove_event", "mousemove")}}, {{domxref("Element/wheel_event", "wheel")}}, {{domxref("Element/touchmove_event", "touchmove")}}, {{domxref("HTMLElement/drag_event", "drag")}}, {{domxref("Element/pointermove_event", "pointermove")}}, and {{domxref("Element/pointerrawupdate_event", "pointerrawupdate")}}.
### Return value
A boolean that indicates whether there are pending input events in the event queue (`true`) or not (`false`).
## Examples
We can use `isInputPending()` inside a task runner structure to run the `yield()` function only when the user is attempting to interact with the page:
```js
function yield() {
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
async function main() {
// Create an array of functions to run
const tasks = [a, b, c, d, e];
while (tasks.length > 0) {
// Yield to a pending user input
if (navigator.scheduling.isInputPending()) {
await yield();
} else {
// Shift the first task off the tasks array
const task = tasks.shift();
// Run the task
task();
}
}
}
```
This allows you to avoid blocking the main thread when the user is actively interacting with the page, potentially providing a smoother user experience. However, by only yielding when necessary, we can continue running the current task when there are no user inputs to process. This also avoids tasks being placed at the back of the queue behind other non-essential browser-initiated tasks that were scheduled after the current one.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Faster input events with Facebook's first browser API contribution](https://engineering.fb.com/2019/04/22/developer-tools/isinputpending-api/) on engineering.fb.com (2019)
- [Better JS scheduling with isInputPending()](https://developer.chrome.com/docs/capabilities/web-apis/isinputpending) on developer.chrome.com (2020)
- [Optimizing long tasks](https://web.dev/articles/optimize-long-tasks#yield_only_when_necessary) on web.dev (2022)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/intersectionobserver/index.md | ---
title: IntersectionObserver
slug: Web/API/IntersectionObserver
page-type: web-api-interface
browser-compat: api.IntersectionObserver
---
{{APIRef("Intersection Observer API")}}
The **`IntersectionObserver`** interface of the [Intersection Observer API](/en-US/docs/Web/API/Intersection_Observer_API) provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's {{Glossary('viewport')}}. The ancestor element or viewport is referred to as the root.
When an `IntersectionObserver` is created, it's configured to watch for given ratios of visibility within the root. The configuration cannot be changed once the `IntersectionObserver` is created, so a given observer object is only useful for watching for specific changes in degree of visibility; however, you can watch multiple target elements with the same observer.
## Constructor
- {{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}}
- : Creates a new `IntersectionObserver` object which will execute a specified callback function when it detects that a target element's visibility has crossed one or more thresholds.
## Instance properties
- {{domxref("IntersectionObserver.root")}} {{ReadOnlyInline}}
- : The {{domxref("Element")}} or {{domxref("Document")}} whose bounds are used as the bounding box when testing for intersection. If no `root` value was passed to the constructor or its value is `null`, the top-level document's viewport is used.
- {{domxref("IntersectionObserver.rootMargin")}} {{ReadOnlyInline}}
- : An offset rectangle applied to the root's {{Glossary('bounding box')}} when calculating intersections, effectively shrinking or growing the root for calculation purposes. The value returned by this property may not be the same as the one specified when calling the constructor as it may be changed to match internal requirements. Each offset can be expressed in pixels (`px`) or as a percentage (`%`). The default is "0px 0px 0px 0px".
- {{domxref("IntersectionObserver.thresholds")}} {{ReadOnlyInline}}
- : A list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area to bounding box area of an observed target. Notifications for a target are generated when any of the thresholds are crossed for that target. If no value was passed to the constructor, 0 is used.
## Instance methods
- {{domxref("IntersectionObserver.disconnect()")}}
- : Stops the `IntersectionObserver` object from observing any target.
- {{domxref("IntersectionObserver.observe()")}}
- : Tells the `IntersectionObserver` a target element to observe.
- {{domxref("IntersectionObserver.takeRecords()")}}
- : Returns an array of {{domxref("IntersectionObserverEntry")}} objects for all observed targets.
- {{domxref("IntersectionObserver.unobserve()")}}
- : Tells the `IntersectionObserver` to stop observing a particular target element.
## Examples
```js
const intersectionObserver = new IntersectionObserver((entries) => {
// If intersectionRatio is 0, the target is out of view
// and we do not need to do anything.
if (entries[0].intersectionRatio <= 0) return;
loadItems(10);
console.log("Loaded new items");
});
// start observing
intersectionObserver.observe(document.querySelector(".scrollerFooter"));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref('MutationObserver')}}
- {{domxref('PerformanceObserver')}}
- {{domxref('ResizeObserver')}}
| 0 |
data/mdn-content/files/en-us/web/api/intersectionobserver | data/mdn-content/files/en-us/web/api/intersectionobserver/takerecords/index.md | ---
title: "IntersectionObserver: takeRecords() method"
short-title: takeRecords()
slug: Web/API/IntersectionObserver/takeRecords
page-type: web-api-instance-method
browser-compat: api.IntersectionObserver.takeRecords
---
{{APIRef("Intersection Observer API")}}
The {{domxref("IntersectionObserver")}} method
**`takeRecords()`** returns an array of
{{domxref("IntersectionObserverEntry")}} objects, one for each targeted element which
has experienced an intersection change since the last time the intersections were
checked, either explicitly through a call to this method or implicitly by an automatic
call to the observer's callback.
> **Note:** If you use the callback to monitor these changes, you don't
> need to call this method. Calling this method clears the pending intersection list, so
> the callback will not be run.
## Syntax
```js-nolint
takeRecords()
```
### Parameters
None.
### Return value
An array of {{domxref("IntersectionObserverEntry")}} objects, one for each target
element whose intersection with the root has changed since the last time the
intersections were checked.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Intersection Observer API](/en-US/docs/Web/API/Intersection_Observer_API)
| 0 |
data/mdn-content/files/en-us/web/api/intersectionobserver | data/mdn-content/files/en-us/web/api/intersectionobserver/observe/index.md | ---
title: "IntersectionObserver: observe() method"
short-title: observe()
slug: Web/API/IntersectionObserver/observe
page-type: web-api-instance-method
browser-compat: api.IntersectionObserver.observe
---
{{APIRef("Intersection Observer API")}}
The {{domxref("IntersectionObserver")}} method
**`observe()`** adds an element to the set of target elements
being watched by the `IntersectionObserver`. One observer has one set of
thresholds and one root, but can watch multiple target elements for visibility changes
in keeping with those.
To stop observing the element, call
{{domxref("IntersectionObserver.unobserve()")}}.
When the visibility of the specified element crosses over one of the observer's
visibility thresholds (as listed in {{domxref("IntersectionObserver.thresholds")}}), the
observer's callback is executed with an array of
{{domxref("IntersectionObserverEntry")}} objects representing the intersection changes
which occurred. Note that this design allows multiple elements' intersection changes to
be processed by a single call to the callback.
> **Note:** the observer [callback](/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver#callback) will always fire the first render cycle after `observe()` is called, even if the observed element has not yet moved with respect to the viewport.
> This means that, for example, an element that is outside the viewport when `observe()` is called on it will result in the callback being immediately called with at least one [entry](/en-US/docs/Web/API/IntersectionObserverEntry) with [`intersecting`](/en-US/docs/Web/API/IntersectionObserverEntry/isIntersecting) set to `false`.
> An element inside the viewport will result in the callback being immediately called with at least one entry with `intersecting` set to `true`.
## Syntax
```js-nolint
observe(targetElement)
```
### Parameters
- `targetElement`
- : An {{domxref("element")}} whose visibility within the root is to be monitored. This
element must be a descendant of the root element (or contained within the current
document, if the root is the document's viewport).
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
// Register IntersectionObserver
const io = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0) {
// Add 'active' class if observation target is inside viewport
entry.target.classList.add("active");
} else {
// Remove 'active' class otherwise
entry.target.classList.remove("active");
}
});
});
// Declares what to observe, and observes its properties.
const boxElList = document.querySelectorAll(".box");
boxElList.forEach((el) => {
io.observe(el);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("IntersectionObserver.unobserve()")}}
| 0 |
data/mdn-content/files/en-us/web/api/intersectionobserver | data/mdn-content/files/en-us/web/api/intersectionobserver/thresholds/index.md | ---
title: "IntersectionObserver: thresholds property"
short-title: thresholds
slug: Web/API/IntersectionObserver/thresholds
page-type: web-api-instance-property
browser-compat: api.IntersectionObserver.thresholds
---
{{APIRef("Intersection Observer API")}}
The {{domxref("IntersectionObserver")}} interface's read-only
**`thresholds`** property returns the list of intersection
thresholds that was specified when the observer was instantiated with
{{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}}. If
only one threshold ratio was provided when instantiating the object, this will be an
array containing that single value.
See the [Intersection Observer](/en-US/docs/Web/API/Intersection_Observer_API#thresholds) page to
learn how thresholds work.
## Value
An array of intersection thresholds, originally specified using the
`threshold` property when instantiating the observer. If only one observer
was specified, without being in an array, this value is a one-entry array containing
that threshold. Regardless of the order your original `threshold` array was
in, this one is always sorted in numerically increasing order.
If no `threshold` option was included when
`IntersectionObserver()` was used to instantiate the observer, the value of
`thresholds` is `[0]`.
> **Note:** Although the `options` object you can specify when creating an
> {{domxref("IntersectionObserver")}} has a field named
> `threshold`, this property is called
> `thresholds`. Confusing? Yes. If you accidentally use
> `thresholds` as the name of the field in your `options`, the
> `thresholds` array will wind up being `[0.0]`, which is likely
> not what you expect. Debugging chaos may ensue.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/intersectionobserver | data/mdn-content/files/en-us/web/api/intersectionobserver/root/index.md | ---
title: "IntersectionObserver: root property"
short-title: root
slug: Web/API/IntersectionObserver/root
page-type: web-api-instance-property
browser-compat: api.IntersectionObserver.root
---
{{APIRef("Intersection Observer API")}}
The {{domxref("IntersectionObserver")}} interface's read-only
**`root`** property identifies the {{domxref("Element")}} or
{{domxref("Document")}} whose bounds are treated as the {{Glossary("bounding box")}}
of the {{Glossary("viewport")}} for the element which is the observer's target.
If the `root` is `null`, then the bounds of the actual document
viewport are used.
## Value
A {{domxref("Element")}} or {{domxref("Document")}} object whose bounding box is used
as the bounds of the viewport for the purposes of determining how much of the target
element is visible. The intersection of this bounding rectangle, offset by any margins
specified in the options passed to the
{{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}}
constructor, the target element's bounds, minus the bounds of every element or other
object which overlaps the target element, is considered to be the visible area of the
target element.
If `root` is `null`, then the owning document is used as the
root, and the bounds its viewport (that is, the visible area of the document) are used
as the root bounds.
## Examples
This example sets the {{cssxref("border")}} of the intersection observer's root element
to be a 2-pixel medium green line.
```js
observer.root.style.border = "2px solid #44aa44";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Timing element visibility with the Intersection Observer API](/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility)
| 0 |
data/mdn-content/files/en-us/web/api/intersectionobserver | data/mdn-content/files/en-us/web/api/intersectionobserver/intersectionobserver/index.md | ---
title: "IntersectionObserver: IntersectionObserver() constructor"
short-title: IntersectionObserver()
slug: Web/API/IntersectionObserver/IntersectionObserver
page-type: web-api-constructor
browser-compat: api.IntersectionObserver.IntersectionObserver
---
{{APIRef("Intersection Observer API")}}
The **`IntersectionObserver()`** constructor creates and returns a new {{domxref("IntersectionObserver")}} object.
The `rootMargin`, if specified, is checked to ensure it's syntactically correct.
If not specified, or an empty string, the default is `0px 0px 0px 0px`.
The `threshold`s, if specified, are checked to ensure that they're all in the range 0.0 and 1.0 inclusive, and the threshold list is sorted in ascending numeric order.
If the threshold list is empty, it's set to the array `[0.0]`.
## Syntax
```js-nolint
new IntersectionObserver(callback)
new IntersectionObserver(callback, options)
```
### Parameters
- `callback`
- : A function which is called when the percentage of the target element is visible crosses a threshold.
The callback receives as input two parameters:
- `entries`
- : An array of {{domxref("IntersectionObserverEntry")}} objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold.
- `observer`
- : The {{domxref("IntersectionObserver")}} for which the callback is being invoked.
- `options` {{optional_inline}}
- : An optional object which customizes the observer. All properties are optional.
You can provide any combination of the following options:
- `root`
- : An {{domxref("Element")}} or {{domxref("Document")}} object which is an ancestor of the intended target, whose bounding rectangle will be considered the viewport.
Any part of the target not visible in the visible area of the `root` is not considered visible. If not specified, the observer uses the document's
viewport as the root, with no margin, and a 0% threshold (meaning that even a one-pixel change is enough to trigger a callback).
- `rootMargin`
- : A string which specifies a set of offsets to add to the root's {{Glossary('bounding_box')}} when calculating intersections, effectively shrinking
or growing the root for calculation purposes.
The syntax is approximately the same as that for the CSS {{cssxref("margin")}} property;
see [The intersection root and root margin](/en-US/docs/Web/API/Intersection_Observer_API#the_intersection_root_and_root_margin) for more information on how the margin works and the syntax.
The default is "0px 0px 0px 0px".
- `threshold`
- : Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to total bounding box area for the observed target.
A value of 0.0 means that even a single visible pixel counts as the target being visible.
1.0 means that the entire target element is visible.
See [Thresholds](/en-US/docs/Web/API/Intersection_Observer_API#thresholds) for a more in-depth description of how thresholds are used.
The default is a threshold of 0.0.
### Return value
A new {{domxref("IntersectionObserver")}} which can be used to watch for the visibility of a target element within the specified `root` crossing through any of the
specified visibility `threshold`s.
Call its {{domxref("IntersectionObserver.observe", "observe()")}} method to begin watching for the visibility changes on a given target.
### Exceptions
- `SyntaxError` {{domxref("DOMException")}}
- : The specified `rootMargin` is invalid.
- {{jsxref("RangeError")}}
- : One or more of the values in `threshold` is outside the range 0.0 to 1.0.
## Examples
This example creates a new intersection observer which calls the function `myObserverCallback` every time the visible area of the element being observed changes by at least 10%.
```js
let observer = new IntersectionObserver(myObserverCallback, { threshold: 0.1 });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/intersectionobserver | data/mdn-content/files/en-us/web/api/intersectionobserver/disconnect/index.md | ---
title: "IntersectionObserver: disconnect() method"
short-title: disconnect()
slug: Web/API/IntersectionObserver/disconnect
page-type: web-api-instance-method
browser-compat: api.IntersectionObserver.disconnect
---
{{APIRef("Intersection Observer API")}}
The {{domxref("IntersectionObserver")}} method
**`disconnect()`** stops watching all of its target elements
for visibility changes.
## Syntax
```js-nolint
disconnect()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("IntersectionObserver.observe", "observe()")}}
- {{domxref("IntersectionObserver.unobserve", "unobserve()")}}
| 0 |
data/mdn-content/files/en-us/web/api/intersectionobserver | data/mdn-content/files/en-us/web/api/intersectionobserver/rootmargin/index.md | ---
title: "IntersectionObserver: rootMargin property"
short-title: rootMargin
slug: Web/API/IntersectionObserver/rootMargin
page-type: web-api-instance-property
browser-compat: api.IntersectionObserver.rootMargin
---
{{APIRef("Intersection Observer API")}}
The {{domxref("IntersectionObserver")}} interface's read-only
**`rootMargin`** property is a string with syntax similar to
that of the CSS {{cssxref("margin")}} property. Each side of the rectangle represented
by `rootMargin` is added to the corresponding side in the
{{domxref("IntersectionObserver.root", "root")}} element's {{Glossary("bounding box")}}
before the intersection test is performed. This lets you, for example, adjust the bounds
outward so that the target element is considered 100% visible even if a certain number
of pixels worth of width or height is clipped away, or treat the target as partially
hidden if an edge is too close to the edge of the root's bounding box.
See [how intersections are calculated](/en-US/docs/Web/API/Intersection_Observer_API#how_intersection_is_calculated)
for a more in-depth look at the root margin and how it works with
the root's bounding box.
## Value
A string, formatted similarly to the CSS {{cssxref("margin")}} property's value, which
contains offsets for one or more sides of the root's bounding box. These offsets are
added to the corresponding values in the root's bounding box before the intersection
between the resulting rectangle and the target element's bounds.
The string returned by this property may not match the one specified when the
{{domxref("IntersectionObserver")}} was instantiated. The browser is permitted to alter
the values
If `rootMargin` isn't specified when the object was instantiated, it
defaults to the string `"0px 0px 0px 0px"`, meaning that the intersection
will be computed between the root element's unmodified bounds rectangle and the target's
bounds. [How intersections are calculated](/en-US/docs/Web/API/Intersection_Observer_API#how_intersection_is_calculated)
describes how the `rootMargin` is used in more detail.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/intersectionobserver | data/mdn-content/files/en-us/web/api/intersectionobserver/unobserve/index.md | ---
title: "IntersectionObserver: unobserve() method"
short-title: unobserve()
slug: Web/API/IntersectionObserver/unobserve
page-type: web-api-instance-method
browser-compat: api.IntersectionObserver.unobserve
---
{{APIRef("Intersection Observer API")}}
The {{domxref("IntersectionObserver")}} method
**`unobserve()`** instructs the
`IntersectionObserver` to stop observing the specified target
element.
## Syntax
```js-nolint
unobserve(target)
```
### Parameters
- `target`
- : The {{domxref("Element")}} to cease observing. If the specified element isn't being
observed, this method does nothing and no exception is thrown.
### Return value
None ({{jsxref("undefined")}}).
## Examples
This snippet shows an observer being created, an element being observed, and then being
unobserved.
```js
const observer = new IntersectionObserver(callback);
observer.observe(document.getElementById("elementToObserve"));
// …
observer.unobserve(document.getElementById("elementToObserve"));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Intersection Observer API](/en-US/docs/Web/API/Intersection_Observer_API)
- {{domxref("IntersectionObserver.observe()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/audioencoder/index.md | ---
title: AudioEncoder
slug: Web/API/AudioEncoder
page-type: web-api-interface
status:
- experimental
browser-compat: api.AudioEncoder
---
{{APIRef("WebCodecs API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`AudioEncoder`** interface of the [WebCodecs API](/en-US/docs/Web/API/WebCodecs_API) encodes {{domxref("AudioData")}} objects.
{{InheritanceDiagram}}
## Constructor
- {{domxref("AudioEncoder.AudioEncoder", "AudioEncoder()")}} {{Experimental_Inline}}
- : Creates a new `AudioEncoder` object.
## Instance properties
_Inherits properties from its parent, {{DOMxRef("EventTarget")}}._
- {{domxref("AudioEncoder.encodeQueueSize")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : An integer representing the number of encode queue requests.
- {{domxref("AudioEncoder.state")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Represents the state of the underlying codec and whether it is configured for encoding.
### Events
- {{domxref("AudioEncoder.dequeue_event", "dequeue")}} {{Experimental_Inline}}
- : Fires to signal a decrease in {{domxref("AudioEncoder.encodeQueueSize")}}.
## Static methods
- {{domxref("AudioEncoder.isConfigSupported_static", "AudioEncoder.isConfigSupported()")}} {{Experimental_Inline}}
- : Returns a promise indicating whether the provided `AudioEncoderConfig` is supported.
## Instance methods
_Inherits methods from its parent, {{DOMxRef("EventTarget")}}._
- {{domxref("AudioEncoder.configure()")}} {{Experimental_Inline}}
- : Enqueues a control message to configure the audio encoder for encoding chunks.
- {{domxref("AudioEncoder.encode()")}} {{Experimental_Inline}}
- : Enqueues a control message to encode a given {{domxref("AudioData")}} objects.
- {{domxref("AudioEncoder.flush()")}} {{Experimental_Inline}}
- : Returns a promise that resolves once all pending messages in the queue have been completed.
- {{domxref("AudioEncoder.reset()")}} {{Experimental_Inline}}
- : Resets all states including configuration, control messages in the control message queue, and all pending callbacks.
- {{domxref("AudioEncoder.close()")}} {{Experimental_Inline}}
- : Ends all pending work and releases system resources.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audioencoder | data/mdn-content/files/en-us/web/api/audioencoder/configure/index.md | ---
title: "AudioEncoder: configure() method"
short-title: configure()
slug: Web/API/AudioEncoder/configure
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.AudioEncoder.configure
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`configure()`** method of the {{domxref("AudioEncoder")}} interface enqueues a control message to configure the audio encoder for encoding chunks.
## Syntax
```js-nolint
configure(config)
```
### Parameters
- `config`
- : A dictionary object containing the following members:
- `codec`
- : A string containing a [valid codec string](https://www.w3.org/TR/webcodecs-codec-registry/#audio-codec-registry). See ["codecs" parameter](/en-US/docs/Web/Media/Formats/codecs_parameter#codec_options_by_container) for details on codec string construction.
- `sampleRate`
- : An integer representing the number of frame samples per second.
- `numberOfChannels`
- : An integer representing the number of audio channels.
- `bitrate` {{optional_inline}}
- : An integer representing the bitrate.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the provided `config` is invalid.
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the {{domxref("AudioEncoder.state","state")}} is `"closed"`.
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if the provided `config` is valid but the user agent cannot provide a codec that can decode this profile.
## Examples
The following example creates a new {{domxref("AudioEncoder")}} and configures it with some of the available options.
```js
const init = {
output: handleOutput,
error: (e) => {
console.log(e.message);
},
};
let config = {
codec: "opus",
sampleRate: 44100,
numberOfChannels: 2,
bitrate: 128_000, // 128 kbps
};
let encoder = new AudioEncoder(init);
encoder.configure(config);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audioencoder | data/mdn-content/files/en-us/web/api/audioencoder/dequeue_event/index.md | ---
title: "AudioEncoder: dequeue event"
short-title: dequeue
slug: Web/API/AudioEncoder/dequeue_event
page-type: web-api-event
status:
- experimental
browser-compat: api.AudioEncoder.dequeue_event
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`dequeue`** event of the {{domxref("AudioEncoder")}} interface fires to signal a decrease in {{domxref("AudioEncoder.encodeQueueSize")}}.
This eliminates the need for developers to use a {{domxref("setTimeout()")}} poll to determine when the queue has decreased, and more work should be queued up.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("dequeue", (event) => {});
ondequeue = (event) => {};
```
## Example
```js
audioEncoder.addEventListener("dequeue", (event) => {
// Queue up more encoding work
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audioencoder | data/mdn-content/files/en-us/web/api/audioencoder/encodequeuesize/index.md | ---
title: "AudioEncoder: encodeQueueSize property"
short-title: encodeQueueSize
slug: Web/API/AudioEncoder/encodeQueueSize
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.AudioEncoder.encodeQueueSize
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`encodeQueueSize`** read-only property of the {{domxref("AudioEncoder")}} interface returns the number of pending encode requests in the queue.
## Value
An integer containing the number of requests.
## Examples
The following example prints the size of the queue to the console.
```js
console.log(AudioEncoder.encodeQueueSize);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audioencoder | data/mdn-content/files/en-us/web/api/audioencoder/flush/index.md | ---
title: "AudioEncoder: flush() method"
short-title: flush()
slug: Web/API/AudioEncoder/flush
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.AudioEncoder.flush
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`flush()`** method of the {{domxref("AudioEncoder")}} interface returns a Promise that resolves once all pending messages in the queue have been completed.
## Syntax
```js-nolint
flush()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves with undefined.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the Promise is rejected because the {{domxref("AudioEncoder.state","state")}} is not `"configured"`.
## Examples
The following example flushes the `AudioEncoder`.
```js
AudioEncoder.flush();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audioencoder | data/mdn-content/files/en-us/web/api/audioencoder/isconfigsupported_static/index.md | ---
title: "AudioEncoder: isConfigSupported() static method"
short-title: isConfigSupported()
slug: Web/API/AudioEncoder/isConfigSupported_static
page-type: web-api-static-method
status:
- experimental
browser-compat: api.AudioEncoder.isConfigSupported_static
---
{{APIRef("WebCodecs API")}}{{SecureContext_Header}}{{SeeCompatTable}}
The **`isConfigSupported()`** static method of the {{domxref("AudioEncoder")}} interface checks if the given config is supported (that is, if {{domxref("AudioEncoder")}} objects can be successfully configured with the given config).
## Syntax
```js-nolint
AudioEncoder.isConfigSupported(config)
```
### Parameters
- `config`
- : The dictionary object accepted by {{domxref("AudioEncoder.configure")}}
### Return value
A {{jsxref("Promise")}} that resolves with an object containing the following members:
- `supported`
- : A boolean value which is `true` if the given config is supported by the encoder.
- `config`
- : A copy of the given config with all the fields recognized by the encoder.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the provided `config` is invalid; that is, if doesn't have required values (such as an empty `codec` field) or has invalid values (such as a negative `sampleRate`).
## Examples
The following example tests if the browser supports several audio codecs.
```js
const codecs = ["mp4a.40.2", "mp3", "alaw", "ulaw"];
const configs = [];
for (const codec of codecs) {
configs.push({
codec,
sampleRate: 48000,
numberOfChannels: 1,
not_supported_field: 123,
});
}
for (const config of configs) {
const support = await AudioEncoder.isConfigSupported(config);
console.log(
`AudioEncoder's config ${JSON.stringify(support.config)} support: ${
support.supported
}`,
);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audioencoder | data/mdn-content/files/en-us/web/api/audioencoder/state/index.md | ---
title: "AudioEncoder: state property"
short-title: state
slug: Web/API/AudioEncoder/state
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.AudioEncoder.state
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`state`** read-only property of the {{domxref("AudioEncoder")}} interface returns the current state of the underlying codec.
## Value
A string containing one of the following values:
- `"unconfigured"`
- : The codec is not configured for decoding.
- `"configured"`
- : The codec has a valid configuration and is ready.
- `"closed"`
- : The codec is no longer usable and system resources have been released.
## Examples
The following example prints the state of the `AudioEncoder` to the console.
```js
console.log(AudioEncoder.state);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audioencoder | data/mdn-content/files/en-us/web/api/audioencoder/reset/index.md | ---
title: "AudioEncoder: reset() method"
short-title: reset()
slug: Web/API/AudioEncoder/reset
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.AudioEncoder.reset
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`reset()`** method of the {{domxref("AudioEncoder")}} interface resets all states including configuration, control messages in the control message queue, and all pending callbacks.
## Syntax
```js-nolint
reset()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following example resets the `AudioEncoder`.
```js
AudioEncoder.reset();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audioencoder | data/mdn-content/files/en-us/web/api/audioencoder/audioencoder/index.md | ---
title: "AudioEncoder: AudioEncoder() constructor"
short-title: AudioEncoder()
slug: Web/API/AudioEncoder/AudioEncoder
page-type: web-api-constructor
status:
- experimental
browser-compat: api.AudioEncoder.AudioEncoder
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`AudioEncoder()`** constructor creates a new {{domxref("AudioEncoder")}} object with the provided `init.output` callback assigned as the output callback, the provided `init.error` callback as the error callback, and the {{domxref("AudioEncoder.state")}} set to `"unconfigured"`.
## Syntax
```js-nolint
new AudioEncoder(init)
```
### Parameters
- `init`
- : An object containing two required callbacks.
- `output`
- : A callback which takes a {{domxref("EncodedAudioChunk")}} object as the first argument, and an optional metadata object as the second. The metadata object has one member, `decoderConfig` which has an object as its value containing:
- `codec`
- : A string containing a [valid codec string](https://www.w3.org/TR/webcodecs-codec-registry/#audio-codec-registry).
- `sampleRate`
- : An integer representing the number of frame samples per second.
- `numberOfChannels`
- : An integer representing the number of audio channels.
- `description` {{optional_inline}}
- : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}} containing a sequence of codec specific bytes, commonly known as extradata.
- `error`
- : A callback which takes an {{jsxref("Error")}} object as its only argument.
## Examples
In the following example an `AudioEncoder` is created with the two required callback functions, one to deal with the decoded frame and the other to handle errors.
```js
const audioEncoder = new AudioEncoder({
output: processAudio,
error: onEncoderError,
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audioencoder | data/mdn-content/files/en-us/web/api/audioencoder/encode/index.md | ---
title: "AudioEncoder: encode() method"
short-title: encode()
slug: Web/API/AudioEncoder/encode
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.AudioEncoder.encode
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`encode()`** method of the {{domxref("AudioEncoder")}} interface enqueues a control message to encode a given {{domxref("AudioData")}} object.
## Syntax
```js-nolint
encode(data)
```
### Parameters
- `data`
- : An {{domxref("AudioData")}} object.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the {{domxref("AudioEncoder.state","state")}} is not `"configured"`.
- {{jsxref("TypeError")}}
- : Thrown if the `AudioData` object has been [transferred](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects).
## Examples
In the following example `encode` is passed an `AudioData` object.
```js
encoder.encode(data);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audioencoder | data/mdn-content/files/en-us/web/api/audioencoder/close/index.md | ---
title: "AudioEncoder: close() method"
short-title: close()
slug: Web/API/AudioEncoder/close
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.AudioEncoder.close
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`close()`** method of the {{domxref("AudioEncoder")}} interface ends all pending work and releases system resources.
## Syntax
```js-nolint
close()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following example closes the `AudioEncoder`.
```js
AudioEncoder.close();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfefuncgelement/index.md | ---
title: SVGFEFuncGElement
slug: Web/API/SVGFEFuncGElement
page-type: web-api-interface
browser-compat: api.SVGFEFuncGElement
---
{{APIRef("SVG")}}
The **`SVGFEFuncGElement`** interface corresponds to the {{SVGElement("feFuncG")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface not provide any specific properties, but inherits properties from its parent interface, {{domxref("SVGComponentTransferFunctionElement")}}._
## Instance methods
_This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGComponentTransferFunctionElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("feFuncG")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/console/index.md | ---
title: console
slug: Web/API/console
page-type: web-api-interface
browser-compat: api.console
---
{{APIRef("Console API")}}
The **`console`** object provides access to the debugging console (e.g., the [Web console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html) in Firefox). The specifics of how it works vary from browser to browser or server runtimes (Node.js, for example), but there is a _de facto_ set of features that are typically provided.
The `console` object can be accessed from any global object. {{domxref("Window")}} on browsing scopes and {{domxref("WorkerGlobalScope")}} as specific variants in workers via the property console. It's exposed as {{domxref("Window.console")}}, and can be referenced as `console`. For example:
```js
console.log("Failed to open the specified link");
```
This page documents the [Methods](#methods) available on the `console` object and gives a few [Usage](#usage) examples.
{{AvailableInWorkers}}
> **Note:** Certain online IDEs and editors may implement the console API differently than the browsers. As a result, certain functionality of the console API, such as the timer methods, may not be outputted in the console of online IDEs or editors. Always open your browser's DevTools console to see the logs as shown in this documentation.
## Instance methods
- {{domxref("console/assert_static", "console.assert()")}}
- : Log a message and stack trace to console if the first argument is `false`.
- {{domxref("console/clear_static", "console.clear()")}}
- : Clear the console.
- {{domxref("console/count_static", "console.count()")}}
- : Log the number of times this line has been called with the given label.
- {{domxref("console/countReset_static", "console.countReset()")}}
- : Resets the value of the counter with the given label.
- {{domxref("console/debug_static", "console.debug()")}}
- : Outputs a message to the console with the log level `debug`.
- {{domxref("console/dir_static", "console.dir()")}}
- : Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
- {{domxref("console/dirxml_static", "console.dirxml()")}}
- : Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.
- {{domxref("console/error_static", "console.error()")}}
- : Outputs an error message. You may use [string substitution](#using_string_substitutions) and additional arguments with this method.
- `console.exception()` {{Non-standard_inline}} {{deprecated_inline}}
- : An alias for `console.error()`.
- {{domxref("console/group_static", "console.group()")}}
- : Creates a new inline [group](#using_groups_in_the_console), indenting all following output by another level. To move back out a level, call `console.groupEnd()`.
- {{domxref("console/groupCollapsed_static", "console.groupCollapsed()")}}
- : Creates a new inline [group](#using_groups_in_the_console), indenting all following output by another level. However, unlike `console.group()` this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call `console.groupEnd()`.
- {{domxref("console/groupEnd_static", "console.groupEnd()")}}
- : Exits the current inline [group](#using_groups_in_the_console).
- {{domxref("console/info_static", "console.info()")}}
- : Informative logging of information. You may use [string substitution](#using_string_substitutions) and additional arguments with this method.
- {{domxref("console/log_static", "console.log()")}}
- : For general output of logging information. You may use [string substitution](#using_string_substitutions) and additional arguments with this method.
- {{domxref("console/profile_static", "console.profile()")}} {{Non-standard_inline}}
- : Starts the browser's built-in profiler (for example, the [Firefox performance tool](https://firefox-source-docs.mozilla.org/devtools-user/performance/index.html)). You can specify an optional name for the profile.
- {{domxref("console/profileEnd_static", "console.profileEnd()")}} {{Non-standard_inline}}
- : Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the [Firefox performance tool](https://firefox-source-docs.mozilla.org/devtools-user/performance/index.html)).
- {{domxref("console/table_static", "console.table()")}}
- : Displays tabular data as a table.
- {{domxref("console/time_static", "console.time()")}}
- : Starts a [timer](#timers) with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
- {{domxref("console/timeEnd_static", "console.timeEnd()")}}
- : Stops the specified [timer](#timers) and logs the elapsed time in milliseconds since it started.
- {{domxref("console/timeLog_static", "console.timeLog()")}}
- : Logs the value of the specified [timer](#timers) to the console.
- {{domxref("console/timeStamp_static", "console.timeStamp()")}} {{Non-standard_inline}}
- : Adds a marker to the browser performance tool's timeline ([Chrome](https://developer.chrome.com/docs/devtools/evaluate-performance/reference/) or [Firefox](https://profiler.firefox.com/docs/#/./guide-ui-tour-timeline)).
- {{domxref("console/trace_static", "console.trace()")}}
- : Outputs a [stack trace](#stack_traces).
- {{domxref("console/warn_static", "console.warn()")}}
- : Outputs a warning message. You may use [string substitution](#using_string_substitutions) and additional arguments with this method.
## Examples
### Outputting text to the console
The console's most frequently used feature is logging text and other data. There are several categories of output you can generate using the {{domxref("console/log_static", "console.log()")}}, {{domxref("console/info_static", "console.info()")}}, {{domxref("console/warn_static", "console.warn()")}}, {{domxref("console/error_static", "console.error()")}}, or {{domxref("console/debug_static", "console.debug()")}} methods. Each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to view only the kinds of output that interest you.
There are two ways to use each of the output methods:
- Pass in a variable number of arguments whose string representations get concatenated into one string, then output to the console.
- Pass in a string containing zero or more substitution strings followed by a variable number of arguments to replace them.
#### Outputting a single object
The simplest way to use the logging methods is to output a single object:
```js
const someObject = { str: "Some text", id: 5 };
console.log(someObject);
```
The output looks something like this:
```plain
{str:"Some text", id:5}
```
#### Outputting multiple objects
You can also output multiple objects by listing them when calling the logging method, like this:
```js
const car = "Dodge Charger";
const someObject = { str: "Some text", id: 5 };
console.info("My first car was a", car, ". The object is:", someObject);
```
The output will look like this:
```plain
My first car was a Dodge Charger. The object is: {str:"Some text", id:5}
```
#### Using string substitutions
When passing a string to one of the `console` object's methods that accepts a string (such as `console.log()`), you may use these substitution strings:
- `%o` or `%O`
- : Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
- `%d` or `%i`
- : Outputs an integer. Number formatting is supported, for example `console.log("Foo %.2d", 1.1)` will output the number as two significant figures with a leading 0: `Foo 01`.
- `%s`
- : Outputs a string.
- `%f`
- : Outputs a floating-point value. Formatting is supported, for example `console.log("Foo %.2f", 1.1)` will output the number to 2 decimal places: `Foo 1.10`.
> **Note:** Precision formatting doesn't work in Chrome.
Each of these pulls the next argument after the format string off the parameter list. For example:
```js
for (let i = 0; i < 5; i++) {
console.log("Hello, %s. You've called me %d times.", "Bob", i + 1);
}
```
The output looks like this:
```plain
Hello, Bob. You've called me 1 times.
Hello, Bob. You've called me 2 times.
Hello, Bob. You've called me 3 times.
Hello, Bob. You've called me 4 times.
Hello, Bob. You've called me 5 times.
```
#### Styling console output
You can use the `%c` directive to apply a CSS style to console output:
```js
console.log(
"This is %cMy stylish message",
"color: yellow; font-style: italic; background-color: blue;padding: 2px",
);
```
The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.

You may use `%c` multiple times:
```js
console.log(
"Multiple styles: %cred %corange",
"color: red",
"color: orange",
"Additional unformatted message",
);
```
The properties usable along with the `%c` syntax are as follows (at least, in Firefox — they may differ in other browsers):
- {{cssxref("background")}} and its longhand equivalents
- {{cssxref("border")}} and its longhand equivalents
- {{cssxref("border-radius")}}
- {{cssxref("box-decoration-break")}}
- {{cssxref("box-shadow")}}
- {{cssxref("clear")}} and {{cssxref("float")}}
- {{cssxref("color")}}
- {{cssxref("cursor")}}
- {{cssxref("display")}}
- {{cssxref("font")}} and its longhand equivalents
- {{cssxref("line-height")}}
- {{cssxref("margin")}}
- {{cssxref("outline")}} and its longhand equivalents
- {{cssxref("padding")}}
- `text-*` properties such as {{cssxref("text-transform")}}
- {{cssxref("white-space")}}
- {{cssxref("word-spacing")}} and {{cssxref("word-break")}}
- {{cssxref("writing-mode")}}
> **Note:** The console message behaves like an inline element by default. To see the effects of `padding`, `margin`, etc. you should set it to for example `display: inline-block`.
### Using groups in the console
You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call `console.group()`. The `console.groupCollapsed()` method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.
To exit the current group, call `console.groupEnd()`. For example, given this code:
```js
console.log("This is the outer level");
console.group("First group");
console.log("In the first group");
console.group("Second group");
console.log("In the second group");
console.warn("Still in the second group");
console.groupEnd();
console.log("Back to the first group");
console.groupEnd();
console.debug("Back to the outer level");
```
The output looks like this:

### Timers
You can start a timer to calculate the duration of a specific operation. To start one, call the `console.time()` method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the `console.timeEnd()` method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.
For example, given this code:
```js
console.time("answer time");
alert("Click to continue");
console.timeLog("answer time");
alert("Do a bunch of other stuff…");
console.timeEnd("answer time");
```
Will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console:

Notice that the timer's name is displayed both when the timer is started and when it's stopped.
### Stack traces
The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call {{domxref("console/trace_static", "console.trace()")}}. Given code like this:
```js
function foo() {
function bar() {
console.trace();
}
bar();
}
foo();
```
The output in the console looks something like this:

## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## Notes
- At least in Firefox, if a page defines a `console` object, that object overrides the one built into Firefox.
## See also
- [Firefox Developer Tools](https://firefox-source-docs.mozilla.org/devtools-user/index.html)
- [Web console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html) — how the Web console in Firefox handles console API calls
- [about:debugging](https://firefox-source-docs.mozilla.org/devtools-user/about_colon_debugging/index.html) — how to see console output when the debugging target is a mobile device
### Other implementations
- [Google Chrome DevTools](https://developer.chrome.com/docs/devtools/console/api/)
- [Microsoft Edge DevTools](https://docs.microsoft.com/archive/microsoft-edge/legacy/developer/)
- [Safari Web Inspector](https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/timelog_static/index.md | ---
title: "console: timeLog() static method"
short-title: timeLog()
slug: Web/API/console/timelog_static
page-type: web-api-instance-method
browser-compat: api.console.timeLog_static
---
{{APIRef("Console API")}}{{AvailableInWorkers}}
The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling {{domxref("console/time_static", "console.time()")}}.
## Syntax
```js-nolint
timeLog()
timeLog(label)
timeLog(label, val1)
timeLog(label, val1, /* …, */ valN)
```
### Parameters
- `label` {{optional_inline}}
- : The name of the timer to log to the console. If this is omitted the label "default" is used.
- `valN` {{optional_inline}}
- : Additional values to be logged to the console after the timer output.
### Return value
None ({{jsxref("undefined")}}).
## Description
The `console.timeLog()` method logs the current value of a timer.
The method can be passed the name of a timer. This will attempt to log the value of a timer created with that name in a previous call to {{domxref("console/time_static", "console.time()")}}:
```js
console.time("reticulating splines");
reticulateSplines();
console.timeLog("reticulating splines");
// reticulating splines: 650ms
```
If the timer name is omitted, then the timer is named `"default"`:
```js
console.time();
reticulateSplines();
console.timeLog();
// default: 780ms
```
```js
console.time("default");
reticulateSplines();
console.timeLog();
// default: 780ms
```
If there is no corresponding timer, `console.timeLog()` logs a warning like:
```plain
Timer "timer name" doesn't exist.
```
You can log additional values to the console after the timer output:
```js
console.time();
reticulateSplines();
console.timeLog("default", "Hello", "world");
// default: 780ms Hello world
```
See [Timers](/en-US/docs/Web/API/console#timers) in the documentation for more details and examples.
## Examples
```js
console.time("answer time");
alert("Click to continue");
console.timeLog("answer time");
alert("Do a bunch of other stuff…");
console.timeEnd("answer time");
```
The output from the example above shows the time taken by the user to dismiss the first alert box, followed by the cumulative time it took for the user to dismiss both alerts:
```plain
answer time: 2542ms debugger eval code:3:9
answer time: 4161ms - timer ended
```
Notice that the timer's name is displayed when the timer value is logged using `console.timeLog()` and again when it's stopped. In addition, the call to `console.timeEnd()` has the additional information, "timer ended" to make it obvious that the timer is no longer tracking time.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("console/time_static", "console.time()")}}
- {{domxref("console/timeEnd_static", "console.timeEnd()")}}
- [Node.JS documentation for `console.timeLog()`](https://nodejs.org/docs/latest/api/console.html#consoletimeloglabel-data)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/timestamp_static/index.md | ---
title: "console: timeStamp() static method"
short-title: timeStamp()
slug: Web/API/console/timestamp_static
page-type: web-api-instance-method
status:
- non-standard
browser-compat: api.console.timeStamp_static
---
{{APIRef("Console API")}}{{Non-standard_header}}
The **`console.timeStamp()`** static method adds a single marker to the browser's Performance tool ([Firefox](https://profiler.firefox.com/docs/#/), [Chrome](https://developer.chrome.com/docs/devtools/evaluate-performance/reference/)). This lets you correlate a point in your code with the other events recorded in the timeline, such as layout and paint events.
You can optionally supply an argument to label the timestamp, and this label will then be shown alongside the marker.
{{AvailableInWorkers}}
## Syntax
```js-nolint
timeStamp(label)
```
### Parameters
- `label` {{Optional_Inline}}
- : Label for the timestamp.
### Return value
None ({{jsxref("undefined")}}).
## Browser compatibility
{{Compat}}
## See also
- {{domxref("console/time_static", "console.time()")}}
- {{domxref("console/timeLog_static", "console.timeLog()")}}
- {{domxref("console/timeEnd_static", "console.timeEnd()")}}
- [Adding markers with the console API](https://web.archive.org/web/20211207010020/https://firefox-source-docs.mozilla.org/devtools-user/performance/waterfall/index.html#adding-markers-with-the-console-api)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/groupcollapsed_static/index.md | ---
title: "console: groupCollapsed() static method"
short-title: groupCollapsed()
slug: Web/API/console/groupcollapsed_static
page-type: web-api-instance-method
browser-compat: api.console.groupCollapsed_static
---
{{APIRef("Console API")}}
The **`console.groupCollapsed()`** static method creates a new inline group in the console. Unlike {{domxref("console/group_static", "console.group()")}}, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group.
Call {{domxref("console/groupEnd_static", "console.groupEnd()")}} to back out to the parent group.
See [Using groups in the console](/en-US/docs/Web/API/console#using_groups_in_the_console) in the {{domxref("console")}} documentation for details and examples.
{{AvailableInWorkers}}
## Syntax
```js-nolint
groupCollapsed()
groupCollapsed(label)
```
### Parameters
- `label` {{Optional_Inline}}
- : Label for the group.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("console/group_static", "console.group()")}}
- {{domxref("console/groupEnd_static", "console.groupEnd()")}}
- [Microsoft Edge's documentation for `console.groupCollapsed()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#groupcollapsed)
- [Node.JS documentation for `console.groupCollapsed()`](https://nodejs.org/docs/latest/api/console.html#consolegroupcollapsed)
- [Google Chrome's documentation for `console.groupCollapsed()`](https://developer.chrome.com/docs/devtools/console/api/#groupcollapsed)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/clear_static/index.md | ---
title: "console: clear() static method"
short-title: clear()
slug: Web/API/console/clear_static
page-type: web-api-instance-method
browser-compat: api.console.clear_static
---
{{APIRef("Console API")}}
The **`console.clear()`** static method clears the console if the console allows it. A graphical console, like those running on browsers, will allow it; a console displaying on the terminal, like the one running on Node, will not support it, and will have no effect (and no error).
## Syntax
```js-nolint
clear()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.clear()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#clear)
- [Node.JS documentation for `console.clear()`](https://nodejs.org/docs/latest/api/console.html#consoleclear)
- [Google Chrome's documentation for `console.clear()`](https://developer.chrome.com/docs/devtools/console/api/#clear)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/dir_static/index.md | ---
title: "console: dir() static method"
short-title: dir()
slug: Web/API/console/dir_static
page-type: web-api-instance-method
browser-compat: api.console.dir_static
---
{{APIRef("Console API")}}
The **`console.dir()`** static method displays an interactive list of the properties of the specified JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.
In other words, `console.dir()` is the way to see all the properties of a specified JavaScript object in console by which the developer can easily get the properties of the object.
{{AvailableInWorkers}}

## Syntax
```js-nolint
dir(object)
```
### Parameters
- `object`
- : A JavaScript object whose properties should be output.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.dir()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#dir)
- [Node.JS documentation for `console.dir()`](https://nodejs.org/docs/latest/api/console.html#consoledirobj-options)
- [Google Chrome's documentation for `console.dir()`](https://developer.chrome.com/docs/devtools/console/api/#dir)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/assert_static/index.md | ---
title: "console: assert() static method"
short-title: assert()
slug: Web/API/console/assert_static
page-type: web-api-instance-method
browser-compat: api.console.assert_static
---
{{APIRef("Console API")}}
The **`console.assert()`** static method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.
{{AvailableInWorkers}}
## Syntax
```js-nolint
assert(assertion)
assert(assertion, obj1)
assert(assertion, obj1, obj2)
assert(assertion, obj1, obj2, /* …, */ objN)
assert(assertion, msg)
assert(assertion, msg, subst1)
assert(assertion, msg, subst1, /* …, */ substN)
```
### Parameters
- `assertion`
- : Any boolean expression. If the assertion is false, a generic message indicating assertion failure is written to the console.
- `obj1` … `objN`
- : A list of JavaScript objects to output. A representation of each of these objects is output to the console after a generic assertion failure message (which may be different from the message output when these objects are not present) in the order given with some type of separation between the message and between each of them. There is a special case if `obj1` is a string, which is described subsequently.
- `msg`
- : A JavaScript string containing zero or more substitution strings, which are replaced with `subst1` through `substN` in consecutive order up to the number of substitution strings. A colon, a space, and then the substituted string are appended to the generic assertion message to form a detailed assertion message, and the result is output to the console.
- `subst1` … `substN`
- : JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output. See [Using string substitutions](/en-US/docs/Web/API/console#using_string_substitutions) for a description of how substitutions work. If there are more substutition objects than there are substitution strings, the extra objects are themselves written to the console after the detailed assertion message in the same manner as described for objects written after a generic assertion message.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following code example demonstrates the use of a JavaScript object following the assertion:
```js
const errorMsg = "the # is not even";
for (let number = 2; number <= 5; number++) {
console.log(`the # is ${number}`);
console.assert(number % 2 === 0, "%o", { number, errorMsg });
}
// output:
// the # is 2
// the # is 3
// Assertion failed: {number: 3, errorMsg: "the # is not even"}
// the # is 4
// the # is 5
// Assertion failed: {number: 5, errorMsg: "the # is not even"}
```
See [Using string substitutions](/en-US/docs/Web/API/console#using_string_substitutions) in the documentation of {{domxref("console")}} for further details.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.assert()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#assert)
- [Node.JS documentation for `console.assert()`](https://nodejs.org/docs/latest/api/console.html#consoleassertvalue-message)
- [Google Chrome's documentation for `console.dir()`](https://developer.chrome.com/docs/devtools/console/api/#dir)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/profileend_static/index.md | ---
title: "console: profileEnd() static method"
short-title: profileEnd()
slug: Web/API/console/profileend_static
page-type: web-api-instance-method
status:
- non-standard
browser-compat: api.console.profileEnd_static
---
{{APIRef("Console API")}}{{Non-standard_header}}
The **`console.profileEnd()`** static method stops recording a profile previously started with {{domxref("console/profile_static", "console.profile()")}}.
You can optionally supply an argument to name the profile. Doing so enables you to stop only that profile if you have multiple profiles being recorded.
- If `console.profileEnd()` is passed a profile name, and it matches the name of a profile being recorded, then that profile is stopped.
- If `console.profileEnd()` is passed a profile name and it does not match the name of a profile being recorded, no changes will be made.
- If `console.profileEnd()` is not passed a profile name, the most recently started profile is stopped.
{{AvailableInWorkers}}
## Syntax
```js-nolint
profileEnd(profileName)
```
### Parameters
- `profileName` {{Optional_Inline}}
- : The name to give the profile.
### Return value
None ({{jsxref("undefined")}}).
## Browser compatibility
{{Compat}}
## See also
- {{domxref("console/profile_static", "console.profile()")}}
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/warn_static/index.md | ---
title: "console: warn() static method"
short-title: warn()
slug: Web/API/console/warn_static
page-type: web-api-instance-method
browser-compat: api.console.warn_static
---
{{APIRef("Console API")}}
The **`console.warn()`** static method outputs a warning message to the console.
{{AvailableInWorkers}}
> **Note:** In Chrome and Firefox, warnings have a small exclamation point icon next to them in the console log.
## Syntax
```js-nolint
warn(obj1)
warn(obj1, /* …, */ objN)
warn(msg)
warn(msg, subst1, /* …, */ substN)
```
### Parameters
- `obj1` … `objN`
- : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console.
- `msg`
- : A JavaScript string containing zero or more substitution strings, which are replaced with `subst1` through `substN` in consecutive order.
- `subst1` … `substN`
- : JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output. See [Using string substitutions](/en-US/docs/Web/API/console#using_string_substitutions) for a description of how substitutions work.
See [Outputting text to the console](/en-US/docs/Web/API/console#outputting_text_to_the_console) in the documentation of the {{domxref("console")}} object for details.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.warn()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#warn)
- [Node.JS documentation for `console.warn()`](https://nodejs.org/docs/latest/api/console.html#consolewarndata-args)
- [Google Chrome's documentation for `console.warn()`](https://developer.chrome.com/docs/devtools/console/api/#warn)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/timeend_static/index.md | ---
title: "console: timeEnd() static method"
short-title: timeEnd()
slug: Web/API/console/timeend_static
page-type: web-api-instance-method
browser-compat: api.console.timeEnd_static
---
{{APIRef("Console API")}}
The **`console.timeEnd()`** static method stops a timer that was previously started by calling {{domxref("console/time_static", "console.time()")}}.
See [Timers](/en-US/docs/Web/API/console#timers) in the documentation for details and examples.
{{AvailableInWorkers}}
## Syntax
```js-nolint
timeEnd()
timeEnd(label)
```
### Parameters
- `label` {{optional_inline}}
- : A string representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console along with an indicator that the time has ended. If omitted, the label "default" is used.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
console.time("answer time");
alert("Click to continue");
console.timeLog("answer time");
alert("Do a bunch of other stuff…");
console.timeEnd("answer time");
```
The output from the example above shows the time taken by the user to dismiss the first alert box, followed by the cumulative time it took for the user to dismiss both alerts:

Notice that the timer's name is displayed when the timer value is logged using `console.timeLog()` and again when it's stopped. In addition, the call to `console.timeEnd()` has the additional information, "timer ended" to make it obvious that the timer is no
longer tracking time.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("console/time_static", "console.time()")}}
- {{domxref("console/timeLog_static", "console.timeLog()")}}
- [Microsoft Edge's documentation for `console.timeEnd()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#timeend)
- [Node.JS documentation for `console.timeEnd()`](https://nodejs.org/docs/latest/api/console.html#consoletimeendlabel)
- [Google Chrome's documentation for `console.timeEnd()`](https://developer.chrome.com/docs/devtools/console/api/#timeend)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/error_static/index.md | ---
title: "console: error() static method"
short-title: error()
slug: Web/API/console/error_static
page-type: web-api-instance-method
browser-compat: api.console.error_static
---
{{APIRef("Console API")}}
The **`console.error()`** static method outputs an error message to the console.
{{AvailableInWorkers}}
## Syntax
```js-nolint
error(obj1)
error(obj1, /* …, */ objN)
error(msg)
error(msg, subst1, /* …, */ substN)
```
### Parameters
- `obj1` … `objN`
- : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console.
- `msg`
- : A JavaScript string containing zero or more substitution strings, which are replaced with `subst1` through `substN` in consecutive order.
- `subst1` … `substN`
- : JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output. See [Using string substitutions](/en-US/docs/Web/API/console#using_string_substitutions) for a description of how substitutions work.
See [Outputting text to the console](/en-US/docs/Web/API/console#outputting_text_to_the_console) in the documentation of the {{domxref("console")}} object for details.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.error()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#error)
- [Node.JS documentation for `console.error()`](https://nodejs.org/docs/latest/api/console.html#consoleerrordata-args)
- [Google Chrome's documentation for `console.error()`](https://developer.chrome.com/docs/devtools/console/api/#error)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/countreset_static/index.md | ---
title: "console: countReset() static method"
short-title: countReset()
slug: Web/API/console/countreset_static
page-type: web-api-instance-method
browser-compat: api.console.countReset_static
---
{{APIRef("Console API")}}
The **`console.countReset()`** static method resets counter used with {{domxref("console/count_static", "console.count()")}}.
{{AvailableInWorkers}}
## Syntax
```js-nolint
countReset()
countReset(label)
```
### Parameters
- `label` {{optional_inline}}
- : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0.
### Return value
None ({{jsxref("undefined")}}).
## Examples
For example, given code like this:
```js
let user = "";
function greet() {
console.count();
return `hi ${user}`;
}
user = "bob";
greet();
user = "alice";
greet();
greet();
console.count();
console.countReset();
```
Console output will look something like this:
```plain
"default: 1"
"default: 2"
"default: 3"
"default: 4"
"default: 0"
```
Note that the call to `console.counterReset()` resets the value of the default counter to zero.
If we pass the `user` variable as the `label` argument with the string "bob" to the first invocation of `console.count()`, and the string "alice" to the second:
```js
let user = "";
function greet() {
console.count(user);
return `hi ${user}`;
}
user = "bob";
greet();
user = "alice";
greet();
greet();
console.countReset("bob");
console.count("alice");
```
We will see output like this:
```plain
"bob: 1"
"alice: 1"
"alice: 2"
"bob: 0"
"alice: 3"
```
Resetting the value of the counter "bob" only changes the value of that counter. The value of "alice" is unchanged.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.countReset()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#countreset)
- [Node.JS documentation for `console.countReset()`](https://nodejs.org/docs/latest/api/console.html#consolecountresetlabel)
- [Google Chrome's documentation for `console.countReset()`](https://developer.chrome.com/docs/devtools/console/api/#countreset)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/dirxml_static/index.md | ---
title: "console: dirxml() static method"
short-title: dirxml()
slug: Web/API/console/dirxml_static
page-type: web-api-instance-method
browser-compat: api.console.dirxml_static
---
{{APIRef("Console API")}}
The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is not possible to display as an element the JavaScript Object view is shown instead. The output is presented as a hierarchical listing of expandable nodes that let you see the contents of child nodes.
## Syntax
```js-nolint
dirxml(object)
```
### Parameters
- `object`
- : A JavaScript object whose properties should be output.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.dirxml()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#dirxml)
- [Node.JS documentation for `console.dirxml()`](https://nodejs.org/docs/latest/api/console.html#consoledirxmldata)
- [Google Chrome's documentation for `console.dirxml()`](https://developer.chrome.com/docs/devtools/console/api/#dirxml)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/profile_static/index.md | ---
title: "console: profile() static method"
short-title: profile()
slug: Web/API/console/profile_static
page-type: web-api-instance-method
status:
- non-standard
browser-compat: api.console.profile_static
---
{{APIRef("Console API")}}{{Non-standard_header}}
The **`console.profile()`** static method starts recording a performance profile (for example, the [Firefox performance tool](https://firefox-source-docs.mozilla.org/devtools-user/performance/index.html)).
You can optionally supply an argument to name the profile and this then enables you to stop only that profile if multiple profiles being recorded. See {{domxref("console/profileEnd_static", "console.profileEnd()")}} to see how this argument is interpreted.
To stop recording call {{domxref("console/profileEnd_static", "console.profileEnd()")}}.
{{AvailableInWorkers}}
## Syntax
```js-nolint
profile(profileName)
```
### Parameters
- `profileName` {{Optional_Inline}}
- : The name to give the profile.
### Return value
None ({{jsxref("undefined")}}).
## Browser compatibility
{{Compat}}
## See also
- {{domxref("console/profileEnd_static", "console.profileEnd()")}}
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/group_static/index.md | ---
title: "console: group() static method"
short-title: group()
slug: Web/API/console/group_static
page-type: web-api-instance-method
browser-compat: api.console.group_static
---
{{APIRef("Console API")}}
The **`console.group()`** static method creates a new inline group in the [Web console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html) log, causing any subsequent console messages to be indented by an additional level, until {{domxref("console/groupend_static", "console.groupEnd()")}} is called.
{{AvailableInWorkers}}
## Syntax
```js-nolint
group()
group(label)
```
### Parameters
- `label` {{optional_inline}}
- : Label for the group.
### Return value
None ({{jsxref("undefined")}}).
## Examples
You can use nested groups to help organize your output by visually associating related messages. To create a new nested block, call `console.group()`. The `console.groupCollapsed()` method is similar, but the new block is collapsed and requires clicking a disclosure button to read it.
To exit the current group, call `console.groupEnd()`. For example, given this code:
```js
console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.log("Back to the outer level");
```
The output looks like this:

See [Using groups in the console](/en-US/docs/Web/API/console#using_groups_in_the_console) in the documentation of {{domxref("console")}} for more details.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("console/groupEnd_static", "console.groupEnd()")}}
- {{domxref("console/groupCollapsed_static", "console.groupCollapsed()")}}
- [Microsoft Edge's documentation for `console.group()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#group)
- [Node.JS documentation for `console.group()`](https://nodejs.org/docs/latest/api/console.html#consolegrouplabel)
- [Google Chrome's documentation for `console.group()`](https://developer.chrome.com/docs/devtools/console/api/#group)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/table_static/index.md | ---
title: "console: table() static method"
short-title: table()
slug: Web/API/console/table_static
page-type: web-api-instance-method
browser-compat: api.console.table_static
---
{{APIRef("Console API")}}
The **`console.table()`** static method displays tabular data as a table.
This function takes one mandatory argument `data`, which must be an array or an object, and one additional optional parameter `columns`.
It logs `data` as a table. Each element in the array (or enumerable property if `data` is an object) will be a row in the table.
The first column in the table will be labeled `(index)`. If `data` is an array, then its values will be the array indices. If `data` is an object, then its values will be the property names. Note that (in Firefox) `console.table` is limited to displaying 1000 rows (first row is the labeled index).
{{AvailableInWorkers}}
### Collections of primitive types
The `data` argument may be an array or an object.
```js
// an array of strings
console.table(["apples", "oranges", "bananas"]);
```
| (index) | Values |
| ------- | --------- |
| 0 | 'apples' |
| 1 | 'oranges' |
| 2 | 'bananas' |
```js
// an object whose properties are strings
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const me = new Person("Tyrone", "Jones");
console.table(me);
```
| (index) | Values |
| --------- | -------- |
| firstName | 'Tyrone' |
| lastName | 'Jones' |
### Collections of compound types
If the elements in the array, or properties in the object, are themselves arrays or objects, then their elements or properties are enumerated in the row, one per column:
```js
// an array of arrays
const people = [
["Tyrone", "Jones"],
["Janet", "Smith"],
["Maria", "Cruz"],
];
console.table(people);
```
| (index) | 0 | 1 |
| ------- | -------- | ------- |
| 0 | 'Tyrone' | 'Jones' |
| 1 | 'Janet' | 'Smith' |
| 2 | 'Maria' | 'Cruz' |
```js
// an array of objects
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const tyrone = new Person("Tyrone", "Jones");
const janet = new Person("Janet", "Smith");
const maria = new Person("Maria", "Cruz");
console.table([tyrone, janet, maria]);
```
Note that if the array contains objects, then the columns are labeled with the property name.
| (index) | firstName | lastName |
| ------- | --------- | -------- |
| 0 | 'Tyrone' | 'Jones' |
| 1 | 'Janet' | 'Smith' |
| 2 | 'Maria' | 'Cruz' |
```js
// an object whose properties are objects
const family = {};
family.mother = new Person("Janet", "Jones");
family.father = new Person("Tyrone", "Jones");
family.daughter = new Person("Maria", "Jones");
console.table(family);
```
| (index) | firstName | lastName |
| -------- | --------- | -------- |
| daughter | 'Maria' | 'Jones' |
| father | 'Tyrone' | 'Jones' |
| mother | 'Janet' | 'Jones' |
### Restricting the columns displayed
By default, `console.table()` lists all elements in each row. You can use the optional `columns` parameter to select a subset of columns to display:
```js
// an array of objects, logging only firstName
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const tyrone = new Person("Tyrone", "Jones");
const janet = new Person("Janet", "Smith");
const maria = new Person("Maria", "Cruz");
console.table([tyrone, janet, maria], ["firstName"]);
```
| (index) | firstName |
| ------- | --------- |
| 0 | 'Tyrone' |
| 1 | 'Janet' |
| 2 | 'Maria' |
### Sorting columns
You can sort the table by a particular column by clicking on that column's label.
## Syntax
```js-nolint
table(data)
table(data, columns)
```
### Parameters
- `data`
- : The data to display. This must be either an array or an object.
- `columns`
- : An array containing the names of columns to include in the output.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.table()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#table)
- [Node.JS documentation for `console.table()`](https://nodejs.org/docs/latest/api/console.html#consoletabletabulardata-properties)
- [Google Chrome's documentation for `console.table()`](https://developer.chrome.com/docs/devtools/console/api/#table)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/log_static/index.md | ---
title: "console: log() static method"
short-title: log()
slug: Web/API/console/log_static
page-type: web-api-instance-method
browser-compat: api.console.log_static
---
{{APIRef("Console API")}}
The **`console.log()`** static method outputs a message to the console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.
{{AvailableInWorkers}}
## Syntax
```js-nolint
log(obj1)
log(obj1, /* …, */ objN)
log(msg)
log(msg, subst1, /* …, */ substN)
```
### Parameters
- `obj1` … `objN`
- : A list of JavaScript objects to output. Objects are output in the order listed. Please be warned that if you log objects in the latest versions of Chrome and Firefox, what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console.
- `msg`
- : A JavaScript string containing zero or more substitution strings.
- `subst1` … `substN`
- : JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output.
See [Outputting text to the console](/en-US/docs/Web/API/console#outputting_text_to_the_console) in the documentation of {{domxref("console")}} for details.
### Return value
None ({{jsxref("undefined")}}).
## Logging objects
Information about an object is lazily retrieved. This means that the log message shows the content of an object at the time when it's first viewed, not when it was logged. For example:
```js
const obj = {};
console.log(obj);
obj.prop = 123;
```
This will output `{}`. However, if you expand the object's details, you will see `prop: 123`.
If you are going to mutate your object and you want to prevent the logged information from being updated, you can [deep-clone](/en-US/docs/Glossary/Deep_copy) the object before logging it. A common way is to {{jsxref("JSON.stringify()")}} and then {{jsxref("JSON.parse()")}} it:
```js
console.log(JSON.parse(JSON.stringify(obj)));
```
There are other alternatives that work in browsers, such as [`structuredClone()`](/en-US/docs/Web/API/structuredClone), which are more effective at cloning different types of objects.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.log()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#log)
- [Node.JS documentation for `console.log()`](https://nodejs.org/docs/latest/api/console.html#consolelogdata-args)
- [Google Chrome's documentation for `console.log()`](https://developer.chrome.com/docs/devtools/console/api/#log)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/info_static/index.md | ---
title: "console: info() static method"
short-title: info()
slug: Web/API/console/info_static
page-type: web-api-instance-method
browser-compat: api.console.info_static
---
{{APIRef("Console API")}}
The **`console.info()`** static method outputs an informational message to the console. In Firefox, a small "i" icon is displayed next to these items in the console's log.
{{AvailableInWorkers}}
## Syntax
```js-nolint
info(obj1)
info(obj1, /* …, */ objN)
info(msg)
info(msg, subst1, /* …, */ substN)
```
### Parameters
- `obj1` … `objN`
- : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console.
- `msg`
- : A JavaScript string containing zero or more substitution strings, which are replaced with `subst1` through `substN` in consecutive order.
- `subst1` … `substN`
- : JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output. See [Using string substitutions](/en-US/docs/Web/API/console#using_string_substitutions) for a description of how substitutions work.
See [Outputting text to the console](/en-US/docs/Web/API/console#outputting_text_to_the_console) in the documentation of the {{domxref("console")}} object for details.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.info()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#info)
- [Node.JS documentation for `console.info()`](https://nodejs.org/docs/latest/api/console.html#consoleinfodata-args)
- [Google Chrome's documentation for `console.info()`](https://developer.chrome.com/docs/devtools/console/api/#info)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/groupend_static/index.md | ---
title: "console: groupEnd() static method"
short-title: groupEnd()
slug: Web/API/console/groupend_static
page-type: web-api-instance-method
browser-compat: api.console.groupEnd_static
---
{{APIRef("Console API")}}
The **`console.groupEnd()`** static method exits the current inline group in the console. See [Using groups in the console](/en-US/docs/Web/API/console#using_groups_in_the_console) in the {{domxref("console")}} documentation for details and examples.
{{AvailableInWorkers}}
## Syntax
```js-nolint
groupEnd()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("console/group_static", "console.group()")}}
- {{domxref("console/groupCollapsed_static", "console.groupCollapsed()")}}
- [Microsoft Edge's documentation for `console.groupEnd()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#groupend)
- [Node.JS documentation for `console.groupEnd()`](https://nodejs.org/docs/latest/api/console.html#consolegroupend)
- [Google Chrome's documentation for `console.groupEnd()`](https://developer.chrome.com/docs/devtools/console/api/#groupend)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/count_static/index.md | ---
title: "console: count() static method"
short-title: count()
slug: Web/API/console/count_static
page-type: web-api-instance-method
browser-compat: api.console.count_static
---
{{APIRef("Console API")}}
The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called.
{{AvailableInWorkers}}
## Syntax
```js-nolint
count()
count(label)
```
### Parameters
- `label` {{Optional_Inline}}
- : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label.
### Return value
None ({{jsxref("undefined")}}).
## Examples
For example, given code like this:
```js
let user = "";
function greet() {
console.count();
return `hi ${user}`;
}
user = "bob";
greet();
user = "alice";
greet();
greet();
console.count();
```
Console output will look something like this:
```plain
"default: 1"
"default: 2"
"default: 3"
"default: 4"
```
The label is displayed as `default` because no explicit label was supplied.
If we pass the `user` variable as the `label` argument to the first invocation of `console.count()`, and the string "alice" to the second:
```js
let user = "";
function greet() {
console.count(user);
return `hi ${user}`;
}
user = "bob";
greet();
user = "alice";
greet();
greet();
console.count("alice");
```
We will see output like this:
```plain
"bob: 1"
"alice: 1"
"alice: 2"
"alice: 3"
```
We're now maintaining separate counts based only on the value of `label`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.count()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#count)
- [Node.JS documentation for `console.count()`](https://nodejs.org/docs/latest/api/console.html#consolecountlabel)
- [Google Chrome's documentation for `console.count()`](https://developer.chrome.com/docs/devtools/console/api/#count)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/time_static/index.md | ---
title: "console: time() static method"
short-title: time()
slug: Web/API/console/time_static
page-type: web-api-instance-method
browser-compat: api.console.time_static
---
{{APIRef("Console API")}}
The **`console.time()`** static method starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call {{domxref("console/timeEnd_static", "console.timeEnd()")}} with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.
See [Timers](/en-US/docs/Web/API/console#timers) in the {{domxref("console")}} documentation for details and examples.
{{AvailableInWorkers}}
## Syntax
```js-nolint
time()
time(label)
```
### Parameters
- `label` {{optional_inline}}
- : A string representing the name to give the new timer. This will identify the timer; use the same name when calling {{domxref("console/timeEnd_static", "console.timeEnd()")}} to stop the timer and get the time output to the console. If omitted, the label `"default"` is used.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("console/timeEnd_static", "console.timeEnd()")}}
- {{domxref("console/timeLog_static", "console.timeLog()")}}
- [Microsoft Edge's documentation for `console.time()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#time)
- [Node.JS documentation for `console.time()`](https://nodejs.org/docs/latest/api/console.html#consoletimelabel)
- [Google Chrome's documentation for `console.time()`](https://developer.chrome.com/docs/devtools/console/api/#time)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/debug_static/index.md | ---
title: "console: debug() static method"
short-title: debug()
slug: Web/API/console/debug_static
page-type: web-api-instance-method
browser-compat: api.console.debug_static
---
{{APIRef("Console API")}}
The **`console.debug()`** static method outputs a message to the console at the "debug" log level. The message is only displayed to the user if the console is configured to display debug output. In most cases, the log level is configured within the console UI. This log level might correspond to the `Debug` or `Verbose` log level.
{{AvailableInWorkers}}
## Syntax
```js-nolint
debug(obj1)
debug(obj1, /* …, */ objN)
debug(msg)
debug(msg, subst1, /* …, */ substN)
```
### Parameters
- `obj1` … `objN`
- : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console.
- `msg`
- : A JavaScript string containing zero or more substitution strings, which are replaced with `subst1` through `substN` in consecutive order.
- `subst1` … `substN`
- : JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output. See [Using string substitutions](/en-US/docs/Web/API/console#using_string_substitutions) for a description of how substitutions work.
See [Outputting text to the console](/en-US/docs/Web/API/console#outputting_text_to_the_console) in the documentation of the {{domxref("console")}} object for details.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.debug()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#debug)
- [Node.JS documentation for `console.debug()`](https://nodejs.org/docs/latest/api/console.html#consoledebugdata-args)
- [Google Chrome's documentation for `console.debug()`](https://developer.chrome.com/docs/devtools/console/api/#debug)
| 0 |
data/mdn-content/files/en-us/web/api/console | data/mdn-content/files/en-us/web/api/console/trace_static/index.md | ---
title: "console: trace() static method"
short-title: trace()
slug: Web/API/console/trace_static
page-type: web-api-instance-method
browser-compat: api.console.trace_static
---
{{APIRef("Console API")}}
The **`console.trace()`** static method outputs a stack trace to the console.
{{AvailableInWorkers}}
> **Note:** In some browsers, `console.trace()` may also output the sequence of calls and asynchronous events leading to the current `console.trace()` which are not on the call stack — to help identify the origin of the current event evaluation loop.
See [Stack traces](/en-US/docs/Web/API/console#stack_traces) in the {{domxref("console")}} documentation for details and examples.
## Syntax
```js-nolint
trace()
trace(object1, /* …, */ objectN)
```
### Parameters
- `objects` {{optional_inline}}
- : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the {{domxref("console/log_static", "console.log()")}} method.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
function foo() {
function bar() {
console.trace();
}
bar();
}
foo();
```
In the console, the following trace will be displayed:
```plain
bar
foo
<anonymous>
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Microsoft Edge's documentation for `console.trace()`](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/api#trace)
- [Node.JS documentation for `console.trace()`](https://nodejs.org/docs/latest/api/console.html#consoletracemessage-args)
- [Google Chrome's documentation for `console.trace()`](https://developer.chrome.com/docs/devtools/console/api/#trace)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/background_synchronization_api/index.md | ---
title: Background Synchronization API
slug: Web/API/Background_Synchronization_API
page-type: web-api-overview
status:
- experimental
browser-compat:
- api.SyncManager
- api.ServiceWorkerGlobalScope.sync_event
spec-urls: https://wicg.github.io/background-sync/spec/
---
{{DefaultAPISidebar("Background Sync")}}{{Securecontext_Header}}{{SeeCompatTable}}
The **Background Synchronization API** enables a web app to defer tasks so that they can be run in a [service worker](/en-US/docs/Web/API/Service_Worker_API) once the user has a stable network connection.
## Concepts and usage
The Background Synchronization API allows web applications to defer server synchronization work to their service worker to handle at a later time, if the device is offline. Uses may include sending requests in the background if they couldn't be sent while the application was being used.
For example, an email client application could let its users compose and send messages at any time, even when the device has no network connection. The application frontend just registers a sync request and the service worker gets alerted when the network is present again and handles the sync.
The {{domxref('SyncManager')}} interface is available through {{domxref('ServiceWorkerRegistration.sync')}}. A unique tag identifier is set to 'name' the sync event, which can then be listened for within the {{domxref('ServiceWorker')}} script. Once the event is received you can then run any functionality available, such as sending requests to the server.
As this API relies on service workers, functionality provided by this API is only available in a secure context.
## Interfaces
- {{domxref('SyncManager')}} {{Experimental_Inline}}
- : Registers tasks to be run in a service worker at a later time with network connectivity. These tasks are referred to as _background sync requests_.
- {{domxref('SyncEvent')}} {{Experimental_Inline}}
- : Represents a synchronization event, sent to the [global scope](/en-US/docs/Web/API/ServiceWorkerGlobalScope) of a {{domxref('ServiceWorker')}}. It provides a way to run tasks in the service worker once the device has network connectivity.
### Extensions to other interfaces
The following additions to the [Service Worker API](/en-US/docs/Web/API/Service_Worker_API) provide an entry point for setting up background synchronization.
- {{domxref("ServiceWorkerRegistration.sync")}} {{ReadOnlyInline}}
- : Returns a reference to the {{domxref("SyncManager")}} interface for registering tasks to run once the device has network connectivity.
- {{domxref("ServiceWorkerGlobalScope/sync_event", "sync")}} event
- : An event handler fired whenever a {{domxref("ServiceWorkerGlobalScope/sync_event", "sync")}} event occurs. This happens as soon as the network becomes available.
## Examples
The following examples show how to use the interface.
### Requesting a background sync
The following asynchronous function registers a background sync from a browsing context:
```js
async function syncMessagesLater() {
const registration = await navigator.serviceWorker.ready;
try {
await registration.sync.register("sync-messages");
} catch {
console.log("Background Sync could not be registered!");
}
}
```
### Verifying a background sync by Tag
This code checks to see if a background sync task with a given tag is registered.
```js
navigator.serviceWorker.ready.then((registration) => {
registration.sync.getTags().then((tags) => {
if (tags.includes("sync-messages"))
console.log("Messages sync already requested");
});
});
```
### Listening for a background sync within a Service Worker
The following example shows how to respond to a background sync event in the service worker.
```js
self.addEventListener("sync", (event) => {
if (event.tag === "sync-messages") {
event.waitUntil(sendOutboxMessages());
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Introducing Background Sync](https://developer.chrome.com/blog/background-sync/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/eventtarget/index.md | ---
title: EventTarget
slug: Web/API/EventTarget
page-type: web-api-interface
browser-compat: api.EventTarget
---
{{ApiRef("DOM")}}
The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them.
In other words, any target of events implements the three methods associated with this interface.
{{domxref("Element")}}, and its children, as well as {{domxref("Document")}} and {{domxref("Window")}}, are the most common event targets,
but other objects can be event targets, too.
For example {{domxref("IDBRequest")}}, {{domxref("AudioNode")}}, and {{domxref("AudioContext")}} are also event targets.
Many event targets (including elements, documents, and windows) also support setting [event handlers](/en-US/docs/Web/Events/Event_handlers) via `onevent` properties and attributes.
{{InheritanceDiagram}}
## Constructor
- {{domxref("EventTarget.EventTarget()", "EventTarget()")}}
- : Creates a new `EventTarget` object instance.
## Instance methods
- {{domxref("EventTarget.addEventListener()")}}
- : Registers an event handler of a specific event type on the `EventTarget`.
- {{domxref("EventTarget.removeEventListener()")}}
- : Removes an event listener from the `EventTarget`.
- {{domxref("EventTarget.dispatchEvent()")}}
- : Dispatches an event to this `EventTarget`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Event reference](/en-US/docs/Web/Events) – the events available in the platform.
- [Introduction to events](/en-US/docs/Learn/JavaScript/Building_blocks/Events)
- {{domxref("Event")}} interface
| 0 |
data/mdn-content/files/en-us/web/api/eventtarget | data/mdn-content/files/en-us/web/api/eventtarget/removeeventlistener/index.md | ---
title: "EventTarget: removeEventListener() method"
short-title: removeEventListener()
slug: Web/API/EventTarget/removeEventListener
page-type: web-api-instance-method
browser-compat: api.EventTarget.removeEventListener
---
{{APIRef("DOM")}}
The **`removeEventListener()`** method of the {{domxref("EventTarget")}} interface
removes an event listener previously registered with {{domxref("EventTarget.addEventListener()")}} from the target.
The event listener to be removed is identified using a combination of the event type,
the event listener function itself, and various optional options that may affect the matching process;
see [Matching event listeners for removal](#matching_event_listeners_for_removal).
Calling `removeEventListener()` with arguments that do not identify any
currently registered [event listener](/en-US/docs/Web/API/EventTarget/addEventListener#the_event_listener_callback) on the `EventTarget` has no
effect.
If an [event listener](/en-US/docs/Web/API/EventTarget/addEventListener#the_event_listener_callback) is removed from an {{domxref("EventTarget")}} while another listener of the target is processing an event, it will not be triggered by the event. However, it can be reattached.
> **Warning:** If a listener is registered twice, one with the _capture_ flag set and one without, you must remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa.
Event listeners can also be removed by passing an {{domxref("AbortSignal")}} to an {{domxref("EventTarget/addEventListener()", "addEventListener()")}} and then later calling {{domxref("AbortController/abort()", "abort()")}} on the controller owning the signal.
## Syntax
```js-nolint
removeEventListener(type, listener)
removeEventListener(type, listener, options)
removeEventListener(type, listener, useCapture)
```
### Parameters
- `type`
- : A string which specifies the type of event for which to remove an event listener.
- `listener`
- : The [event listener](/en-US/docs/Web/API/EventTarget/addEventListener#the_event_listener_callback) function of the event handler to remove from the
event target.
- `options` {{optional_inline}}
- : An options object that specifies characteristics about the event listener.
The available options are:
- `capture`: A boolean value that specifies whether the [event listener](/en-US/docs/Web/API/EventTarget/addEventListener#the_event_listener_callback) to be removed is registered as a capturing listener or not. If this parameter is absent, the default value `false` is assumed.
- `useCapture` {{optional_inline}}
- : A boolean value that specifies whether the [event listener](/en-US/docs/Web/API/EventTarget/addEventListener#the_event_listener_callback) to be removed is registered as a
capturing listener or not. If this parameter is absent, the default value `false` is assumed.
### Return value
None.
### Matching event listeners for removal
Given an event listener previously added by calling
{{domxref("EventTarget.addEventListener", "addEventListener()")}}, you may eventually
come to a point at which you need to remove it. Obviously, you need to specify the same
`type` and `listener` parameters to
`removeEventListener()`. But what about the `options`
or `useCapture` parameters?
While `addEventListener()` will let you add the same listener more than once
for the same type if the options are different, the only option
`removeEventListener()` checks is the
`capture`/`useCapture` flag. Its value must
match for `removeEventListener()` to match, but the other values don't.
For example, consider this call to `addEventListener()`:
```js
element.addEventListener("mousedown", handleMouseDown, true);
```
Now consider each of these two calls to `removeEventListener()`:
```js
element.removeEventListener("mousedown", handleMouseDown, false); // Fails
element.removeEventListener("mousedown", handleMouseDown, true); // Succeeds
```
The first call fails because the value of `useCapture` doesn't match. The
second succeeds, since `useCapture` matches up.
Now consider this:
```js
element.addEventListener("mousedown", handleMouseDown, { passive: true });
```
Here, we specify an `options` object in which
`passive` is set to `true`, while the other options are left to
the default value of `false`.
Now look at each of these calls to `removeEventListener()` in turn. Any of
them in which `capture` or `useCapture` is
`true` fail; all others succeed.
Only the `capture` setting matters to `removeEventListener()`.
```js
element.removeEventListener("mousedown", handleMouseDown, { passive: true }); // Succeeds
element.removeEventListener("mousedown", handleMouseDown, { capture: false }); // Succeeds
element.removeEventListener("mousedown", handleMouseDown, { capture: true }); // Fails
element.removeEventListener("mousedown", handleMouseDown, { passive: false }); // Succeeds
element.removeEventListener("mousedown", handleMouseDown, false); // Succeeds
element.removeEventListener("mousedown", handleMouseDown, true); // Fails
```
It's worth noting that some browser releases have been inconsistent on this, and unless
you have specific reasons otherwise, it's probably wise to use the same values used for
the call to `addEventListener()` when calling
`removeEventListener()`.
## Example
This example shows how to add a `mouseover`-based event listener that
removes a `click`-based event listener.
```js
const body = document.querySelector("body");
const clickTarget = document.getElementById("click-target");
const mouseOverTarget = document.getElementById("mouse-over-target");
let toggle = false;
function makeBackgroundYellow() {
body.style.backgroundColor = toggle ? "white" : "yellow";
toggle = !toggle;
}
clickTarget.addEventListener("click", makeBackgroundYellow, false);
mouseOverTarget.addEventListener("mouseover", () => {
clickTarget.removeEventListener("click", makeBackgroundYellow, false);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("EventTarget.addEventListener()")}}
| 0 |
data/mdn-content/files/en-us/web/api/eventtarget | data/mdn-content/files/en-us/web/api/eventtarget/dispatchevent/index.md | ---
title: "EventTarget: dispatchEvent() method"
short-title: dispatchEvent()
slug: Web/API/EventTarget/dispatchEvent
page-type: web-api-instance-method
browser-compat: api.EventTarget.dispatchEvent
---
{{APIRef("DOM")}}
The **`dispatchEvent()`** method of the {{domxref("EventTarget")}} sends an {{domxref("Event")}} to the object, (synchronously) invoking the affected
event listeners in the appropriate order. The normal event processing
rules (including the capturing and optional bubbling phase) also apply to events
dispatched manually with `dispatchEvent()`.
Calling `dispatchEvent()` is the last step to _firing an event_. The event
should have already been created and initialized using an {{domxref("Event/Event", "Event()")}} constructor.
> **Note:** When calling this method, the {{domxref("Event.target")}} property is initialized to the current `EventTarget`.
Unlike "native" events, which are fired by the browser and invoke event handlers
asynchronously via the [event loop](/en-US/docs/Web/JavaScript/Event_loop),
`dispatchEvent()` invokes event handlers _synchronously_. All applicable event
handlers are called and return before `dispatchEvent()` returns.
## Syntax
```js-nolint
dispatchEvent(event)
```
### Parameter
- `event`
- : The {{domxref("Event")}} object to dispatch. Its {{domxref("Event.target")}} property will be set to the current {{domxref("EventTarget")}}.
### Return value
`false` if `event` is cancelable, and at least one of the event handlers which received `event` called {{domxref("Event.preventDefault()")}}. Otherwise `true`.
### Exceptions
- `InvalidStateError` {{domxref("DomException")}}
- : Thrown if the event's type was not specified during event initialization.
> **Warning:** Exceptions thrown by event handlers are reported as uncaught exceptions. The event
> handlers run on a nested callstack; they block the caller until they complete, but
> exceptions do not propagate to the caller.
## Example
See [Creating and triggering events](/en-US/docs/Web/Events/Creating_and_triggering_events).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [Event object reference](/en-US/docs/Web/API/Event)
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.