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/webgl_lose_context | data/mdn-content/files/en-us/web/api/webgl_lose_context/losecontext/index.md | ---
title: "WEBGL_lose_context: loseContext() method"
short-title: loseContext()
slug: Web/API/WEBGL_lose_context/loseContext
page-type: webgl-extension-method
browser-compat: api.WEBGL_lose_context.loseContext
---
{{APIRef("WebGL")}}
The **WEBGL_lose_context.loseContext()** method is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and allows you to simulate losing
the context of a {{domxref("WebGLRenderingContext")}} context.
It triggers the steps described in the WebGL specification for handling context lost.
The context will remain lost until {{domxref("WEBGL_lose_context.restoreContext()")}} is
called.
## Syntax
```js-nolint
loseContext()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
With this method, you can simulate the
[`webglcontextlost`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event)
event:
```js
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");
canvas.addEventListener(
"webglcontextlost",
(e) => {
console.log(e);
},
false,
);
gl.getExtension("WEBGL_lose_context").loseContext();
// WebGLContextEvent event with type "webglcontextlost" is logged.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.isContextLost()")}}
- Events:
[`webglcontextlost`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event),
[`webglcontextrestored`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextrestored_event),
[`webglcontextcreationerror`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextcreationerror_event)
| 0 |
data/mdn-content/files/en-us/web/api/webgl_lose_context | data/mdn-content/files/en-us/web/api/webgl_lose_context/restorecontext/index.md | ---
title: "WEBGL_lose_context: restoreContext() method"
short-title: restoreContext()
slug: Web/API/WEBGL_lose_context/restoreContext
page-type: webgl-extension-method
browser-compat: api.WEBGL_lose_context.restoreContext
---
{{APIRef("WebGL")}}
The **WEBGL_lose_context.restoreContext()** method is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and allows you to simulate
restoring the context of a {{domxref("WebGLRenderingContext")}} object.
## Syntax
```js-nolint
restoreContext()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
Browsers may not report WebGL errors by default. WebGL's error reporting works by calling {{domxref("WEBGLRenderingContext.getError", "getError()")}} and checking for errors. The following exceptions may be thrown:
- `INVALID_OPERATION`
- : Thrown if the context was not lost.
## Examples
With this method, you can simulate the
[`webglcontextrestored`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextrestored_event)
event:
```js
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");
canvas.addEventListener(
"webglcontextrestored",
(e) => {
console.log(e);
},
false,
);
gl.getExtension("WEBGL_lose_context").restoreContext();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.isContextLost()")}}
- Events:
[`webglcontextlost`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event),
[`webglcontextrestored`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextrestored_event),
[`webglcontextcreationerror`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextcreationerror_event)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgstringlist/index.md | ---
title: SVGStringList
slug: Web/API/SVGStringList
page-type: web-api-interface
browser-compat: api.SVGStringList
---
{{APIRef("SVG")}}
## SVG string list interface
The `SVGStringList` defines a list of strings.
An `SVGStringList` object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown.
### Interface overview
<table class="no-markdown">
<tbody>
<tr>
<th scope="row">Also implement</th>
<td><em>None</em></td>
</tr>
<tr>
<th scope="row">Methods</th>
<td>
<ul>
<li><code>void clear()</code></li>
<li>
string
<code>initialize(string <em>newItem</em>)</code>
</li>
<li>
string
<code>getItem(number <em>index</em>)</code>
</li>
<li>
string
<code>insertItemBefore(string <em>newItem</em>, number <em>index</em>)</code>
</li>
<li>
string
<code>replaceItem(string <em>newItem</em>,
number <em>index</em>)</code>
</li>
<li>
string
<code>removeItem(number <em>index</em>)</code>
</li>
<li>
string
<code>appendItem(string <em>newItem</em>)</code>
</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">Properties</th>
<td>
<ul>
<li>readonly unsigned long <code>numberOfItems</code></li>
<li>
readonly unsigned long
<code>length</code> {{non-standard_inline}}
</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">Normative document</th>
<td>
<a href="https://www.w3.org/TR/SVG11/types.html#InterfaceSVGStringList"
>SVG 1.1 (2nd Edition)</a
>
</td>
</tr>
</tbody>
</table>
## Instance properties
<table class="no-markdown">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>numberOfItems</code></td>
<td><code>unsigned long</code></td>
<td>The number of items in the list.</td>
</tr>
<tr>
<td><code>length</code></td>
<td><code>unsigned long</code></td>
<td>
A mirror of the value in <code>numberOfItems</code>, for consistency
with other interfaces. {{non-standard_inline}}
</td>
</tr>
</tbody>
</table>
## Instance methods
<table class="no-markdown">
<thead>
<tr>
<th>Name & Arguments</th>
<th>Return</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code><strong>clear</strong>()</code>
</td>
<td><em>void</em></td>
<td>
<p>
Clears all existing current items from the list, with the result being
an empty list.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{domxref("DOMException")}} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code><strong>initialize</strong>(string <em>newItem</em>)</code>
</td>
<td>string</td>
<td>
<p>
Clears all existing current items from the list and re-initializes the
list to hold the single item specified by the parameter. If the
inserted item is already in a list, it is removed from its previous
list before it is inserted into this list. The inserted item is the
item itself and not a copy. The return value is the item inserted into
the list.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{domxref("DOMException")}} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code><strong>getItem</strong>(number <em>index</em>)</code>
</td>
<td>string</td>
<td>
<p>
Returns the specified item from the list. The returned item is the
item itself and not a copy. Any changes made to the item are
immediately reflected in the list. The first item is number 0.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{domxref("DOMException")}} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code
><strong>insertItemBefore</strong>(string <em>newItem</em>, number <em>index</em>)</code>
</td>
<td>string</td>
<td>
<p>
Inserts a new item into the list at the specified position. The first
item is number 0. If <code>newItem</code> is already in a list, it is
removed from its previous list before it is inserted into this list.
The inserted item is the item itself and not a copy. If the item is
already in this list, note that the index of the item to insert before
is before the removal of the item. If the <code>index</code> is equal
to 0, then the new item is inserted at the front of the list. If the
index is greater than or equal to <code>numberOfItems</code>, then the
new item is appended to the end of the list.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{domxref("DOMException")}} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code
><strong>replaceItem</strong>(string <em>newItem</em>, number <em>index</em>)</code
>
</td>
<td>string</td>
<td>
<p>
Replaces an existing item in the list with a new item. If
<code>newItem</code> is already in a list, it is removed from its
previous list before it is inserted into this list. The inserted item
is the item itself and not a copy. If the item is already in this
list, note that the index of the item to replace is before the removal
of the item.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{domxref("DOMException")}} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
<li>
a {{domxref("DOMException")}} with code
<code>INDEX_SIZE_ERR</code> is raised if the index number is greater
than or equal to <code>numberOfItems</code>.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code
><strong>removeItem</strong>(in unsigned long <em>index</em>)</code
>
</td>
<td>string</td>
<td>
<p>Removes an existing item from the list.</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{domxref("DOMException")}} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
<li>
a {{domxref("DOMException")}} with code
<code>INDEX_SIZE_ERR</code> is raised if the index number is greater
than or equal to <code>numberOfItems</code>.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code
><strong>appendItem</strong>(string <em>newItem</em>)</code
>
</td>
<td>string</td>
<td>
<p>
Inserts a new item at the end of the list. If <code>newItem</code> is
already in a list, it is removed from its previous list before it is
inserted into this list. The inserted item is the item itself and not
a copy.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{domxref("DOMException")}} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
</ul>
</td>
</tr>
</tbody>
</table>
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/file/index.md | ---
title: File
slug: Web/API/File
page-type: web-api-interface
browser-compat: api.File
---
{{APIRef("File API")}}{{AvailableInWorkers}}
The **`File`** interface provides information about files and allows JavaScript in a web page to access their content.
`File` objects are generally retrieved from a {{DOMxRef("FileList")}} object returned as a result of a user selecting files using the {{HTMLElement("input")}} element, or from a drag and drop operation's {{DOMxRef("DataTransfer")}} object.
A `File` object is a specific kind of {{DOMxRef("Blob")}}, and can be used in any context that a Blob can. In particular, {{DOMxRef("FileReader")}}, {{DOMxRef("URL.createObjectURL_static", "URL.createObjectURL()")}}, {{DOMxRef("createImageBitmap()")}}, the [`body`](/en-US/docs/Web/API/fetch#body) option to {{domxref("fetch()")}}, and {{DOMxRef("XMLHttpRequest", "", "send()")}} accept both `Blob`s and `File`s.
See [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications) for more information and examples.
{{InheritanceDiagram}}
## Constructor
- {{DOMxRef("File.File", "File()")}}
- : Returns a newly constructed `File`.
## Instance properties
_The `File` interface also inherits properties from the {{DOMxRef("Blob")}} interface._
- {{DOMxRef("File.lastModified")}} {{ReadOnlyInline}}
- : Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight).
- {{DOMxRef("File.lastModifiedDate")}} {{Deprecated_Inline}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : Returns the last modified {{JSxRef("Date")}} of the file referenced by the `File` object.
- {{DOMxRef("File.name")}} {{ReadOnlyInline}}
- : Returns the name of the file referenced by the `File` object.
- {{DOMxRef("File.webkitRelativePath")}} {{ReadOnlyInline}}
- : Returns the path the URL of the {{DOMxRef("File")}} is relative to.
## Instance methods
_The `File` interface also inherits methods from the {{DOMxRef("Blob")}} interface._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications)
- {{DOMxRef("FileReader")}}
| 0 |
data/mdn-content/files/en-us/web/api/file | data/mdn-content/files/en-us/web/api/file/name/index.md | ---
title: "File: name property"
short-title: name
slug: Web/API/File/name
page-type: web-api-instance-property
browser-compat: api.File.name
---
{{APIRef("File API")}}{{AvailableInWorkers}}
The **`name`** read-only property of the {{domxref("File")}} interface returns the name of the file represented by a {{domxref("File")}} object. For security
reasons, the path is excluded from this property.
## Value
A string, containing the name of the file without path, such as "My Resume.rtf".
## Examples
### HTML
```html
<input type="file" id="filepicker" multiple />
<div>
<p>List of selected files:</p>
<ul id="output"></ul>
</div>
```
### JavaScript
```js
const output = document.getElementById("output");
const filepicker = document.getElementById("filepicker");
filepicker.addEventListener("change", (event) => {
const files = event.target.files;
output.textContent = "";
for (const file of files) {
const li = document.createElement("li");
li.textContent = file.name;
output.appendChild(li);
}
});
```
### Result
{{EmbedLiveSample('Examples')}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications)
| 0 |
data/mdn-content/files/en-us/web/api/file | data/mdn-content/files/en-us/web/api/file/webkitrelativepath/index.md | ---
title: "File: webkitRelativePath property"
short-title: webkitRelativePath
slug: Web/API/File/webkitRelativePath
page-type: web-api-instance-property
browser-compat: api.File.webkitRelativePath
---
{{APIRef("File API")}}{{AvailableInWorkers}}
The **`webkitRelativePath`** read-only property of the {{domxref("File")}} interface
contains a string which specifies the file's path relative to the
directory selected by the user in an {{HTMLElement("input")}} element with its
[`webkitdirectory`](/en-US/docs/Web/HTML/Element/input#webkitdirectory) attribute set.
## Value
A string containing the path of the file relative to the ancestor
directory the user selected.
## Example
In this example, a directory picker is presented which lets the user choose one or more
directories. When the {{domxref("HTMLElement/change_event", "change")}} event occurs, a list of all files contained
within the selected directory hierarchies is generated and displayed.
### HTML
```html
<input type="file" id="filepicker" name="fileList" webkitdirectory multiple />
<output id="output"></output>
```
```css hidden
output {
display: block;
white-space: pre-wrap;
}
```
### JavaScript
```js
const output = document.getElementById("output");
const filepicker = document.getElementById("filepicker");
filepicker.addEventListener("change", (event) => {
const files = event.target.files;
for (const file of files) {
output.textContent += `${file.webkitRelativePath}\n`;
}
});
```
### Result
{{EmbedLiveSample('Example')}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- {{domxref("HTMLInputElement.webkitEntries")}}
- {{domxref("HTMLInputElement.webkitdirectory")}}
| 0 |
data/mdn-content/files/en-us/web/api/file | data/mdn-content/files/en-us/web/api/file/lastmodifieddate/index.md | ---
title: "File: lastModifiedDate property"
short-title: lastModifiedDate
slug: Web/API/File/lastModifiedDate
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.File.lastModifiedDate
---
{{APIRef("File API")}}{{AvailableInWorkers}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`lastModifiedDate`** read-only property of the {{domxref("File")}} interface returns the last modified date of the file. Files without a known last modified date return the current date.
## Value
A [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object indicating the date and time at which the file was last modified.
## Examples
```js
// fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput">
const fileInput = document.getElementById("myfileinput");
for (const file of fileInput.files) {
console.log(
`${file.name} has a last modified date of ${file.lastModifiedDate}`,
);
}
```
## Reduced time precision
To offer protection against timing attacks and {{glossary("fingerprinting")}}, the precision of `someFile.lastModifiedDate.getTime()` might get rounded depending on browser settings.
In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms.
```js
// reduced time precision (2ms) in Firefox 60
someFile.lastModifiedDate.getTime();
// 1519211809934
// 1519211810362
// 1519211811670
// …
// reduced time precision with `privacy.resistFingerprinting` enabled
someFile.lastModifiedDate.getTime();
// 1519129853500
// 1519129858900
// 1519129864400
// …
```
In Firefox, you can also enable `privacy.resistFingerprinting`, the precision will be 100ms or the value of `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever is larger.
## Specifications
_Though present in early draft of the File API spec, this property has been removed from it and is now non-standard. Use {{domxref("File.lastModified")}} instead._
## Browser compatibility
{{Compat}}
## See also
- {{domxref("File")}}
| 0 |
data/mdn-content/files/en-us/web/api/file | data/mdn-content/files/en-us/web/api/file/file/index.md | ---
title: "File: File() constructor"
short-title: File()
slug: Web/API/File/File
page-type: web-api-constructor
browser-compat: api.File.File
---
{{APIRef("File API")}}{{AvailableInWorkers}}
The **`File()`** constructor creates a new {{domxref("File")}}
object instance.
## Syntax
```js-nolint
new File(fileBits, fileName)
new File(fileBits, fileName, options)
```
### Parameters
- `fileBits`
- : An [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol)
object such as an {{jsxref("Array")}}, having {{jsxref("ArrayBuffer")}}s,
{{jsxref("TypedArray")}}s, {{jsxref("DataView")}}s, {{domxref("Blob")}}s, strings,
or a mix of any of such elements, that will be put inside the {{domxref("File")}}.
Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings.
- `fileName`
- : A string representing the file name or the path to the file.
- `options` {{optional_inline}}
- : An options object containing optional attributes for the file. Available options are
as follows:
- `type` {{optional_inline}}
- : A string representing the MIME type of the
content that will be put into the file. Defaults to a value of `""`.
- `endings` {{optional_inline}}
- : How to interpret newline characters (`\n`) within the contents, if
the data is text. The default value, `transparent`, copies newline
characters into the blob without changing them. To convert newlines to the host
system's native convention, specify the value `native`.
- `lastModified` {{optional_inline}}
- : A number representing the number of milliseconds
between the Unix time epoch and when the file was last modified. Defaults to a
value of {{jsxref("Date.now()")}}.
## Examples
```js
const file = new File(["foo"], "foo.txt", {
type: "text/plain",
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("FileReader")}}
- {{domxref("Blob")}}
| 0 |
data/mdn-content/files/en-us/web/api/file | data/mdn-content/files/en-us/web/api/file/lastmodified/index.md | ---
title: "File: lastModified property"
short-title: lastModified
slug: Web/API/File/lastModified
page-type: web-api-instance-property
browser-compat: api.File.lastModified
---
{{APIRef("File API")}}{{AvailableInWorkers}}
The **`lastModified`** read-only property of the {{domxref("File")}} interface provides the
last modified date of the file as the number of milliseconds since the Unix
epoch (January 1, 1970 at midnight). Files without a known last modified date return the
current date.
## Value
A number that represents the number of milliseconds since the Unix epoch.
## Examples
The example below will loop through the files you choose, and print whether each file was modified within the past year.
### HTML
```html
<input type="file" id="filepicker" name="fileList" multiple />
<output id="output"></output>
```
```css hidden
output {
display: block;
white-space: pre-wrap;
}
```
### JavaScript
```js
const output = document.getElementById("output");
const filepicker = document.getElementById("filepicker");
filepicker.addEventListener("change", (event) => {
const files = event.target.files;
const now = new Date();
output.textContent = "";
for (const file of files) {
const date = new Date(file.lastModified);
// true if the file hasn't been modified for more than 1 year
const stale = now.getTime() - file.lastModified > 31_536_000_000;
output.textContent += `${file.name} is ${
stale ? "stale" : "fresh"
} (${date}).\n`;
}
});
```
### Result
{{EmbedLiveSample('Examples')}}
### Dynamically created files
If a File is created dynamically, the last modified time can be supplied in the
{{domxref("File.File()", "new File()")}} constructor function. If it is missing,
`lastModified` inherits the current time from {{jsxref("Date.now()")}} at the
moment the `File` object gets created.
```js
const fileWithDate = new File([], "file.bin", {
lastModified: new Date(2017, 1, 1),
});
console.log(fileWithDate.lastModified); // returns 1485903600000
const fileWithoutDate = new File([], "file.bin");
console.log(fileWithoutDate.lastModified); // returns current time
```
## Reduced time precision
To offer protection against timing attacks and {{glossary("fingerprinting")}}, the precision of
`someFile.lastModified` might get rounded depending on browser settings.
In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by
default and defaults to 20us in Firefox 59; in 60 it will be 2ms.
```js
// reduced time precision (2ms) in Firefox 60
someFile.lastModified;
// 1519211809934
// 1519211810362
// 1519211811670
// …
// reduced time precision with `privacy.resistFingerprinting` enabled
someFile.lastModified;
// 1519129853500
// 1519129858900
// 1519129864400
// …
```
In Firefox, if you enable `privacy.resistFingerprinting`, the
precision will be 100ms or the value of
`privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever
is larger.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("File")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/performancelongtasktiming/index.md | ---
title: PerformanceLongTaskTiming
slug: Web/API/PerformanceLongTaskTiming
page-type: web-api-interface
status:
- experimental
browser-compat: api.PerformanceLongTaskTiming
---
{{SeeCompatTable}}{{APIRef("Performance API")}}
The **`PerformanceLongTaskTiming`** interface provides information about tasks that occupy the UI thread for 50 milliseconds or more.
## Description
Long tasks that block the main thread for 50ms or more cause, among other issues:
- Delayed {{glossary("Time to interactive")}} (TTI).
- High/variable input latency.
- High/variable event handling latency.
- Janky animations and scrolling.
A long task is any uninterrupted period where the main UI thread is busy for 50ms or longer. Common examples include:
- Long-running event handlers.
- Expensive reflows and other re-renders.
- Work the browser does between different turns of the event loop that exceeds 50 ms.
Long tasks refer to "culprit browsing context container", or "the container" for short, which is the top-level page, {{HTMLElement("iframe")}}, {{HTMLElement("embed")}} or {{HTMLElement("object")}} that the task occurred within.
For tasks that don't occur within the top-level page and for figuring out which container is responsible for the long task, the {{domxref("TaskAttributionTiming")}} interface provides the `containerId`, `containerName` and `containerSrc` properties, which may provide more information about the source of the task.
## Inheritance
`PerformanceLongTaskTiming` inherits from {{domxref("PerformanceEntry")}}.
{{InheritanceDiagram}}
## Instance properties
This interface extends the following {{domxref("PerformanceEntry")}} properties for long task timing performance entry types by qualifying them as follows:
- {{domxref("PerformanceEntry.duration")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("DOMHighResTimeStamp")}} representing the elapsed time between the start and end of the task, with a 1ms granularity.
- {{domxref("PerformanceEntry.entryType")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Always returns `"longtask"`
- {{domxref("PerformanceEntry.name")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns one of the following strings referring to the browsing context or frame that can be attributed to the long task:
- `"cross-origin-ancestor"`
- `"cross-origin-descendant"`
- `"cross-origin-unreachable"`
- `"multiple-contexts"`
- `"same-origin-ancestor"`
- `"same-origin-descendant"`
- `"same-origin"`
- `"self"`
- `"unknown"`
- {{domxref("PerformanceEntry.startTime")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("DOMHighResTimeStamp")}} representing the time when the task started.
This interface also supports the following properties:
- {{domxref("PerformanceLongTaskTiming.attribution")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a sequence of {{domxref('TaskAttributionTiming')}} instances.
## Instance methods
- {{domxref("PerformanceLongTaskTiming.toJSON()")}} {{Experimental_Inline}}
- : Returns a JSON representation of the `PerformanceLongTaskTiming` object.
## Examples
### Getting long tasks
To get long task timing information, create a {{domxref("PerformanceObserver")}} instance and then call its [`observe()`](/en-US/docs/Web/API/PerformanceObserver/observe) method, passing in `"longtask"` as the value of the [`type`](/en-US/docs/Web/API/PerformanceEntry/entryType) option. You also need to set `buffered` to `true` to get access to long tasks the user agent buffered while constructing the document. The `PerformanceObserver` object's callback will then be called with a list of `PerformanceLongTaskTiming` objects which you can analyze.
```js
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
console.log(entry);
});
});
observer.observe({ type: "longtask", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("TaskAttributionTiming")}}
| 0 |
data/mdn-content/files/en-us/web/api/performancelongtasktiming | data/mdn-content/files/en-us/web/api/performancelongtasktiming/attribution/index.md | ---
title: "PerformanceLongTaskTiming: attribution property"
short-title: attribution
slug: Web/API/PerformanceLongTaskTiming/attribution
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.PerformanceLongTaskTiming.attribution
---
{{SeeCompatTable}}{{APIRef("Performance API")}}
The **`attribution`** readonly property of the {{domxref("PerformanceLongTaskTiming")}} interface returns an array of {{domxref('TaskAttributionTiming')}} objects.
## Value
An {{jsxref("Array")}} of {{domxref('TaskAttributionTiming')}} objects.
## Examples
### Logging attributions for long tasks
```js
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
entry.attribution.forEach((attributionEntry) => {
console.log(attributionEntry);
});
});
});
observer.observe({ type: "longtask", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref('TaskAttributionTiming')}}
| 0 |
data/mdn-content/files/en-us/web/api/performancelongtasktiming | data/mdn-content/files/en-us/web/api/performancelongtasktiming/tojson/index.md | ---
title: "PerformanceLongTaskTiming: toJSON() method"
short-title: toJSON()
slug: Web/API/PerformanceLongTaskTiming/toJSON
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.PerformanceLongTaskTiming.toJSON
---
{{APIRef("Performance API")}}{{SeeCompatTable}}
The **`toJSON()`** method of the {{domxref("PerformanceLongTaskTiming")}} interface is a {{Glossary("Serialization","serializer")}}; it returns a JSON representation of the {{domxref("PerformanceLongTaskTiming")}} object.
## Syntax
```js-nolint
toJSON()
```
### Parameters
None.
### Return value
A {{jsxref("JSON")}} object that is the serialization of the {{domxref("PerformanceLongTaskTiming")}} object.
## Examples
### Using the toJSON method
In this example, calling `entry.toJSON()` returns a JSON representation of the `PerformanceLongTaskTiming` object.
```js
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
console.log(entry.toJSON());
});
});
observer.observe({ type: "longtask", buffered: true });
```
This would log a JSON object like so:
```json
{
"name": "self",
"entryType": "longtask",
"startTime": 183,
"duration": 60,
"attribution": [
{
"name": "unknown",
"entryType": "taskattribution",
"startTime": 0,
"duration": 0,
"containerType": "window",
"containerSrc": "",
"containerId": "",
"containerName": ""
}
]
}
```
To get a JSON string, you can use [`JSON.stringify(entry)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) directly; it will call `toJSON()` automatically.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("JSON")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlhrelement/index.md | ---
title: HTMLHRElement
slug: Web/API/HTMLHRElement
page-type: web-api-interface
browser-compat: api.HTMLHRElement
---
{{APIRef("HTML DOM")}}
The **`HTMLHRElement`** interface provides special properties (beyond those of the {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating {{HTMLElement("hr")}} elements.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLHRElement.align")}} {{deprecated_inline}}
- : A string, an enumerated attribute indicating alignment of the rule with respect to the surrounding context.
- {{domxref("HTMLHRElement.color")}} {{deprecated_inline}}
- : A string representing the name of the color of the rule.
- {{domxref("HTMLHRElement.noshade")}} {{deprecated_inline}}
- : A boolean value that sets the rule to have no shading.
- {{domxref("HTMLHRElement.size")}} {{deprecated_inline}}
- : A string representing the height of the rule.
- {{domxref("HTMLHRElement.width")}} {{deprecated_inline}}
- : A string representing the width of the rule on the page.
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}_.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{HTMLElement("hr")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/background_tasks_api/index.md | ---
title: Background Tasks API
slug: Web/API/Background_Tasks_API
page-type: web-api-overview
browser-compat: api.Window.requestIdleCallback
---
{{DefaultAPISidebar("Background Tasks")}}
The **Cooperative Scheduling of Background Tasks API** (also referred to as the Background Tasks API or the `requestIdleCallback()` API) provides the ability to queue tasks to be executed automatically by the user agent when it determines that there is free time to do so.
> **Note:** This API is _not available_ in [Web Workers](/en-US/docs/Web/API/Web_Workers_API).
## Concepts and usage
The main thread of a Web browser is centered around its event loop. This code draws any pending updates to the {{domxref("Document")}} currently being displayed, runs any JavaScript code the page needs to run, accepts events from input devices, and dispatches those events to the elements that should receive them. In addition, the event loop handles interactions with the operating system, updates to the browser's own user interface, and so forth. It's an extremely busy chunk of code, and your main JavaScript code may run right inside this thread along with all of this. Certainly most if not all code that is capable of making changes to the DOM is running in the main thread, since it's common for user interface changes to only be available to the main thread.
Because event handling and screen updates are two of the most obvious ways users notice performance issues, it's important for your code to be a good citizen of the Web and help to prevent stalls in the execution of the event loop. In the past, there's been no way to do this reliably other than by writing code that's as efficient as possible and by offloading as much work as possible to [workers](/en-US/docs/Web/API/Web_Workers_API). {{domxref("Window.requestIdleCallback()")}} makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag. If you stay within the limit given, you can make the user's experience much better.
### Getting the most out of idle callbacks
Because idle callbacks are intended to give your code a way to cooperate with the event loop to ensure that the system is utilized to its full potential without over-tasking it, resulting in lag or other performance problems, you should be thoughtful about how you go about using them.
- **Use idle callbacks for tasks which don't have high priority.** Because you don't know how many callbacks have been established, and you don't know how busy the user's system is, you don't know how often your callback will be run (unless you specify a `timeout`). There's no guarantee that every pass through the event loop (or even every screen update cycle) will include any idle callbacks being executed; if the event loop uses all available time, you're out of luck (again, unless you've used a `timeout`).
- **Idle callbacks should do their best not to overrun the time allotted.** While the browser, your code, and the Web in general will continue to run normally if you go over the specified time limit (even if you go _way_ over it), the time restriction is intended to ensure that you leave the system enough time to finish the current pass through the event loop and get on to the next one without causing other code to stutter or animation effects to lag. Currently, {{domxref("IdleDeadline.timeRemaining", "timeRemaining()")}} has an upper limit of 50 milliseconds, but in reality you will often have less time than that, since the event loop may already be eating into that time on complex sites, with browser extensions needing processor time, and so forth.
- **Avoid making changes to the DOM within your idle callback.** By the time your callback is run, the current frame has already finished drawing, and all layout updates and computations have been completed. If you make changes that affect layout, you may force a situation in which the browser has to stop and do recalculations that would otherwise be unnecessary. If your callback needs to change the DOM, it should use {{domxref("Window.requestAnimationFrame()")}} to schedule that.
- **Avoid tasks whose run time can't be predicted.** Your idle callback should avoid doing anything that could take an unpredictable amount of time. For example, anything which might affect layout should be avoided. You should also avoid resolving or rejecting {{jsxref("Promise")}}s, since that would invoke the handler for that promise's resolution or rejection as soon as your callback returns.
- **Use timeouts when you need to, but only when you need to.** Using timeouts can ensure that your code runs in a timely manner, but it can also allow you to cause lag or animation stutters by mandating that the browser call you when there's not enough time left for you to run without disrupting performance.
## Interfaces
The Background Tasks API adds only one new interface:
- {{domxref("IdleDeadline")}}
- : An object of this type is passed to the idle callback to provide an estimate of how long the idle period is expected to last, as well as whether or not the callback is running because its timeout period has expired.
The {{domxref("Window")}} interface is also augmented by this API to offer the new {{domxref("window.requestIdleCallback", "requestIdleCallback()")}} and {{domxref("window.cancelIdleCallback", "cancelIdleCallback()")}} methods.
## Example
In this example, we'll take a look at how you can use {{domxref("window.requestIdleCallback", "requestIdleCallback()")}} to run time-consuming, low-priority tasks during time the browser would otherwise be idle. In addition, this example demonstrates how to schedule updates to the document content using {{domxref("window.requestAnimationFrame", "requestAnimationFrame()")}}.
Below you'll find only the HTML and JavaScript for this example. The CSS is not shown, since it's not particularly crucial to understanding this functionality.
### HTML
In order to be oriented about what we're trying to accomplish, let's have a look at the HTML. This establishes a box (`id="container"`) that's used to present the progress of an operation (because you never know how long decoding "quantum filament tachyon emissions" will take, after all) as well as a second main box (`id="logBox"`), which is used to display textual output.
```html
<p>
Demonstration of using cooperatively scheduled background tasks using the
<code>requestIdleCallback()</code> method.
</p>
<div id="container">
<div class="label">Decoding quantum filament tachyon emissions…</div>
<progress id="progress" value="0"></progress>
<button class="button" id="startButton">Start</button>
<div class="label counter">
Task <span id="currentTaskNumber">0</span> of
<span id="totalTaskCount">0</span>
</div>
</div>
<div id="logBox">
<div class="logHeader">Log</div>
<div id="log"></div>
</div>
```
The progress box uses a {{HTMLElement("progress")}} element to show the progress, along with a label with sections that are changed to present numeric information about the progress. In addition, there's a "Start" button (creatively given the ID "startButton"), which the user will use to start the data processing.
```css hidden
body {
font-family: "Open Sans", "Lucida Grande", "Arial", sans-serif;
font-size: 16px;
}
#logBox {
margin-top: 16px;
width: 400px;
height: 500px;
border-radius: 6px;
border: 1px solid black;
box-shadow: 4px 4px 2px black;
}
.logHeader {
margin: 0;
padding: 0 6px 4px;
height: 22px;
background-color: lightblue;
border-bottom: 1px solid black;
border-radius: 6px 6px 0 0;
}
#log {
font:
12px "Courier",
monospace;
padding: 6px;
overflow: auto;
overflow-y: scroll;
width: 388px;
height: 460px;
}
#container {
width: 400px;
padding: 6px;
border-radius: 6px;
border: 1px solid black;
box-shadow: 4px 4px 2px black;
display: block;
overflow: auto;
}
.label {
display: inline-block;
}
.counter {
text-align: right;
padding-top: 4px;
float: right;
}
.button {
padding-top: 2px;
padding-bottom: 4px;
width: 100px;
display: inline-block;
float: left;
border: 1px solid black;
cursor: pointer;
text-align: center;
margin-top: 0;
color: white;
background-color: darkgreen;
}
#progress {
width: 100%;
padding-top: 6px;
}
```
### JavaScript
Now that the document structure is defined, construct the JavaScript code that will do the work. The goal: to be able to add requests to call functions to a queue, with an idle callback that runs those functions whenever the system is idle for long enough a time to make progress.
#### Variable declarations
```js
const taskList = [];
let totalTaskCount = 0;
let currentTaskNumber = 0;
let taskHandle = null;
```
These variables are used to manage the list of tasks that are waiting to be performed, as well as status information about the task queue and its execution:
- `taskList` is an {{jsxref("Array")}} of objects, each representing one task waiting to be run.
- `totalTaskCount` is a counter of the number of tasks that have been added to the queue; it will only go up, never down. We use this to do the math to present progress as a percentage of total work to do.
- `currentTaskNumber` is used to track how many tasks have been processed so far.
- `taskHandle` is a reference to the task currently being processed.
```js
const totalTaskCountElem = document.getElementById("totalTaskCount");
const currentTaskNumberElem = document.getElementById("currentTaskNumber");
const progressBarElem = document.getElementById("progress");
const startButtonElem = document.getElementById("startButton");
const logElem = document.getElementById("log");
```
Next we have variables which reference the DOM elements we need to interact with. These elements are:
- `totalTaskCountElem` is the {{HTMLElement("span")}} we use to insert the total number of tasks created into the status display in the progress box.
- `currentTaskNumberElem` is the element used to display the number of tasks processed so far.
- `progressBarElem` is the {{HTMLElement("progress")}} element showing the percentage of the tasks processed so far.
- `startButtonElem` is the start button.
- `logElem` is the {{HTMLElement("div")}} we'll insert logged text messages into.
```js
let logFragment = null;
let statusRefreshScheduled = false;
```
Finally, we set up a couple of variables for other items:
- `logFragment` will be used to store a {{domxref("DocumentFragment")}} that's generated by our logging functions to create content to append to the log when the next animation frame is rendered.
- `statusRefreshScheduled` is used to track whether or not we've already scheduled an update of the status display box for the upcoming frame, so that we only do it once per frame
```js hidden
requestIdleCallback =
requestIdleCallback ||
((handler) => {
const startTime = Date.now();
return setTimeout(() => {
handler({
didTimeout: false,
timeRemaining() {
return Math.max(0, 50.0 - (Date.now() - startTime));
},
});
}, 1);
});
cancelIdleCallback =
cancelIdleCallback ||
((id) => {
clearTimeout(id);
});
```
#### Managing the task queue
Next, let's look at the way we manage the tasks that need to be performed. We're going to do this by creating a FIFO queue of tasks, which we'll run as time allows during the idle callback period.
##### Enqueueing tasks
First, we need a function that enqueues tasks for future execution. That function, `enqueueTask()`, looks like this:
```js
function enqueueTask(taskHandler, taskData) {
taskList.push({
handler: taskHandler,
data: taskData,
});
totalTaskCount++;
if (!taskHandle) {
taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000 });
}
scheduleStatusRefresh();
}
```
`enqueueTask()` accepts as input two parameters:
- `taskHandler` is a function which will be called to handle the task.
- `taskData` is an object which is passed into the task handler as an input parameter, to allow the task to receive custom data.
To enqueue the task, we [push](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) an object onto the `taskList` array; the object contains the `taskHandler` and `taskData` values under the names `handler` and `data`, respectively, then increment `totalTaskCount`, which reflects the total number of tasks which have ever been enqueued (we don't decrement it when tasks are removed from the queue).
Next, we check to see if we already have an idle callback created; if `taskHandle` is 0, we know there isn't an idle callback yet, so we call {{domxref("Window.requestIdleCallback", "requestIdleCallback()")}} to create one. It's configured to call a function called `runTaskQueue()`, which we'll look at shortly, and with a `timeout` of 1 second, so that it will be run at least once per second even if there isn't any actual idle time available.
##### Running tasks
Our idle callback handler, `runTaskQueue()`, gets called when the browser determines there's enough idle time available to let us do some work or our timeout of one second expires. This function's job is to run our enqueued tasks.
```js
function runTaskQueue(deadline) {
while (
(deadline.timeRemaining() > 0 || deadline.didTimeout) &&
taskList.length
) {
const task = taskList.shift();
currentTaskNumber++;
task.handler(task.data);
scheduleStatusRefresh();
}
if (taskList.length) {
taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000 });
} else {
taskHandle = 0;
}
}
```
`runTaskQueue()`'s core is a loop which continues as long as there's time left (as determined by checking {{domxref("IdleDeadline.timeRemaining", "deadline.timeRemaining")}}) to be sure it's more than 0 or if the timeout limit was reached ({{domxref("IdleDeadline.didTimeout", "deadline.didTimeout")}} is true), and as long as there are tasks in the task list.
For each task in the queue that we have time to execute, we do the following:
1. We [remove the task object from the queue](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift).
2. We increment `currentTaskNumber` to track how many tasks we've executed.
3. We call the task's handler, `task.handler`, passing into it the task's data object (`task.data`).
4. We call a function, `scheduleStatusRefresh()`, to handle scheduling a screen update to reflect changes to our progress.
When time runs out, if there are still tasks left in the list, we call {{domxref("Window.requestIdleCallback", "requestIdleCallback()")}} again so that we can continue to process the tasks the next time there's idle time available. If the queue is empty, we set taskHandle to 0 to indicate that we don't have a callback scheduled. That way, we'll know to request a callback next time `enqueueTask()` is called.
#### Updating the status display
One thing we want to be able to do is update our document with log output and progress information. However, you can't safely change the DOM from within an idle callback. Instead, we'll use {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} to ask the browser to call us when it's safe to update the display.
##### Scheduling display updates
DOM changes are scheduled by calling the `scheduleStatusRefresh()` function.
```js
function scheduleStatusRefresh() {
if (!statusRefreshScheduled) {
requestAnimationFrame(updateDisplay);
statusRefreshScheduled = true;
}
}
```
This is a simple function. It checks to see if we've already scheduled a display refresh by checking the value of `statusRefreshScheduled`. If it's `false`, we call {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} to schedule a refresh, providing the `updateDisplay()` function to be called to handle that work.
##### Updating the display
The `updateDisplay()` function is responsible for drawing the contents of the progress box and the log. It's called by the browser when the DOM is in a safe condition for us to apply changes during the process of rendering the next frame.
```js
function updateDisplay() {
const scrolledToEnd =
logElem.scrollHeight - logElem.clientHeight <= logElem.scrollTop + 1;
if (totalTaskCount) {
if (progressBarElem.max !== totalTaskCount) {
totalTaskCountElem.textContent = totalTaskCount;
progressBarElem.max = totalTaskCount;
}
if (progressBarElem.value !== currentTaskNumber) {
currentTaskNumberElem.textContent = currentTaskNumber;
progressBarElem.value = currentTaskNumber;
}
}
if (logFragment) {
logElem.appendChild(logFragment);
logFragment = null;
}
if (scrolledToEnd) {
logElem.scrollTop = logElem.scrollHeight - logElem.clientHeight;
}
statusRefreshScheduled = false;
}
```
First, `scrolledToEnd` is set to `true` if the text in the log is scrolled to the bottom; otherwise it's set to `false`. We'll use that to determine if we should update the scroll position to ensure that the log stays at the end when we're done adding content to it.
Next, we update the progress and status information if any tasks have been enqueued.
1. If the current maximum value of the progress bar is different from the current total number of enqueued tasks (`totalTaskCount`), then we update the contents of the displayed total number of tasks (`totalTaskCountElem`) and the maximum value of the progress bar, so that it scales properly.
2. We do the same thing with the number of tasks processed so far; if `progressBarElem.value` is different from the task number currently being processed (`currentTaskNumber`), then we update the displayed value of the currently-being-processed task and the current value of the progress bar.
Then, if there's text waiting to be added to the log (that is, if `logFragment` isn't `null`), we append it to the log element using {{domxref("Node.appendChild", "Element.appendChild()")}} and set `logFragment` to `null` so we don't add it again.
If the log was scrolled to the end when we started, we make sure it still is. Then we set `statusRefreshScheduled` to `false` to indicate that we've handled the refresh and that it's safe to request a new one.
#### Adding text to the log
The `log()` function adds the specified text to the log. Since we don't know at the time `log()` is called whether or not it's safe to immediately touch the DOM, we will cache the log text until it's safe to update. Above, in the code for `updateDisplay()`, you can find the code that actually adds the logged text to the log element when the animation frame is being updated.
```js
function log(text) {
if (!logFragment) {
logFragment = document.createDocumentFragment();
}
const el = document.createElement("div");
el.textContent = text;
logFragment.appendChild(el);
}
```
First, we create a {{domxref("DocumentFragment")}} object named `logFragment` if one doesn't currently exist. This element is a pseudo-DOM into which we can insert elements without immediately changing the main DOM itself.
We then create a new {{HTMLElement("div")}} element and set its contents to match the input `text`. Then we append the new element to the end of the pseudo-DOM in `logFragment`. `logFragment` will accumulate log entries until the next time `updateDisplay()` is called because the DOM for the changes.
### Running tasks
Now that we've got the task management and display maintenance code done, we can actually start setting up code to run tasks that get work done.
#### The task handler
The function we'll be using as our task handler—that is, the function that will be used as the value of the task object's `handler` property—is `logTaskHandler()`. It's a simple function that outputs a bunch of stuff to the log for each task. In your own application, you'd replace this code with whatever task it is you wish to perform during idle time. Just remember that anything you want to do that changes the DOM needs to be handled through {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}}.
```js
function logTaskHandler(data) {
log(`Running task #${currentTaskNumber}`);
for (let i = 0; i < data.count; i += 1) {
log(`${(i + 1).toString()}. ${data.text}`);
}
}
```
#### The main program
Everything is triggered when the user clicks the Start button, which causes the `decodeTechnoStuff()` function to be called.
```js hidden
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
```
```js
function decodeTechnoStuff() {
totalTaskCount = 0;
currentTaskNumber = 0;
updateDisplay();
const n = getRandomIntInclusive(100, 200);
for (let i = 0; i < n; i++) {
const taskData = {
count: getRandomIntInclusive(75, 150),
text: `This text is from task number ${i + 1} of ${n}`,
};
enqueueTask(logTaskHandler, taskData);
}
}
document
.getElementById("startButton")
.addEventListener("click", decodeTechnoStuff, false);
```
`decodeTechnoStuff()` starts by zeroing the values of totalTaskCount (the number of tasks added to the queue so far) and currentTaskNumber (the task currently being run), and then calls `updateDisplay()` to reset the display to its "nothing's happened yet" state.
This example will create a random number of tasks (between 100 and 200 of them). To do so, we use the [`getRandomIntInclusive()` function](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_integer_between_two_values_inclusive) that's provided as an example in the documentation for {{jsxref("Math.random()")}} to get the number of tasks to create.
Then we start a loop to create the actual tasks. For each task, we create an object, `taskData`, which includes two properties:
- `count` is the number of strings to output into the log from the task.
- `text` is the text to output to the log the number of times specified by `count`.
Each task is then enqueued by calling `enqueueTask()`, passing in `logTaskHandler()` as the handler function and the `taskData` object as the object to pass into the function when it's called.
### Result
Below is the actual functioning result of the code above. Try it out, play with it in your browser's developer tools, and experiment with using it in your own code.
{{ EmbedLiveSample('Example', 600, 700) }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Window.requestIdleCallback()")}}
- {{domxref("Window.cancelIdleCallback()")}}
- {{domxref("IdleDeadline")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlanchorelement/index.md | ---
title: HTMLAnchorElement
slug: Web/API/HTMLAnchorElement
page-type: web-api-interface
browser-compat: api.HTMLAnchorElement
---
{{APIRef("HTML DOM")}}
The **`HTMLAnchorElement`** interface represents hyperlink elements and provides special properties and methods (beyond those of the regular {{domxref("HTMLElement")}} object interface that they inherit from) for manipulating the layout and presentation of such elements. This interface corresponds to [`<a>`](/en-US/docs/Web/HTML/Element/a) element; not to be confused with [`<link>`](/en-US/docs/Web/HTML/Element/link), which is represented by [`HTMLLinkElement`](/en-US/docs/Web/API/HTMLLinkElement).
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLAnchorElement.download")}}
- : A string indicating that the linked resource is intended to be downloaded rather than displayed in the browser. The value represent the proposed name of the file. If the name is not a valid filename of the underlying OS, browser will adapt it.
- {{domxref("HTMLAnchorElement.hash")}}
- : A string representing the fragment identifier, including the leading hash mark ('`#`'), if any, in the referenced URL.
- {{domxref("HTMLAnchorElement.host")}}
- : A string representing the hostname and port (if it's not the default port) in the referenced URL.
- {{domxref("HTMLAnchorElement.hostname")}}
- : A string representing the hostname in the referenced URL.
- {{domxref("HTMLAnchorElement.href")}}
- : A string that is the result of parsing the [`href`](/en-US/docs/Web/HTML/Element/a#href) HTML attribute relative to the document, containing a valid URL of a linked resource.
- {{domxref("HTMLAnchorElement.hreflang")}}
- : A string that reflects the [`hreflang`](/en-US/docs/Web/HTML/Element/a#hreflang) HTML attribute, indicating the language of the linked resource.
- {{domxref("HTMLAnchorElement.origin")}} {{ReadOnlyInline}}
- : Returns a string containing the origin of the URL, that is its scheme, its domain and its port.
- {{domxref("HTMLAnchorElement.password")}}
- : A string containing the password specified before the domain name.
- {{domxref("HTMLAnchorElement.pathname")}}
- : A string containing an initial `'/'` followed by the path of the URL, not including the query string or fragment.
- {{domxref("HTMLAnchorElement.ping")}}
- : A space-separated list of URLs. When the link is followed, the browser will send {{HTTPMethod("POST")}} requests with the body PING to the URLs.
- {{domxref("HTMLAnchorElement.port")}}
- : A string representing the port component, if any, of the referenced URL.
- {{domxref("HTMLAnchorElement.protocol")}}
- : A string representing the protocol component, including trailing colon ('`:`'), of the referenced URL.
- {{domxref("HTMLAnchorElement.referrerPolicy")}}
- : A string that reflects the [`referrerpolicy`](/en-US/docs/Web/HTML/Element/a#referrerpolicy) HTML attribute indicating which referrer to use.
- {{domxref("HTMLAnchorElement.rel")}}
- : A string that reflects the [`rel`](/en-US/docs/Web/HTML/Element/a#rel) HTML attribute, specifying the relationship of the target object to the linked object.
- {{domxref("HTMLAnchorElement.relList")}} {{ReadOnlyInline}}
- : Returns a {{domxref("DOMTokenList")}} that reflects the [`rel`](/en-US/docs/Web/HTML/Element/a#rel) HTML attribute, as a list of tokens.
- {{domxref("HTMLAnchorElement.search")}}
- : A string representing the search element, including leading question mark ('`?`'), if any, of the referenced URL.
- {{domxref("HTMLAnchorElement.target")}}
- : A string that reflects the [`target`](/en-US/docs/Web/HTML/Element/a#target) HTML attribute, indicating where to display the linked resource.
- {{domxref("HTMLAnchorElement.text")}}
- : A string being a synonym for the {{domxref("Node.textContent")}} property.
- {{domxref("HTMLAnchorElement.type")}}
- : A string that reflects the [`type`](/en-US/docs/Web/HTML/Element/a#type) HTML attribute, indicating the MIME type of the linked resource.
- {{domxref("HTMLAnchorElement.username")}}
- : A string containing the username specified before the domain name.
### Obsolete properties
- {{domxref("HTMLAnchorElement.charset")}} {{deprecated_inline}}
- : A string representing the character encoding of the linked resource.
- {{domxref("HTMLAnchorElement.coords")}} {{deprecated_inline}}
- : A string representing a comma-separated list of coordinates.
- {{domxref("HTMLAnchorElement.name")}} {{deprecated_inline}}
- : A string representing the anchor name.
- {{domxref("HTMLAnchorElement.rev")}} {{deprecated_inline}}
- : A string representing that the [`rev`](/en-US/docs/Web/HTML/Element/a#rev) HTML attribute, specifying the relationship of the link object to the target object.
> **Note:** Currently the W3C HTML 5.2 spec states that `rev` is no longer obsolete, whereas the WHATWG living standard still has it labeled obsolete. Until this discrepancy is resolved, you should still assume it is obsolete.
- {{domxref("HTMLAnchorElement.shape")}} {{deprecated_inline}}
- : A string representing the shape of the active area.
## Instance methods
_Inherits methods from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLAnchorElement.toString()")}}
- : Returns a string containing the whole URL. It is a synonym for {{domxref("HTMLAnchorElement.href")}}, though it can't be used to modify the value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{HTMLElement("a")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/origin/index.md | ---
title: "HTMLAnchorElement: origin property"
short-title: origin
slug: Web/API/HTMLAnchorElement/origin
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.origin
---
{{APIRef("HTML DOM")}}
The
**`HTMLAnchorElement.origin`** read-only property is a
string containing the Unicode serialization of the origin of the
represented URL.
That is:
- for URL using the `http` or `https`, the scheme followed by
`'://'`, followed by the domain, followed by `':'`, followed by
the port (the default port, `80` and `443` respectively, if
explicitly specified);
- for URL using `file:` scheme, the value is browser dependent;
- for URL using the `blob:` scheme, the origin of the URL following
`blob:`. E.g `"blob:https://mozilla.org"` will have
`"https://mozilla.org".`
## Value
A string.
## Examples
```js
// An <a id="myAnchor" href="https://developer.mozilla.org/en-US/HTMLAnchorElement"> element is in the document
const anchor = document.getElementById("myAnchor");
anchor.origin; // returns 'https://developer.mozilla.org'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/tostring/index.md | ---
title: "HTMLAnchorElement: toString() method"
short-title: toString()
slug: Web/API/HTMLAnchorElement/toString
page-type: web-api-instance-method
browser-compat: api.HTMLAnchorElement.toString
---
{{ApiRef("URL API")}}
The **`HTMLAnchorElement.toString()`** {{Glossary("stringifier")}}
method returns a string containing the whole URL. It is a read-only
version of {{domxref("HTMLAnchorElement.href")}}.
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
A string containing the element's complete URL.
## Examples
### Calling toString on an anchor element
```js
// An <a id="myAnchor" href="/en-US/docs/HTMLAnchorElement"> element is in the document
const anchor = document.getElementById("myAnchor");
anchor.toString(); // returns 'https://developer.mozilla.org/en-US/docs/HTMLAnchorElement'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/target/index.md | ---
title: "HTMLAnchorElement: target property"
short-title: target
slug: Web/API/HTMLAnchorElement/target
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.target
---
{{ApiRef("HTML DOM")}}
The **`target`** property of the {{domxref("HTMLAnchorElement")}} interface is a string that indicates where to display the linked resource.
It reflects the [`target`](/en-US/docs/Web/HTML/Element/a#target) attribute of the {{HTMLElement("a")}} element.
## Value
A string representing the target. Its value can be:
- The name of a {{HTMLElement("frame")}}.
- One of the [keyword with specific values](/en-US/docs/Web/HTML/Element/a#target):`_blank`, `_self`, `_parent`, or `_top`.
## Example
```html
<a href="www.example1.com" class="link1" target="_blank">example1</a>
```
```js
const link = document.querySelector(".link1");
console.log(link.target); // output: "_blank"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLBaseElement.target")}} property
- {{domxref("HTMLFormElement.target")}} property
- {{domxref("HTMLAreaElement.target")}} property
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/username/index.md | ---
title: "HTMLAnchorElement: username property"
short-title: username
slug: Web/API/HTMLAnchorElement/username
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.username
---
{{ApiRef("HTML DOM")}}
The **`HTMLAnchorElement.username`** property is a
string containing the username specified before the domain name.
## Value
A string.
## Examples
### Getting the username from an anchor link
```js
// An <a id="myAnchor" href="https://anonymous:[email protected]/en-US/docs/HTMLAnchorElement"> element is in the document
const anchor = document.getElementByID("myAnchor");
anchor.username; // returns 'anonymous'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/search/index.md | ---
title: "HTMLAnchorElement: search property"
short-title: search
slug: Web/API/HTMLAnchorElement/search
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.search
---
{{ApiRef("HTML DOM")}}
The **`HTMLAnchorElement.search`** property is a search
string, also called a _query string_, that is a string containing
a `'?'` followed by the parameters of the URL.
Modern browsers provide
[`URLSearchParams`](/en-US/docs/Web/API/URLSearchParams/get#examples)
and
[`URL.searchParams`](/en-US/docs/Web/API/URL/searchParams#examples)
to make it easy to parse out the parameters from the querystring.
## Value
A string.
## Examples
### Getting the search string from an anchor link
```js
// An <a id="myAnchor" href="/en-US/docs/HTMLAnchorElement?q=123"> element is in the document
const anchor = document.getElementById("myAnchor");
anchor.search; // returns '?q=123'
```
### Advanced parsing using URLSearchParams
Alternatively, [`URLSearchParams`](/en-US/docs/Web/API/URLSearchParams/get#examples) can be used:
```js
let params = new URLSearchParams(queryString);
let q = parseInt(params.get("q")); // returns the number 123
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/ping/index.md | ---
title: "HTMLAnchorElement: ping property"
short-title: ping
slug: Web/API/HTMLAnchorElement/ping
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.ping
---
{{ApiRef("HTML DOM")}}
The **`ping`** property of the {{domxref("HTMLAnchorElement")}} interface is a space-separated list of URLs. When the link is followed, the browser will send {{HTTPMethod("POST")}} requests with the body PING to the URLs.
It reflects the `ping` attribute of the {{HTMLElement("a")}} element.
> **Note:** This property is not effective in Firefox and its usage may be limited due to privacy and security concerns.
## Example
```html
<a
id="exampleLink"
href="https://example.com"
ping="https://example-tracking.com https://example-analytics.com"
>Example Link</a
>
```
```js
const anchorElement = document.getElementById("exampleLink");
console.log(anchorElement.ping); // Output: "https://example-tracking.com https://example-analytics.com"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLAreaElement.ping")}} property
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/port/index.md | ---
title: "HTMLAnchorElement: port property"
short-title: port
slug: Web/API/HTMLAnchorElement/port
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.port
---
{{ApiRef("HTML DOM")}}
The **`HTMLAnchorElement.port`** property is a
string containing the port number of the URL. If the URL does not
contain an explicit port number, it will be set to `''`.
## Value
A string.
## Examples
### Getting the port from an anchor link
```js
// An <a id="myAnchor" href="https://developer.mozilla.org:443/en-US/docs/HTMLAnchorElement"> element is in the document
const anchor = document.getElementByID("myAnchor");
anchor.port; // returns '443'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/hash/index.md | ---
title: "HTMLAnchorElement: hash property"
short-title: hash
slug: Web/API/HTMLAnchorElement/hash
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.hash
---
{{ APIRef("HTML DOM") }}
The
**`HTMLAnchorElement.hash`** property returns a
string containing a `'#'` followed by the fragment
identifier of the URL.
The fragment is [URL encoded](https://en.wikipedia.org/wiki/URL_encoding). If the URL does not
have a fragment identifier, this property contains an empty string, `""`.
## Value
A string.
## Examples
### Getting the hash from an anchor link
Given this HTML
```html
<a id="myAnchor" href="/en-US/docs/HTMLAnchorElement#Examples">Examples</a>
```
you can get the hash of the anchor like this:
```js
const anchor = document.getElementById("myAnchor");
anchor.hash; // returns '#Examples'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/pathname/index.md | ---
title: "HTMLAnchorElement: pathname property"
short-title: pathname
slug: Web/API/HTMLAnchorElement/pathname
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.pathname
---
{{ApiRef("HTML DOM")}}
The **`HTMLAnchorElement.pathname`** property is a
string containing an initial `'/'` followed by the path of
the URL not including the query string or fragment (or the empty string if there is no
path).
## Value
A string.
## Examples
```js
// An <a id="myAnchor" href="/en-US/docs/HTMLAnchorElement"> element is in the document
const anchor = document.getElementById("myAnchor");
anchor.pathname; // returns '/en-US/docs/HTMLAnchorElement'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/text/index.md | ---
title: "HTMLAnchorElement: text property"
short-title: text
slug: Web/API/HTMLAnchorElement/text
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.text
---
{{ApiRef("HTML DOM")}}
The **`text`** property of the {{domxref("HTMLAnchorElement")}} represents the text inside the the element.
This property represents the same information as {{domxref("Node.textContent")}}.
## Value
A string.
## Example
```html
<a id="exampleLink" href="https://example.com">Example Link</a>
<p class="text"></p>
```
```css
#exampleLink {
font-size: 1.5rem;
}
```
```js
const anchorElement = document.getElementById("exampleLink");
const pTag = document.querySelector(".text");
pTag.textContent = `Text property: ${anchorElement.text}`;
```
### Result
{{EmbedLiveSample("Example",100,100)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLScriptElement.text")}} property
- {{domxref("HTMLOptionElement.text")}} property
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/rellist/index.md | ---
title: "HTMLAnchorElement: relList property"
short-title: relList
slug: Web/API/HTMLAnchorElement/relList
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.relList
---
{{APIRef("HTML DOM")}}
The **`HTMLAnchorElement.relList`** read-only property reflects the [`rel`](/en-US/docs/Web/HTML/Attributes/rel) attribute. It is a live {{domxref("DOMTokenList")}} containing the set of link types indicating the relationship between the resource represented by the {{HTMLElement("a")}} element and the current document.
The property itself is read-only, meaning you can't substitute the
{{domxref("DOMTokenList")}} with another one, but its contents can still be changed.
## Value
A live {{domxref("DOMTokenList")}} of strings.
## Examples
```js
const anchors = document.getElementsByTagName("a");
for (const anchor of anchors) {
const list = anchor.relList;
console.log(
`New anchor node found with ${list.length} link types in relList.`,
);
list.forEach((relValue) => {
console.log(relValue);
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The equivalent property on {{HTMLElement("area")}} and {{HTMLElement("link")}},
{{domxref("HTMLAreaElement.relList")}} and {{domxref("HTMLLinkElement.relList")}}.
- The very same list but as a space-separated tokens in a string:
{{domxref("HTMLAnchorElement.rel")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/hostname/index.md | ---
title: "HTMLAnchorElement: hostname property"
short-title: hostname
slug: Web/API/HTMLAnchorElement/hostname
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.hostname
---
{{ApiRef("HTML DOM")}}
The **`HTMLAnchorElement.hostname`** property is a
string containing the domain of the URL.
## Value
A string.
## Examples
```js
// An <a id="myAnchor" href="/en-US/docs/HTMLAnchorElement"> element is in the document
const anchor = document.getElementById("myAnchor");
anchor.hostname; // returns 'developer.mozilla.org'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/host/index.md | ---
title: "HTMLAnchorElement: host property"
short-title: host
slug: Web/API/HTMLAnchorElement/host
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.host
---
{{ApiRef("HTML DOM")}}
The **`HTMLAnchorElement.host`** property is a
string containing the host, that is the _hostname_, and then,
if the _port_ of the URL is nonempty, a `':'`, and the _port_
of the URL.
## Value
A string.
## Examples
```js
const anchor = document.createElement("a");
anchor.href = "https://developer.mozilla.org/en-US/HTMLAnchorElement";
anchor.host === "developer.mozilla.org";
anchor.href = "https://developer.mozilla.org:443/en-US/HTMLAnchorElement";
anchor.host === "developer.mozilla.org";
// The port number is not included because 443 is the scheme's default port
anchor.href = "https://developer.mozilla.org:4097/en-US/HTMLAnchorElement";
anchor.host === "developer.mozilla.org:4097";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/href/index.md | ---
title: "HTMLAnchorElement: href property"
short-title: href
slug: Web/API/HTMLAnchorElement/href
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.href
---
{{ApiRef("HTML DOM")}}
The **`HTMLAnchorElement.href`** property is a
{{Glossary("stringifier")}} that returns a string containing the whole URL, and allows
the href to be updated.
## Value
A string.
## Examples
```js
// An <a id="myAnchor" href="https://developer.mozilla.org/en-US/HTMLAnchorElement"> element is in the document
const anchor = document.getElementById("myAnchor");
anchor.href; // returns 'https://developer.mozilla.org/en-US/HTMLAnchorElement'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/download/index.md | ---
title: "HTMLAnchorElement: download property"
short-title: download
slug: Web/API/HTMLAnchorElement/download
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.download
---
{{APIRef("HTML DOM")}}
The **`HTMLAnchorElement.download`** property is a
string indicating that the linked resource is intended to be
downloaded rather than displayed in the browser. The value, if any, specifies the
default file name for use in labeling the resource in a local file system. If the name
is not a valid file name in the underlying OS, the browser will adjust it.
> **Note:** This value might not be used for download. This value cannot
> be used to determine whether the download will occur.
## Value
A string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/password/index.md | ---
title: "HTMLAnchorElement: password property"
short-title: password
slug: Web/API/HTMLAnchorElement/password
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.password
---
{{ApiRef("HTML DOM")}}
The **`HTMLAnchorElement.password`** property is a
string containing the password specified before the domain name.
If it is set without first setting the
[`username`](/en-US/docs/Web/API/HTMLAnchorElement/username)
property, it silently fails.
## Value
A string.
## Examples
```js
// An <a id="myAnchor" href="https://anonymous:[email protected]/en-US/docs/HTMLAnchorElement"> is in the document
const anchor = document.getElementByID("myAnchor");
anchor.password; // returns 'flabada'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/type/index.md | ---
title: "HTMLAnchorElement: type property"
short-title: type
slug: Web/API/HTMLAnchorElement/type
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.type
---
{{ApiRef("HTML DOM")}}
The **`type`** property of the {{domxref("HTMLAnchorElement")}} interface is a string that indicates the MIME type of the linked resource.
It reflects the `type` attribute of the {{HTMLElement("a")}} element.
## Value
A string.
## Example
```html
<a id="exampleLink" href="https://example.com" type="text/html">Example Link</a>
<p class="type"></p>
```
```css
#exampleLink {
font-size: 1.5rem;
}
```
```js
const anchorElement = document.getElementById("exampleLink");
const pTag = document.querySelector(".type");
console.log(anchorElement.type); // Output: "text/html"
pTag.textContent = anchorElement.type;
```
{{EmbedLiveSample("Example",100,100)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLLinkElement.type")}} property
- {{domxref("HTMLSourceElement.type")}} property
- {{domxref("HTMLEmbedElement.type")}} property
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/protocol/index.md | ---
title: "HTMLAnchorElement: protocol property"
short-title: protocol
slug: Web/API/HTMLAnchorElement/protocol
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.protocol
---
{{ApiRef("HTML DOM")}}
The
**`HTMLAnchorElement.protocol`**
property is a string representing the protocol scheme of the URL,
including the final `':'`.
## Value
A string.
## Examples
### Getting the protocol of an anchor link
```js
// An <a id="myAnchor" href="https://developer.mozilla.org/en-US/HTMLAnchorElement"> element is in the document
const anchor = document.getElementById("myAnchor");
anchor.protocol; // returns 'https:'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLAnchorElement")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/rel/index.md | ---
title: "HTMLAnchorElement: rel property"
short-title: rel
slug: Web/API/HTMLAnchorElement/rel
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.rel
---
{{APIRef("HTML DOM")}}
The **`HTMLAnchorElement.rel`** property reflects the [`rel`](/en-US/docs/Web/HTML/Attributes/rel) attribute. It is a string containing a space-separated list of link types indicating the relationship between the resource represented by the {{HTMLElement("a")}} element and the current document.
## Value
A string.
## Examples
```js
const anchors = document.getElementsByTagName("a");
for (const anchor of anchors) {
alert(`Rel: ${anchor.rel}`);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The equivalent property on {{HTMLElement("area")}} and {{HTMLElement("link")}},
{{domxref("HTMLAreaElement.rel")}} and {{domxref("HTMLLinkElement.rel")}}.
- The very same list but as tokens: {{domxref("HTMLAnchorElement.relList")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/referrerpolicy/index.md | ---
title: "HTMLAnchorElement: referrerPolicy property"
short-title: referrerPolicy
slug: Web/API/HTMLAnchorElement/referrerPolicy
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.referrerPolicy
---
{{APIRef}}
The
**`HTMLAnchorElement.referrerPolicy`**
property reflect the HTML [`referrerpolicy`](/en-US/docs/Web/HTML/Element/a#referrerpolicy) attribute of the
{{HTMLElement("a")}} element defining which referrer is sent when fetching the resource.
## Value
A string; one of the following:
- `no-referrer`
- : The {{HTTPHeader("Referer")}} header will be omitted entirely. No referrer
information is sent along with requests.
- `no-referrer-when-downgrade`
- : The URL is sent
as a referrer when the protocol security level stays the same (e.g.HTTP→HTTP,
HTTPS→HTTPS), but isn't sent to a less secure destination (e.g. HTTPS→HTTP).
- `origin`
- : Only send the origin of the document as the referrer in all cases.
The document `https://example.com/page.html` will send the referrer
`https://example.com/`.
- `origin-when-cross-origin`
- : Send a full URL when performing a same-origin request, but only send the origin of
the document for other cases.
- `same-origin`
- : A referrer will be sent for [same-site origins](/en-US/docs/Web/Security/Same-origin_policy), but
cross-origin requests will contain no referrer information.
- `strict-origin`
- : Only send the origin of the document as the referrer when the protocol security
level stays the same (e.g. HTTPS→HTTPS), but don't send it to a less secure
destination (e.g. HTTPS→HTTP).
- `strict-origin-when-cross-origin` (default)
- : This is the user agent's default behavior if no policy is specified. Send a full URL when performing a same-origin request, only send the origin when the
protocol security level stays the same (e.g. HTTPS→HTTPS), and send no header to a
less secure destination (e.g. HTTPS→HTTP).
- `unsafe-url`
- : Send a full URL when performing a same-origin or cross-origin request. This policy
will leak origins and paths from TLS-protected resources to insecure origins.
Carefully consider the impact of this setting.
## Examples
```js
const elt = document.createElement("a");
const linkText = document.createTextNode("My link");
elt.appendChild(linkText);
elt.href = "https://developer.mozilla.org/en-US/";
elt.referrerPolicy = "no-referrer";
const div = document.getElementById("divAround");
div.appendChild(elt); // When clicked, the link will not send a referrer header.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLImageElement.referrerPolicy")}},
{{domxref("HTMLAreaElement.referrerPolicy")}}, and
{{domxref("HTMLIFrameElement.referrerPolicy")}}.
| 0 |
data/mdn-content/files/en-us/web/api/htmlanchorelement | data/mdn-content/files/en-us/web/api/htmlanchorelement/hreflang/index.md | ---
title: "HTMLAnchorElement: hreflang property"
short-title: hreflang
slug: Web/API/HTMLAnchorElement/hreflang
page-type: web-api-instance-property
browser-compat: api.HTMLAnchorElement.hreflang
---
{{ApiRef("HTML DOM")}}
The **`hreflang`** property of the {{domxref("HTMLAnchorElement")}} interface is a string that is the language of the linked resource.
It reflects the `hreflang` attribute of the {{HTMLElement("a")}} element and is the empty string (`""`) if there is no `hreflang` element.
Web browsers and search engines may use this information to understand the language of the linked content better, but they are not required to follow it. The value provided for the `hreflang` attribute adheres to the format defined in {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}. If not, it is ignored.
Web browsers do not rely solely on the `hreflang` attribute after fetching the linked resource. Instead, they use language information directly associated with the resource (e.g., through HTTP headers) to determine its language.
## Value
A string that contains a language tag, or the empty string (`""`) if there is no `hreflang` element.
## Example
```html
<a id="exampleLink" href="https://example.com" hreflang="en-IN">Example Link</a>
<p class="hreflang"></p>
```
```css
#exampleLink {
font-size: 1.5rem;
}
```
```js
const anchorElement = document.getElementById("exampleLink");
const pTag = document.querySelector(".hreflang");
console.log(anchorElement.hreflang); // Outputs: "en-IN"
pTag.textContent = anchorElement.hreflang;
```
## Result
{{EmbedLiveSample("Example",100,100)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLLinkElement.hreflang")}} property
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpubindgrouplayout/index.md | ---
title: GPUBindGroupLayout
slug: Web/API/GPUBindGroupLayout
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPUBindGroupLayout
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUBindGroupLayout`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} defines the structure and purpose of related GPU resources such as buffers that will be used in a pipeline, and is used as a template when creating {{domxref("GPUBindGroup")}}s.
A `GPUBindGroupLayout` object instance is created using the {{domxref("GPUDevice.createBindGroupLayout()")}} method.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("GPUBindGroupLayout.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/gpubindgrouplayout | data/mdn-content/files/en-us/web/api/gpubindgrouplayout/label/index.md | ---
title: "GPUBindGroupLayout: label property"
short-title: label
slug: Web/API/GPUBindGroupLayout/label
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUBindGroupLayout.label
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`label`** property of the
{{domxref("GPUBindGroupLayout")}} 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.createBindGroupLayout()")}} call, or you can get and set it directly on the `GPUBindGroupLayout` 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 `GPUBindGroupLayout.label`:
```js
// ...
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: "storage",
},
},
],
});
bindGroupLayout.label = "mybindgrouplayout";
console.log(bindGroupLayout.label); // "mybindgrouplayout";
```
Setting a label via the originating {{domxref("GPUDevice.createBindGroupLayout()")}} call, and then getting it via `GPUBindGroupLayout.label`:
```js
// ...
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: "storage",
},
},
],
label: "mybindgrouplayout",
});
console.log(bindGroupLayout.label); // "mybindgrouplayout";
```
## 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/battery_status_api/index.md | ---
title: Battery Status API
slug: Web/API/Battery_Status_API
page-type: web-api-overview
browser-compat:
- api.BatteryManager
- api.Navigator.getBattery
spec-urls: https://w3c.github.io/battery/
---
{{DefaultAPISidebar("Battery API")}}{{securecontext_header}}
The **Battery Status API**, more often referred to as the **Battery API**, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change. This can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss.
> **Note:** This API is _not available_ in [Web Workers](/en-US/docs/Web/API/Web_Workers_API) (not exposed via {{domxref("WorkerNavigator")}}).
## Interfaces
- {{domxref("BatteryManager")}}
- : Provides information about the system's battery charge level.
### Extensions to other interfaces
- {{domxref("Navigator.getBattery()")}}
- : Returns a {{JSxRef("Promise")}} that resolves with a {{DOMxRef("BatteryManager")}} object.
## Example
In this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. This is done by listening for the {{domxref("BatteryManager.chargingchange_event", "chargingchange")}}, {{domxref("BatteryManager.levelchange_event", "levelchange")}}, {{domxref("BatteryManager.chargingtimechange_event", "chargingtimechange")}}, {{domxref("BatteryManager.dischargingtimechange_event", "dischargingtimechange")}} events.
```js
navigator.getBattery().then((battery) => {
function updateAllBatteryInfo() {
updateChargeInfo();
updateLevelInfo();
updateChargingInfo();
updateDischargingInfo();
}
updateAllBatteryInfo();
battery.addEventListener("chargingchange", () => {
updateChargeInfo();
});
function updateChargeInfo() {
console.log(`Battery charging? ${battery.charging ? "Yes" : "No"}`);
}
battery.addEventListener("levelchange", () => {
updateLevelInfo();
});
function updateLevelInfo() {
console.log(`Battery level: ${battery.level * 100}%`);
}
battery.addEventListener("chargingtimechange", () => {
updateChargingInfo();
});
function updateChargingInfo() {
console.log(`Battery charging time: ${battery.chargingTime} seconds`);
}
battery.addEventListener("dischargingtimechange", () => {
updateDischargingInfo();
});
function updateDischargingInfo() {
console.log(`Battery discharging time: ${battery.dischargingTime} seconds`);
}
});
```
See also [the example in the specification](https://www.w3.org/TR/battery-status/#examples).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Hacks blog post - Using the Battery API](https://hacks.mozilla.org/2012/02/using-the-battery-api-part-of-webapi/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/authenticatorresponse/index.md | ---
title: AuthenticatorResponse
slug: Web/API/AuthenticatorResponse
page-type: web-api-interface
browser-compat: api.AuthenticatorResponse
---
{{APIRef("Web Authentication API")}}{{securecontext_header}}
The **`AuthenticatorResponse`** interface of the [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) is the base interface for interfaces that provide a cryptographic root of trust for a key pair. The child interfaces include information from the browser such as the challenge origin and either may be returned from {{domxref("PublicKeyCredential.response")}}.
## Interfaces based on AuthenticatorResponse
Below is a list of interfaces based on the AuthenticatorResponse interface.
- {{domxref("AuthenticatorAssertionResponse")}}
- {{domxref("AuthenticatorAttestationResponse")}}
## Instance properties
- {{domxref("AuthenticatorResponse.clientDataJSON")}}
- : A [JSON](/en-US/docs/Learn/JavaScript/Objects/JSON) string in an {{jsxref("ArrayBuffer")}}, representing the client data that was passed to {{domxref("CredentialsContainer.create()")}} or {{domxref("CredentialsContainer.get()")}}.
## Instance methods
None.
## Examples
### Getting an AuthenticatorAssertionResponse
```js
const options = {
challenge: new Uint8Array([
/* bytes sent from the server */
]),
};
navigator.credentials
.get({ publicKey: options })
.then((credentialInfoAssertion) => {
const assertionResponse = credentialInfoAssertion.response;
// send assertion response back to the server
// to proceed with the control of the credential
})
.catch((err) => console.error(err));
```
### Getting an AuthenticatorAttestationResponse
```js
const publicKey = {
challenge: new Uint8Array([
21, 31, 105 /* 29 more random bytes generated by the server */,
]),
rp: {
name: "Example CORP",
id: "login.example.com",
},
user: {
id: new Uint8Array(16),
name: "[email protected]",
displayName: "John Doe",
},
pubKeyCredParams: [
{
type: "public-key",
alg: -7,
},
],
};
navigator.credentials
.create({ publicKey })
.then((newCredentialInfo) => {
const attestationResponse = newCredentialInfo.response;
})
.catch((err) => console.error(err));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("AuthenticatorAttestationResponse")}}
- {{domxref("AuthenticatorAssertionResponse")}}
- {{domxref("PublicKeyCredential.response")}}
| 0 |
data/mdn-content/files/en-us/web/api/authenticatorresponse | data/mdn-content/files/en-us/web/api/authenticatorresponse/clientdatajson/index.md | ---
title: "AuthenticatorResponse: clientDataJSON property"
short-title: clientDataJSON
slug: Web/API/AuthenticatorResponse/clientDataJSON
page-type: web-api-instance-property
browser-compat: api.AuthenticatorResponse.clientDataJSON
---
{{APIRef("Web Authentication API")}}{{securecontext_header}}
The **`clientDataJSON`** property of the {{domxref("AuthenticatorResponse")}} interface stores a [JSON](/en-US/docs/Learn/JavaScript/Objects/JSON) string in an
{{jsxref("ArrayBuffer")}}, representing the client data that was passed to {{domxref("CredentialsContainer.create()", "navigator.credentials.create()")}} or {{domxref("CredentialsContainer.get()", "navigator.credentials.get()")}}. This property is only accessed on one of the child objects of `AuthenticatorResponse`, specifically {{domxref("AuthenticatorAttestationResponse")}} or {{domxref("AuthenticatorAssertionResponse")}}.
## Value
An {{jsxref("ArrayBuffer")}}.
## Instance properties
After the `clientDataJSON` object is converted from an
`ArrayBuffer` to a JavaScript object, it will have the following properties:
- `challenge`
- : The [base64url](/en-US/docs/Glossary/Base64)
encoded version of the cryptographic challenge sent from the relying party's server.
The original value are passed as the `challenge` option in
{{domxref("CredentialsContainer.get()")}} or
{{domxref("CredentialsContainer.create()")}}.
- `crossOrigin` {{optional_inline}}
- : A boolean. If set to `true`, it means that the calling context is an {{htmlelement("iframe")}} that is not same origin with its ancestor frames.
- `origin`
- : The fully qualified origin of the relying party which has been given by the
client/browser to the authenticator. We should expect the _relying party's
id_ to be a suffix of this value.
- `tokenBinding` {{optional_inline}} {{deprecated_inline}}
- : An object describing the state of [the token binding protocol](https://datatracker.ietf.org/doc/html/rfc8471) for the communication with the relying party. It has two properties:
- `status`: A string which is either `"supported"` which
indicates the client support token binding but did not negotiate with the relying
party or `"present"` when token binding was used already
- `id`: A string which is the [base64url](/en-US/docs/Glossary/Base64)
encoding of the token binding ID which was used for the communication.
Should this property be absent, it would indicate that the client does not support
token binding.
> **Note:** `tokenBinding` is deprecated as of Level 3 of the spec, but the field is reserved so that it won't be reused for a different purpose.
- `topOrigin` {{optional_inline}}
- : Contains the fully qualified top-level origin of the relying party. It is set only if it `crossOrigin` is `true`.
- `type`
- : A string which is either `"webauthn.get"` when an existing credential is
retrieved or `"webauthn.create"` when a new credential is created.
## Examples
```js
function arrayBufferToStr(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
// pk is a PublicKeyCredential that is the result of a create() or get() Promise
const clientDataStr = arrayBufferToStr(pk.clientDataJSON);
const clientDataObj = JSON.parse(clientDataStr);
console.log(clientDataObj.type); // "webauthn.create" or "webauthn.get"
console.log(clientDataObj.challenge); // base64 encoded String containing the original challenge
console.log(clientDataObj.origin); // the window.origin
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlheadelement/index.md | ---
title: HTMLHeadElement
slug: Web/API/HTMLHeadElement
page-type: web-api-interface
browser-compat: api.HTMLHeadElement
---
{{APIRef("HTML DOM")}}
The **`HTMLHeadElement`** interface contains the descriptive information, or metadata, for a document. This object inherits all of the properties and methods described in the {{domxref("HTMLElement")}} interface.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLHeadElement.profile")}} {{deprecated_inline}}
- : A string representing the URIs of one or more metadata profiles (white space separated).
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{HTMLElement("head")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svganimateelement/index.md | ---
title: SVGAnimateElement
slug: Web/API/SVGAnimateElement
page-type: web-api-interface
browser-compat: api.SVGAnimateElement
---
{{APIRef("SVG")}}
The **`SVGAnimateElement`** interface corresponds to the {{SVGElement("animate")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface has no properties but inherits properties from its parent, {{domxref("SVGAnimationElement")}}._
## Instance methods
_This interface has no methods but inherits methods from its parent, {{domxref("SVGAnimationElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/reporterror/index.md | ---
title: reportError() global function
short-title: reportError()
slug: Web/API/reportError
page-type: web-api-global-function
browser-compat: api.reportError
---
{{APIRef}} {{AvailableInWorkers}}
The **`reportError()`** global method may be used to report errors to the console or global event handlers, emulating an uncaught JavaScript exception.
This feature is primarily intended for custom event-dispatching or callback-manipulating libraries.
Libraries can use this feature to catch errors in callback code and re-throw them to the top level handler.
This ensures that an exception in one callback will not prevent others from being handled, while at the same time ensuring that stack trace information is still readily available for debugging at the top level.
<!-- {{EmbedInteractiveExample("pages/js/self-reporterror.html")}} -->
## Syntax
```js-nolint
reportError(throwable)
```
### Parameters
- `throwable`
- : An error object such as a {{jsxref("TypeError")}}.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : The method is called without an error argument.
## Examples
Feature test for the method using:
```js
if (typeof self.reportError === "function") {
// function is defined
}
```
The following code shows how you might create and report an error, and how it may be caught using either the global `onerror` handler or by adding a listener for the `error` event.
Note that the handler assigned to `onerror` must return `true` to stop the event propagating further.
```js
const newError = new Error("Some error message", "someFile.js", 11);
self.reportError(newError);
window.onerror = (message, source, lineno, colno, error) => {
console.error(`message: ${error.message}, lineno: ${lineno}`);
return true;
};
self.addEventListener("error", (error) => {
console.error(error.filename);
});
// Output
// > "message:Some error message, lineno: 11"
// > "someFile.js"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`Window`](/en-US/docs/Web/API/Window#methods_implemented_from_elsewhere)
- [`WorkerGlobalScope`](/en-US/docs/Web/API/WorkerGlobalScope#methods_implemented_from_elsewhere)
- [error](/en-US/docs/Web/API/HTMLElement/error_event) event
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/url_pattern_api/index.md | ---
title: URL Pattern API
slug: Web/API/URL_Pattern_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.URLPattern
spec-urls: https://urlpattern.spec.whatwg.org/
---
{{DefaultAPISidebar("URL Pattern API")}}{{SeeCompatTable}}
The **URL Pattern API** defines a syntax that is used to create URL pattern
matchers. These patterns can be matched against URLs or individual URL
components. The URL Pattern API is used by the {{domxref("URLPattern")}}
interface.
{{AvailableInWorkers}}
## Concepts and usage
The pattern syntax is based on the syntax from the
[path-to-regexp](https://github.com/pillarjs/path-to-regexp) library. Patterns
can contain:
- Literal strings which will be matched exactly.
- Wildcards (`/posts/*`) that match any character.
- Named groups (`/books/:id`) which extract a part of the matched URL.
- Non-capturing groups (`/books{/old}?`) which make parts of a pattern optional
or be matched multiple times.
- {{jsxref("RegExp")}} groups (`/books/(\\d+)`) which make arbitrarily complex
regex matches with a few [limitations](#regex_matchers_limitations).
You can find details about the syntax in the [pattern syntax](#pattern_syntax)
section below.
## Interfaces
The URL Pattern API only has a single related interface:
- {{domxref("URLPattern")}} {{Experimental_Inline}}
- : Represents a pattern that can match URLs or parts of URLs. The pattern can contain capturing groups that extract parts of the matched URL.
## Pattern syntax
The syntax for patterns is based on the
[path-to-regexp](https://github.com/pillarjs/path-to-regexp) JavaScript library.
This syntax is similar to the one used in
[Ruby on Rails](https://rubyonrails.org), or JavaScript frameworks like
[Express](https://expressjs.com/) or [Next.js](https://nextjs.org/).
### Fixed text and capture groups
Each pattern can contain a combination of fixed text and groups. The fixed text
is a sequence of characters that is matched exactly. Groups match an arbitrary
string based on matching rules. Each URL part has its own default rules that are
explained below, but they can be overwritten.
```js
// A pattern matching some fixed text
const pattern = new URLPattern({ pathname: "/books" });
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.exec("https://example.com/books").pathname.groups); // {}
```
```js
// A pattern matching with a named group
const pattern = new URLPattern({ pathname: "/books/:id" });
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { id: '123' }
```
### Segment wildcard
By default, a group matching the `pathname` part of the URL will match all
characters but the forward slash (`/`). In the `hostname` part, the group will
match all characters except the dot (`.`). In all other parts, the group will
match all characters. The segment wildcard is non-greedy, meaning that it will
match the shortest possible string.
### Regex matchers
Instead of using the default match rules for a group, you can use a regex for
each group. This regex defines the matching rules for the group. Below is an
example of a regex matcher on a named group that constrains the group to only
match if it contains one or more digits:
```js
const pattern = new URLPattern("/books/:id(\\d+)", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books/abc")); // false
console.log(pattern.test("https://example.com/books/")); // false
```
### Regex matchers limitations
Some regex patterns do not work as you may expect:
- Starts with `^` will only match if used at the start of the protocol portion of the URLPattern and is redundant if used.
```js
// with `^` in pathname
const pattern = new URLPattern({ pathname: "(^b)" });
console.log(pattern.test("https://example.com/ba")); // false
console.log(pattern.test("https://example.com/xa")); // false
```
```js
// with `^` in protocol
const pattern = new URLPattern({ protocol: "(^https?)" });
console.log(pattern.test("https://example.com/index.html")); // true
console.log(pattern.test("xhttps://example.com/index.html")); // false
```
```js
// without `^` in protocol
const pattern = new URLPattern({ protocol: "(https?)" });
console.log(pattern.test("https://example.com/index.html")); // true
console.log(pattern.test("xhttps://example.com/index.html")); // false
```
- Ends with `$` will only match if used at the end of the hash portion of the URLPattern and is redundant if used.
```js
// with `$` in pathname
const pattern = new URLPattern({ pathname: "(path$)" });
console.log(pattern.test("https://example.com/path")); // false
console.log(pattern.test("https://example.com/other")); // false
```
```js
// with `$` in hash
const pattern = new URLPattern({ hash: "(hash$)" });
console.log(pattern.test("https://example.com/#hash")); // true
console.log(pattern.test("xhttps://example.com/#otherhash")); // false
```
```js
// without `$` in hash
const pattern = new URLPattern({ hash: "(hash)" });
console.log(pattern.test("https://example.com/#hash")); // true
console.log(pattern.test("xhttps://example.com/#otherhash")); // false
```
- Lookaheads, and lookbehinds will never match any portion of the URLPattern.
```js
// lookahead
const pattern = new URLPattern({ pathname: "(a(?=b))" });
console.log(pattern.test("https://example.com/ab")); // false
console.log(pattern.test("https://example.com/ax")); // false
```
```js
// negative-lookahead
const pattern = new URLPattern({ pathname: "(a(?!b))" });
console.log(pattern.test("https://example.com/ab")); // false
console.log(pattern.test("https://example.com/ax")); // false
```
```js
// lookbehind
const pattern = new URLPattern({ pathname: "((?<=b)a)" });
console.log(pattern.test("https://example.com/ba")); // false
console.log(pattern.test("https://example.com/xa")); // false
```
```js
// negative-lookbehind
const pattern = new URLPattern({ pathname: "((?<!b)a)" });
console.log(pattern.test("https://example.com/ba")); // false
console.log(pattern.test("https://example.com/xa")); // false
```
- Parentheses need to be escaped in range expressions within URLPattern even though they don't in RegExp.
```js
new URLPattern({ pathname: "([()])" }); // throws
new URLPattern({ pathname: "([\\(\\)])" }); // ok
new RegExp("[()]"); // ok
new RegExp("[\\(\\)]"); // ok
```
### Unnamed and named groups
Groups can either be named or unnamed. Named groups are specified by prefixing
the group name with a colon (`:`). Regexp groups that are not prefixed by a
colon and a name are unnamed. Unnamed groups are numerically indexed in the match
result based on their order in the pattern.
```js
// A named group
const pattern = new URLPattern("/books/:id(\\d+)", "https://example.com");
console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { id: '123' }
```
```js
// An unnamed group
const pattern = new URLPattern("/books/(\\d+)", "https://example.com");
console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { '0': '123' }
```
### Group modifiers
Groups can also have modifiers. These are specified after the group name (or
after the regexp if there is one). There are three modifiers: `?` to make the
group optional, `+` to make the group repeat one or more times, and `*` to make
the group repeat zero or more times.
```js
// An optional group
const pattern = new URLPattern("/books/:id?", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/books/")); // false
console.log(pattern.test("https://example.com/books/123/456")); // false
console.log(pattern.test("https://example.com/books/123/456/789")); // false
```
```js
// A repeating group with a minimum of one
const pattern = new URLPattern("/books/:id+", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // false
console.log(pattern.test("https://example.com/books/")); // false
console.log(pattern.test("https://example.com/books/123/456")); // true
console.log(pattern.test("https://example.com/books/123/456/789")); // true
```
```js
// A repeating group with a minimum of zero
const pattern = new URLPattern("/books/:id*", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/books/")); // false
console.log(pattern.test("https://example.com/books/123/456")); // true
console.log(pattern.test("https://example.com/books/123/456/789")); // true
```
### Group delimiters
Patterns can also contain group delimiters. These are pieces of a pattern that
are surrounded by curly braces (`{}`). These group delimiters are not captured
in the match result like capturing groups, but can still have modifiers applied
to them, just like groups. If group delimiters are not modified by a modifier,
they are treated as if the items in them were just part of the parent pattern.
Group delimiters may not contain other group delimiters, but may contain any
other pattern items (capturing groups, regex, wildcard, or fixed text).
```js
// A group delimiter with a ? (optional) modifier
const pattern = new URLPattern("/book{s}?", "https://example.com");
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/book")); // true
console.log(pattern.exec("https://example.com/books").pathname.groups); // {}
```
```js
// A group delimiter without a modifier
const pattern = new URLPattern("/book{s}", "https://example.com");
console.log(pattern.pathname); // /books
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/book")); // false
```
```js
// A group delimiter containing a capturing group
const pattern = new URLPattern({ pathname: "/blog/:id(\\d+){-:title}?" });
console.log(pattern.test("https://example.com/blog/123-my-blog")); // true
console.log(pattern.test("https://example.com/blog/123")); // true
console.log(pattern.test("https://example.com/blog/my-blog")); // false
```
### Automatic group prefixing in pathnames
In patterns that match against the `pathname` part of a URL, groups get an
automatic slash (`/`) prefix added if the group definition is preceded by a
slash (`/`). This is useful for groups with modifiers, as it allows for
repeating groups to work as expected.
If you do not want automatic prefixing, you can disable it by surrounding the
group with group delimiters (`{}`). Group delimiters do not have automatic
prefixing behavior.
```js
// A pattern with an optional group, preceded by a slash
const pattern = new URLPattern("/books/:id?", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/books/")); // false
```
```js
// A pattern with a repeating group, preceded by a slash
const pattern = new URLPattern("/books/:id+", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books/123/456")); // true
console.log(pattern.test("https://example.com/books/123/")); // false
console.log(pattern.test("https://example.com/books/123/456/")); // false
```
```js
// Segment prefixing does not occur outside of pathname patterns
const pattern = new URLPattern({ hash: "/books/:id?" });
console.log(pattern.test("https://example.com#/books/123")); // true
console.log(pattern.test("https://example.com#/books")); // false
console.log(pattern.test("https://example.com#/books/")); // true
```
```js
// Disabling segment prefixing for a group using a group delimiter
const pattern = new URLPattern({ pathname: "/books/{:id}?" });
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // false
console.log(pattern.test("https://example.com/books/")); // true
```
### Wildcard tokens
The wildcard token (`*`) is a shorthand for an unnamed capturing group that
matches all characters zero or more times. You can place this anywhere in the
pattern. The wildcard is greedy, meaning that it will match the longest possible
string.
```js
// A wildcard at the end of a pattern
const pattern = new URLPattern("/books/*", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // false
console.log(pattern.test("https://example.com/books/")); // true
console.log(pattern.test("https://example.com/books/123/456")); // true
```
```js
// A wildcard in the middle of a pattern
const pattern = new URLPattern("/*.png", "https://example.com");
console.log(pattern.test("https://example.com/image.png")); // true
console.log(pattern.test("https://example.com/image.png/123")); // false
console.log(pattern.test("https://example.com/folder/image.png")); // true
console.log(pattern.test("https://example.com/.png")); // true
```
### Pattern normalization
When a pattern is parsed it is automatically normalized to a canonical form. For
example, unicode characters are percent encoded in the pathname property,
punycode encoding is used in the hostname, default port numbers are elided,
paths like `/foo/./bar/` are collapsed to just `/foo/bar`, etc. In addition,
there are some pattern representations that parse to the same underlying
meaning, like `foo` and `{foo}`. Such cases are normalized to the simplest form.
In this case `{foo}` gets changed to `foo`.
## Case sensitivity
The URL Pattern API treats many parts of the URL as case-sensitive by default when matching. In contrast, many client-side JavaScript frameworks use case-insensitive URL matching. An `ignoreCase` option is available on the {{domxref("URLPattern.URLPattern", "URLPattern()")}} constructor to enable case-insensitive matching if desired.
```js
// Case-sensitive matching by default
const pattern = new URLPattern("https://example.com/2022/feb/*");
console.log(pattern.test("https://example.com/2022/feb/xc44rsz")); // true
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz")); // false
```
Setting the `ignoreCase` option to `true` in the constructor switches all matching operations to case-insensitive for the given pattern:
```js
// Case-insensitive matching
const pattern = new URLPattern("https://example.com/2022/feb/*", {
ignoreCase: true,
});
console.log(pattern.test("https://example.com/2022/feb/xc44rsz")); // true
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz")); // true
```
## Examples
### Filter on a specific URL component
The following example shows how a `URLPattern` filters a specific URL component.
When the `URLPattern()` constructor is called with a structured object of
component patterns any missing components default to the `*` wildcard value.
```js
// Construct a URLPattern that matches a specific domain and its subdomains.
// All other URL components default to the wildcard `*` pattern.
const pattern = new URLPattern({
hostname: "{*.}?example.com",
});
console.log(pattern.hostname); // '{*.}?example.com'
console.log(pattern.protocol); // '*'
console.log(pattern.username); // '*'
console.log(pattern.password); // '*'
console.log(pattern.pathname); // '*'
console.log(pattern.search); // '*'
console.log(pattern.hash); // '*'
console.log(pattern.test("https://example.com/foo/bar")); // true
console.log(pattern.test({ hostname: "cdn.example.com" })); // true
console.log(pattern.test("custom-protocol://example.com/other/path?q=1")); // false
// Prints `false` because the hostname component does not match
console.log(pattern.test("https://cdn-example.com/foo/bar"));
```
### Construct a URLPattern from a full URL string
The following example shows how to construct a `URLPattern` from a full URL
string with embedded patterns. For example, a `:` can be both the URL protocol
suffix, like `https:`, and the beginning of a named pattern group, like `:foo`.
It "just works" if there is no ambiguity between whether a character is part of
the URL syntax or part of the pattern syntax.
```js
// Construct a URLPattern that matches URLs to CDN servers loading jpg images.
// URL components not explicitly specified, like search and hash here, result
// in the empty string similar to the URL() constructor.
const pattern = new URLPattern("https://cdn-*.example.com/*.jpg");
console.log(pattern.protocol); // 'https'
console.log(pattern.hostname); // 'cdn-*.example.com'
console.log(pattern.pathname); // '/*.jpg'
console.log(pattern.username); // ''
console.log(pattern.password); // ''
console.log(pattern.search); // ''
console.log(pattern.hash); // ''
// Prints `true`
console.log(
pattern.test("https://cdn-1234.example.com/product/assets/hero.jpg"),
);
// Prints `false` because the search component does not match
console.log(
pattern.test("https://cdn-1234.example.com/product/assets/hero.jpg?q=1"),
);
```
### Constructing a URLPattern with an ambiguous URL string
The following example shows how a `URLPattern` constructed from an ambiguous
string will favor treating characters as part of the pattern syntax. In this
case the `:` character could be the protocol component suffix or it could be the
prefix for a named group in the pattern. The constructor chooses to treat this
as part of the pattern and therefore determines this is a relative pathname
pattern. Since there is no base URL the relative pathname cannot be resolved and
it throws an error.
```js
// Throws because this is interpreted as a single relative pathname pattern
// with a ":foo" named group and there is no base URL.
const pattern = new URLPattern("data:foo*");
```
### Escaping characters to disambiguate URLPattern constructor strings
The following example shows how an ambiguous constructor string character can be
escaped to be treated as a URL separator instead of a pattern character. Here
`:` is escaped as `\\:`.
```js
// Constructs a URLPattern treating the `:` as the protocol suffix.
const pattern = new URLPattern("data\\:foo*");
console.log(pattern.protocol); // 'data'
console.log(pattern.pathname); // 'foo*'
console.log(pattern.username); // ''
console.log(pattern.password); // ''
console.log(pattern.hostname); // ''
console.log(pattern.port); // ''
console.log(pattern.search); // ''
console.log(pattern.hash); // ''
console.log(pattern.test("data:foobar")); // true
```
### Using base URLs for test() and exec()
The following example shows how `test()` and `exec()` can use base URLs.
```js
const pattern = new URLPattern({ hostname: "example.com", pathname: "/foo/*" });
// Prints `true` as the hostname based in the dictionary `baseURL` property
// matches.
console.log(
pattern.test({
pathname: "/foo/bar",
baseURL: "https://example.com/baz",
}),
);
// Prints `true` as the hostname in the second argument base URL matches.
console.log(pattern.test("/foo/bar", "https://example.com/baz"));
// Throws because the second argument cannot be passed with a dictionary input.
try {
pattern.test({ pathname: "/foo/bar" }, "https://example.com/baz");
} catch (e) {}
// The `exec()` method takes the same arguments as `test()`.
const result = pattern.exec("/foo/bar", "https://example.com/baz");
console.log(result.pathname.input); // '/foo/bar'
console.log(result.pathname.groups[0]); // 'bar'
console.log(result.hostname.input); // 'example.com'
```
### Using base URLs in the URLPattern constructor
The follow example shows how base URLs can also be used to construct the
`URLPattern`. Note that the base URL in these cases is treated strictly as a URL
and cannot contain any pattern syntax itself.
Also, since the base URL provides a value for every component the resulting
`URLPattern` will also have a value for every component, even if it's the empty
string. This means you do not get the "default to wildcard" behavior.
```js
const pattern1 = new URLPattern({
pathname: "/foo/*",
baseURL: "https://example.com",
});
console.log(pattern1.protocol); // 'https'
console.log(pattern1.hostname); // 'example.com'
console.log(pattern1.pathname); // '/foo/*'
console.log(pattern1.username); // ''
console.log(pattern1.password); // ''
console.log(pattern1.port); // ''
console.log(pattern1.search); // ''
console.log(pattern1.hash); // ''
// Equivalent to pattern1
const pattern2 = new URLPattern("/foo/*", "https://example.com");
// Throws because a relative constructor string must have a base URL to resolve
// against.
try {
const pattern3 = new URLPattern("/foo/*");
} catch (e) {}
```
### Accessing matched group values
The following example shows how input values that match pattern groups can later
be accessed from the `exec()` result object. Unnamed groups are assigned index
numbers sequentially.
```js
const pattern = new URLPattern({ hostname: "*.example.com" });
const result = pattern.exec({ hostname: "cdn.example.com" });
console.log(result.hostname.groups[0]); // 'cdn'
console.log(result.hostname.input); // 'cdn.example.com'
console.log(result.inputs); // [{ hostname: 'cdn.example.com' }]
```
### Accessing matched group values using custom names
The following example shows how groups can be given custom names which can be
used to accessed the matched value in the result object.
```js
// Construct a URLPattern using matching groups with custom names. These
// names can then be later used to access the matched values in the result
// object.
const pattern = new URLPattern({ pathname: "/:product/:user/:action" });
const result = pattern.exec({ pathname: "/store/wanderview/view" });
console.log(result.pathname.groups.product); // 'store'
console.log(result.pathname.groups.user); // 'wanderview'
console.log(result.pathname.groups.action); // 'view'
console.log(result.pathname.input); // '/store/wanderview/view'
console.log(result.inputs); // [{ pathname: '/store/wanderview/view' }]
```
### Custom regular expression groups
The following example shows how a matching group can use a custom regular
expression.
```js
const pattern = new URLPattern({ pathname: "/(foo|bar)" });
console.log(pattern.test({ pathname: "/foo" })); // true
console.log(pattern.test({ pathname: "/bar" })); // true
console.log(pattern.test({ pathname: "/baz" })); // false
const result = pattern.exec({ pathname: "/foo" });
console.log(result.pathname.groups[0]); // 'foo'
```
### Named group with a custom regular expression
The following example shows how to use a custom regular expression with a named
group.
```js
const pattern = new URLPattern({ pathname: "/:type(foo|bar)" });
const result = pattern.exec({ pathname: "/foo" });
console.log(result.pathname.groups.type); // 'foo'
```
### Making matching groups optional
The following example shows how to make a matching group optional by placing a
`?` modifier after it. For the pathname component this also causes any preceding
`/` character to be treated as an optional prefix to the group.
```js
const pattern = new URLPattern({ pathname: "/product/(index.html)?" });
console.log(pattern.test({ pathname: "/product/index.html" })); // true
console.log(pattern.test({ pathname: "/product" })); // true
const pattern2 = new URLPattern({ pathname: "/product/:action?" });
console.log(pattern2.test({ pathname: "/product/view" })); // true
console.log(pattern2.test({ pathname: "/product" })); // true
// Wildcards can be made optional as well. This may not seem to make sense
// since they already match the empty string, but it also makes the prefix
// `/` optional in a pathname pattern.
const pattern3 = new URLPattern({ pathname: "/product/*?" });
console.log(pattern3.test({ pathname: "/product/wanderview/view" })); // true
console.log(pattern3.test({ pathname: "/product" })); // true
console.log(pattern3.test({ pathname: "/product/" })); // true
```
### Making matching groups repeated
The following example shows how a matching group can be made repeated by placing
`+` modifier after it. In the `pathname` component this also treats the `/`
prefix as special. It is repeated with the group.
```js
const pattern = new URLPattern({ pathname: "/product/:action+" });
const result = pattern.exec({ pathname: "/product/do/some/thing/cool" });
result.pathname.groups.action; // 'do/some/thing/cool'
console.log(pattern.test({ pathname: "/product" })); // false
```
### Making matching groups optional and repeated
The following example shows how to make a matching group that is both optional
and repeated. Do this by placing a `*` modifier after the group. Again, the
pathname component treats the `/` prefix as special. It both becomes optional
and is also repeated with the group.
```js
const pattern = new URLPattern({ pathname: "/product/:action*" });
const result = pattern.exec({ pathname: "/product/do/some/thing/cool" });
console.log(result.pathname.groups.action); // 'do/some/thing/cool'
console.log(pattern.test({ pathname: "/product" })); // true
```
### Using a custom prefix or suffix for an optional or repeated modifier
The following example shows how curly braces can be used to denote a custom
prefix and/or suffix to be operated on by a subsequent `?`, `*`, or `+`
modifier.
```js
const pattern = new URLPattern({ hostname: "{:subdomain.}*example.com" });
console.log(pattern.test({ hostname: "example.com" })); // true
console.log(pattern.test({ hostname: "foo.bar.example.com" })); // true
console.log(pattern.test({ hostname: ".example.com" })); // false
const result = pattern.exec({ hostname: "foo.bar.example.com" });
console.log(result.hostname.groups.subdomain); // 'foo.bar'
```
### Making text optional or repeated without a matching group
The following example shows how curly braces can be used to denote fixed text
values as optional or repeated without using a matching group.
```js
const pattern = new URLPattern({ pathname: "/product{/}?" });
console.log(pattern.test({ pathname: "/product" })); // true
console.log(pattern.test({ pathname: "/product/" })); // true
const result = pattern.exec({ pathname: "/product/" });
console.log(result.pathname.groups); // {}
```
### Using multiple components and features at once
The following example shows how many features can be combined across multiple
URL components.
```js
const pattern = new URLPattern({
protocol: "http{s}?",
username: ":user?",
password: ":pass?",
hostname: "{:subdomain.}*example.com",
pathname: "/product/:action*",
});
const result = pattern.exec(
"http://foo:[email protected]/product/view?q=12345",
);
console.log(result.username.groups.user); // 'foo'
console.log(result.password.groups.pass); // 'bar'
console.log(result.hostname.groups.subdomain); // 'sub'
console.log(result.pathname.groups.action); // 'view'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- A polyfill of `URLPattern` is available
[on GitHub](https://github.com/kenchris/urlpattern-polyfill)
- The pattern syntax used by URLPattern is similar to the syntax used by
[path-to-regexp](https://github.com/pillarjs/path-to-regexp)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/audiodestinationnode/index.md | ---
title: AudioDestinationNode
slug: Web/API/AudioDestinationNode
page-type: web-api-interface
browser-compat: api.AudioDestinationNode
---
{{APIRef("Web Audio API")}}
The `AudioDestinationNode` interface represents the end destination of an audio graph in a given context — usually the speakers of your device. It can also be the node that will "record" the audio data when used with an `OfflineAudioContext`.
`AudioDestinationNode` has no output (as it _is_ the output, no more `AudioNode` can be linked after it in the audio graph) and one input. The number of channels in the input must be between `0` and the `maxChannelCount` value or an exception is raised.
The `AudioDestinationNode` of a given `AudioContext` can be retrieved using the {{domxref("BaseAudioContext/destination", "AudioContext.destination")}} property.
{{InheritanceDiagram}}
<table class="properties">
<tbody>
<tr>
<th scope="row">Number of inputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Number of outputs</th>
<td><code>0</code></td>
</tr>
<tr>
<th scope="row">Channel count mode</th>
<td><code>"explicit"</code></td>
</tr>
<tr>
<th scope="row">Channel count</th>
<td><code>2</code></td>
</tr>
<tr>
<th scope="row">Channel interpretation</th>
<td><code>"speakers"</code></td>
</tr>
</tbody>
</table>
## Instance properties
_Inherits properties from its parent, {{domxref("AudioNode")}}_.
- {{domxref("AudioDestinationNode.maxChannelCount")}}
- : An `unsigned long` defining the maximum number of channels that the physical device can handle.
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("AudioNode")}}_.
## Example
There is no complex set up for using an `AudioDestinationNode` — by default, this represents the output of the user's system (e.g. their speakers), so you can get it hooked up inside an audio graph using only a few lines of code:
```js
const audioCtx = new AudioContext();
const source = audioCtx.createMediaElementSource(myMediaElement);
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
```
To see a more complete implementation, check out one of our MDN Web Audio examples, such as [Voice-change-o-matic](https://mdn.github.io/webaudio-examples/voice-change-o-matic/) or [Violent Theremin](https://github.com/mdn/webaudio-examples/tree/main/violent-theremin).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/audiodestinationnode | data/mdn-content/files/en-us/web/api/audiodestinationnode/maxchannelcount/index.md | ---
title: "AudioDestinationNode: maxChannelCount property"
short-title: maxChannelCount
slug: Web/API/AudioDestinationNode/maxChannelCount
page-type: web-api-instance-property
browser-compat: api.AudioDestinationNode.maxChannelCount
---
{{ APIRef("Web Audio API") }}
The `maxchannelCount` property of the {{ domxref("AudioDestinationNode") }} interface is an `unsigned long` defining the maximum amount of channels that the physical device can handle.
The {{domxref("AudioNode.channelCount")}} property can be set between 0 and this value (both included). If `maxChannelCount` is `0`, like in {{domxref("OfflineAudioContext")}}, the channel count cannot be changed.
## Value
An `unsigned long`.
## Examples
The following would set up a simple audio graph, featuring an `AudioDestinationNode` with `maxChannelCount` of 2:
```js
const audioCtx = new AudioContext();
const source = audioCtx.createMediaElementSource(myMediaElement);
source.connect(gainNode);
audioCtx.destination.maxChannelCount = 2;
gainNode.connect(audioCtx.destination);
```
To see a more complete implementation, check out one of our MDN Web Audio examples, such as [Voice-change-o-matic](https://mdn.github.io/webaudio-examples/voice-change-o-matic/) or [Violent Theremin](https://mdn.github.io/webaudio-examples/violent-theremin/).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/usb/index.md | ---
title: USB
slug: Web/API/USB
page-type: web-api-interface
status:
- experimental
browser-compat: api.USB
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{securecontext_header}}
The **`USB`** interface of the [WebUSB API](/en-US/docs/Web/API/WebUSB_API) provides attributes and methods for finding and connecting USB devices from a web page.
Use {{domxref("navigator.usb")}} to get access to the `USB` object.
The USB interface inherits from {{domxref("EventTarget")}}.
{{InheritanceDiagram}}
## Instance properties
None.
## Instance methods
- {{domxref("USB.getDevices()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves with an array of {{domxref("USBDevice")}} objects for paired attached devices.
- {{domxref("USB.requestDevice()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves with an instance of {{domxref("USBDevice")}} if the specified device is found. Calling this function triggers the user agent's pairing flow.
## Events
- {{domxref("USB.connect_event", "connect")}} {{Experimental_Inline}}
- : Fired whenever a previously paired device is connected.
- {{domxref("USB.disconnect_event", "disconnect")}} {{Experimental_Inline}}
- : Fired whenever a paired device is disconnected.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usb | data/mdn-content/files/en-us/web/api/usb/disconnect_event/index.md | ---
title: "USB: disconnect event"
short-title: disconnect
slug: Web/API/USB/disconnect_event
page-type: web-api-event
status:
- experimental
browser-compat: api.USB.disconnect_event
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`disconnect`** event of the {{DOMxRef("USB")}} interface is fired whenever a paired device is disconnected.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("disconnect", (event) => {});
ondisconnect = (event) => {};
```
## Event type
A {{domxref("USBConnectionEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("USBConnectionEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("USBConnectionEvent.device", "device")}} {{ReadOnlyInline}}
- : The {{domxref("USBDevice")}} the event is fired for.
## Examples
Once a USB device is disconnected, you might want to update the UI.
```js
navigator.usb.addEventListener("disconnect", (event) => {
// Remove event.device from the UI.
});
```
Alternatively, you can use the `USB.ondiscconnect` event handler property to establish a handler for the `disconnect` event:
```js
navigator.usb.ondisconnect = (event) => {
// Remove event.device from the UI.
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usb | data/mdn-content/files/en-us/web/api/usb/requestdevice/index.md | ---
title: "USB: requestDevice() method"
short-title: requestDevice()
slug: Web/API/USB/requestDevice
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USB.requestDevice
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{securecontext_header}}
The **`requestDevice()`** method of the {{domxref("USB")}}
interface returns a {{jsxref("Promise")}} that resolves with an instance of
{{domxref("USBDevice")}} if the specified device is found. Calling this function
triggers the user agent's pairing flow.
## Syntax
```js-nolint
requestDevice(filters)
```
### Parameters
- `filters`
- : An array of filter objects for possible devices you would like to pair. Each filter
object can have the following properties:
- `vendorId`
- `productId`
- `classCode`
- `subclassCode`
- `protocolCode`
- `serialNumber`
### Return value
A {{JSxRef("Promise")}} that resolves with an instance of {{DOMxRef("USBDevice")}}.
## Security
[Transient user activation](/en-US/docs/Web/Security/User_activation) is required. The user has to interact with the page or a UI element in order for this feature to work.
## Examples
The following example looks for one of two USB devices. Notice that two product IDs are
specified. Both are passed to `requestDevice()`. This triggers a user-agent
flow that prompts the user to select a device for pairing. Only the selected device is
passed to `then()`.
The number of filters does not specify the number of devices shown by the user agent.
For example, if only a USB device with product ID `0xa800` is found, then
only one device will be listed by the user agent. On the other hand if the user agent
finds two of the first listed device and one of the second, then all three devices will
be listed.
```js
const filters = [
{ vendorId: 0x1209, productId: 0xa800 },
{ vendorId: 0x1209, productId: 0xa850 },
];
navigator.usb
.requestDevice({ filters })
.then((usbDevice) => {
console.log(`Product name: ${usbDevice.productName}`);
})
.catch((e) => {
console.error(`There is no device. ${e}`);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usb | data/mdn-content/files/en-us/web/api/usb/connect_event/index.md | ---
title: "USB: connect event"
short-title: connect
slug: Web/API/USB/connect_event
page-type: web-api-event
status:
- experimental
browser-compat: api.USB.connect_event
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`connect`** event of the {{DOMxRef("USB")}} interface is fired whenever a paired device is connected.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("connect", (event) => {});
onconnect = (event) => {};
```
## Event type
A {{domxref("USBConnectionEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("USBConnectionEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("USBConnectionEvent.device", "device")}} {{ReadOnlyInline}}
- : The {{domxref("USBDevice")}} the event is fired for.
## Examples
Once a USB device is connected, you might want to update the UI.
```js
navigator.usb.addEventListener("connect", (event) => {
// Add event.device to the UI.
});
```
Alternatively, you can use the `USB.onconnect` event handler property to establish a handler for the `connect` event:
```js
navigator.usb.onconnect = (event) => {
// Add event.device to the UI.
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usb | data/mdn-content/files/en-us/web/api/usb/getdevices/index.md | ---
title: "USB: getDevices() method"
short-title: getDevices()
slug: Web/API/USB/getDevices
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USB.getDevices
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{securecontext_header}}
The **`getDevices`** method of the {{DOMxRef("USB")}} interface
returns a {{JSxRef("Promise")}} that resolves with an array of {{DOMxRef("USBDevice")}}
objects for paired attached devices. For information on pairing devices, see
{{DOMxRef("USB.requestDevice()")}}.
## Syntax
```js-nolint
getDevices()
```
### Parameters
None.
### Return value
A {{JSxRef("Promise")}} that resolves with an array of {{DOMxRef("USBDevice")}}
objects.
## Examples
The following example logs the product name and serial number of paired devices to the
console. For information on pairing devices, see
{{DOMxRef("USB.requestDevice","USB.requestDevice()")}}.
```js
navigator.usb.getDevices().then((devices) => {
console.log(`Total devices: ${devices.length}`);
devices.forEach((device) => {
console.log(
`Product name: ${device.productName}, serial number ${device.serialNumber}`,
);
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgtextpathelement/index.md | ---
title: SVGTextPathElement
slug: Web/API/SVGTextPathElement
page-type: web-api-interface
browser-compat: api.SVGTextPathElement
---
{{APIRef("SVG")}}
The **`SVGTextPathElement`** interface corresponds to the {{SVGElement("textPath")}} element.
{{InheritanceDiagram}}
## Constants
### Method types
<table class="no-markdown">
<tbody>
<tr>
<th>Name</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td><code>TEXTPATH_METHODTYPE_UNKNOWN</code></td>
<td>0</td>
<td>
The type is not one of predefined types. It is invalid to attempt to
define a new value of this type or to attempt to switch an existing
value to this type.
</td>
</tr>
<tr>
<td><code>TEXTPATH_METHODTYPE_ALIGN</code></td>
<td>1</td>
<td>Corresponds to the value <code>align</code>.</td>
</tr>
<tr>
<td><code>TEXTPATH_METHODTYPE_STRETCH</code></td>
<td>2</td>
<td>Corresponds to the value <code>stretch</code>.</td>
</tr>
</tbody>
</table>
### Spacing types
<table class="no-markdown">
<tbody>
<tr>
<th>Name</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td><code>TEXTPATH_SPACINGTYPE_UNKNOWN</code></td>
<td>0</td>
<td>
The type is not one of predefined types. It is invalid to attempt to
define a new value of this type or to attempt to switch an existing
value to this type.
</td>
</tr>
<tr>
<td><code>TEXTPATH_SPACINGTYPE_AUTO</code></td>
<td>1</td>
<td>Corresponds to the value <code>auto</code>.</td>
</tr>
<tr>
<td><code>TEXTPATH_SPACINGTYPE_EXACT</code></td>
<td>2</td>
<td>Corresponds to the value <code>exact</code>.</td>
</tr>
</tbody>
</table>
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGTextContentElement")}}._
- {{domxref("SVGTextPathElement.href")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("href")}} or {{SVGAttr("xlink:href")}} {{deprecated_inline}} attribute of the given element.
- {{domxref("SVGTextPathElement.startOffset")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the X component of the {{SVGAttr("startOffset")}} attribute of the given element.
- {{domxref("SVGTextPathElement.method")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("method")}} attribute of the given element. It takes one of the `TEXTPATH_METHODTYPE_*` constants defined on this interface.
- {{domxref("SVGTextPathElement.spacing")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("spacing")}} attribute of the given element. It takes one of the `TEXTPATH_SPACINGTYPE_*` constants defined on this interface.
## Instance methods
_This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGTextContentElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("textPath")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xranchor/index.md | ---
title: XRAnchor
slug: Web/API/XRAnchor
page-type: web-api-interface
status:
- experimental
browser-compat: api.XRAnchor
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}{{SeeCompatTable}}
The **`XRAnchor`** interface creates anchors which keep track of the pose that is fixed relative to the real world. With anchors, you can specify poses in the world that need to be updated to correctly reflect the evolving understanding of the world, such that the poses remain aligned with the same place in the physical world. That helps to build an illusion that the placed objects are really present in the user's environment.
## Instance properties
- {{domxref("XRAnchor.anchorSpace")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns an {{domxref("XRSpace")}} object to locate the anchor relative to other `XRSpace` objects.
## Instance methods
- {{domxref("XRAnchor.delete()")}} {{Experimental_Inline}}
- : Removes the anchor.
## Examples
### Requesting a session with anchors enabled
```js
navigator.xr.requestSession("immersive-ar", {
requireFeatures: ["anchors"],
});
```
### Adding anchors
You can use {{domxref("XRFrame.createAnchor()")}} to create an anchor.
```js
frame.createAnchor(anchorPose, referenceSpace).then(
(anchor) => {
// Do stuff with the anchor (assign objects that will be relative to this anchor)
},
(error) => {
console.error(`Could not create anchor: ${error}`);
},
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRAnchorSet")}}
- {{domxref("XRFrame.createAnchor()")}}
- {{domxref("XRFrame.trackedAnchors")}}
- {{domxref("XRHitTestResult.createAnchor()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xranchor | data/mdn-content/files/en-us/web/api/xranchor/anchorspace/index.md | ---
title: "XRAnchor: anchorSpace property"
short-title: anchorSpace
slug: Web/API/XRAnchor/anchorSpace
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRAnchor.anchorSpace
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The read-only **`anchorSpace`** property of the {{domxref("XRAnchor")}} interface returns an {{domxref("XRSpace")}} object to locate the anchor relative to other `XRSpace` objects. It can be passed to {{domxref("XRFrame.getPose()")}} subsequently.
## Value
An {{domxref("XRSpace")}} object.
## Examples
### Updating anchors
```js
for (const anchor of frame.trackedAnchors) {
const pose = frame.getPose(anchor.anchorSpace, referenceSpace);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xranchor | data/mdn-content/files/en-us/web/api/xranchor/delete/index.md | ---
title: "XRAnchor: delete() method"
short-title: delete()
slug: Web/API/XRAnchor/delete
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRAnchor.delete
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`delete()`** method of the {{domxref("XRAnchor")}} interface removes an anchor. This can be useful when an application is no longer interested in receiving updates to an anchor.
## Syntax
```js-nolint
delete()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
### Removing all anchors
```js
let anchorsCollection = new Set();
// Upon creating anchors, add them to the Set
// anchorsCollection.add(anchor);
for (const anchor of anchorsCollection) {
anchor.delete();
}
anchorsCollection.clear();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssskewx/index.md | ---
title: CSSSkewX
slug: Web/API/CSSSkewX
page-type: web-api-interface
browser-compat: api.CSSSkewX
---
{{APIRef("CSS Typed OM")}}
The **`CSSSkewX`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents the [`skewX()`](/en-US/docs/Web/CSS/transform-function/skewX) value of the individual {{CSSXRef('transform')}} property in CSS. It inherits properties and methods from its parent {{domxref("CSSTransformValue")}}.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CSSSkewX.CSSSkewX", "CSSSkewX()")}}
- : Creates a new `CSSSkewX` object.
## Instance properties
- {{domxref('CSSSkewX.ax','ax')}}
- : Returns or sets the x-axis value.
## Examples
To Do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssskewx | data/mdn-content/files/en-us/web/api/cssskewx/ax/index.md | ---
title: "CSSSkewX: ax property"
short-title: ax
slug: Web/API/CSSSkewX/ax
page-type: web-api-instance-property
browser-compat: api.CSSSkewX.ax
---
{{APIRef("CSS Typed OM")}}
The **`ax`** property of the
{{domxref("CSSSkewX")}} interface gets and sets the angle used to distort the element
along the x-axis (or abscissa).
## Value
A {{domxref("CSSNumericValue")}}.
## Examples
To do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssskewx | data/mdn-content/files/en-us/web/api/cssskewx/cssskewx/index.md | ---
title: "CSSSkewX: CSSSkewX() constructor"
short-title: CSSSkewX()
slug: Web/API/CSSSkewX/CSSSkewX
page-type: web-api-constructor
browser-compat: api.CSSSkewX.CSSSkewX
---
{{APIRef("CSS Typed OM")}}
The **`CSSSkewX()`** constructor creates a new
{{domxref("CSSSkewX")}} object which represents the
[`skewX()`](/en-US/docs/Web/CSS/transform-function/skewX)
value of the individual {{CSSXRef('transform')}} property in CSS.
## Syntax
```js-nolint
new CSSSkewX(ax)
```
### Parameters
- {{domxref('CSSSkewx.ax','ax')}}
- : A value for the `ax` angle of the {{domxref('CSSSkewX')}} object to be
constructed. This must be a {{domxref('CSSNumericValue')}}.
## Examples
To do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/contentindex/index.md | ---
title: ContentIndex
slug: Web/API/ContentIndex
page-type: web-api-interface
status:
- experimental
browser-compat: api.ContentIndex
---
{{APIRef("Content Index API")}}{{SeeCompatTable}}
The **`ContentIndex`** interface of the [Content Index API](/en-US/docs/Web/API/Content_Index_API) allows developers to register their offline enabled content with the browser.
## Instance properties
There are no properties of this interface.
## Instance methods
- {{domxref('ContentIndex.add()')}} {{Experimental_Inline}}
- : Registers an item with the [content index](/en-US/docs/Web/API/Content_Index_API).
- {{domxref('ContentIndex.delete()')}} {{Experimental_Inline}}
- : Unregisters an item from the currently indexed content.
- {{domxref('ContentIndex.getAll()')}} {{Experimental_Inline}}
- : Returns a {{jsxref('Promise')}} that resolves with an iterable list of content index entries.
## Examples
### Feature detection and interface access
Here we get a reference to the {{domxref('ServiceWorkerRegistration')}}, then check for the `index` property, which gives us access to the content index interface.
```js
// reference registration
const registration = await navigator.serviceWorker.ready;
// feature detection
if ("index" in registration) {
// Content Index API functionality
const contentIndex = registration.index;
}
```
### Adding to the content index
Here we're declaring an item in the correct format and creating an asynchronous function which uses the {{domxref('ContentIndex.add','add()')}} method to register it with the [content index](/en-US/docs/Web/API/Content_Index_API).
```js
// our content
const item = {
id: "post-1",
url: "/posts/amet.html",
title: "Amet consectetur adipisicing",
description:
"Repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.",
icons: [
{
src: "/media/dark.png",
sizes: "128x128",
type: "image/png",
},
],
category: "article",
};
// our asynchronous function to add indexed content
async function registerContent(data) {
const registration = await navigator.serviceWorker.ready;
// feature detect Content Index
if (!registration.index) {
return;
}
// register content
try {
await registration.index.add(data);
} catch (e) {
console.log("Failed to register content: ", e.message);
}
}
```
### Retrieving items within the current index
The below example shows an asynchronous function that retrieves items within the [content index](/en-US/docs/Web/API/Content_Index_API) and iterates over each entry, building a list for the interface.
```js
async function createReadingList() {
// access our service worker registration
const registration = await navigator.serviceWorker.ready;
// get our index entries
const entries = await registration.index.getAll();
// create a containing element
const readingListElem = document.createElement("div");
// test for entries
if (!Array.length) {
// if there are no entries, display a message
const message = document.createElement("p");
message.innerText =
"You currently have no articles saved for offline reading.";
readingListElem.append(message);
} else {
// if entries are present, display in a list of links to the content
const listElem = document.createElement("ul");
for (const entry of entries) {
const listItem = document.createElement("li");
const anchorElem = document.createElement("a");
anchorElem.innerText = entry.title;
anchorElem.setAttribute("href", entry.url);
listElem.append(listItem);
}
readingListElem.append(listElem);
}
}
```
### Unregistering indexed content
Below is an asynchronous function, that removes an item from the [content index](/en-US/docs/Web/API/Content_Index_API).
```js
async function unregisterContent(article) {
// reference registration
const registration = await navigator.serviceWorker.ready;
// feature detect Content Index
if (!registration.index) return;
// unregister content from index
await registration.index.delete(article.id);
}
```
All the above methods are available within the scope of the [service worker](/en-US/docs/Web/API/ServiceWorker). They are accessible from the {{domxref('WorkerGlobalScope.self')}} property:
```js
// service worker script
self.registration.index.add(item);
self.registration.index.delete(item.id);
const contentIndexItems = self.registration.index.getAll();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/)
- [Service Worker API, along with information about Cache and CacheStorage](/en-US/docs/Web/API/Service_Worker_API)
| 0 |
data/mdn-content/files/en-us/web/api/contentindex | data/mdn-content/files/en-us/web/api/contentindex/add/index.md | ---
title: "ContentIndex: add() method"
short-title: add()
slug: Web/API/ContentIndex/add
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.ContentIndex.add
---
{{APIRef("Content Index API")}}{{SeeCompatTable}}
The **`add()`** method of the
{{domxref("ContentIndex")}} interface registers an item with the [content index](/en-US/docs/Web/API/Content_Index_API).
## Syntax
```js-nolint
add(contentDescription)
```
### Parameters
- `contentDescription`
- : An {{jsxref('Object')}} containing the following data:
- `id`
- : A unique {{jsxref('String')}} identifier.
- `title`
- : A {{jsxref('String')}} title for the item. Used in
user-visible lists of content.
- `description`
- : A {{jsxref('String')}} description of the item. Used
in user-visible lists of content.
- `url`
- : A {{jsxref('String')}} containing the URL of the corresponding
HTML document. Needs to be under the scope of the current
{{domxref('ServiceWorker','service worker')}}.
- `category` {{Optional_Inline}}
- : A {{jsxref('String')}} defining the
category of content. Can be:
- `''` An empty {{jsxref('String')}}, this is the default.
- `homepage`
- `article`
- `video`
- `audio`
- `icons` {{Optional_Inline}}
- : An {{jsxref('Array')}} of image
resources, defined as an {{jsxref('Object')}} with the following data:
- `src`
- : A URL {{jsxref('String')}} of the source image.
- `sizes` {{Optional_Inline}}
- : A {{jsxref('String')}} representation of the image size.
- `type` {{Optional_Inline}}
- : The {{Glossary("MIME type")}} of the image.
### Return value
Returns a {{jsxref("Promise")}} that resolves with `undefined`
### Exceptions
- {{jsxref("TypeError")}}
- : This exception is thrown in the following conditions:
- The service worker's registration is not present or the service worker does not
contain a {{domxref('FetchEvent')}}.
- The `id`, `title`, `description` or
`url` are missing, not of type {{jsxref('String')}}, or an empty {{jsxref('String')}}.
- One of the items in `icons` are not an image type, or fetching one of the items in `icons` failed with a network error.
## Examples
Here we're declaring an item in the correct format and creating an asynchronous
function which uses the `add` method to register it with the
[content index](/en-US/docs/Web/API/Content_Index_API).
```js
// our content
const item = {
id: "post-1",
url: "/posts/amet.html",
title: "Amet consectetur adipisicing",
description:
"Repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.",
icons: [
{
src: "/media/dark.png",
sizes: "128x128",
type: "image/png",
},
],
category: "article",
};
// our asynchronous function to add indexed content
async function registerContent(data) {
const registration = await navigator.serviceWorker.ready;
// feature detect Content Index
if (!registration.index) {
return;
}
// register content
try {
await registration.index.add(data);
} catch (e) {
console.log("Failed to register content: ", e.message);
}
}
```
The `add` method can also be used within the
[service worker](/en-US/docs/Web/API/ServiceWorker) scope.
```js
// our content
const item = {
id: "post-1",
url: "/posts/amet.html",
title: "Amet consectetur adipisicing",
description:
"Repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.",
icons: [
{
src: "/media/dark.png",
sizes: "128x128",
type: "image/png",
},
],
category: "article",
};
self.registration.index.add(item);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/)
- [Service Worker API, along with information about Cache and CacheStorage](/en-US/docs/Web/API/Service_Worker_API)
| 0 |
data/mdn-content/files/en-us/web/api/contentindex | data/mdn-content/files/en-us/web/api/contentindex/delete/index.md | ---
title: "ContentIndex: delete() method"
short-title: delete()
slug: Web/API/ContentIndex/delete
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.ContentIndex.delete
---
{{APIRef("Content Index API")}}{{SeeCompatTable}}
The **`delete()`** method of the
{{domxref("ContentIndex")}} interface unregisters an item from the currently indexed
content.
> **Note:** Calling `delete()` only affects the index. It does not delete anything
> from the {{domxref('Cache')}}.
## Syntax
```js-nolint
ContentIndex.delete(id).then(/* … */)
```
### Parameters
- `id`
- : The unique identifier of the indexed content you want the {{domxref("ContentIndex")}} object to remove.
### Return value
Returns a {{jsxref("Promise")}} that resolves with `undefined`
### Exceptions
No exceptions are thrown.
## Examples
Below is an asynchronous function, that removes an item from the [content index](/en-US/docs/Web/API/Content_Index_API). We receive a reference to the current
{{domxref('ServiceWorkerRegistration')}}, which allows us to access the
{{domxref('ServiceWorkerRegistration.index','index')}} property and thus access the
`delete` method.
```js
async function unregisterContent(article) {
// reference registration
const registration = await navigator.serviceWorker.ready;
// feature detect Content Index
if (!registration.index) return;
// unregister content from index
await registration.index.delete(article.id);
}
```
The `delete` method can also be used within the
[service worker](/en-US/docs/Web/API/ServiceWorker) scope.
```js
self.registration.index.delete("my-id");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/)
- [Service Worker API, along with information about Cache and CacheStorage](/en-US/docs/Web/API/Service_Worker_API)
| 0 |
data/mdn-content/files/en-us/web/api/contentindex | data/mdn-content/files/en-us/web/api/contentindex/getall/index.md | ---
title: "ContentIndex: getAll() method"
short-title: getAll()
slug: Web/API/ContentIndex/getAll
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.ContentIndex.getAll
---
{{APIRef("Content Index API")}}{{SeeCompatTable}}
The **`getAll()`** method of the
{{domxref("ContentIndex")}} interface returns a {{jsxref('Promise')}} that resolves with
an iterable list of content index entries.
## Syntax
```js-nolint
getAll()
```
### Parameters
This method receives no parameters.
### Return value
Returns a {{jsxref("Promise")}} that resolves with an {{jsxref('Array')}} of
`contentDescription` items.
- `contentDescription`
- : Each item returned is an {{jsxref('Object')}} containing the following data:
- `id`
- : A unique {{jsxref('String')}} identifier.
- `title`
- : A {{jsxref('String')}} title of the item.
Used in user-visible lists of content.
- `description`
- : A {{jsxref('String')}} description of the item.
Used in user-visible lists of content.
- `url`
- : A {{jsxref('String')}} containing the URL of the corresponding HTML document.
Needs to be under the scope of the current {{domxref('ServiceWorker','service worker')}}.
- `category` {{Optional_Inline}}
- : A {{jsxref('String')}} defining the category of content.
Can be:
- `''` An empty {{jsxref('String')}}, this is the default.
- `homepage`
- `article`
- `video`
- `audio`
- `icons` {{Optional_Inline}}
- : An {{jsxref('Array')}} of image resources, defined as an {{jsxref('Object')}} with the following data:
- `src`
- : A URL {{jsxref('String')}} of the source image.
- `sizes` {{Optional_Inline}}
- : A {{jsxref('String')}} representation of the image size.
- `type` {{Optional_Inline}}
- : The {{Glossary("MIME type")}} of the image.
### Exceptions
No exceptions are thrown. If there are no items in the Content Index, an empty
{{jsxref('Array')}} is returned.
## Examples
The below example shows an asynchronous function that retrieves items within the
[content index](/en-US/docs/Web/API/Content_Index_API) and iterates over each entry, building
a list for the interface.
```js
async function createReadingList() {
// access our service worker registration
const registration = await navigator.serviceWorker.ready;
// get our index entries
const entries = await registration.index.getAll();
// create a containing element
const readingListElem = document.createElement("div");
// test for entries
if (!Array.length) {
// if there are no entries, display a message
const message = document.createElement("p");
message.innerText =
"You currently have no articles saved for offline reading.";
readingListElem.append(message);
} else {
// if entries are present, display in a list of links to the content
const listElem = document.createElement("ul");
for (const entry of entries) {
const listItem = document.createElement("li");
const anchorElem = document.createElement("a");
anchorElem.innerText = entry.title;
anchorElem.setAttribute("href", entry.url);
listElem.append(listItem);
}
readingListElem.append(listElem);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/)
- [Service Worker API, along with information about Cache and CacheStorage](/en-US/docs/Web/API/Service_Worker_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/offscreencanvasrenderingcontext2d/index.md | ---
title: OffscreenCanvasRenderingContext2D
slug: Web/API/OffscreenCanvasRenderingContext2D
page-type: web-api-interface
browser-compat: api.OffscreenCanvasRenderingContext2D
---
{{APIRef}}
The **`OffscreenCanvasRenderingContext2D`** interface is a {{domxref("CanvasRenderingContext2D")}} rendering context for drawing to the bitmap of an `OffscreenCanvas` object.
It is similar to the `CanvasRenderingContext2D` object, with the following differences:
- there is no support for user-interface features (`drawFocusIfNeeded`, and `scrollPathIntoView`)
- its `canvas` attribute refers to an `OffscreenCanvas` object rather than a {{HtmlElement("canvas")}} element
- it has a `commit()` method for pushing rendered images to the context's `OffscreenCanvas` object's placeholder {{HtmlElement("canvas")}} element
## Example
The following code snippet creates a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor.
The `transferControlToOffscreen()` method is used to transfer the `OffscreenCanvas` object to the worker:
```js
const canvas = document.getElementById("canvas");
const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker("worker.js");
worker.postMessage({ canvas: offscreen }, [offscreen]);
```
In the worker thread, we can use the `OffscreenCanvasRenderingContext2D` to draw to the bitmap of the `OffscreenCanvas` object:
```js
onmessage = (event) => {
const canvas = event.data.canvas;
const offCtx = canvas.getContext("2d");
// draw to the offscreen canvas context
offCtx.fillStyle = "red";
offCtx.fillRect(0, 0, 100, 100);
};
```
For a full example, see our [OffscreenCanvas worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/offscreen-canvas-worker) ([run OffscreenCanvas worker](https://mdn.github.io/dom-examples/web-workers/offscreen-canvas-worker/)).
## Additional methods
The following method is new to the `OffscreenCanvasRenderingContext2D` interface and does not exist in the `CanvasRenderingContext2D` interface:
- {{domxref("OffscreenCanvasRenderingContext2D.commit()", "commit()")}}
- : Pushes the rendered image to the context's `OffscreenCanvas` object's placeholder {{HtmlElement("canvas")}} element.
## Unsupported features
The following user interface methods are **not supported** by the `OffscreenCanvasRenderingContext2D` interface:
- {{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}}
- : If a given element is focused, this method draws a focus ring around the current path.
- {{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{Experimental_Inline}}
- : Scrolls the current path or a given path into the view.
## Inherited properties and methods
_The following properties and methods are inherited from {{domxref("CanvasRenderingContext2D")}}. They have the same usage as in `CanvasRenderingContext2D`_
### Context
- {{domxref("CanvasRenderingContext2D.isContextLost()")}} {{Experimental_Inline}}
- : Returns `true` if the rendering context was lost.
### Drawing rectangles
- {{domxref("CanvasRenderingContext2D.clearRect()")}}
- : Sets all pixels in the rectangle defined by starting point _(x, y)_ and size _(width, height)_ to transparent black, erasing any previously drawn content.
- {{domxref("CanvasRenderingContext2D.fillRect()")}}
- : Draws a filled rectangle at _(x, y)_ position whose size is determined by _width_ and _height_.
- {{domxref("CanvasRenderingContext2D.strokeRect()")}}
- : Paints a rectangle which has a starting point at _(x, y)_ and has a _w_ width and an _h_ height onto the canvas, using the current stroke style.
### Drawing text
The following methods and properties control drawing text. See also the {{domxref("TextMetrics")}} object for text properties.
- {{domxref("CanvasRenderingContext2D.fillText()")}}
- : Draws (fills) a given text at the given (x, y) position.
- {{domxref("CanvasRenderingContext2D.strokeText()")}}
- : Draws (strokes) a given text at the given (x, y) position.
- {{domxref("CanvasRenderingContext2D.measureText()")}}
- : Returns a {{domxref("TextMetrics")}} object.
- {{domxref("CanvasRenderingContext2D.textRendering")}}
- : Text rendering. Possible values: `auto` (default), `optimizeSpeed`, `optimizeLegibility`,
### Line styles
The following methods and properties control how lines are drawn.
- {{domxref("CanvasRenderingContext2D.lineWidth")}}
- : Width of lines. Default `1.0`.
- {{domxref("CanvasRenderingContext2D.lineCap")}}
- : Type of endings on the end of lines. Possible values: `butt` (default), `round`, `square`.
- {{domxref("CanvasRenderingContext2D.lineJoin")}}
- : Defines the type of corners where two lines meet. Possible values: `round`, `bevel`, `miter` (default).
- {{domxref("CanvasRenderingContext2D.miterLimit")}}
- : Miter limit ratio. Default `10`.
- {{domxref("CanvasRenderingContext2D.getLineDash()")}}
- : Returns the current line dash pattern array containing an even number of non-negative numbers.
- {{domxref("CanvasRenderingContext2D.setLineDash()")}}
- : Sets the current line dash pattern.
- {{domxref("CanvasRenderingContext2D.lineDashOffset")}}
- : Specifies where to start a dash array on a line.
### Text styles
The following properties control how text is laid out.
- {{domxref("CanvasRenderingContext2D.font")}}
- : Font setting. Default value `10px sans-serif`.
- {{domxref("CanvasRenderingContext2D.textAlign")}}
- : Text alignment setting. Possible values: `start` (default), `end`, `left`, `right`, `center`.
- {{domxref("CanvasRenderingContext2D.textBaseline")}}
- : Baseline alignment setting. Possible values: `top`, `hanging`, `middle`, `alphabetic` (default), `ideographic`, `bottom`.
- {{domxref("CanvasRenderingContext2D.direction")}}
- : Directionality. Possible values: `ltr`, `rtl`, `inherit` (default).
- {{domxref("CanvasRenderingContext2D.letterSpacing")}}
- : Letter spacing. Default: `0px`.
- {{domxref("CanvasRenderingContext2D.fontKerning")}}
- : Font kerning. Possible values: `auto` (default), `normal`, `none`.
- {{domxref("CanvasRenderingContext2D.fontStretch")}}
- : Font stretch. Possible values: `ultra-condensed`, `extra-condensed`, `condensed`, `semi-condensed`, `normal` (default), `semi-expanded`, `expanded`, `extra-expanded`, `ultra-expanded`.
- {{domxref("CanvasRenderingContext2D.fontVariantCaps")}}
- : Font variant caps. Possible values: `normal` (default), `small-caps`, `all-small-caps`, `petite-caps`, `all-petite-caps`, `unicase`, `titling-caps`.
- {{domxref("CanvasRenderingContext2D.textRendering")}} {{experimental_inline}}
- : Text rendering. Possible values: `auto` (default), `optimizeSpeed`, `optimizeLegibility`, `geometricPrecision`.
- {{domxref("CanvasRenderingContext2D.wordSpacing")}}
- : Word spacing. Default value: `0px`
### Fill and stroke styles
Fill styling is used for colors and styles inside shapes and stroke styling is used for the lines around shapes.
- {{domxref("CanvasRenderingContext2D.fillStyle")}}
- : Color or style to use inside shapes. Default `#000` (black).
- {{domxref("CanvasRenderingContext2D.strokeStyle")}}
- : Color or style to use for the lines around shapes. Default `#000` (black).
### Gradients and patterns
- {{domxref("CanvasRenderingContext2D.createConicGradient()")}}
- : Creates a conic gradient around a point given by coordinates represented by the parameters.
- {{domxref("CanvasRenderingContext2D.createLinearGradient()")}}
- : Creates a linear gradient along the line given by the coordinates represented by the parameters.
- {{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
- : Creates a radial gradient given by the coordinates of the two circles represented by the parameters.
- {{domxref("CanvasRenderingContext2D.createPattern()")}}
- : Creates a pattern using the specified image. It repeats the source in the directions specified by the repetition argument. This method returns a {{domxref("CanvasPattern")}}.
### Shadows
- {{domxref("CanvasRenderingContext2D.shadowBlur")}}
- : Specifies the blurring effect. Default: `0`.
- {{domxref("CanvasRenderingContext2D.shadowColor")}}
- : Color of the shadow. Default: fully-transparent black.
- {{domxref("CanvasRenderingContext2D.shadowOffsetX")}}
- : Horizontal distance the shadow will be offset. Default: `0`.
- {{domxref("CanvasRenderingContext2D.shadowOffsetY")}}
- : Vertical distance the shadow will be offset. Default: `0`.
### Paths
The following methods can be used to manipulate paths of objects.
- {{domxref("CanvasRenderingContext2D.beginPath()")}}
- : Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.
- {{domxref("CanvasRenderingContext2D.closePath()")}}
- : Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.
- {{domxref("CanvasRenderingContext2D.moveTo()")}}
- : Moves the starting point of a new sub-path to the (x, y) coordinates.
- {{domxref("CanvasRenderingContext2D.lineTo()")}}
- : Connects the last point in the current sub-path to the specified (x, y) coordinates with a straight line.
- {{domxref("CanvasRenderingContext2D.bezierCurveTo()")}}
- : Adds a cubic Bézier curve to the current path.
- {{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}}
- : Adds a quadratic Bézier curve to the current path.
- {{domxref("CanvasRenderingContext2D.arc()")}}
- : Adds a circular arc to the current path.
- {{domxref("CanvasRenderingContext2D.arcTo()")}}
- : Adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line.
- {{domxref("CanvasRenderingContext2D.ellipse()")}}
- : Adds an elliptical arc to the current path.
- {{domxref("CanvasRenderingContext2D.rect()")}}
- : Creates a path for a rectangle at position (x, y) with a size that is determined by _width_ and _height_.
### Drawing paths
- {{domxref("CanvasRenderingContext2D.fill()")}}
- : Fills the current sub-paths with the current fill style.
- {{domxref("CanvasRenderingContext2D.stroke()")}}
- : Strokes the current sub-paths with the current stroke style.
- {{domxref("CanvasRenderingContext2D.clip()")}}
- : Creates a clipping path from the current sub-paths. Everything drawn after `clip()` is called appears inside the clipping path only. For an example, see [Clipping paths](/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing) in the Canvas tutorial.
- {{domxref("CanvasRenderingContext2D.isPointInPath()")}}
- : Reports whether or not the specified point is contained in the current path.
- {{domxref("CanvasRenderingContext2D.isPointInStroke()")}}
- : Reports whether or not the specified point is inside the area contained by the stroking of a path.
- {{domxref("CanvasRenderingContext2D.roundRect()")}}
- : Addition to CanvasPath that allows users to render rectangles with rounded corners.
### Transformations
Objects in the `CanvasRenderingContext2D` rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and {{domxref("Path2D")}} objects. The methods listed below remain for historical and compatibility reasons as {{domxref("DOMMatrix")}} objects are used in most parts of the API nowadays and will be used in the future instead.
- {{domxref("CanvasRenderingContext2D.getTransform()")}}
- : Retrieves the current transformation matrix being applied to the context.
- {{domxref("CanvasRenderingContext2D.rotate()")}}
- : Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.
- {{domxref("CanvasRenderingContext2D.scale()")}}
- : Adds a scaling transformation to the canvas units by x horizontally and by y vertically.
- {{domxref("CanvasRenderingContext2D.translate()")}}
- : Adds a translation transformation by moving the canvas and its origin x horizontally and y vertically on the grid.
- {{domxref("CanvasRenderingContext2D.transform()")}}
- : Multiplies the current transformation matrix with the matrix described by its arguments.
- {{domxref("CanvasRenderingContext2D.setTransform()")}}
- : Resets the current transform to the identity matrix, and then invokes the `transform()` method with the same arguments.
- {{domxref("CanvasRenderingContext2D.resetTransform()")}}
- : Resets the current transform by the identity matrix.
### Compositing
- {{domxref("CanvasRenderingContext2D.globalAlpha")}}
- : Alpha value that is applied to shapes and images before they are composited onto the canvas. Default `1.0` (opaque).
- {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}}
- : With `globalAlpha` applied this sets how shapes and images are drawn onto the existing bitmap.
### Drawing images
- {{domxref("CanvasRenderingContext2D.drawImage()")}}
- : Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.
### Pixel manipulation
See also the {{domxref("ImageData")}} object.
- {{domxref("CanvasRenderingContext2D.createImageData()")}}
- : Creates a new, blank {{domxref("ImageData")}} object with the specified dimensions. All of the pixels in the new object are transparent black.
- {{domxref("CanvasRenderingContext2D.getImageData()")}}
- : Returns an {{domxref("ImageData")}} object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at _(sx, sy)_ and has an _sw_ width and _sh_ height.
- {{domxref("CanvasRenderingContext2D.putImageData()")}}
- : Paints data from the given {{domxref("ImageData")}} object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.
### Image smoothing
- {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}}
- : Image smoothing mode; if disabled, images will not be smoothed if scaled.
- {{domxref("CanvasRenderingContext2D.imageSmoothingQuality")}}
- : Allows you to set the quality of image smoothing.
### The canvas state
The `CanvasRenderingContext2D` rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:
- {{domxref("CanvasRenderingContext2D.save()")}}
- : Saves the current drawing style state using a stack so you can revert any change you make to it using `restore()`.
- {{domxref("CanvasRenderingContext2D.restore()")}}
- : Restores the drawing style state to the last element on the 'state stack' saved by `save()`.
- {{domxref("CanvasRenderingContext2D.canvas")}}
- : A read-only reference to an `OffscreenCanvas` object.
- {{domxref("CanvasRenderingContext2D.getContextAttributes()")}}
- : Returns an object containing the actual context attributes. Context attributes can be requested with {{domxref("HTMLCanvasElement.getContext()")}}.
- {{domxref("CanvasRenderingContext2D.reset()")}}
- : Resets the current drawing style state to the default values.
### Filters
- {{domxref("CanvasRenderingContext2D.filter")}}
- : Applies a CSS or SVG filter to the canvas; e.g., to change its brightness or blurriness.
## Unsupported properties and methods
The following methods are **not supported** in the `OffscreenCanvasRenderingContext2D` interface:
- {{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}}
- : If a given element is focused, this method draws a focus ring around the current path.
- {{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{Experimental_Inline}}
- : Scrolls the current path or a given path into the view.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLCanvasElement")}}
- {{HTMLElement("canvas")}}
| 0 |
data/mdn-content/files/en-us/web/api/offscreencanvasrenderingcontext2d | data/mdn-content/files/en-us/web/api/offscreencanvasrenderingcontext2d/commit/index.md | ---
title: "OffscreenCanvasRenderingContext2D: commit() method"
short-title: commit()
slug: Web/API/OffscreenCanvasRenderingContext2D/commit
page-type: web-api-instance-method
browser-compat: api.OffscreenCanvasRenderingContext2D.commit
---
{{APIRef}}
The
**`OffscreenCanvasRenderingContext2D.commit()`**
method of the [Canvas 2D API](/en-US/docs/Web/API/OffscreenCanvasRenderingContext2D) copies the rendering context's bitmap to the bitmap of the placeholder {{HtmlElement("canvas")}} element of the associated `OffscreenCanvas` object.
The copy operation is synchronous. Calling this method is not needed for the transfer, since it happens automatically during the event-loop execution.
## Syntax
```js-nolint
commit()
```
## Examples
```js
const placeholder = document.createElement("canvas");
const offscreen = placeholder.transferControlToOffscreen();
const ctx = offscreenCanvas.getContext("2d");
// Perform some drawing using the 2d context
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 10, 10);
// Push placeholder to the canvas element
ctx.commit();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The interface defining this method: {{domxref("OffscreenCanvasRenderingContext2D")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/console_api/index.md | ---
title: Console API
slug: Web/API/Console_API
page-type: guide
browser-compat: api.console
---
{{DefaultAPISidebar("Console API")}}
The Console API provides functionality to allow developers to perform debugging tasks, such as logging messages or the values of variables at set points in your code, or timing how long an operation takes to complete.
{{AvailableInWorkers}}
## Concepts and usage
The Console API started as a largely proprietary API, with different browsers implementing it, albeit in inconsistent ways. [The Console API spec](https://console.spec.whatwg.org/) was created to define consistent behavior, and all modern browsers eventually settled on implementing this behavior — although some implementations still have their own additional proprietary functions. Find out about these at:
- [Google Chrome DevTools implementation](https://developer.chrome.com/docs/devtools/console/api/)
- [Safari DevTools implementation](https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html)
Usage is very simple — the {{domxref("console")}} object contains many methods that you can call to perform rudimentary debugging tasks, generally focused around logging various values to the browser's [Web Console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html).
By far the most commonly-used method is {{domxref("console/log_static", "console.log()")}}, which is used to log the current value contained inside a specific variable.
## Interfaces
- {{domxref("console")}}
- : Provides rudimentary debugging functionality, including logging, stack traces, timers, and counters.
## Examples
```js
let myString = "Hello world";
// Output "Hello world" to the console
console.log(myString);
```
See the [console](/en-US/docs/Web/API/console#usage) reference page for more examples.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/audio_output_devices_api/index.md | ---
title: Audio Output Devices API
slug: Web/API/Audio_Output_Devices_API
page-type: web-api-overview
status:
- experimental
browser-compat:
- api.MediaDevices.selectAudioOutput
- api.HTMLMediaElement.setSinkId
- api.HTMLMediaElement.sinkId
- http.headers.Permissions-Policy.speaker-selection
spec-urls: https://w3c.github.io/mediacapture-output/
---
{{DefaultAPISidebar("Audio Output Devices API")}}{{securecontext_header}}{{SeeCompatTable}}
The **Audio Output Devices API** allows web applications to prompt users about what output device should be used for audio playback.
## Concepts and usage
Operating systems commonly allow users to specify that audio should be played from speakers, a Bluetooth headset, or some other audio output device.
This API allows applications to provide this same functionality from within a web page.
Even if allowed by a permission policy, access to a particular audio output device still requires explicit user permission, as the user may be in a location where playing audio through some output devices is not appropriate.
The API provides the {{domxref("MediaDevices.selectAudioOutput()")}} method that allows users to select their desired audio output from those that are allowed by the [`speaker-selection`](/en-US/docs/Web/HTTP/Headers/Permissions-Policy/speaker-selection) directive of the {{httpheader("Permissions-Policy")}} HTTP header for the document.
The selected device then has user permission, allowing it to be enumerated with {{domxref("MediaDevices.enumerateDevices()")}} and set as the audio output device using {{domxref("HTMLMediaElement.setSinkId()")}}.
Audio devices may arbitrarily connect and disconnect.
Applications that wish to react to this kind of change can listen to the {{domxref("MediaDevices/devicechange_event", "devicechange")}} event and use {{domxref("MediaDevices.enumerateDevices", "enumerateDevices()")}} to determine if `sinkId` is present in the returned devices.
This might trigger, for example, pausing or unpausing playback.
## Interfaces
### Extensions to interfaces
The Audio Output Devices API extends the following APIs, adding the listed features:
#### MediaDevices
- {{domxref("MediaDevices.selectAudioOutput()")}}
- : This method prompts the user to select a specific audio output device, for example a speaker or headset.
Selecting a device grants user permission to use that device and returns information about the device, including its ID.
#### HTMLMediaElement
- {{domxref("HTMLMediaElement.setSinkId()")}}
- : This method sets the ID of the audio device to use for output, which will be used if permitted.
- {{domxref("HTMLMediaElement.sinkId")}}
- : This property returns the unique ID of the audio device being used for output, or an empty string if the default user agent device is being used.
## Security requirements
Access to the API is subject to the following constraints:
- All methods and properties may only be called in a [secure context](/en-US/docs/Web/Security/Secure_Contexts).
- {{domxref("MediaDevices.selectAudioOutput()")}} grants user permission for a selected device to be used as the audio output sink:
- Access may be gated by the [`speaker-selection`](/en-US/docs/Web/HTTP/Headers/Permissions-Policy/speaker-selection) HTTP [Permission Policy](/en-US/docs/Web/HTTP/Permissions_Policy).
- [Transient user activation](/en-US/docs/Web/Security/User_activation) is required.
The user has to interact with the page or a UI element for the method to be called.
- {{domxref("HTMLMediaElement.setSinkId()")}} sets a permitted ID as the audio output:
- Access may be gated by the [`speaker-selection`](/en-US/docs/Web/HTTP/Headers/Permissions-Policy/speaker-selection) HTTP [Permission Policy](/en-US/docs/Web/HTTP/Permissions_Policy).
- User permission is required to set a non-default device ID.
- This can come from selection in the prompt launched by `MediaDevices.selectAudioOutput()`
- User permission to set the output device is also implicitly granted if the user has already granted permission to use a media input device in the same group with {{domxref("MediaDevices.getUserMedia()")}}.
<!-- The line below is "true" but this is not implemented in any browser -->
<!-- The permission status can be queried using the [Permissions API](/en-US/docs/Web/API/Permissions_API) method [`navigator.permissions.query()`](/en-US/docs/Web/API/Permissions/query), passing a permission descriptor with the `speaker-selection` permission. -->
## Examples
Here's an example of using `selectAudioOutput()`, within a function that is triggered by a button click, and then setting the selected device as the audio output.
The code first checks if `selectAudioOutput()` is supported, and if it is, uses it to select an output and return a [device ID](/en-US/docs/Web/API/MediaDeviceInfo/deviceId).
We then play some audio using the default output, and then call `setSinkId()` in order to switch to the selected output device.
```js
document.querySelector("#myButton").addEventListener("click", async () => {
if (!navigator.mediaDevices.selectAudioOutput) {
console.log("selectAudioOutput() not supported or not in secure context.");
return;
}
// Display prompt to select device
const audioDevice = await navigator.mediaDevices.selectAudioOutput();
// Create an audio element and start playing audio on the default device
const audio = document.createElement("audio");
audio.src = "https://example.com/audio.mp3";
audio.play();
// Change the sink to the selected audio output device.
audio.setSinkId(audioDevice.deviceId);
});
```
Note that if you log the output details, they might look something like this:
```js
console.log(
`${audioDevice.kind}: ${audioDevice.label} id = ${audioDevice.deviceId}`,
);
// audiooutput: Realtek Digital Output (Realtek(R) Audio) id = 0wE6fURSZ20H0N2NbxqgowQJLWbwo+5ablCVVJwRM3k=
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlbodyelement/index.md | ---
title: HTMLBodyElement
slug: Web/API/HTMLBodyElement
page-type: web-api-interface
browser-compat: api.HTMLBodyElement
---
{{APIRef("HTML DOM")}}
The **`HTMLBodyElement`** interface provides special properties (beyond those inherited from the regular {{ domxref("HTMLElement") }} interface) for manipulating {{HtmlElement("body")}} elements.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLBodyElement.aLink")}} {{deprecated_inline}}
- : A string that represents the color of active hyperlinks.
- {{domxref("HTMLBodyElement.background")}} {{deprecated_inline}}
- : A string that represents the description of the location of the background image resource. Note that this is not an URI, though some older version of some browsers do expect it.
- {{domxref("HTMLBodyElement.bgColor")}} {{deprecated_inline}}
- : A string that represents the background color for the document.
- {{domxref("HTMLBodyElement.link")}} {{deprecated_inline}}
- : A string that represents the color of unvisited links.
- {{domxref("HTMLBodyElement.text")}} {{deprecated_inline}}
- : A string that represents the foreground color of text.
- {{domxref("HTMLBodyElement.vLink")}} {{deprecated_inline}}
- : A string that represents the color of visited links.
## Instance methods
_No specific methods; inherits methods from its parent, {{domxref("HTMLElement")}}._
## Event handlers
The {{domxref("HTMLElement")}} events are inherited.
The following {{domxref("Window")}} `onXYZ` event handler properties are also available as aliases targeting the `window` object. However, it is advised to listen to them on the `window` object directly rather than on `HTMLBodyElement`.
> **Note:** Using `addEventListener()` on `HTMLBodyElement` will not work for the `onXYZ` event handlers listed below. Listen to the events on the {{domxref("window")}} object instead.
- {{domxref("window.afterprint_event", "HTMLBodyElement.onafterprint")}}
- : Fired after the associated document has started printing or the print preview has been closed.
- {{domxref("window.beforeprint_event", "HTMLBodyElement.onbeforeprint")}}
- : Fired when the associated document is about to be printed or previewed for printing.
- {{domxref("window.beforeunload_event", "HTMLBodyElement.onbeforeunload")}}
- : Fired when the window, the document and its resources are about to be unloaded.
- {{domxref("window.gamepadconnected_event", "HTMLBodyElement.ongamepadconnected")}}
- : Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.
- {{domxref("window.gamepaddisconnected_event", "HTMLBodyElement.ongamepaddisconnected")}}
- : Fired when the browser detects that a gamepad has been disconnected.
- {{domxref("window.hashchange_event", "HTMLBodyElement.onhashchange")}}
- : Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol).
- {{domxref("window.languagechange_event", "HTMLBodyElement.onlanguagechange")}}
- : Fired when the user's preferred language changes.
- {{domxref("window.message_event", "HTMLBodyElement.onmessage")}}
- : Fired when the window receives a message, for example from a call to [`Window.postMessage()`](/en-US/docs/Web/API/Window/postMessage) from another browsing context.
- {{domxref("window.messageerror_event", "HTMLBodyElement.onmessageerror")}}
- : Fired when the window receives a message that can't be deserialized.
- {{domxref("window.offline_event", "HTMLBodyElement.onoffline")}}
- : Fired when the browser has lost access to the network and the value of {{domxref("Navigator.onLine")}} switches to `false`.
- {{domxref("window.online_event", "HTMLBodyElement.ononline")}}
- : Fired when the browser has gained access to the network and the value of {{domxref("Navigator.onLine")}} switches to `true`.
- {{domxref("window.pagehide_event", "HTMLBodyElement.onpagehide")}}
- : Fired when the browser hides the current page in the process of presenting a different page from the session's history.
- {{domxref("window.pageshow_event", "HTMLBodyElement.onpageshow")}}
- : Fired when the browser displays the window's document due to navigation.
- {{domxref("window.popstate_event", "HTMLBodyElement.onpopstate")}}
- : Fired when the active history entry changes while the user navigates the session history.
- {{domxref("window.rejectionhandled_event", "HTMLBodyElement.onrejectionhandled")}}
- : Fired whenever a JavaScript {{jsxref("Promise")}} is rejected and the rejection has been handled.
- {{domxref("window.storage_event", "HTMLBodyElement.onstorage")}}
- : Fired when a storage area (`localStorage`) has been modified in the context of another document.
- {{domxref("window.unhandledrejection_event", "HTMLBodyElement.onunhandledrejection")}}
- : Fired whenever a {{jsxref("Promise")}} is rejected but the rejection was not handled.
- {{domxref("window.unload_event", "HTMLBodyElement.onunload")}}
- : Fired when the document is being unloaded.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- HTML element implementing this interface: {{ HTMLElement("body") }}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/screen_wake_lock_api/index.md | ---
title: Screen Wake Lock API
slug: Web/API/Screen_Wake_Lock_API
page-type: web-api-overview
browser-compat:
- api.WakeLock
- api.WakeLockSentinel
spec-urls: https://w3c.github.io/screen-wake-lock/
---
{{DefaultAPISidebar("Screen Wake Lock API")}}{{securecontext_header}}
The **Screen Wake Lock API** provides a way to prevent devices from dimming or locking the screen when an application needs to keep running.
## Concepts and usage
Most devices by default turn off their screen after a specified amount of time to prolong the life of the hardware. Modern devices do this to save on battery power. Whilst this is a useful feature, some applications need the screen to stay awake to be their most useful.
The Screen Wake Lock API prevents the screen from turning off, dimming or locking. It allows for a simple platform-based solution for visible (active) documents to acquire the platform screen wake lock.
There are plenty of use cases for keeping a screen on, including reading an ebook, map navigation, following a recipe, presenting to an audience, scanning a QR/barcode or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake).
You acquire a {{DOMxRef("WakeLockSentinel")}} object by calling the {{domxref('WakeLock.request','navigator.wakeLock.request()')}} {{jsxref('Promise')}}-based method that resolves if the platform allows it. A request may be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the document is not active or visible.
It is good practice to store a reference to the sentinel object to allow the application to later control release.
The sentinel is attached to the underlying system wake lock. It can be released by the system, again if the battery power is too low or the document is not active or visible. It can also be released manually via the {{domxref('WakeLockSentinel.release()')}} method.
After being released a `WakeLockSentinel` can no longer be used. If a screen wake lock is required again/still, the application will need to request a new one.
The Screen Wake Lock API should be used to keep the screen on to benefit usability. It's a good idea to show some feedback on the interface to show if wake lock is active and a way for the user to disable it if they wish.
## Interfaces
- {{domxref("WakeLock")}}
- : Prevents device screens from dimming or locking when an application needs to keep running.
- {{domxref("WakeLockSentinel")}}
- : Provides a handle to the underlying platform wake lock and if referenced can be manually released and reacquired. Get an instance of the object by calling {{domxref('WakeLock.request')}}.
### Extensions to other interfaces
- {{domxref("Navigator.wakelock")}} {{ReadOnlyInline}}
- : Returns a {{domxref("WakeLock")}} object instance, from which all other functionality can be accessed.
- [`Permissions-Policy: screen-wake-lock`](/en-US/docs/Web/HTTP/Headers/Permissions-Policy/screen-wake-lock)
- : Access to the API is gated by the [`Permissions-Policy`](/en-US/docs/Web/HTTP/Headers/Permissions-Policy) directive `screen-wake-lock`.
See [Security considerations](#security_considerations) below.
## Examples
### Feature detection
This code checks for wake lock support and updates the UI accordingly.
```js
if ("wakeLock" in navigator) {
isSupported = true;
statusElem.textContent = "Screen Wake Lock API supported!";
} else {
wakeButton.disabled = true;
statusElem.textContent = "Wake lock is not supported by this browser.";
}
```
### Requesting a wake lock
The following example demonstrates how to request a {{domxref('WakeLockSentinel')}} object. The {{domxref('WakeLock.request')}} method is {{jsxref('Promise')}}-based and so we can create an asynchronous function, which in turn updates the UI to reflect the wake lock is active.
```js
// Create a reference for the Wake Lock.
let wakeLock = null;
// create an async function to request a wake lock
try {
wakeLock = await navigator.wakeLock.request("screen");
statusElem.textContent = "Wake Lock is active!";
} catch (err) {
// The Wake Lock request has failed - usually system related, such as battery.
statusElem.textContent = `${err.name}, ${err.message}`;
}
```
### Releasing wake lock
The following example shows how to release the previously acquired wake lock.
```js
wakeLock.release().then(() => {
wakeLock = null;
});
```
### Listening for wake lock release
This example updates the UI if the wake lock has been released for any reason (such as navigating away from the active window/tab).
```js
wakeLock.addEventListener("release", () => {
// the wake lock has been released
statusElem.textContent = "Wake Lock has been released";
});
```
### Reacquiring a wake lock
The following code reacquires the wake lock should the visibility of the document change and the wake lock is released.
```js
document.addEventListener("visibilitychange", async () => {
if (wakeLock !== null && document.visibilityState === "visible") {
wakeLock = await navigator.wakeLock.request("screen");
}
});
```
### Putting it all together
You can find the [complete code on GitHub here](https://github.com/mdn/dom-examples/tree/main/screen-wake-lock-api). The [demo](https://mdn.github.io/dom-examples/screen-wake-lock-api/) uses a button to acquire a wake lock and also release it, which in turn updates the UI. The UI also updates if the wake lock is released automatically for any reason. There's a checkbox which when checked, will automatically reacquire the wake lock if the document's visibility state changes and becomes visible again.
## Performance considerations
- Release the screen wake lock when user ends activity that required always-on screen. For example, a ticketing app which uses QR codes to transmit ticket information, might acquire screen wake lock when the QR code is displayed (so that code is successfully scanned) but release afterwards. A presentation app might hold the lock only while a presentation is active, but not when presentation is being edited.
- If your app is performing long-running downloads, consider using background fetch.
- If your app is synchronizing data from a remote server, consider using background sync.
- Only active documents can acquire screen wake locks and previously acquired locks are automatically released when document becomes inactive. Therefore make sure to re-acquire screen wake lock if necessary when document becomes active (listen for [visibilitychange](/en-US/docs/Web/API/Document/visibilitychange_event) event).
## Security considerations
Access to the Screen Wake Lock API is controlled by the [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) directive {{HTTPHeader("Permissions-Policy/screen-wake-lock","screen-wake-lock")}}.
When using the [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy), the default allowlist for `screen-wake-lock` is `self`.
This allows lock wake usage in same-origin nested frames but prevents third-party content from using locks.
Third party usage can be enabled by the server first setting the `Permissions-Policy` header to grant permission a particular third party origin.
```http
Permissions-Policy: screen-wake-lock=(self b.example.com)
```
Then the `allow="screen-wake-lock"` attribute must be added the frame container element for sources from that origin:
```html
<iframe src="https://b.example.com" allow="screen-wake-lock"/></iframe>
```
Browsers may also block the screen lock in a particular document for an implementation specific reason, such as a user or platform setting.
They are expected to provide some unobtrusive mechanism to inform the user when wake lock is active, and to provide users the ability to remove the application's screen lock.
The [Permissions API](/en-US/docs/Web/API/Permissions_API) `screen-wake-lock` permission can be used to test whether access to use the screen lock is `granted`, `denied` or `prompt` (requires user acknowledgement of a prompt).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Stay awake with the Screen Wake Lock API](https://developer.chrome.com/docs/capabilities/web-apis/wake-lock/)
- [A Screen Wake Lock API demo on glitch](https://wake-lock-demo.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/fontdata/index.md | ---
title: FontData
slug: Web/API/FontData
page-type: web-api-interface
status:
- experimental
browser-compat: api.FontData
---
{{APIRef("Local Font Access API")}}{{SeeCompatTable}}
The **`FontData`** interface of the {{domxref("Local Font Access API", "Local Font Access API", "", "nocode")}} represents a single local font face.
## Instance properties
- {{domxref('FontData.family')}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the family of the font face.
- {{domxref('FontData.fullName')}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the full name of the font face.
- {{domxref('FontData.postscriptName')}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the PostScript name of the font face.
- {{domxref('FontData.style')}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the style of the font face.
## Instance methods
- {{domxref('FontData.blob()')}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that fulfills with a {{domxref("Blob")}} containing the raw bytes of the underlying font file.
## Examples
For a working live demo, see [Font Select Demo](https://local-font-access.glitch.me/demo/).
### Font enumeration
The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.
```js
async function logFontData() {
try {
const availableFonts = await window.queryLocalFonts();
for (const fontData of availableFonts) {
console.log(fontData.postscriptName);
console.log(fontData.fullName);
console.log(fontData.family);
console.log(fontData.style);
}
} catch (err) {
console.error(err.name, err.message);
}
}
```
### Accessing low-level data
The {{domxref("FontData.blob", "blob()")}} method provides access to low-level [SFNT](https://en.wikipedia.org/wiki/SFNT) data — this is a font file format that can contain other font formats, such as PostScript, TrueType, OpenType, or Web Open Font Format (WOFF).
```js
async function computeOutlineFormat() {
try {
const availableFonts = await window.queryLocalFonts({
postscriptNames: ["ComicSansMS"],
});
for (const fontData of availableFonts) {
// `blob()` returns a Blob containing valid and complete
// SFNT-wrapped font data.
const sfnt = await fontData.blob();
// Slice out only the bytes we need: the first 4 bytes are the SFNT
// version info.
// Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
const sfntVersion = await sfnt.slice(0, 4).text();
let outlineFormat = "UNKNOWN";
switch (sfntVersion) {
case "\x00\x01\x00\x00":
case "true":
case "typ1":
outlineFormat = "truetype";
break;
case "OTTO":
outlineFormat = "cff";
break;
}
console.log("Outline format:", outlineFormat);
}
} catch (err) {
console.error(err.name, err.message);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Use advanced typography with local fonts](https://developer.chrome.com/docs/capabilities/web-apis/local-fonts)
- {{cssxref("@font-face")}}
| 0 |
data/mdn-content/files/en-us/web/api/fontdata | data/mdn-content/files/en-us/web/api/fontdata/family/index.md | ---
title: "FontData: family property"
short-title: family
slug: Web/API/FontData/family
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.FontData.family
---
{{APIRef("Local Font Access API")}}{{SeeCompatTable}}
The **`family`** read-only property of the {{domxref("FontData")}} interface returns the family of the font face.
This is the name used when referring to the font family from code, for example, in the {{cssxref("font-family")}} property or in places within the {{cssxref("@font-face")}} at-rule such as the `local()` function.
Examples include:
- Apple SD Gothic Neo
- Arial Black
- Avenir Next
- Katari
- YuMincho +36p Kana
## Value
A string.
## Examples
The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.
```js
async function logFontData() {
try {
const availableFonts = await window.queryLocalFonts();
for (const fontData of availableFonts) {
console.log(fontData.postscriptName);
console.log(fontData.fullName);
console.log(fontData.family);
console.log(fontData.style);
}
} catch (err) {
console.error(err.name, err.message);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Use advanced typography with local fonts](https://developer.chrome.com/docs/capabilities/web-apis/local-fonts)
- {{cssxref("@font-face")}}
| 0 |
data/mdn-content/files/en-us/web/api/fontdata | data/mdn-content/files/en-us/web/api/fontdata/blob/index.md | ---
title: "FontData: blob() method"
short-title: blob()
slug: Web/API/FontData/blob
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.FontData.blob
---
{{APIRef("Local Font Access API")}}{{SeeCompatTable}}
The **`blob()`** method of the {{domxref("FontData")}} interface returns a {{jsxref("Promise")}} that fulfills with a {{domxref("Blob")}} containing the raw bytes of the underlying font file.
## Syntax
```js-nolint
blob()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that fulfills with a {{domxref("Blob")}} containing the raw bytes of the underlying font file.
## Examples
The `blob()` method provides access to low-level [SFNT](https://en.wikipedia.org/wiki/SFNT) data — this is a font file format that can contain other font formats, such as PostScript, TrueType, OpenType, or Web Open Font Format (WOFF).
```js
async function computeOutlineFormat() {
try {
const availableFonts = await window.queryLocalFonts({
postscriptNames: ["ComicSansMS"],
});
for (const fontData of availableFonts) {
// `blob()` returns a Blob containing valid and complete
// SFNT-wrapped font data.
const sfnt = await fontData.blob();
// Slice out only the bytes we need: the first 4 bytes are the SFNT
// version info.
// Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
const sfntVersion = await sfnt.slice(0, 4).text();
let outlineFormat = "UNKNOWN";
switch (sfntVersion) {
case "\x00\x01\x00\x00":
case "true":
case "typ1":
outlineFormat = "truetype";
break;
case "OTTO":
outlineFormat = "cff";
break;
}
console.log("Outline format:", outlineFormat);
}
} catch (err) {
console.error(err.name, err.message);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Use advanced typography with local fonts](https://developer.chrome.com/docs/capabilities/web-apis/local-fonts)
- {{cssxref("@font-face")}}
| 0 |
data/mdn-content/files/en-us/web/api/fontdata | data/mdn-content/files/en-us/web/api/fontdata/postscriptname/index.md | ---
title: "FontData: postscriptName property"
short-title: postscriptName
slug: Web/API/FontData/postscriptName
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.FontData.postscriptName
---
{{APIRef("Local Font Access API")}}{{SeeCompatTable}}
The **`postscriptName`** read-only property of the {{domxref("FontData")}} interface returns the PostScript name of the font face.
This is the name used to uniquely identify the PostScript font, and is generally an unbroken sequence of characters that includes the font's name and style.
Examples include:
- AppleSDGothicNeo-UltraLight
- Arial-Black
- AvenirNext-Heavy
- Katari-MediumItalic
- YuMin_36pKn-Extrabold
## Value
A string.
## Examples
The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.
```js
async function logFontData() {
try {
const availableFonts = await window.queryLocalFonts();
for (const fontData of availableFonts) {
console.log(fontData.postscriptName);
console.log(fontData.fullName);
console.log(fontData.family);
console.log(fontData.style);
}
} catch (err) {
console.error(err.name, err.message);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Use advanced typography with local fonts](https://developer.chrome.com/docs/capabilities/web-apis/local-fonts)
- {{cssxref("@font-face")}}
| 0 |
data/mdn-content/files/en-us/web/api/fontdata | data/mdn-content/files/en-us/web/api/fontdata/style/index.md | ---
title: "FontData: style property"
short-title: style
slug: Web/API/FontData/style
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.FontData.style
---
{{APIRef("Local Font Access API")}}{{SeeCompatTable}}
The **`style`** read-only property of the {{domxref("FontData")}} interface returns the style of the font face.
This is the value used to select the style of the font you want to use, for example inside the {{cssxref("font-style")}} property.
Examples include:
- UltraLight
- Regular
- Heavy
- Medium Italic
- Extrabold
## Value
A string.
## Examples
The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.
```js
async function logFontData() {
try {
const availableFonts = await window.queryLocalFonts();
for (const fontData of availableFonts) {
console.log(fontData.postscriptName);
console.log(fontData.fullName);
console.log(fontData.family);
console.log(fontData.style);
}
} catch (err) {
console.error(err.name, err.message);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Use advanced typography with local fonts](https://developer.chrome.com/docs/capabilities/web-apis/local-fonts)
- {{cssxref("@font-face")}}
| 0 |
data/mdn-content/files/en-us/web/api/fontdata | data/mdn-content/files/en-us/web/api/fontdata/fullname/index.md | ---
title: "FontData: fullName property"
short-title: fullName
slug: Web/API/FontData/fullName
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.FontData.fullName
---
{{APIRef("Local Font Access API")}}{{SeeCompatTable}}
The **`fullName`** read-only property of the {{domxref("FontData")}} interface returns the full name of the font face. This is usually a human-readable name used to identify the font, e.g., "Optima Bold".
Examples include:
- Apple SD Gothic Neo UltraLight
- Arial Black
- Avenir Next Heavy
- Katari Medium Italic
- YuMincho +36p Kana Extrabold
## Value
A string.
## Examples
The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.
```js
async function logFontData() {
try {
const availableFonts = await window.queryLocalFonts();
for (const fontData of availableFonts) {
console.log(fontData.postscriptName);
console.log(fontData.fullName);
console.log(fontData.family);
console.log(fontData.style);
}
} catch (err) {
console.error(err.name, err.message);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Use advanced typography with local fonts](https://developer.chrome.com/docs/capabilities/web-apis/local-fonts)
- {{cssxref("@font-face")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlbaseelement/index.md | ---
title: HTMLBaseElement
slug: Web/API/HTMLBaseElement
page-type: web-api-interface
browser-compat: api.HTMLBaseElement
---
{{APIRef("HTML DOM")}}
The **`HTMLBaseElement`** interface contains the base URI for a document. This object inherits all of the properties and methods as described in the {{domxref("HTMLElement")}} interface.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLBaseElement.href")}}
- : A string that reflects the [`href`](/en-US/docs/Web/HTML/Element/base#href) HTML attribute, containing a base URL for relative URLs in the document.
- {{domxref("HTMLBaseElement.target")}}
- : A string that reflects the [`target`](/en-US/docs/Web/HTML/Element/base#target) HTML attribute, containing a default target browsing context or frame for elements that do not have a target reference specified.
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- HTML element implementing this interface: {{ HTMLElement("base") }}
| 0 |
data/mdn-content/files/en-us/web/api/htmlbaseelement | data/mdn-content/files/en-us/web/api/htmlbaseelement/target/index.md | ---
title: "HTMLBaseElement: target property"
short-title: target
slug: Web/API/HTMLBaseElement/target
page-type: web-api-instance-property
browser-compat: api.HTMLBaseElement.target
---
{{ApiRef("HTML DOM")}}
The `target` property of the {{domxref("HTMLBaseElement")}} interface is a string that represents the default target tab to show the resulting output for hyperlinks and form elements.
It reflects the [`target`](/en-US/docs/Web/HTML/Element/base#target) attribute of the {{HTMLElement("base")}} element.
## Value
A string representing the target. Its value can be:
- The name of a {{HTMLElement("frame")}}.
- One of the [keyword with specific values](/en-US/docs/Web/HTML/Element/base#target):`_blank`, `_self`, `_parent`, or `_top`.
## Example
```html
<head>
<base target="_top" />
</head>
```
```js
const baseElement = document.getElementsByTagName("base")[0];
console.log(baseElement.target); // Output: '_top'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLAnchorElement.target")}} property
- {{domxref("HTMLAreaElement.target")}} property
- {{domxref("HTMLFormElement.target")}} property
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/web_speech_api/index.md | ---
title: Web Speech API
slug: Web/API/Web_Speech_API
page-type: web-api-overview
browser-compat:
- api.SpeechRecognition
- api.SpeechSynthesis
---
{{DefaultAPISidebar("Web Speech API")}}
The **Web Speech API** enables you to incorporate voice data into web apps.
The Web Speech API has two parts: `SpeechSynthesis` (Text-to-Speech), and `SpeechRecognition` (Asynchronous Speech Recognition.)
## Web Speech Concepts and Usage
The Web Speech API makes web apps able to handle voice data.
There are two components to this API:
- Speech recognition is accessed via the {{domxref("SpeechRecognition")}} interface, which provides the ability to recognize voice context from an audio input (normally via the device's default speech recognition service) and respond appropriately.
Generally you'll use the interface's constructor to create a new {{domxref("SpeechRecognition")}} object, which has a number of event handlers available for detecting when speech is input through the device's microphone. The {{domxref("SpeechGrammar")}} interface represents a container for a particular set of grammar that your app should recognize.
Grammar is defined using [JSpeech Grammar Format](https://www.w3.org/TR/jsgf/) (**JSGF**.)
- Speech synthesis is accessed via the {{domxref("SpeechSynthesis")}} interface, a text-to-speech component that allows programs to read out their text content (normally via the device's default speech synthesizer.) Different voice types are represented by {{domxref("SpeechSynthesisVoice")}} objects, and different parts of text that you want to be spoken are represented by {{domxref("SpeechSynthesisUtterance")}} objects.
You can get these spoken by passing them to the {{domxref("SpeechSynthesis.speak()")}} method.
For more details on using these features, see [Using the Web Speech API](/en-US/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API).
## Web Speech API Interfaces
### Speech recognition
- {{domxref("SpeechRecognition")}}
- : The controller interface for the recognition service; this also handles the {{domxref("SpeechRecognitionEvent")}} sent from the recognition service.
- {{domxref("SpeechRecognitionAlternative")}}
- : Represents a single word that has been recognized by the speech recognition service.
- {{domxref("SpeechRecognitionErrorEvent")}}
- : Represents error messages from the recognition service.
- {{domxref("SpeechRecognitionEvent")}}
- : The event object for the {{domxref("SpeechRecognition.result_event", "result")}} and {{domxref("SpeechRecognition.nomatch_event", "nomatch")}} events, and contains all the data associated with an interim or final speech recognition result.
- {{domxref("SpeechGrammar")}}
- : The words or patterns of words that we want the recognition service to recognize.
- {{domxref("SpeechGrammarList")}}
- : Represents a list of {{domxref("SpeechGrammar")}} objects.
- {{domxref("SpeechRecognitionResult")}}
- : Represents a single recognition match, which may contain multiple {{domxref("SpeechRecognitionAlternative")}} objects.
- {{domxref("SpeechRecognitionResultList")}}
- : Represents a list of {{domxref("SpeechRecognitionResult")}} objects, or a single one if results are being captured in {{domxref("SpeechRecognition.continuous","continuous")}} mode.
### Speech synthesis
- {{domxref("SpeechSynthesis")}}
- : The controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides.
- {{domxref("SpeechSynthesisErrorEvent")}}
- : Contains information about any errors that occur while processing {{domxref("SpeechSynthesisUtterance")}} objects in the speech service.
- {{domxref("SpeechSynthesisEvent")}}
- : Contains information about the current state of {{domxref("SpeechSynthesisUtterance")}} objects that have been processed in the speech service.
- {{domxref("SpeechSynthesisUtterance")}}
- : Represents a speech request.
It contains the content the speech service should read and information about how to read it (e.g. language, pitch and volume.)
- {{domxref("SpeechSynthesisVoice")}}
- : Represents a voice that the system supports.
Every `SpeechSynthesisVoice` has its own relative speech service including information about language, name and URI.
- {{domxref("Window.speechSynthesis")}}
- : Specified out as part of a `[NoInterfaceObject]` interface called `SpeechSynthesisGetter`, and Implemented by the `Window` object, the `speechSynthesis` property provides access to the {{domxref("SpeechSynthesis")}} controller, and therefore the entry point to speech synthesis functionality.
## Errors
For information on errors reported by the Speech API (for example, `"language-not-supported"` and `"language-unavailable"`), see the following documentation:
- [`error` property of the `SpeechRecognitionErrorEvent` object](/en-US/docs/Web/API/SpeechRecognitionErrorEvent/error)
- [`error` property of the `SpeechSynthesisErrorEvent` object](/en-US/docs/Web/API/SpeechSynthesisErrorEvent/error)
## Examples
The [Web Speech API examples](https://github.com/mdn/dom-examples/tree/main/web-speech-api) on GitHub contains demos to illustrate speech recognition and synthesis.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Speech API](/en-US/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API)
- [SitePoint article](https://www.sitepoint.com/talking-web-pages-and-the-speech-synthesis-api/)
- [HTML5Rocks article](https://developer.chrome.com/blog/web-apps-that-talk-introduction-to-the-speech-synthesis-api/)
| 0 |
data/mdn-content/files/en-us/web/api/web_speech_api | data/mdn-content/files/en-us/web/api/web_speech_api/using_the_web_speech_api/index.md | ---
title: Using the Web Speech API
slug: Web/API/Web_Speech_API/Using_the_Web_Speech_API
page-type: guide
---
{{DefaultAPISidebar("Web Speech API")}}
The Web Speech API provides two distinct areas of functionality — speech recognition, and speech synthesis (also known as text to speech, or tts) — which open up interesting new possibilities for accessibility, and control mechanisms. This article provides a simple introduction to both areas, along with demos.
## Speech recognition
Speech recognition involves receiving speech through a device's microphone, which is then checked by a speech recognition service against a list of grammar (basically, the vocabulary you want to have recognized in a particular app.) When a word or phrase is successfully recognized, it is returned as a result (or list of results) as a text string, and further actions can be initiated as a result.
The Web Speech API has a main controller interface for this — {{domxref("SpeechRecognition")}} — plus a number of closely-related interfaces for representing grammar, results, etc. Generally, the default speech recognition system available on the device will be used for the speech recognition — most modern OSes have a speech recognition system for issuing voice commands. Think about Dictation on macOS, Siri on iOS, Cortana on Windows 10, Android Speech, etc.
> **Note:** On some browsers, such as Chrome, using Speech Recognition on a web page involves a server-based recognition engine. Your audio is sent to a web service for recognition processing, so it won't work offline.
### Demo
To show simple usage of Web speech recognition, we've written a demo called [Speech color changer](https://github.com/mdn/dom-examples/tree/main/web-speech-api/speech-color-changer). When the screen is tapped/clicked, you can say an HTML color keyword, and the app's background color will change to that color.

To run the demo, navigate to the [live demo URL](https://mdn.github.io/dom-examples/web-speech-api/speech-color-changer/) in a supporting mobile browser (such as Chrome).
### HTML and CSS
The HTML and CSS for the app is really trivial. We have a title, instructions paragraph, and a div into which we output diagnostic messages.
```html
<h1>Speech color changer</h1>
<p>Tap/click then say a color to change the background color of the app.</p>
<div>
<p class="output"><em>…diagnostic messages</em></p>
</div>
```
The CSS provides a very simple responsive styling so that it looks OK across devices.
### JavaScript
Let's look at the JavaScript in a bit more detail.
#### Prefixed properties
Browsers currently support speech recognition with prefixed properties.
Therefore at the start of our code we include these lines to allow for both prefixed properties and unprefixed versions that may be supported in future:
```js
const SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition;
const SpeechGrammarList =
window.SpeechGrammarList || window.webkitSpeechGrammarList;
const SpeechRecognitionEvent =
window.SpeechRecognitionEvent || window.webkitSpeechRecognitionEvent;
```
#### The grammar
The next part of our code defines the grammar we want our app to recognize. The following variable is defined to hold our grammar:
```js
const colors = [
"aqua",
"azure",
"beige",
"bisque",
"black",
"blue",
"brown",
"chocolate",
"coral" /* … */,
];
const grammar = `#JSGF V1.0; grammar colors; public <color> = ${colors.join(
" | ",
)};`;
```
The grammar format used is [JSpeech Grammar Format](https://www.w3.org/TR/jsgf/) (**JSGF**) — you can find a lot more about it at the previous link to its spec. However, for now let's just run through it quickly:
- The lines are separated by semicolons, just like in JavaScript.
- The first line — `#JSGF V1.0;` — states the format and version used. This always needs to be included first.
- The second line indicates a type of term that we want to recognize. `public` declares that it is a public rule, the string in angle brackets defines the recognized name for this term (`color`), and the list of items that follow the equals sign are the alternative values that will be recognized and accepted as appropriate values for the term. Note how each is separated by a pipe character.
- You can have as many terms defined as you want on separate lines following the above structure, and include fairly complex grammar definitions. For this basic demo, we are just keeping things simple.
#### Plugging the grammar into our speech recognition
The next thing to do is define a speech recognition instance to control the recognition for our application. This is done using the {{domxref("SpeechRecognition.SpeechRecognition()","SpeechRecognition()")}} constructor. We also create a new speech grammar list to contain our grammar, using the {{domxref("SpeechGrammarList.SpeechGrammarList()","SpeechGrammarList()")}} constructor.
```js
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
```
We add our `grammar` to the list using the {{domxref("SpeechGrammarList.addFromString()")}} method. This accepts as parameters the string we want to add, plus optionally a weight value that specifies the importance of this grammar in relation of other grammars available in the list (can be from 0 to 1 inclusive.) The added grammar is available in the list as a {{domxref("SpeechGrammar")}} object instance.
```js
speechRecognitionList.addFromString(grammar, 1);
```
We then add the {{domxref("SpeechGrammarList")}} to the speech recognition instance by setting it to the value of the {{domxref("SpeechRecognition.grammars")}} property. We also set a few other properties of the recognition instance before we move on:
- {{domxref("SpeechRecognition.continuous")}}: Controls whether continuous results are captured (`true`), or just a single result each time recognition is started (`false`).
- {{domxref("SpeechRecognition.lang")}}: Sets the language of the recognition. Setting this is good practice, and therefore recommended.
- {{domxref("SpeechRecognition.interimResults")}}: Defines whether the speech recognition system should return interim results, or just final results. Final results are good enough for this simple demo.
- {{domxref("SpeechRecognition.maxAlternatives")}}: Sets the number of alternative potential matches that should be returned per result. This can sometimes be useful, say if a result is not completely clear and you want to display a list if alternatives for the user to choose the correct one from. But it is not needed for this simple demo, so we are just specifying one (which is actually the default anyway.)
```js
recognition.grammars = speechRecognitionList;
recognition.continuous = false;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;
```
#### Starting the speech recognition
After grabbing references to the output {{htmlelement("div")}} and the HTML element (so we can output diagnostic messages and update the app background color later on), we implement an onclick handler so that when the screen is tapped/clicked, the speech recognition service will start. This is achieved by calling {{domxref("SpeechRecognition.start()")}}. The `forEach()` method is used to output colored indicators showing what colors to try saying.
```js
const diagnostic = document.querySelector(".output");
const bg = document.querySelector("html");
const hints = document.querySelector(".hints");
let colorHTML = "";
colors.forEach((color, i) => {
console.log(color, i);
colorHTML += `<span style="background-color:${color};"> ${color} </span>`;
});
hints.innerHTML = `Tap or click then say a color to change the background color of the app. Try ${colorHTML}.`;
document.body.onclick = () => {
recognition.start();
console.log("Ready to receive a color command.");
};
```
#### Receiving and handling results
Once the speech recognition is started, there are many event handlers that can be used to retrieve results, and other pieces of surrounding information (see the [`SpeechRecognition` events](/en-US/docs/Web/API/SpeechRecognition#events).) The most common one you'll probably use is the {{domxref("SpeechRecognition.result_event", "result")}} event, which is fired once a successful result is received:
```js
recognition.onresult = (event) => {
const color = event.results[0][0].transcript;
diagnostic.textContent = `Result received: ${color}.`;
bg.style.backgroundColor = color;
console.log(`Confidence: ${event.results[0][0].confidence}`);
};
```
The second line here is a bit complex-looking, so let's explain it step by step. The {{domxref("SpeechRecognitionEvent.results")}} property returns a {{domxref("SpeechRecognitionResultList")}} object containing {{domxref("SpeechRecognitionResult")}} objects. It has a getter so it can be accessed like an array — so the first `[0]` returns the `SpeechRecognitionResult` at position 0. Each `SpeechRecognitionResult` object contains {{domxref("SpeechRecognitionAlternative")}} objects that contain individual recognized words. These also have getters so they can be accessed like arrays — the second `[0]` therefore returns the `SpeechRecognitionAlternative` at position 0. We then return its `transcript` property to get a string containing the individual recognized result as a string, set the background color to that color, and report the color recognized as a diagnostic message in the UI.
We also use the {{domxref("SpeechRecognition.speechend_event", "speechend")}} event to stop the speech recognition service from running (using {{domxref("SpeechRecognition.stop()")}}) once a single word has been recognized and it has finished being spoken:
```js
recognition.onspeechend = () => {
recognition.stop();
};
```
#### Handling errors and unrecognized speech
The last two handlers are there to handle cases where speech was recognized that wasn't in the defined grammar, or an error occurred. The {{domxref("SpeechRecognition.nomatch_event", "nomatch")}} event seems to be supposed to handle the first case mentioned, although note that at the moment it doesn't seem to fire correctly; it just returns whatever was recognized anyway:
```js
recognition.onnomatch = (event) => {
diagnostic.textContent = "I didn't recognize that color.";
};
```
The {{domxref("SpeechRecognition.error_event", "error")}} event handles cases where there is an actual error with the recognition successfully — the {{domxref("SpeechRecognitionErrorEvent.error")}} property contains the actual error returned:
```js
recognition.onerror = (event) => {
diagnostic.textContent = `Error occurred in recognition: ${event.error}`;
};
```
## Speech synthesis
Speech synthesis (aka text-to-speech, or TTS) involves receiving synthesizing text contained within an app to speech, and playing it out of a device's speaker or audio output connection.
The Web Speech API has a main controller interface for this — {{domxref("SpeechSynthesis")}} — plus a number of closely-related interfaces for representing text to be synthesized (known as utterances), voices to be used for the utterance, etc. Again, most OSes have some kind of speech synthesis system, which will be used by the API for this task as available.
### Demo
To show simple usage of Web speech synthesis, we've provided a demo called [Speak easy synthesis](https://github.com/mdn/dom-examples/tree/main/web-speech-api/speak-easy-synthesis). This includes a set of form controls for entering text to be synthesized, and setting the pitch, rate, and voice to use when the text is uttered. After you have entered your text, you can press <kbd>Enter</kbd>/<kbd>Return</kbd> to hear it spoken.

To run the demo, navigate to the [live demo URL](https://mdn.github.io/dom-examples/web-speech-api/speak-easy-synthesis/) in a supporting mobile browser.
### HTML and CSS
The HTML and CSS are again pretty trivial, containing a title, some instructions for use, and a form with some simple controls. The {{htmlelement("select")}} element is initially empty, but is populated with {{htmlelement("option")}}s via JavaScript (see later on.)
```html
<h1>Speech synthesizer</h1>
<p>
Enter some text in the input below and press return to hear it. change voices
using the dropdown menu.
</p>
<form>
<input type="text" class="txt" />
<div>
<label for="rate">Rate</label
><input type="range" min="0.5" max="2" value="1" step="0.1" id="rate" />
<div class="rate-value">1</div>
<div class="clearfix"></div>
</div>
<div>
<label for="pitch">Pitch</label
><input type="range" min="0" max="2" value="1" step="0.1" id="pitch" />
<div class="pitch-value">1</div>
<div class="clearfix"></div>
</div>
<select></select>
</form>
```
### JavaScript
Let's investigate the JavaScript that powers this app.
#### Setting variables
First of all, we capture references to all the DOM elements involved in the UI, but more interestingly, we capture a reference to {{domxref("Window.speechSynthesis")}}. This is API's entry point — it returns an instance of {{domxref("SpeechSynthesis")}}, the controller interface for web speech synthesis.
```js
const synth = window.speechSynthesis;
const inputForm = document.querySelector("form");
const inputTxt = document.querySelector(".txt");
const voiceSelect = document.querySelector("select");
const pitch = document.querySelector("#pitch");
const pitchValue = document.querySelector(".pitch-value");
const rate = document.querySelector("#rate");
const rateValue = document.querySelector(".rate-value");
const voices = [];
```
#### Populating the select element
To populate the {{htmlelement("select")}} element with the different voice options the device has available, we've written a `populateVoiceList()` function. We first invoke {{domxref("SpeechSynthesis.getVoices()")}}, which returns a list of all the available voices, represented by {{domxref("SpeechSynthesisVoice")}} objects. We then loop through this list — for each voice we create an {{htmlelement("option")}} element, set its text content to display the name of the voice (grabbed from {{domxref("SpeechSynthesisVoice.name")}}), the language of the voice (grabbed from {{domxref("SpeechSynthesisVoice.lang")}}), and `-- DEFAULT` if the voice is the default voice for the synthesis engine (checked by seeing if {{domxref("SpeechSynthesisVoice.default")}} returns `true`.)
We also create `data-` attributes for each option, containing the name and language of the associated voice, so we can grab them easily later on, and then append the options as children of the select.
```js
function populateVoiceList() {
voices = synth.getVoices();
for (const voice of voices) {
const option = document.createElement("option");
option.textContent = `${voice.name} (${voice.lang})`;
if (voice.default) {
option.textContent += " — DEFAULT";
}
option.setAttribute("data-lang", voice.lang);
option.setAttribute("data-name", voice.name);
voiceSelect.appendChild(option);
}
}
```
Older browser don't support the {{domxref("SpeechSynthesis.voiceschanged_event", "voiceschanged")}} event, and just return a list of voices when {{domxref("SpeechSynthesis.getVoices()")}} is fired.
While on others, such as Chrome, you have to wait for the event to fire before populating the list.
To allow for both cases, we run the function as shown below:
```js
populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoiceList;
}
```
#### Speaking the entered text
Next, we create an event handler to start speaking the text entered into the text field. We are using an [onsubmit](/en-US/docs/Web/API/HTMLFormElement/submit_event) handler on the form so that the action happens when <kbd>Enter</kbd>/<kbd>Return</kbd> is pressed. We first create a new {{domxref("SpeechSynthesisUtterance.SpeechSynthesisUtterance()", "SpeechSynthesisUtterance()")}} instance using its constructor — this is passed the text input's value as a parameter.
Next, we need to figure out which voice to use. We use the {{domxref("HTMLSelectElement")}} `selectedOptions` property to return the currently selected {{htmlelement("option")}} element. We then use this element's `data-name` attribute, finding the {{domxref("SpeechSynthesisVoice")}} object whose name matches this attribute's value. We set the matching voice object to be the value of the {{domxref("SpeechSynthesisUtterance.voice")}} property.
Finally, we set the {{domxref("SpeechSynthesisUtterance.pitch")}} and {{domxref("SpeechSynthesisUtterance.rate")}} to the values of the relevant range form elements. Then, with all necessary preparations made, we start the utterance being spoken by invoking {{domxref("SpeechSynthesis.speak()")}}, passing it the {{domxref("SpeechSynthesisUtterance")}} instance as a parameter.
```js
inputForm.onsubmit = (event) => {
event.preventDefault();
const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
const selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
for (const voice of voices) {
if (voice.name === selectedOption) {
utterThis.voice = voice;
}
}
utterThis.pitch = pitch.value;
utterThis.rate = rate.value;
synth.speak(utterThis);
```
In the final part of the handler, we include an {{domxref("SpeechSynthesisUtterance.pause_event", "pause")}} event to demonstrate how {{domxref("SpeechSynthesisEvent")}} can be put to good use. When {{domxref("SpeechSynthesis.pause()")}} is invoked, this returns a message reporting the character number and name that the speech was paused at.
```js
utterThis.onpause = (event) => {
const char = event.utterance.text.charAt(event.charIndex);
console.log(
`Speech paused at character ${event.charIndex} of "${event.utterance.text}", which is "${char}".`,
);
};
```
Finally, we call [blur()](/en-US/docs/Web/API/HTMLElement/blur) on the text input. This is mainly to hide the keyboard on Firefox OS.
```js
inputTxt.blur();
}
```
#### Updating the displayed pitch and rate values
The last part of the code updates the `pitch`/`rate` values displayed in the UI, each time the slider positions are moved.
```js
pitch.onchange = () => {
pitchValue.textContent = pitch.value;
};
rate.onchange = () => {
rateValue.textContent = rate.value;
};
```
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mutationobserver/index.md | ---
title: MutationObserver
slug: Web/API/MutationObserver
page-type: web-api-interface
browser-compat: api.MutationObserver
---
{{APIRef("DOM WHATWG")}}
The {{domxref("MutationObserver")}} interface provides the ability to watch for changes being made to the [DOM](/en-US/docs/Web/API/Document_Object_Model) tree. It is designed as a replacement for the older [Mutation Events](/en-US/docs/Web/API/MutationEvent) feature, which was part of the DOM3 Events specification.
## Constructor
- {{domxref("MutationObserver.MutationObserver", "MutationObserver()")}}
- : Creates and returns a new `MutationObserver` which will invoke a specified callback function when DOM changes occur.
## Instance methods
- {{domxref("MutationObserver.disconnect()", "disconnect()")}}
- : Stops the `MutationObserver` instance from receiving further notifications until and unless {{domxref("MutationObserver.observe", "observe()")}} is called again.
- {{domxref("MutationObserver.observe()", "observe()")}}
- : Configures the `MutationObserver` to begin receiving notifications through its callback function when DOM changes matching the given options occur.
- {{domxref("MutationObserver.takeRecords()", "takeRecords()")}}
- : Removes all pending notifications from the `MutationObserver`'s notification queue and returns them in a new {{jsxref("Array")}} of {{domxref("MutationRecord")}} objects.
## Mutation Observer & customize resize event listener & demo
<https://codepen.io/milofultz/pen/LYjPXPw>
## Example
The following example was adapted from [this blog post](https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/).
```js
// Select the node that will be observed for mutations
const targetNode = document.getElementById("some-id");
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = (mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
console.log("A child node has been added or removed.");
} else if (mutation.type === "attributes") {
console.log(`The ${mutation.attributeName} attribute was modified.`);
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref('PerformanceObserver')}}
- {{domxref('ResizeObserver')}}
- {{domxref('IntersectionObserver')}}
- [A brief overview](https://developer.chrome.com/blog/detect-dom-changes-with-mutation-observers/)
- [A more in-depth discussion](https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/)
- [A screencast by Chromium developer Rafael Weinstein](https://www.youtube.com/watch?v=eRZ4pO0gVWw)
| 0 |
data/mdn-content/files/en-us/web/api/mutationobserver | data/mdn-content/files/en-us/web/api/mutationobserver/takerecords/index.md | ---
title: "MutationObserver: takeRecords() method"
short-title: takeRecords()
slug: Web/API/MutationObserver/takeRecords
page-type: web-api-instance-method
browser-compat: api.MutationObserver.takeRecords
---
{{APIRef("DOM WHATWG")}}
The {{domxref("MutationObserver")}} method
**`takeRecords()`** returns a list of all matching DOM changes
that have been detected but not yet processed by the observer's callback function,
leaving the mutation queue empty.
The most common use case for this is to
immediately fetch all pending mutation records immediately prior to disconnecting the
observer, so that any pending mutations can be processed when shutting down the
observer.
## Syntax
```js-nolint
takeRecords()
```
### Parameters
None.
### Return value
An array of {{domxref("MutationRecord")}} objects, each describing one change applied to
the observed portion of the document's DOM tree.
> **Note:** The queue of mutations which have occurred, but not been
> delivered to the observer's callback is left empty after calling
> `takeRecords()`.
## Examples
In this example, we demonstrate how to handle any undelivered
{{domxref("MutationRecord")}}s by calling `takeRecords()` just before
disconnecting the observer.
```js
const targetNode = document.querySelector("#someElement");
const observerOptions = {
childList: true,
attributes: true,
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);
/* later, when it's time to stop observing… */
/* handle any still-pending mutations */
let mutations = observer.takeRecords();
observer.disconnect();
if (mutations.length > 0) {
callback(mutations);
}
```
The code in lines 12–17 fetches any unprocessed mutation records, then invokes the
callback with the records so that they can be processed. This is done immediately prior
to calling {{domxref("MutationObserver.disconnect", "disconnect()")}} to stop observing
the DOM.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mutationobserver | data/mdn-content/files/en-us/web/api/mutationobserver/observe/index.md | ---
title: "MutationObserver: observe() method"
short-title: observe()
slug: Web/API/MutationObserver/observe
page-type: web-api-instance-method
browser-compat: api.MutationObserver.observe
---
{{APIRef("DOM WHATWG")}}
The {{domxref("MutationObserver")}} method **`observe()`** configures the `MutationObserver`
callback to begin receiving notifications of changes to the DOM that match the given options.
Depending on the configuration, the observer may watch a single {{domxref("Node")}} in the DOM tree, or that node and some or all of its descendant nodes.
To stop the `MutationObserver` (so that none of its callbacks will be triggered any longer), call {{domxref("MutationObserver.disconnect()")}}.
## Syntax
```js-nolint
observe(target, options)
```
### Parameters
- `target`
- : A DOM {{domxref("Node")}} (which may be an {{domxref("Element")}}) within the DOM
tree to watch for changes, or to be the root of a subtree of nodes to be watched.
- `options`
- : An object providing options that describe which DOM mutations should be reported to `mutationObserver`'s `callback`.
At a minimum, one of `childList`, `attributes`, and/or `characterData` must be `true` when you call {{domxref("MutationObserver.observe", "observe()")}}.
Otherwise, a `TypeError` exception will be thrown.
Options are as follows:
- `subtree` {{optional_inline}}
- : Set to `true` to extend monitoring to the entire subtree of nodes rooted at `target`.
All of the other properties are then extended to all of the nodes in the subtree instead of applying solely to the `target` node. The default value is `false`.
- `childList` {{optional_inline}}
- : Set to `true` to monitor the target node (and, if `subtree` is `true`, its descendants) for the addition of new child nodes or removal of existing child nodes.
The default value is `false`.
- `attributes` {{optional_inline}}
- : Set to `true` to watch for changes to the value of attributes on the node or nodes being monitored. The default value is `true` if either of `attributeFilter` or `attributeOldValue` is specified, otherwise the default value is `false`.
- `attributeFilter` {{optional_inline}}
- : An array of specific attribute names to be monitored.
If this property isn't included, changes to all attributes cause mutation notifications.
- `attributeOldValue` {{optional_inline}}
- : Set to `true` to record the previous value of any attribute that changes when monitoring the node or nodes for attribute changes;
See [Monitoring attribute values](#monitoring_attribute_values) for an example of watching for attribute changes and recording values.
The default value is `false`.
- `characterData` {{optional_inline}}
- : Set to `true` to monitor the specified target node (and, if `subtree` is `true`, its descendants) for changes to the character data contained within the node or nodes.
The default value is `true` if `characterDataOldValue` is specified, otherwise the default value is `false`.
- `characterDataOldValue` {{optional_inline}}
- : Set to `true` to record the previous value of a node's text whenever the text changes on nodes being monitored.
The default value is `false`.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref('TypeError')}}
- : Thrown in any of the following circumstances:
- The `options` are configured such that nothing will actually be monitored.
(For example, if `childList`, `attributes`, and `characterData` are all `false`.)
- The value of `options.attributes` is `false` (indicating that attribute changes are not to be monitored), but `attributeOldValue` is `true` and/or
`attributeFilter` is present.
- The `characterDataOldValue` option is `true` but `characterData` is `false` (indicating that character changes are not to be monitored).
## Usage notes
### Reusing MutationObservers
You can call `observe()` multiple times on the same
`MutationObserver` to watch for changes to different parts of the DOM tree
and/or different types of changes. There are some caveats to note:
- If you call `observe()` on a node that's already being observed by the same `MutationObserver`, all existing observers are automatically removed from all targets being observed before the new observer is activated.
- If the same `MutationObserver` is not already in use on the target, then the existing observers are left alone and the new one is added.
### Observation follows nodes when disconnected
Mutation observers are intended to let you be able to watch the desired set of nodes
over time, even if the direct connections between those nodes are severed. If you begin
watching a subtree of nodes, and a portion of that subtree is detached and moved
elsewhere in the DOM, you continue to watch the detached segment of nodes, receiving the
same callbacks as before the nodes were detached from the original subtree.
In other words, until you've been notified that nodes are being split off from your monitored subtree, you'll get notifications of changes to that split-off subtree and its nodes.
This prevents you from missing changes that occur after the connection is severed
and before you have a chance to specifically begin monitoring the moved node or subtree for changes.
Theoretically, this means that if you keep track of the {{domxref("MutationRecord")}} objects describing the changes that occur, you should be able to "undo" the changes,
rewinding the DOM back to its initial state.
## Examples
### Basic usage
In this example, we demonstrate how to call the method **`observe()`** on an instance of {{domxref("MutationObserver")}}, once it has been set up, passing it a target element
and an `options` object.
```js
// create a new instance of `MutationObserver` named `observer`,
// passing it a callback function
const observer = new MutationObserver(() => {
console.log("callback that runs when observer is triggered");
});
// call `observe()`, passing it the element to observe, and the options object
observer.observe(document.querySelector("#element-to-observe"), {
subtree: true,
childList: true,
});
```
### Using `attributeFilter`
In this example, a Mutation Observer is set up to watch for changes to the
`status` and `username` attributes in any elements contained
within a subtree that displays the names of users in a chat room. This lets the code,
for example, reflect changes to users' nicknames, or to mark them as away from keyboard
(AFK) or offline.
```js
function callback(mutationList) {
mutationList.forEach((mutation) => {
switch (mutation.type) {
case "attributes":
switch (mutation.attributeName) {
case "status":
userStatusChanged(mutation.target.username, mutation.target.status);
break;
case "username":
usernameChanged(mutation.oldValue, mutation.target.username);
break;
}
break;
}
});
}
const userListElement = document.querySelector("#userlist");
const observer = new MutationObserver(callback);
observer.observe(userListElement, {
attributeFilter: ["status", "username"],
attributeOldValue: true,
subtree: true,
});
```
### Monitoring attribute values
In this example we observe an element for attribute value changes, and add a button which toggles the element's [`dir`](/en-US/docs/Web/HTML/Global_attributes/dir) attribute between `"ltr"` and `"rtl"`. Inside the observer's callback, we log the old value of the attribute.
#### HTML
```html
<button id="toggle">Toggle direction</button><br />
<div id="container">
<input type="text" id="rhubarb" dir="ltr" value="Tofu" />
</div>
<pre id="output"></pre>
```
#### CSS
```css
body {
background-color: paleturquoise;
}
button,
input,
pre {
margin: 0.5rem;
}
```
#### JavaScript
```js
const toggle = document.querySelector("#toggle");
const rhubarb = document.querySelector("#rhubarb");
const observerTarget = document.querySelector("#container");
const output = document.querySelector("#output");
toggle.addEventListener("click", () => {
rhubarb.dir = rhubarb.dir === "ltr" ? "rtl" : "ltr";
});
const config = {
subtree: true,
attributeOldValue: true,
};
const callback = (mutationList) => {
for (const mutation of mutationList) {
if (mutation.type === "attributes") {
output.textContent = `The ${mutation.attributeName} attribute was modified from "${mutation.oldValue}".`;
}
}
};
const observer = new MutationObserver(callback);
observer.observe(observerTarget, config);
```
#### Result
{{EmbedLiveSample("Monitoring attribute values")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mutationobserver | data/mdn-content/files/en-us/web/api/mutationobserver/disconnect/index.md | ---
title: "MutationObserver: disconnect() method"
short-title: disconnect()
slug: Web/API/MutationObserver/disconnect
page-type: web-api-instance-method
browser-compat: api.MutationObserver.disconnect
---
{{APIRef("DOM WHATWG")}}
The {{domxref("MutationObserver")}} method
**`disconnect()`** tells the observer to stop watching for
mutations.
The observer can be reused by calling its
{{domxref("MutationObserver.observe", "observe()")}} method again.
## Syntax
```js-nolint
disconnect()
```
### Parameters
None.
### Return value
`undefined`.
> **Note:** All notifications of mutations that have already been
> _detected_, but _not yet reported_ to the observer, are discarded.
> To hold on to and handle the detected but unreported mutations, use
> the {{domxref("MutationObserver.takeRecords()", "takeRecords()")}} method.
## Usage notes
If the element being observed is removed from the DOM, and then subsequently released
by the browser's garbage collection mechanism, the `MutationObserver` will stop observing
the removed element. However, the `MutationObserver` itself can continue to exist to observe
other existing elements.
## Examples
This example creates an observer, then disconnects from it, leaving it available for
possible reuse.
```js
const targetNode = document.querySelector("#someElement");
const observerOptions = {
childList: true,
attributes: true,
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);
/* some time later… */
observer.disconnect();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mutationobserver | data/mdn-content/files/en-us/web/api/mutationobserver/mutationobserver/index.md | ---
title: "MutationObserver: MutationObserver() constructor"
short-title: MutationObserver()
slug: Web/API/MutationObserver/MutationObserver
page-type: web-api-constructor
browser-compat: api.MutationObserver.MutationObserver
---
{{APIRef("DOM WHATWG")}}
The DOM **`MutationObserver()`**
constructor — part of the {{domxref("MutationObserver")}} interface — creates and
returns a new observer which invokes a specified callback when DOM events
occur.
DOM observation does not begin immediately; the
{{domxref("MutationObserver.observe", "observe()")}} method must be called first to
establish which portion of the DOM to watch and what kinds of changes to watch for.
## Syntax
```js-nolint
new MutationObserver(callback)
```
### Parameters
- `callback`
- : A function which will be called on each DOM change that qualifies given the
observed node or subtree and options.
The `callback` function takes as input two parameters:
1. An array of {{domxref("MutationRecord")}} objects, describing each change that
occurred.
2. The {{domxref("MutationObserver")}} which invoked the
`callback`. This is most often used to disconnect the observer using {{domxref("MutationObserver.disconnect()")}}.
See the [examples](#examples) below for more details.
### Return value
A new {{domxref("MutationObserver")}} object, configured to call the specified
`callback` when DOM mutations occur.
## Examples
### Observing child elements
This example has buttons to add an {{htmlelement("li")}} element to a list, and to remove the first `<li>` element from the list.
We use a `MutationObserver` to be notified about changes to the list. In the callback, we log additions and removals, and as soon as the list is empty, we disconnect the observer.
The "Reset example" button resets the example to its original state.
#### HTML
```html
<button id="add">Add child</button>
<button id="remove">Remove child</button>
<button id="reset">Reset example</button>
<ul id="container"></ul>
<pre id="log"></pre>
```
#### CSS
```css
#container,
#log {
height: 150px;
overflow: scroll;
}
#container li {
background-color: paleturquoise;
margin: 0.5rem;
}
```
#### JavaScript
```js
const add = document.querySelector("#add");
const remove = document.querySelector("#remove");
const reset = document.querySelector("#reset");
const container = document.querySelector("#container");
const log = document.querySelector("#log");
let namePrefix = 0;
add.addEventListener("click", () => {
const newItem = document.createElement("li");
newItem.textContent = `item ${namePrefix}`;
container.appendChild(newItem);
namePrefix++;
});
remove.addEventListener("click", () => {
const itemToRemove = document.querySelector("li");
if (itemToRemove) {
itemToRemove.parentNode.removeChild(itemToRemove);
}
});
reset.addEventListener("click", () => {
document.location.reload();
});
function logChanges(records, observer) {
for (const record of records) {
for (const addedNode of record.addedNodes) {
log.textContent = `Added: ${addedNode.textContent}\n${log.textContent}`;
}
for (const removedNode of record.removedNodes) {
log.textContent = `Removed: ${removedNode.textContent}\n${log.textContent}`;
}
if (record.target.childNodes.length === 0) {
log.textContent = `Disconnected\n${log.textContent}`;
observer.disconnect();
}
console.log(record.target.childNodes.length);
}
}
const observerOptions = {
childList: true,
subtree: true,
};
const observer = new MutationObserver(logChanges);
observer.observe(container, observerOptions);
```
#### Result
Try clicking "Add child" to add list items, and "Remove child" to remove them. The observer callback logs additions and removals. As soon as the list is empty, the observer logs a "Disconnected" message and disconnects the observer.
The "Reset example" button reloads the example so you can try it again.
{{EmbedLiveSample("Observing child elements", 0, 400)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/midiinput/index.md | ---
title: MIDIInput
slug: Web/API/MIDIInput
page-type: web-api-interface
browser-compat: api.MIDIInput
---
{{APIRef("Web MIDI API")}}{{securecontext_header}}
The **`MIDIInput`** interface of the [Web MIDI API](/en-US/docs/Web/API/Web_MIDI_API) receives messages from a MIDI input port.
{{InheritanceDiagram}}
## Instance properties
_This interface doesn't implement any specific properties, but inherits properties from {{domxref("MIDIPort")}}._
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from {{domxref("MIDIPort")}}._
### Events
- {{domxref("MIDIInput.midimessage_event", "midimessage")}}
- : Fired when the current port receives a MIDI message.
## Examples
In the following example the name of each `MIDIInput` is printed to the console. Then, `midimessage` events are listened for on all input ports. When a message is received the {{domxref("MIDIMessageEvent.data")}} property is printed to the console.
```js
inputs.forEach((input) => {
console.log(input.name); /* inherited property from MIDIPort */
input.onmidimessage = (message) => {
console.log(message.data);
};
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/midiinput | data/mdn-content/files/en-us/web/api/midiinput/midimessage_event/index.md | ---
title: "MIDIInput: midimessage event"
short-title: midimessage
slug: Web/API/MIDIInput/midimessage_event
page-type: web-api-event
browser-compat: api.MIDIInput.midimessage_event
---
{{APIRef("Web MIDI API")}}{{securecontext_header}}
The `midimessage` event of the [Web MIDI API](/en-US/docs/Web/API/Web_MIDI_API) is fired when the MIDI port corresponding to this {{domxref("MIDIInput")}} finishes receiving one or more MIDI messages. An instance of {{domxref("MIDIMessageEvent")}} containing the message that was received is passed to the event handler.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("midimessage", (event) => {});
onmidimessage = (event) => {};
```
## Event type
An {{domxref("MIDIMessageEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MIDIMessageEvent")}}
## Event properties
_This interface also inherits properties from {{domxref("Event")}}._
- {{domxref("MIDIMessageEvent.data")}}
- : A {{jsxref("Uint8Array")}} containing the data bytes of a single MIDI message. See the [MIDI specification](https://www.midi.org/specifications-old/item/table-1-summary-of-midi-message) for more information on its form.
## Examples
In the following example `midimessage` events are listened for on all input ports. When a message is received the {{domxref("MIDIMessageEvent.data")}} property is printed to the console.
```js
inputs.forEach((input) => {
input.onmidimessage = (message) => {
console.log(message.data);
};
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediasession/index.md | ---
title: MediaSession
slug: Web/API/MediaSession
page-type: web-api-interface
browser-compat: api.MediaSession
---
{{APIRef("Media Session API")}}
The **`MediaSession`** interface of the {{domxref("Media Session API", "", "", "nocode")}} allows a web page to provide custom behaviors for standard media playback interactions, and to report metadata that can be sent by the user agent to the device or operating system for presentation in standardized user interface elements.
For example, a smartphone might have a standard panel in its lock screen that provides controls for media playback and information display. A browser on the device can use `MediaSession` to make browser playback controllable from that standard/global user interface.
## Instance properties
- {{domxref("MediaSession.metadata", "metadata")}}
- : Returns an instance of {{domxref("MediaMetadata")}}, which contains rich media metadata for display in a platform UI.
- {{domxref("MediaSession.playbackState", "playbackState")}}
- : Indicates whether the current media session is playing. Valid values are `none`, `paused`, or `playing`.
## Instance methods
- {{domxref("MediaSession.setActionHandler", "setActionHandler()")}}
- : Sets an action handler for a media session action, such as play or pause.
- {{domxref("MediaSession.setCameraActive", "setCameraActive()")}} {{Experimental_Inline}}
- : Indicates to the user agent whether the user's camera is considered to be active.
- {{domxref("MediaSession.setMicrophoneActive", "setMicrophoneActive()")}} {{Experimental_Inline}}
- : Indicates to the user agent whether the user's microphone is considered to be currently muted.
- {{domxref("MediaSession.setPositionState", "setPositionState()")}}
- : Sets the current playback position and speed of the media currently being presented.
## Examples
### Setting up action handlers for a music player
The following example creates a new media session and assigns action handlers to it:
```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",
},
],
});
navigator.mediaSession.setActionHandler("play", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("pause", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("stop", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("seekbackward", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("seekforward", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("seekto", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("previoustrack", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("nexttrack", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("skipad", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("togglecamera", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("togglemicrophone", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("hangup", () => {
/* Code excerpted. */
});
}
```
The following example sets up two functions for playing and pausing, then uses them as callbacks with the relevant action handlers.
```js
const actionHandlers = [
// play
[
"play",
async () => {
// play our audio
await audioEl.play();
// set playback state
navigator.mediaSession.playbackState = "playing";
// update our status element
updateStatus(allMeta[index], "Action: play | Track is playing…");
},
],
[
"pause",
() => {
// pause out audio
audioEl.pause();
// set playback state
navigator.mediaSession.playbackState = "paused";
// update our status element
updateStatus(allMeta[index], "Action: pause | Track has been paused…");
},
],
];
for (const [action, handler] of actionHandlers) {
try {
navigator.mediaSession.setActionHandler(action, handler);
} catch (error) {
console.log(`The media session action "${action}" is not supported yet.`);
}
}
```
### Using action handlers to control a slide presentation
The `"previousslide"` and `"nextslide"` action handlers can be used to handle moving forward and backward through a slide presentation, for example when the user puts their presentation into a {{domxref("Picture-in-Picture API", "Picture-in-Picture", "", "nocode")}} window, and presses the browser-supplied controls for navigating through slides.
```js
try {
navigator.mediaSession.setActionHandler("previousslide", () => {
log('> User clicked "Previous Slide" icon.');
if (slideNumber > 1) slideNumber--;
updateSlide();
});
} catch (error) {
log('Warning! The "previousslide" media session action is not supported.');
}
try {
navigator.mediaSession.setActionHandler("nextslide", () => {
log('> User clicked "Next Slide" icon.');
slideNumber++;
updateSlide();
});
} catch (error) {
log('Warning! The "nextslide" media session action is not supported.');
}
```
See [Presenting Slides / Media Session Sample](https://googlechrome.github.io/samples/media-session/slides.html) for a working example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediasession | data/mdn-content/files/en-us/web/api/mediasession/setcameraactive/index.md | ---
title: "MediaSession: setCameraActive() method"
short-title: setCameraActive()
slug: Web/API/MediaSession/setCameraActive
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.MediaSession.setCameraActive
---
{{APIRef("Media Session API")}}{{SeeCompatTable}}
The **`setCameraActive()`** method of the {{domxref("MediaSession")}} interface is used to indicate to the user agent whether the user's camera is considered to be active.
Call this method on the `navigator` object's
{{domxref("navigator.mediaSession", "mediaSession")}} object.
Note that the status of the camera is not tracked in the {{domxref("MediaSession")}} itself, but must be tracked separately.
## Syntax
```js-nolint
setCameraActive(active)
```
### Parameters
- `active`
- : A boolean indicating whether the camera is considered active or not.
### Return value
None ({{jsxref("undefined")}}).
## Examples
Below is an example of updating the camera active state of the current
{{domxref('MediaSession')}}, as well as listening to requests to change the camera status with {{domxref("MediaSession.setActionHandler", "setActionHandler()")}}.
```js
let cameraActive = false;
navigator.mediaSession.setCameraActive(cameraActive);
navigator.mediaSession.setActionHandler("togglecamera", () => {
cameraActive = !cameraActive;
navigator.mediaSession.setCameraActive(cameraActive);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediasession | data/mdn-content/files/en-us/web/api/mediasession/playbackstate/index.md | ---
title: "MediaSession: playbackState property"
short-title: playbackState
slug: Web/API/MediaSession/playbackState
page-type: web-api-instance-property
browser-compat: api.MediaSession.playbackState
---
{{APIRef("Media Session API")}}
The **`playbackState`** property of the
{{domxref("MediaSession")}} interface indicates whether the current media session is
playing or paused.
## Value
A string indicating the current playback state of the media session.
The value may be one of the following:
- `none`
- : The browsing context doesn't currently know the current playback state, or the
playback state is not available at this time.
- `paused`
- : The browser's media session is currently paused. Playback may be resumed.
- `playing`
- : The browser's media session is currently playing media, which can be paused.
## Example
The following example sets up two functions for playing and pausing, then uses them as
callbacks with the relevant action handlers. Each function harnesses the
`playbackState` property to indicate whether the audio is playing or paused.
```js
const actionHandlers = [
// play
[
"play",
async () => {
// play our audio
await audioEl.play();
// set playback state
navigator.mediaSession.playbackState = "playing";
// update our status element
updateStatus(allMeta[index], "Action: play | Track is playing…");
},
],
[
"pause",
() => {
// pause out audio
audioEl.pause();
// set playback state
navigator.mediaSession.playbackState = "paused";
// update our status element
updateStatus(allMeta[index], "Action: pause | Track has been paused…");
},
],
];
for (const [action, handler] of actionHandlers) {
try {
navigator.mediaSession.setActionHandler(action, handler);
} catch (error) {
console.log(`The media session action "${action}" is not supported yet.`);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediasession | data/mdn-content/files/en-us/web/api/mediasession/setactionhandler/index.md | ---
title: "MediaSession: setActionHandler() method"
short-title: setActionHandler()
slug: Web/API/MediaSession/setActionHandler
page-type: web-api-instance-method
browser-compat: api.MediaSession.setActionHandler
---
{{APIRef("Media Session API")}}
The **`setActionHandler()`** method of the {{domxref("MediaSession")}} interface sets a handler for a media session action.
These actions let a web app receive notifications when the user engages a device's built-in physical or onscreen media controls, such as play, stop, or seek buttons.
## Syntax
```js-nolint
setActionHandler(type, callback)
```
### Parameters
- `type`
- : A string representing an action type to listen for. It will be one
of the following:
- `hangup`
- : End a call.
- `nextslide`
- : Moves to the next slide, when presenting a slide deck.
- `nexttrack`
- : Advances playback to the next track.
- `pause`
- : Pauses playback of the media.
- `play`
- : Begins (or resumes) playback of the media.
- `previousslide`
- : Moves to the previous slide, when presenting a slide deck.
- `previoustrack`
- : Moves back to the previous track.
- `seekbackward`
- : Seeks backward through the media from the current position.
The `seekOffset` property passed to the callback specifies the amount of time to seek backward.
- `seekforward`
- : Seeks forward from the current position through the media.
The `seekOffset` property passed to the callback specifies the amount of time to seek forward.
- `seekto`
- : Moves the playback position to the specified time within the media.
The time to which to seek is specified in the `seekTime` property passed to the callback.
If you intend to perform multiple `seekto` operations in rapid succession, you can also specify the `fastSeek` property passed to the callback with a value of `true`.
This lets the browser know it can take steps to optimize repeated operations, and is likely to result in improved performance.
- `skipad`
- : Skips past the currently playing advertisement or commercial.
This action may or may not be available, depending on the platform and {{Glossary("user agent")}}, or may be disabled due to subscription level or other circumstances.
- `stop`
- : Halts playback entirely.
- `togglecamera`
- : Turn the user's active camera on or off.
- `togglemicrophone`
- : Mute or unmute the user's microphone.
- `callback`
- : A function to call when the specified action type is invoked. The callback should not return a value. The callback receives a dictionary containing the following properties:
- `action`
- : A string representing the action type. This property allows a single callback to handle multiple action types.
- `fastSeek` {{optional_inline}}
- : A [`seekto`](#seekto) action may _optionally_ include this property, which is a Boolean value indicating whether or not to perform a "fast" seek.
A "fast" seek is a seek being performed in a rapid sequence, such as when fast-forwarding or reversing through the media, rapidly skipping through it.
This property can be used to indicate that you should use the shortest possible method to seek the media.
`fastSeek` is not included on the final action in the seek sequence in this situation.
- `seekOffset` {{optional_inline}}
- : If the `action` is either [`seekforward`](#seekforward) or [`seekbackward`](#seekbackward) and this property is present, it is a floating point value which indicates the number of seconds to move the play position forward or backward.
If this property isn't present, those actions should choose a reasonable default distance to skip forward or backward (such as 7 or 10 seconds).
- `seekTime` {{optional_inline}}
- : If the `action` is [`seekto`](#seekto), this property must be present and must be a floating-point value indicating the absolute time within the media to move the playback position to, where 0 indicates the beginning of the media. This property is not present for other action types.
### Return value
None ({{jsxref("undefined")}}).
## Description
To remove a previously-established action handler, call `setActionHandler()` again, specifying `null` as the `callback`.
The action handler receives as input a single parameter: an object which provides both the action type (so the same function can handle multiple action types), as well as data needed in order to perform the action.
## Examples
### Setting up action handlers for a music player
This example creates a new media session and assigns action handlers (which don't do anything) to it.
```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",
},
],
});
navigator.mediaSession.setActionHandler("play", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("pause", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("stop", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("seekbackward", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("seekforward", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("seekto", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("previoustrack", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("nexttrack", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("skipad", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("togglecamera", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("togglemicrophone", () => {
/* Code excerpted. */
});
navigator.mediaSession.setActionHandler("hangup", () => {
/* Code excerpted. */
});
}
```
The following example sets up two functions for playing and pausing, then uses them as callbacks with the relevant action handlers.
```js
const actionHandlers = [
// play
[
"play",
async () => {
// play our audio
await audioEl.play();
// set playback state
navigator.mediaSession.playbackState = "playing";
// update our status element
updateStatus(allMeta[index], "Action: play | Track is playing…");
},
],
[
"pause",
() => {
// pause out audio
audioEl.pause();
// set playback state
navigator.mediaSession.playbackState = "paused";
// update our status element
updateStatus(allMeta[index], "Action: pause | Track has been paused…");
},
],
];
for (const [action, handler] of actionHandlers) {
try {
navigator.mediaSession.setActionHandler(action, handler);
} catch (error) {
console.log(`The media session action "${action}" is not supported yet.`);
}
}
```
This example uses appropriate action handlers to allow seeking in either direction through the playing media.
```js
navigator.mediaSession.setActionHandler("seekbackward", (evt) => {
// User clicked "Seek Backward" media notification icon.
let skipTime = evt.seekOffset || 10; // Time to skip in seconds
audio.currentTime = Math.max(audio.currentTime - skipTime, 0);
});
navigator.mediaSession.setActionHandler("seekforward", (evt) => {
// User clicked "Seek Forward" media notification icon.
let skipTime = evt.seekOffset || 10; // Time to skip in seconds
audio.currentTime = Math.min(audio.currentTime + skipTime, audio.duration);
});
```
To remove a media action handler, assign it to null.
```js
navigator.mediaSession.setActionHandler("nexttrack", null);
```
### Supporting multiple actions in one handler function
You can also, if you prefer, use a single function to handle multiple action types, by checking the value of the `action` property:
```js
let skipTime = 7;
navigator.mediaSession.setActionHandler("seekforward", handleSeek);
navigator.mediaSession.setActionHandler("seekbackward", handleSeek);
function handleSeek(details) {
switch (details.action) {
case "seekforward":
audio.currentTime = Math.min(
audio.currentTime + skipTime,
audio.duration,
);
break;
case "seekbackward":
audio.currentTime = Math.max(audio.currentTime - skipTime, 0);
break;
}
}
```
Here, the `handleSeek()` function handles both `seekbackward` and `seekforward` actions.
### Using action handlers to control a slide presentation
The `"previousslide"` and `"nextslide"` action handlers can be used to handle moving forward and backward through a slide presentation, for example when the user puts their presentation into a {{domxref("Picture-in-Picture API", "Picture-in-Picture", "", "nocode")}} window, and presses the browser-supplied controls for navigating through slides.
```js
try {
navigator.mediaSession.setActionHandler("previousslide", () => {
log('> User clicked "Previous Slide" icon.');
if (slideNumber > 1) slideNumber--;
updateSlide();
});
} catch (error) {
log('Warning! The "previousslide" media session action is not supported.');
}
try {
navigator.mediaSession.setActionHandler("nextslide", () => {
log('> User clicked "Next Slide" icon.');
slideNumber++;
updateSlide();
});
} catch (error) {
log('Warning! The "nextslide" media session action is not supported.');
}
```
See [Presenting Slides / Media Session Sample](https://googlechrome.github.io/samples/media-session/slides.html) for a working example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediasession | data/mdn-content/files/en-us/web/api/mediasession/setpositionstate/index.md | ---
title: "MediaSession: setPositionState() method"
short-title: setPositionState()
slug: Web/API/MediaSession/setPositionState
page-type: web-api-instance-method
browser-compat: api.MediaSession.setPositionState
---
{{APIRef("Media Session API")}}
The **`setPositionState()`** method of the
{{domxref("MediaSession")}} interface is used to update the current
document's media playback position and speed for presentation by user's device in any
kind of interface that provides details about ongoing media. This can be
particularly useful if your code implements a player for type of media not directly
supported by the browser.
Call this method on the `navigator` object's
{{domxref("navigator.mediaSession", "mediaSession")}} object.
## Syntax
```js-nolint
setPositionState()
setPositionState(stateDict)
```
### Parameters
- `stateDict` {{optional_inline}}
- : An object providing updated information about the playback position and speed
of the document's ongoing media. If the object is empty, the existing playback
state information is cleared. This object can contain the following
parameters:
- `duration` {{optional_inline}}
- : A floating-point value giving the total duration of the current media in seconds. This should always be a positive number, with positive infinity ({{jsxref("Infinity")}}) indicating media without a defined end, such as a live stream.
- `playbackRate` {{optional_inline}}
- : A floating-point value indicating the rate at which the media is being played, as a ratio relative to its normal playback speed. Thus, a value of 1 is playing at normal speed, 2 is playing at double speed, and so forth. Negative values indicate that the media is playing in reverse; -1 indicates playback at the normal speed but backward, -2 is double speed in reverse, and so on.
- `position` {{optional_inline}}
- : A floating-point value indicating the last reported playback position of the media in seconds. This must always be a positive value.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : This error can occur in an array of circumstances:
- The specified object's `duration` is missing, negative, or `null`.
- Its `position` is either negative or greater than `duration`.
- Its `playbackRate` is zero.
## Examples
Below is a function which updates the position state of the current
{{domxref('MediaSession')}} track.
```js
function updatePositionState() {
navigator.mediaSession.setPositionState({
duration: audioEl.duration,
playbackRate: audioEl.playbackRate,
position: audioEl.currentTime,
});
}
```
We can use this function when updating {{domxref('MediaMetadata', 'media session
metadata')}} and within callbacks for actions, such as below.
```js
navigator.mediaSession.setActionHandler("seekbackward", (details) => {
// our time to skip
const skipTime = details.seekOffset || 10;
// set our position
audioEl.currentTime = Math.max(audioEl.currentTime - skipTime, 0);
updatePositionState();
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediasession | data/mdn-content/files/en-us/web/api/mediasession/metadata/index.md | ---
title: "MediaSession: metadata property"
short-title: metadata
slug: Web/API/MediaSession/metadata
page-type: web-api-instance-property
browser-compat: api.MediaSession.metadata
---
{{APIRef("Media Session API")}}
The **`metadata`** property of the {{domxref("MediaSession")}}
interface contains a {{domxref("MediaMetadata")}} object providing descriptive
information about the currently playing media, or `null` if the metadata has
not been set. This metadata is provided by the browser to the device for presentation in
any standard media control user interface the device might offer.
## Value
An instance of {{domxref("MediaMetadata")}} containing information about the media
currently being played.
## Example
The following example checks for compatibility and creates a new media session with the
relevant 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/mediasession | data/mdn-content/files/en-us/web/api/mediasession/setmicrophoneactive/index.md | ---
title: "MediaSession: setMicrophoneActive() method"
short-title: setMicrophoneActive()
slug: Web/API/MediaSession/setMicrophoneActive
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.MediaSession.setMicrophoneActive
---
{{APIRef("Media Session API")}}{{SeeCompatTable}}
The **`setMicrophoneActive()`** method of the {{domxref("MediaSession")}} interface is used to indicate to the user agent whether the user's microphone is considered to be currently muted.
Call this method on the `navigator` object's
{{domxref("navigator.mediaSession", "mediaSession")}} object.
Note that the status of the microphone is not tracked in the {{domxref("MediaSession")}} itself, but must be tracked separately.
## Syntax
```js-nolint
setMicrophoneActive(active)
```
### Parameters
- `active`
- : A boolean indicating whether the microphone is considered muted or not.
### Return value
None ({{jsxref("undefined")}}).
## Examples
Below is an example of updating the microphone mute state of the current
{{domxref('MediaSession')}}, as well as listening to requests to change the mute status with {{domxref("MediaSession.setActionHandler", "setActionHandler()")}}.
```js
let microphoneActive = false;
navigator.mediaSession.setMicrophoneActive(microphoneActive);
navigator.mediaSession.setActionHandler("togglemicrophone", () => {
microphoneActive = !microphoneActive;
navigator.mediaSession.setMicrophoneActive(microphoneActive);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/indexeddb_api/index.md | ---
title: IndexedDB API
slug: Web/API/IndexedDB_API
page-type: web-api-overview
spec-urls: https://w3c.github.io/IndexedDB/
---
{{DefaultAPISidebar("IndexedDB")}}
IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data. While [Web Storage](/en-US/docs/Web/API/Web_Storage_API) is useful for storing smaller amounts of data, it is less useful for storing larger amounts of structured data. IndexedDB provides a solution. This is the main landing page for MDN's IndexedDB coverage — here we provide links to the full API reference and usage guides, browser support details, and some explanation of key concepts.
{{AvailableInWorkers}}
## Key concepts and usage
IndexedDB is a transactional database system, like an SQL-based Relational Database Management System (RDBMS). However, unlike SQL-based RDBMSes, which use fixed-column tables, IndexedDB is a JavaScript-based object-oriented database. IndexedDB lets you store and retrieve objects that are indexed with a **key**; any objects supported by the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) can be stored. You need to specify the database schema, open a connection to your database, and then retrieve and update data within a series of **transactions**.
- Read more about [IndexedDB key characteristics and basic terminology](/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology).
- Learn to use IndexedDB asynchronously from first principles with our [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) guide.
> **Note:** Like most web storage solutions, IndexedDB follows a [same-origin policy](https://www.w3.org/Security/wiki/Same_Origin_Policy). So while you can access stored data within a domain, you cannot access data across different domains.
### Synchronous and asynchronous
Operations performed using IndexedDB are done asynchronously, so as not to block applications.
### Storage limits and eviction criteria
There are a number of web technologies that store data of one kind or another on the client side (i.e. on your local disk). IndexedDB is most commonly talked about. The process by which the browser works out how much space to allocate to web data storage and what to delete when that limit is reached is not simple, and differs between browsers. [Browser storage quotas and eviction criteria](/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria) attempts to explain how this works, at least in the case of Firefox.
## Interfaces
To get access to a database, call [`open()`](/en-US/docs/Web/API/IDBFactory/open) on the [`indexedDB`](/en-US/docs/Web/API/indexedDB) property of a [window](/en-US/docs/Web/API/Window) object. This method returns an {{domxref("IDBRequest")}} object; asynchronous operations communicate to the calling application by firing events on {{domxref("IDBRequest")}} objects.
### Connecting to a database
- {{domxref("IDBFactory")}}
- : Provides access to a database. This is the interface implemented by the global object {{domxref("indexedDB")}} and is therefore the entry point for the API.
- {{domxref("IDBOpenDBRequest")}}
- : Represents a request to open a database.
- {{domxref("IDBDatabase")}}
- : Represents a connection to a database. It's the only way to get a transaction on the database.
### Retrieving and modifying data
- {{domxref("IDBTransaction")}}
- : Represents a transaction. You create a transaction on a database, specify the scope (such as which object stores you want to access), and determine the kind of access (read only or readwrite) that you want.
- {{domxref("IDBRequest")}}
- : Generic interface that handles database requests and provides access to results.
- {{domxref("IDBObjectStore")}}
- : Represents an object store that allows access to a set of data in an IndexedDB database, looked up via primary key.
- {{domxref("IDBIndex")}}
- : Also allows access to a subset of data in an IndexedDB database, but uses an index to retrieve the record(s) rather than the primary key. This is sometimes faster than using {{domxref("IDBObjectStore")}}.
- {{domxref("IDBCursor")}}
- : Iterates over object stores and indexes.
- {{domxref("IDBCursorWithValue")}}
- : Iterates over object stores and indexes and returns the cursor's current value.
- {{domxref("IDBKeyRange")}}
- : Defines a key range that can be used to retrieve data from a database in a certain range.
### Custom event interfaces
This specification fires events with the following custom interface:
- {{domxref("IDBVersionChangeEvent")}}
- : The `IDBVersionChangeEvent` interface indicates that the version of the database has changed, as the result of an {{domxref("IDBOpenDBRequest.upgradeneeded_event", "IDBOpenDBRequest.onupgradeneeded")}} event handler function.
## Examples
- [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)): The reference application for the examples in the reference docs.
## Specifications
{{Specifications}}
## See also
- [Web Storage API](/en-US/docs/Web/API/Web_Storage_API)
- [Window: localStorage property](/en-US/docs/Web/API/Window/localStorage)
- [Window: sessionStorage property](/en-US/docs/Web/API/Window/sessionStorage)
- [StorageEvent](/en-US/docs/Web/API/StorageEvent)
| 0 |
data/mdn-content/files/en-us/web/api/indexeddb_api | data/mdn-content/files/en-us/web/api/indexeddb_api/using_indexeddb/index.md | ---
title: Using IndexedDB
slug: Web/API/IndexedDB_API/Using_IndexedDB
page-type: guide
---
{{DefaultAPISidebar("IndexedDB")}}
IndexedDB is a way for you to persistently store data inside a user's browser. Because it lets you create web applications with rich query abilities regardless of network availability, your applications can work both online and offline.
## About this document
This tutorial walks you through using the asynchronous API of IndexedDB. If you are not familiar with IndexedDB, you should first read the [IndexedDB key characteristics and basic terminology](/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology) article.
For the reference documentation on the IndexedDB API, see the [IndexedDB API](/en-US/docs/Web/API/IndexedDB_API) article and its subpages. This article documents the types of objects used by IndexedDB, as well as the methods of the asynchronous API (the synchronous API was removed from spec).
## Basic pattern
The basic pattern that IndexedDB encourages is the following:
1. Open a database.
2. Create an object store in the database.
3. Start a transaction and make a request to do some database operation, like adding or retrieving data.
4. Wait for the operation to complete by listening to the right kind of DOM event.
5. Do something with the results (which can be found on the request object).
With these big concepts under our belts, we can get to more concrete stuff.
## Creating and structuring the store
### Opening a database
We start the whole process like this:
```js
// Let us open our database
const request = window.indexedDB.open("MyTestDatabase", 3);
```
See that? Opening a database is just like any other operation — you have to "request" it.
The open request doesn't open the database or start the transaction right away. The call to the `open()` function returns an [`IDBOpenDBRequest`](/en-US/docs/Web/API/IDBOpenDBRequest) object with a result (success) or error value that you handle as an event. Most other asynchronous functions in IndexedDB do the same thing - return an [`IDBRequest`](/en-US/docs/Web/API/IDBRequest) object with the result or error. The result for the open function is an instance of an `IDBDatabase`.
The second parameter to the open method is the version of the database. The version of the database determines the database schema — the object stores in the database and their structure. If the database doesn't already exist, it is created by the `open` operation, then an `onupgradeneeded` event is triggered and you create the database schema in the handler for this event. If the database does exist but you are specifying an upgraded version number, an `onupgradeneeded` event is triggered straight away, allowing you to provide an updated schema in its handler. More on this later in [Creating or updating the version of the database](#creating_or_updating_the_version_of_the_database) below, and the {{ domxref("IDBFactory.open") }} reference page.
> **Warning:** The version number is an `unsigned long long` number, which means that it can be a very big integer. It also means that you can't use a float, otherwise it will be converted to the closest lower integer and the transaction may not start, nor the `upgradeneeded` event trigger. So for example, don't use 2.4 as a version number:
> `const request = indexedDB.open("MyTestDatabase", 2.4); // don't do this, as the version will be rounded to 2`
#### Generating handlers
The first thing you'll want to do with almost all of the requests you generate is to add success and error handlers:
```js
request.onerror = (event) => {
// Do something with request.errorCode!
};
request.onsuccess = (event) => {
// Do something with request.result!
};
```
Which of the two functions, `onsuccess()` or `onerror()`, gets called? If everything succeeds, a success event (that is, a DOM event whose `type` property is set to `"success"`) is fired with `request` as its `target`. Once it is fired, the `onsuccess()` function on `request` is triggered with the success event as its argument. Otherwise, if there was any problem, an error event (that is, a DOM event whose `type` property is set to `"error"`) is fired at `request`. This triggers the `onerror()` function with the error event as its argument.
The IndexedDB API is designed to minimize the need for error handling, so you're not likely to see many error events (at least, not once you're used to the API!). In the case of opening a database, however, there are some common conditions that generate error events. The most likely problem is that the user decided not to give your web app permission to create a database. One of the main design goals of IndexedDB is to allow large amounts of data to be stored for offline use. (To learn more about how much storage you can have for each browser, see [How much data can be stored? on the Browser storage quotas and eviction criteria page](/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria#how_much_data_can_be_stored).)
Obviously, browsers do not want to allow some advertising network or malicious website to pollute your computer, so browsers used to prompt the user the first time any given web app attempts to open an IndexedDB for storage. The user could choose to allow or deny access. Also, IndexedDB storage in browsers' privacy modes only lasts in-memory until the incognito session is closed.
Now, assuming that the user allowed your request to create a database, and you've received a success event to trigger the success callback; What's next? The request here was generated with a call to `indexedDB.open()`, so `request.result` is an instance of `IDBDatabase`, and you definitely want to save that for later. Your code might look something like this:
```js
let db;
const request = indexedDB.open("MyTestDatabase");
request.onerror = (event) => {
console.error("Why didn't you allow my web app to use IndexedDB?!");
};
request.onsuccess = (event) => {
db = event.target.result;
};
```
#### Handling Errors
As mentioned above, error events bubble. Error events are targeted at the request that generated the error, then the event bubbles to the transaction, and then finally to the database object. If you want to avoid adding error handlers to every request, you can instead add a single error handler on the database object, like so:
```js
db.onerror = (event) => {
// Generic error handler for all errors targeted at this database's
// requests!
console.error(`Database error: ${event.target.errorCode}`);
};
```
One of the common possible errors when opening a database is `VER_ERR`. It indicates that the version of the database stored on the disk is _greater_ than the version that you are trying to open. This is an error case that must always be handled by the error handler.
### Creating or updating the version of the database
When you create a new database or increase the version number of an existing database (by specifying a higher version number than you did previously, when [Opening a database](#opening_a_database)), the `onupgradeneeded` event will be triggered and an [IDBVersionChangeEvent](/en-US/docs/Web/API/IDBVersionChangeEvent) object will be passed to any `onversionchange` event handler set up on `request.result` (i.e., `db` in the example). In the handler for the `upgradeneeded` event, you should create the object stores needed for this version of the database:
```js
// This event is only implemented in recent browsers
request.onupgradeneeded = (event) => {
// Save the IDBDatabase interface
const db = event.target.result;
// Create an objectStore for this database
const objectStore = db.createObjectStore("name", { keyPath: "myKey" });
};
```
In this case, the database will already have the object stores from the previous version of the database, so you do not have to create these object stores again. You only need to create any new object stores, or delete object stores from the previous version that are no longer needed. If you need to change an existing object store (e.g., to change the `keyPath`), then you must delete the old object store and create it again with the new options. (Note that this will delete the information in the object store! If you need to save that information, you should read it out and save it somewhere else before upgrading the database.)
Trying to create an object store with a name that already exists (or trying to delete an object store with a name that does not already exist) will throw an error.
If the `onupgradeneeded` event exits successfully, the `onsuccess` handler of the open database request will then be triggered.
### Structuring the database
Now to structure the database. IndexedDB uses object stores rather than tables, and a single database can contain any number of object stores. Whenever a value is stored in an object store, it is associated with a key. There are several different ways that a key can be supplied depending on whether the object store uses a [key path](/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology#key_path) or a [key generator](/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology#key_generator).
The following table shows the different ways the keys are supplied:
<table class="no-markdown">
<thead>
<tr>
<th scope="col">Key Path (<code>keyPath</code>)</th>
<th scope="col">Key Generator (<code>autoIncrement</code>)</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>No</td>
<td>No</td>
<td>
This object store can hold any kind of value, even primitive values like
numbers and strings. You must supply a separate key argument whenever
you want to add a new value.
</td>
</tr>
<tr>
<td>Yes</td>
<td>No</td>
<td>
This object store can only hold JavaScript objects. The objects must
have a property with the same name as the key path.
</td>
</tr>
<tr>
<td>No</td>
<td>Yes</td>
<td>
This object store can hold any kind of value. The key is generated for
you automatically, or you can supply a separate key argument if you want
to use a specific key.
</td>
</tr>
<tr>
<td>Yes</td>
<td>Yes</td>
<td>
This object store can only hold JavaScript objects. Usually a key is
generated and the value of the generated key is stored in the object in
a property with the same name as the key path. However, if such a
property already exists, the value of that property is used as key
rather than generating a new key.
</td>
</tr>
</tbody>
</table>
You can also create indices on any object store, provided the object store holds objects, not primitives. An index lets you look up the values stored in an object store using the value of a property of the stored object, rather than the object's key.
Additionally, indexes have the ability to enforce simple constraints on the stored data. By setting the unique flag when creating the index, the index ensures that no two objects are stored with both having the same value for the index's key path. So, for example, if you have an object store which holds a set of people, and you want to ensure that no two people have the same email address, you can use an index with the unique flag set to enforce this.
That may sound confusing, but this simple example should illustrate the concepts. First, we'll define some customer data to use in our example:
```js
// This is what our customer data looks like.
const customerData = [
{ ssn: "444-44-4444", name: "Bill", age: 35, email: "[email protected]" },
{ ssn: "555-55-5555", name: "Donna", age: 32, email: "[email protected]" },
];
```
Of course, you wouldn't use someone's social security number as the primary key to a customer table because not everyone has a social security number, and you would store their birth date instead of their age, but let's ignore those unfortunate choices for the sake of convenience and move along.
Now let's look at creating an IndexedDB to store our data:
```js
const dbName = "the_name";
const request = indexedDB.open(dbName, 2);
request.onerror = (event) => {
// Handle errors.
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create an objectStore to hold information about our customers. We're
// going to use "ssn" as our key path because it's guaranteed to be
// unique - or at least that's what I was told during the kickoff meeting.
const objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
// Create an index to search customers by name. We may have duplicates
// so we can't use a unique index.
objectStore.createIndex("name", "name", { unique: false });
// Create an index to search customers by email. We want to ensure that
// no two customers have the same email, so use a unique index.
objectStore.createIndex("email", "email", { unique: true });
// Use transaction oncomplete to make sure the objectStore creation is
// finished before adding data into it.
objectStore.transaction.oncomplete = (event) => {
// Store values in the newly created objectStore.
const customerObjectStore = db
.transaction("customers", "readwrite")
.objectStore("customers");
customerData.forEach((customer) => {
customerObjectStore.add(customer);
});
};
};
```
As indicated previously, `onupgradeneeded` is the only place where you can alter the structure of the database. In it, you can create and delete object stores and build and remove indices.
Object stores are created with a single call to `createObjectStore()`. The method takes a name of the store, and a parameter object. Even though the parameter object is optional, it is very important, because it lets you define important optional properties and refine the type of object store you want to create. In our case, we've asked for an object store named "customers" and defined a `keyPath`, which is the property that makes an individual object in the store unique. That property in this example is "ssn" since a social security number is guaranteed to be unique. "ssn" must be present on every object that is stored in the `objectStore`.
We've also asked for an index named "name" that looks at the `name` property of the stored objects. As with `createObjectStore()`, `createIndex()` takes an optional `options` object that refines the type of index that you want to create. Adding objects that don't have a `name` property still succeeds, but the objects won't appear in the "name" index.
We can now retrieve the stored customer objects using their `ssn` from the object store directly, or using their name by using the index. To learn how this is done, see the section on [using an index](#using_an_index).
### Using a key generator
Setting up an `autoIncrement` flag when creating the object store would enable the key generator for that object store. By default this flag is not set.
With the key generator, the key would be generated automatically as you add the value to the object store. The current number of a key generator is always set to 1 when the object store for that key generator is first created. Basically the newly auto-generated key is increased by 1 based on the previous key. The current number for a key generator never decreases, other than as a result of database operations being reverted, for example, the database transaction is aborted. Therefore deleting a record or even clearing all records from an object store never affects the object store's key generator.
We can create another object store with the key generator as below:
```js
// Open the indexedDB.
const request = indexedDB.open(dbName, 3);
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create another object store called "names" with the autoIncrement flag set as true.
const objStore = db.createObjectStore("names", { autoIncrement: true });
// Because the "names" object store has the key generator, the key for the name value is generated automatically.
// The added records would be like:
// key : 1 => value : "Bill"
// key : 2 => value : "Donna"
customerData.forEach((customer) => {
objStore.add(customer.name);
});
};
```
For more details about the key generator, please see ["W3C Key Generators"](https://www.w3.org/TR/IndexedDB/#key-generator-concept).
## Adding, retrieving, and removing data
Before you can do anything with your new database, you need to start a transaction. Transactions come from the database object, and you have to specify which object stores you want the transaction to span. Once you are inside the transaction, you can access the object stores that hold your data and make your requests. Next, you need to decide if you're going to make changes to the database or if you just need to read from it. Transactions have three available modes: `readonly`, `readwrite`, and `versionchange`.
To change the "schema" or structure of the database—which involves creating or deleting object stores or indexes—the transaction must be in `versionchange` mode. This transaction is opened by calling the {{domxref("IDBFactory.open")}} method with a `version` specified.
To read the records of an existing object store, the transaction can either be in `readonly` or `readwrite` mode. To make changes to an existing object store, the transaction must be in `readwrite` mode. You open such transactions with {{domxref("IDBDatabase.transaction")}}. The method accepts two parameters: the `storeNames` (the scope, defined as an array of object stores that you want to access) and the `mode` (`readonly` or `readwrite`) for the transaction. The method returns a transaction object containing the {{domxref("IDBIndex.objectStore")}} method, which you can use to access your object store. By default, where no mode is specified, transactions open in `readonly` mode.
> **Note:** As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see [Firefox bug 1112702](https://bugzil.la/1112702).) Previously in a `readwrite` transaction, a {{domxref("IDBTransaction.complete_event", "complete")}} event was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the `complete` event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The `complete` event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare most consumers should not need to concern themselves further. If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the `complete` event by creating a transaction using the experimental (non-standard) `readwriteflush` mode (see {{domxref("IDBDatabase.transaction")}}).
You can speed up data access by using the right scope and mode in the transaction. Here are a couple of tips:
- When defining the scope, specify only the object stores you need. This way, you can run multiple transactions with non-overlapping scopes concurrently.
- Only specify a `readwrite` transaction mode when necessary. You can concurrently run multiple `readonly` transactions with overlapping scopes, but you can have only one `readwrite` transaction for an object store. To learn more, see the definition for [transaction](/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology#transaction) in the [IndexedDB key characteristics and basic terminology](/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology) article.
### Adding data to the database
If you've just created a database, then you probably want to write to it. Here's what that looks like:
```js
const transaction = db.transaction(["customers"], "readwrite");
// Note: Older experimental implementations use the deprecated constant IDBTransaction.READ_WRITE instead of "readwrite".
// In case you want to support such an implementation, you can write:
// const transaction = db.transaction(["customers"], IDBTransaction.READ_WRITE);
```
The `transaction()` function takes two arguments (though one is optional) and returns a transaction object. The first argument is a list of object stores that the transaction will span. You can pass an empty array if you want the transaction to span all object stores, but don't do it because the spec says an empty array should generate an InvalidAccessError. If you don't specify anything for the second argument, you get a read-only transaction. Since you want to write to it here you need to pass the `"readwrite"` flag.
Now that you have a transaction you need to understand its lifetime. Transactions are tied very closely to the event loop. If you make a transaction and return to the event loop without using it then the transaction will become inactive. The only way to keep the transaction active is to make a request on it. When the request is finished you'll get a DOM event and, assuming that the request succeeded, you'll have another opportunity to extend the transaction during that callback. If you return to the event loop without extending the transaction then it will become inactive, and so on. As long as there are pending requests the transaction remains active. Transaction lifetimes are really very simple but it might take a little time to get used to. A few more examples will help, too. If you start seeing `TRANSACTION_INACTIVE_ERR` error codes then you've messed something up.
Transactions can receive DOM events of three different types: `error`, `abort`, and `complete`. We've talked about the way that `error` events bubble, so a transaction receives error events from any requests that are generated from it. A more subtle point here is that the default behavior of an error is to abort the transaction in which it occurred. Unless you handle the error by first calling `stopPropagation()` on the error event then doing something else, the entire transaction is rolled back. This design forces you to think about and handle errors, but you can always add a catchall error handler to the database if fine-grained error handling is too cumbersome. If you don't handle an error event or if you call `abort()` on the transaction, then the transaction is rolled back and an `abort` event is fired on the transaction. Otherwise, after all pending requests have completed, you'll get a `complete` event. If you're doing lots of database operations, then tracking the transaction rather than individual requests can certainly aid your sanity.
Now that you have a transaction, you'll need to get the object store from it. Transactions only let you have an object store that you specified when creating the transaction. Then you can add all the data you need.
```js
// Do something when all the data is added to the database.
transaction.oncomplete = (event) => {
console.log("All done!");
};
transaction.onerror = (event) => {
// Don't forget to handle errors!
};
const objectStore = transaction.objectStore("customers");
customerData.forEach((customer) => {
const request = objectStore.add(customer);
request.onsuccess = (event) => {
// event.target.result === customer.ssn;
};
});
```
The `result` of a request generated from a call to `add()` is the key of the value that was added. So in this case, it should equal the `ssn` property of the object that was added, since the object store uses the `ssn` property for the key path. Note that the `add()` function requires that no object already be in the database with the same key. If you're trying to modify an existing entry, or you don't care if one exists already, you can use the `put()` function, as shown below in the [Updating an entry in the database](#updating_an_entry_in_the_database) section.
### Removing data from the database
Removing data is very similar:
```js
const request = db
.transaction(["customers"], "readwrite")
.objectStore("customers")
.delete("444-44-4444");
request.onsuccess = (event) => {
// It's gone!
};
```
### Getting data from the database
Now that the database has some info in it, you can retrieve it in several ways. First, the simple `get()`. You need to provide the key to retrieve the value, like so:
```js
const transaction = db.transaction(["customers"]);
const objectStore = transaction.objectStore("customers");
const request = objectStore.get("444-44-4444");
request.onerror = (event) => {
// Handle errors!
};
request.onsuccess = (event) => {
// Do something with the request.result!
console.log(`Name for SSN 444-44-4444 is ${request.result.name}`);
};
```
That's a lot of code for a "simple" retrieval. Here's how you can shorten it up a bit, assuming that you handle errors at the database level:
```js
db
.transaction("customers")
.objectStore("customers")
.get("444-44-4444").onsuccess = (event) => {
console.log(`Name for SSN 444-44-4444 is ${event.target.result.name}`);
};
```
See how this works? Since there's only one object store, you can avoid passing a list of object stores you need in your transaction and just pass the name as a string. Also, you're only reading from the database, so you don't need a `"readwrite"` transaction. Calling `transaction()` with no mode specified gives you a `"readonly"` transaction. Another subtlety here is that you don't actually save the request object to a variable. Since the DOM event has the request as its target you can use the event to get to the `result` property.
### Updating an entry in the database
Now we've retrieved some data, updating it and inserting it back into the IndexedDB is pretty simple. Let's update the previous example somewhat:
```js
const objectStore = db
.transaction(["customers"], "readwrite")
.objectStore("customers");
const request = objectStore.get("444-44-4444");
request.onerror = (event) => {
// Handle errors!
};
request.onsuccess = (event) => {
// Get the old value that we want to update
const data = event.target.result;
// update the value(s) in the object that you want to change
data.age = 42;
// Put this updated object back into the database.
const requestUpdate = objectStore.put(data);
requestUpdate.onerror = (event) => {
// Do something with the error
};
requestUpdate.onsuccess = (event) => {
// Success - the data is updated!
};
};
```
So here we're creating an `objectStore` and requesting a customer record out of it, identified by its ssn value (`444-44-4444`). We then put the result of that request in a variable (`data`), update the `age` property of this object, then create a second request (`requestUpdate`) to put the customer record back into the `objectStore`, overwriting the previous value.
> **Note:** In this case we've had to specify a `readwrite` transaction because we want to write to the database, not just read from it.
### Using a cursor
Using `get()` requires that you know which key you want to retrieve. If you want to step through all the values in your object store, then you can use a cursor. Here's what it looks like:
```js
const objectStore = db.transaction("customers").objectStore("customers");
objectStore.openCursor().onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
console.log(`Name for SSN ${cursor.key} is ${cursor.value.name}`);
cursor.continue();
} else {
console.log("No more entries!");
}
};
```
The `openCursor()` function takes several arguments. First, you can limit the range of items that are retrieved by using a key range object that we'll get to in a minute. Second, you can specify the direction that you want to iterate. In the above example, we're iterating over all objects in ascending order. The success callback for cursors is a little special. The cursor object itself is the `result` of the request (above we're using the shorthand, so it's `event.target.result`). Then the actual key and value can be found on the `key` and `value` properties of the cursor object. If you want to keep going, then you have to call `continue()` on the cursor. When you've reached the end of the data (or if there were no entries that matched your `openCursor()` request) you still get a success callback, but the `result` property is `undefined`.
One common pattern with cursors is to retrieve all objects in an object store and add them to an array, like this:
```js
const customers = [];
objectStore.openCursor().onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
customers.push(cursor.value);
cursor.continue();
} else {
console.log(`Got all customers: ${customers}`);
}
};
```
> **Note:** Alternatively, you can use `getAll()` to handle this case (and `getAllKeys()`). The following code does precisely the same thing as above:
>
> ```js
> objectStore.getAll().onsuccess = (event) => {
> console.log(`Got all customers: ${event.target.result}`);
> };
> ```
>
> There is a performance cost associated with looking at the `value` property of a cursor, because the object is created lazily. When you use `getAll()` for example, the browser must create all the objects at once. If you're just interested in looking at each of the keys, for instance, it is much more efficient to use a cursor than to use `getAll()`. If you're trying to get an array of all the objects in an object store, though, use `getAll()`.
### Using an index
Storing customer data using the SSN as a key is logical since the SSN uniquely identifies an individual. (Whether this is a good idea for privacy is a different question, and outside the scope of this article.) If you need to look up a customer by name, however, you'll need to iterate over every SSN in the database until you find the right one. Searching in this fashion would be very slow, so instead you can use an index.
```js
// First, make sure you created index in request.onupgradeneeded:
// objectStore.createIndex("name", "name");
// Otherwise you will get DOMException.
const index = objectStore.index("name");
index.get("Donna").onsuccess = (event) => {
console.log(`Donna's SSN is ${event.target.result.ssn}`);
};
```
The "name" index isn't unique, so there could be more than one entry with the `name` set to `"Donna"`. In that case you always get the one with the lowest key value.
If you need to access all the entries with a given `name` you can use a cursor. You can open two different types of cursors on indexes. A normal cursor maps the index property to the object in the object store. A key cursor maps the index property to the key used to store the object in the object store. The differences are illustrated here:
```js
// Using a normal cursor to grab whole customer record objects
index.openCursor().onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
// cursor.key is a name, like "Bill", and cursor.value is the whole object.
console.log(
`Name: ${cursor.key}, SSN: ${cursor.value.ssn}, email: ${cursor.value.email}`,
);
cursor.continue();
}
};
// Using a key cursor to grab customer record object keys
index.openKeyCursor().onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
// cursor.key is a name, like "Bill", and cursor.value is the SSN.
// No way to directly get the rest of the stored object.
console.log(`Name: ${cursor.key}, SSN: ${cursor.primaryKey}`);
cursor.continue();
}
};
```
### Specifying the range and direction of cursors
If you would like to limit the range of values you see in a cursor, you can use an `IDBKeyRange` object and pass it as the first argument to `openCursor()` or `openKeyCursor()`. You can make a key range that only allows a single key, or one that has a lower or upper bound, or one that has both a lower and upper bound. The bound may be "closed" (i.e., the key range includes the given value(s)) or "open" (i.e., the key range does not include the given value(s)). Here's how it works:
```js
// Only match "Donna"
const singleKeyRange = IDBKeyRange.only("Donna");
// Match anything past "Bill", including "Bill"
const lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");
// Match anything past "Bill", but don't include "Bill"
const lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);
// Match anything up to, but not including, "Donna"
const upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);
// Match anything between "Bill" and "Donna", but not including "Donna"
const boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);
// To use one of the key ranges, pass it in as the first argument of openCursor()/openKeyCursor()
index.openCursor(boundKeyRange).onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
// Do something with the matches.
cursor.continue();
}
};
```
Sometimes you may want to iterate in descending order rather than in ascending order (the default direction for all cursors). Switching direction is accomplished by passing `prev` to the `openCursor()` function as the second argument:
```js
objectStore.openCursor(boundKeyRange, "prev").onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
// Do something with the entries.
cursor.continue();
}
};
```
If you just want to specify a change of direction but not constrain the results shown, you can just pass in null as the first argument:
```js
objectStore.openCursor(null, "prev").onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
// Do something with the entries.
cursor.continue();
}
};
```
Since the "name" index isn't unique, there might be multiple entries where `name` is the same. Note that such a situation cannot occur with object stores since the key must always be unique. If you wish to filter out duplicates during cursor iteration over indexes, you can pass `nextunique` (or `prevunique` if you're going backwards) as the direction parameter. When `nextunique` or `prevunique` is used, the entry with the lowest key is always the one returned.
```js
index.openKeyCursor(null, "nextunique").onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
// Do something with the entries.
cursor.continue();
}
};
```
Please see "[IDBCursor Constants](/en-US/docs/Web/API/IDBCursor#constants)" for the valid direction arguments.
## Version changes while a web app is open in another tab
When your web app changes in such a way that a version change is required for your database, you need to consider what happens if the user has the old version of your app open in one tab and then loads the new version of your app in another. When you call `open()` with a greater version than the actual version of the database, all other open databases must explicitly acknowledge the request before you can start making changes to the database (an `onblocked` event is fired until they are closed or reloaded). Here's how it works:
```js
const openReq = mozIndexedDB.open("MyTestDatabase", 2);
openReq.onblocked = (event) => {
// If some other tab is loaded with the database, then it needs to be closed
// before we can proceed.
console.log("Please close all other tabs with this site open!");
};
openReq.onupgradeneeded = (event) => {
// All other databases have been closed. Set everything up.
db.createObjectStore(/* … */);
useDatabase(db);
};
openReq.onsuccess = (event) => {
const db = event.target.result;
useDatabase(db);
return;
};
function useDatabase(db) {
// Make sure to add a handler to be notified if another page requests a version
// change. We must close the database. This allows the other page to upgrade the database.
// If you don't do this then the upgrade won't happen until the user closes the tab.
db.onversionchange = (event) => {
db.close();
console.log(
"A new version of this page is ready. Please reload or close this tab!",
);
};
// Do stuff with the database.
}
```
You should also listen for `VersionError` errors to handle the situation where already opened apps may initiate code leading to a new attempt to open the database, but using an outdated version.
## Security
IndexedDB uses the same-origin principle, which means that it ties the store to the origin of the site that creates it (typically, this is the site domain or subdomain), so it cannot be accessed by any other origin.
Third party window content (e.g. {{htmlelement("iframe")}} content) cannot access IndexedDB if the browser is set to [never accept third party cookies](https://support.mozilla.org/en-US/kb/third-party-cookies-firefox-tracking-protection) (see [Firefox bug 1147821](https://bugzil.la/1147821)).
## Warning about browser shutdown
When the browser shuts down (because the user chose the Quit or Exit option), the disk containing the database is removed unexpectedly, or permissions are lost to the database store, the following things happen:
1. Each transaction on every affected database (or all open databases, in the case of browser shutdown) is aborted with an `AbortError`. The effect is the same as if {{domxref("IDBTransaction.abort()")}} is called on each transaction.
2. Once all of the transactions have completed, the database connection is closed.
3. Finally, the {{domxref("IDBDatabase")}} object representing the database connection receives a {{domxref("IDBDatabase/close_event", "close")}} event. You can use the {{domxref("IDBDatabase.close_event", "IDBDatabase.onclose")}} event handler to listen for these events, so that you know when a database is unexpectedly closed.
The behavior described above is new, and is only available as of the following browser releases: Firefox 50, Google Chrome 31 (approximately).
Prior to these browser versions, the transactions are aborted silently, and no {{domxref("IDBDatabase/close_event", "close")}} event is fired, so there is no way to detect an unexpected database closure.
Since the user can exit the browser at any time, this means that you cannot rely upon any particular transaction to complete, and on older browsers, you don't even get told when they don't complete. There are several implications of this behavior.
First, you should take care to always leave your database in a consistent state at the end of every transaction. For example, suppose that you are using IndexedDB to store a list of items that you allow the user to edit. You save the list after the edit by clearing the object store and then writing out the new list. If you clear the object store in one transaction and write the new list in another transaction, there is a danger that the browser will close after the clear but before the write, leaving you with an empty database. To avoid this, you should combine the clear and the write into a single transaction.
Second, you should never tie database transactions to unload events. If the unload event is triggered by the browser closing, any transactions created in the unload event handler will never complete. An intuitive approach to maintaining some information across browser sessions is to read it from the database when the browser (or a particular page) is opened, update it as the user interacts with the browser, and then save it to the database when the browser (or page) closes. However, this will not work. The database transactions will be created in the unload event handler, but because they are asynchronous they will be aborted before they can execute.
In fact, there is no way to guarantee that IndexedDB transactions will complete, even with normal browser shutdown. See [Firefox bug 870645](https://bugzil.la/870645). As a workaround for this normal shutdown notification, you might track your transactions and add a `beforeunload` event to warn the user if any transactions have not yet completed at the time of unloading.
At least with the addition of the abort notifications and {{domxref("IDBDatabase.close_event", "IDBDatabase.onclose")}}, you can know when this has happened.
## Full IndexedDB example
We have a complete example using the IndexedDB API. The example uses IndexedDB to store and retrieve publications.
- [Try the example](https://mdn.github.io/dom-examples/indexeddb-api/index.html)
- [See the source code](https://github.com/mdn/dom-examples/tree/main/indexeddb-api)
## See also
Further reading for you to find out more information if desired.
### Reference
- [IndexedDB API Reference](/en-US/docs/Web/API/IndexedDB_API)
- [Indexed Database API Specification](https://www.w3.org/TR/IndexedDB/)
- IndexedDB [interface files](https://searchfox.org/mozilla-central/search?q=dom%2FindexedDB%2F.*%5C.idl&path=&case=false®exp=true) in the Firefox source code
### Tutorials and guides
- [Databinding UI Elements with IndexedDB (2012)](https://web.dev/articles/indexeddb-uidatabinding)
- [IndexedDB — The Store in Your Browser](<https://docs.microsoft.com/previous-versions/msdn10/gg679063(v=msdn.10)>)
### Libraries
- [localForage](https://localforage.github.io/localForage/): A Polyfill providing a simple name:value syntax for client-side data storage, which uses IndexedDB in the background, but falls back to Web SQL (deprecated) and then localStorage in browsers that don't support IndexedDB.
- [Dexie.js](https://dexie.org/): A wrapper for IndexedDB that allows much faster code development via nice, simple syntax.
- [JsStore](https://jsstore.net/): A simple and advanced IndexedDB wrapper having SQL like syntax.
- [MiniMongo](https://github.com/mWater/minimongo): A client-side in-memory MongoDB backed by localstorage with server sync over http. MiniMongo is used by MeteorJS.
- [PouchDB](https://pouchdb.com): A client-side implementation of CouchDB in the browser using IndexedDB
- [IDB](https://github.com/jakearchibald/idb): A tiny library that mostly mirrors the IndexedDB API but with small usability improvements.
- [idb-keyval](https://www.npmjs.com/package/idb-keyval): A super-simple-small (\~600B) promise-based keyval store implemented with IndexedDB
- [$mol_db](https://github.com/hyoo-ru/mam_mol/tree/master/db): Tiny (\~1.3kB) TypeScript facade with promise-based API and automatic migrations.
- [RxDB](https://rxdb.info/): A NoSQL client side database that can be used on top of IndexedDB. Supports indexes, compression and replication. Also adds cross tab functionality and observability to IndexedDB.
| 0 |
data/mdn-content/files/en-us/web/api/indexeddb_api | data/mdn-content/files/en-us/web/api/indexeddb_api/basic_terminology/index.md | ---
title: IndexedDB key characteristics and basic terminology
slug: Web/API/IndexedDB_API/Basic_Terminology
page-type: guide
---
{{DefaultAPISidebar("IndexedDB")}}
This article describes the key characteristics of IndexedDB, and introduces some essential terminology relevant to understanding the IndexedDB API.
You'll also find the following articles useful:
- For a detailed tutorial on how to use the API, see [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB).
- For the reference documentation on the IndexedDB API, refer back to the main [IndexedDB API](/en-US/docs/Web/API/IndexedDB_API) article and its subpages, which document the types of objects used by IndexedDB.
- For more information on how the browser handles storing your data in the background, read [Browser storage quotas and eviction criteria](/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria).
## Key characteristics
IndexedDB is a way for you to persistently store data inside a user's browser. Because it lets you create web applications with rich query abilities regardless of network availability, these applications can work both online and offline. IndexedDB is useful for applications that store a large amount of data (for example, a catalog of DVDs in a lending library) and applications that don't need persistent internet connectivity to work (for example, mail clients, to-do lists, and notepads).
IndexedDB lets you store and retrieve objects that are indexed with a "key." All changes that you make to the database happen within transactions. Like most web storage solutions, IndexedDB follows a [same-origin policy](https://www.w3.org/Security/wiki/Same_Origin_Policy). So while you can access stored data within a domain, you cannot access data across different domains.
If you have assumptions from working with other types of databases, you might get thrown off when working with IndexedDB. So the following key characteristics of IndexedDB are important to keep in mind:
- **IndexedDB databases store key-value pairs.** The values can be complex structured objects, and keys can be properties of those objects. You can create indexes that use any property of the objects for quick searching, as well as sorted enumeration. Keys can be binary objects.
- **IndexedDB is built on a transactional database model**. Everything you do in IndexedDB always happens in the context of a [transaction](#transaction). The IndexedDB API provides lots of objects that represent indexes, tables, cursors, and so on, but each of these is tied to a particular transaction. Thus, you cannot execute commands or open cursors outside of a transaction. Transactions have a well-defined lifetime, so attempting to use a transaction after it has completed throws exceptions. Also, transactions auto-commit and cannot be committed manually.
This transaction model is really useful when you consider what might happen if a user opened two instances of your web app in two different tabs simultaneously. Without transactional operations, the two instances could interfere with each other's modifications. If you are not familiar with transactions in a database, read the [Wikipedia article on transactions](https://en.wikipedia.org/wiki/Database_transaction). Also see [transaction](#transaction) under the Definitions section.
- **The IndexedDB API is mostly asynchronous.** The API doesn't give you data by returning values; instead, you have to pass a callback function. You don't "store" a value into the database, or "retrieve" a value out of the database through synchronous means. Instead, you "request" that a database operation happens. You get notified by a DOM event when the operation finishes, and the type of event you get lets you know if the operation succeeded or failed.
- **IndexedDB uses a lot of requests.** Requests are objects that receive the success or failure DOM events that were mentioned previously. They have `onsuccess` and `onerror` properties, and you can call `addEventListener()` and `removeEventListener()` on them. They also have `readyState`, `result`, and `errorCode` properties that tell you the status of the request. The `result` property is particularly magical, as it can be many different things, depending on how the request was generated (for example, an `IDBCursor` instance, or the key for a value that you just inserted into the database).
- **IndexedDB uses DOM events to notify you when results are available.** DOM events always have a `type` property (in IndexedDB, it is most commonly set to `"success"` or `"error"`). DOM events also have a `target` property that indicates where the event is headed. In most cases, the `target` of an event is the `IDBRequest` object that was generated as a result of doing some database operation. Success events don't bubble up and they can't be canceled. Error events, on the other hand, do bubble, and can be cancelled. This is quite important, as error events abort whatever transactions they're running in, unless they are cancelled.
- **IndexedDB is object-oriented.** IndexedDB is not a relational database with tables representing collections of rows and columns. This important and fundamental difference affects the way you design and build your applications.
In a traditional relational data store, you would have a table that stores a collection of rows of data and columns of named types of data. IndexedDB, on the other hand, requires you to create an object store for a type of data and persist JavaScript objects to that store. Each object store can have a collection of indexes that makes it efficient to query and iterate across. If you are not familiar with object-oriented database management systems, read the [Wikipedia article on object database](https://en.wikipedia.org/wiki/Object_database).
- **IndexedDB does not use Structured Query Language (SQL).** It uses queries on an index that produces a cursor, which you use to iterate across the result set. If you are not familiar with NoSQL systems, read the [Wikipedia article on NoSQL](https://en.wikipedia.org/wiki/NoSQL).
- **IndexedDB adheres to a same-origin policy**. An origin is the domain, application layer protocol, and port of a URL of the document where the script is being executed. Each origin has its own associated set of databases. Every database has a name that identifies it within an origin.
The security boundary imposed on IndexedDB prevents applications from accessing data with a different origin. For example, while an app or a page in `http://www.example.com/app/` can retrieve data from `http://www.example.com/dir/`, because they have the same origin, it cannot retrieve data from `http://www.example.com:8080/dir/` (different port) or `https://www.example.com/dir/` (different protocol), because they have different origins.
> **Note:** Third party window content (e.g. {{htmlelement("iframe")}} content) can access the IndexedDB store for the origin it is embedded into, unless the browser is set to [never accept third party cookies](https://support.mozilla.org/en-US/kb/third-party-cookies-firefox-tracking-protection) (see [Firefox bug 1147821](https://bugzil.la/1147821).)
### Limitations
IndexedDB is designed to cover most cases that need client-side storage. However, it is not designed for a few cases like the following:
- Internationalized sorting. Not all languages sort strings in the same way, so internationalized sorting is not supported. While the database can't store data in a specific internationalized order, you can sort the data that you've read out of the database yourself. Note, however, that [locale-aware sorting](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB#locale-aware_sorting) has been allowed with an experimental flag enabled (currently for Firefox only) since Firefox 43.
- Synchronizing. The API is not designed to take care of synchronizing with a server-side database. You have to write code that synchronizes a client-side indexedDB database with a server-side database.
- Full text searching. The API does not have an equivalent of the `LIKE` operator in SQL.
In addition, be aware that browsers can wipe out the database, such as in the following conditions:
- The user requests a wipe out. Many browsers have settings that let users wipe all data stored for a given website, including cookies, bookmarks, stored passwords, and IndexedDB data.
- The browser is in private browsing mode. Some browsers, have "private browsing" (Firefox) or "incognito" (Chrome) modes. At the end of the session, the browser wipes out the database.
- The disk or quota limit has been reached.
- The data is corrupt.
- An incompatible change is made to the feature.
The exact circumstances and browser capabilities change over time, but the general philosophy of the browser vendors is to make the best effort to keep the data when possible.
## Core terminology
This section defines and explains core terminology relevant to understanding the IndexedDB API.
### Database
#### database
A repository of information, typically comprising one or more [_object stores_](#object_store). Each database must have the following:
- Name. This identifies the database within a specific origin and stays constant throughout its lifetime. The name can be any string value (including an empty string).
- Current [_version_](#version). When a database is first created, its version is the integer 1 if not specified otherwise. Each database can have only one version at any given time.
#### database connection
An operation created by opening a _[database](#database)_. A given database can have multiple connections at the same time.
#### durable
In Firefox, IndexedDB used to be **durable**, meaning that in a readwrite transaction a {{domxref("IDBTransaction.complete_event", "complete")}} event was fired only when all data was guaranteed to have been flushed to disk.
As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see [Firefox bug 1112702](https://bugzil.la/1112702)), which is the same behavior as other IndexedDB-supporting browsers. In this case the {{domxref("IDBTransaction.complete_event", "complete")}} event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.
> **Note:** In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the `complete` event by creating a transaction using the experimental (non-standard) `readwriteflush` mode (see {{domxref("IDBDatabase.transaction")}}.) This is currently experimental, and can only be used if the `dom.indexedDB.experimental` pref is set to `true` in `about:config`.
#### index
An index is a specialized object store for looking up records in another object store, called the _referenced object store_. The index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated, or deleted. Each record in an index can point to only one record in its referenced object store, but several indexes can reference the same object store. When the object store changes, all indexes that refer to the object store are automatically updated.
Alternatively, you can also look up records in an object store using the [key](#key).
To learn more on using indexes, see [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB#using_an_index). For the reference documentation on index, see [IDBKeyRange](/en-US/docs/Web/API/IDBKeyRange).
#### object store
The mechanism by which data is stored in the database. The object store persistently holds records, which are key-value pairs. Records within an object store are sorted according to the _[keys](#key)_ in an ascending order.
Every object store must have a name that is unique within its database. The object store can optionally have a _[key generator](#key_generator)_ and a _[key path](#key_path)_. If the object store has a key path, it is using _[in-line keys](#in-line_key)_; otherwise, it is using _[out-of-line keys](#out-of-line_key)_.
For the reference documentation on object store, see {{domxref("IDBObjectStore")}}.
#### request
The operation by which reading and writing on a database is done. Every request represents one read or write operation.
#### transaction
An atomic set of data-access and data-modification operations on a particular database. It is how you interact with the data in a database. In fact, any reading or changing of data in the database must happen in a transaction.
A database connection can have several active transactions associated with it at a time, so long as the writing transactions do not have overlapping [_scopes_](#scope). The scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. So, for example, if a database connection already has a writing transaction with a scope that just covers the `flyingMonkey` object store, you can start a second transaction with a scope of the `unicornCentaur` and `unicornPegasus` object stores. As for reading transactions, you can have several of them — even overlapping ones.
Transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. You can abort the transaction, which rolls back the changes made to the database in the transaction. And you don't even have to wait for the transaction to start or be active to abort it.
The three modes of transactions are: `readwrite`, `readonly`, and `versionchange`. The only way to create and delete object stores and indexes is by using a [`versionchange`](/en-US/docs/Web/API/IDBDatabase/versionchange_event) transaction. To learn more about transaction types, see the reference article for [IndexedDB](/en-US/docs/Web/API/IndexedDB_API).
Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how they relate to versioning, see {{domxref("IDBTransaction")}}, which also has reference documentation.
#### version
When a database is first created, its version is the integer 1. Each database has one version at a time; a database can't exist in multiple versions at once. The only way to change the version is by opening it with a greater version than the current one.
### Key and value
#### in-line key
A key that is stored as part of the stored value. It is found using a _key path_. An in-line key can be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
#### key
A data value by which stored values are organized and retrieved in the object store. The object store can derive the key from one of three sources: a _[key generator](#key_generator)_, a _[key path](#key_path)_, or an explicitly specified value. The key must be of a data type that has a number that is greater than the one before it. Each record in an object store must have a key that is unique within the same store, so you cannot have multiple records with the same key in a given object store.
A key can be one of the following types: [string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), [date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), float, a binary blob, and [array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). For arrays, the key can range from an empty value to infinity. And you can include an array within an array.
Alternatively, you can also look up records in an object store using the _[index](#index)._
#### key generator
A mechanism for producing new keys in an ordered sequence. If an object store does not have a key generator, then the application must provide keys for records being stored. Generators are not shared between stores. This is more a browser implementation detail, because in web development, you don't really create or access key generators.
#### key path
Defines where the browser should extract the key from in the object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods or an array containing any of those. It cannot include spaces.
#### out-of-line key
A key that is stored separately from the value being stored.
#### value
Each record has a value, which could include anything that can be expressed in JavaScript, including [boolean](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean), [number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), [string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), [date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), [object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), [array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), [regexp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp), [undefined](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined), and null.
When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value.
[Blobs](/en-US/docs/Web/API/Blob) and files can be stored, cf. [specification](https://w3c.github.io/IndexedDB/).
### Range and scope
#### cursor
A mechanism for iterating over multiple records with a _key range_. The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. For the reference documentation on cursors, see {{domxref("IDBCursor")}}.
#### key range
A continuous interval over some data type used for keys. Records can be retrieved from object stores and indexes using keys or a range of keys. You can limit or filter the range using lower and upper bounds. For example, you can iterate over all values of a key between x and y.
For the reference documentation on key range, see {{domxref("IDBKeyRange")}}.
#### scope
The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the scopes of writing transactions cannot overlap. You can still start several transactions with the same scope at the same time, but they just queue up and execute one after another.
## Next steps
With an understanding of IndexedDB's key characteristics and core terminology under our belts, we can get to more concrete stuff. For a tutorial on how to use the API, see [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB).
## See also
- [Indexed Database API Specification](https://www.w3.org/TR/IndexedDB/)
- [IndexedDB API Reference](/en-US/docs/Web/API/IndexedDB_API)
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- [IndexedDB — The Store in Your Browser](<https://docs.microsoft.com/previous-versions/msdn10/gg679063(v=msdn.10)>)
| 0 |
data/mdn-content/files/en-us/web/api/indexeddb_api | data/mdn-content/files/en-us/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.md | ---
title: Checking when a deadline is due
slug: Web/API/IndexedDB_API/Checking_when_a_deadline_is_due
page-type: guide
---
{{DefaultAPISidebar("IndexedDB")}}
In this article we look at a complex example involving checking the current time and date against a deadline stored via IndexedDB. The main complication here is checking the stored deadline info (month, hour, day, etc.) against the current time and date taken from a [Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object.

The main example application we will be referring to in this article is **To-do list notifications**, a simple to-do list application that stores task titles and deadline times and dates via [IndexedDB](/en-US/docs/Web/API/IndexedDB_API), and then provides users with notifications when deadline dates are reached, via the [Notification](/en-US/docs/Web/API/Notification), and [Vibration](/en-US/docs/Web/API/Vibration_API) APIs. You can [download the To-do list notifications app from GitHub](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) and play around with the source code, or [view the app running live](https://mdn.github.io/dom-examples/to-do-notifications/).
## The basic problem
In the to-do app, we wanted to first record time and date information in a format that is both machine readable and human understandable when displayed, and then check whether each time and date is occurring at the current moment. Basically, we want to check what the time and date is right now, and then check each stored event to see if any of their deadlines match the current time and date. If they do, we want to let the user know with some kind of notification.
This would be easy if we were just comparing two {{jsxref("Global_Objects/Date", "Date")}} objects, but of course humans don't want to enter deadline information in the same format JavaScript understands. Human-readable dates are quite different, with a number of different representations.
### Recording the date information
To provide a reasonable user experience on mobile devices, and to cut down on ambiguities, I decided to create an HTML form with:

- A text input for entering a title for your to-do list. This is the least avoidable bit of user typing.
- Number inputs for the hour and minute parts of the deadline. On browsers that support `type="number"`, you get a nice little up and down arrow number picker. On mobile platforms you tend to get a numeric keypad for entering data, which is helpful. On others you just get a standard text input, which is okay.
- {{HTMLElement("select")}} elements for inputting the day, month and year of the deadline. Because these values are the most ambiguous for users to enter (7, sunday, sun? 04, 4, April, Apr? 2013, '13, 13?), I decided the best solution was to give them a choice to pick from, which also saves on annoying typing for mobile users. The days are recorded as numerical days of the month, the months are recorded as full month names, and the years are recorded as full four digit year numbers.
When the form's submit button is pressed, we run the `addData()` function, which starts like this:
```js
function addData(e) {
e.preventDefault();
if (!title.value || !hours.value || !minutes.value || !day.value || !month.value || !year.value) {
note.innerHTML += '<li>Data not submitted — form incomplete.</li>';
return;
}
```
In this segment, we check to see if the form fields have all been filled in. If not, we drop a message into our developer notifications pane (see the bottom left of the app UI) to tell the user what is going on, and exit out of the function. This step is mainly for browsers that don't support HTML form validation (I have used the `required` attribute in my HTML to force validation, in those that do.)
```js
else {
const newItem = [
{
taskTitle: title.value,
hours : hours.value,
minutes : minutes.value,
day : day.value,
month : month.value,
year : year.value,
notified : "no"
}
];
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.innerHTML += '<li>Transaction opened for task addition.</li>';
};
transaction.onerror = (event) => {
note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// add our newItem object to the object store
const request = objectStore.add(newItem[0]);
```
In this section we create an object called `newItem` that stores the data in the format required to insert it into the database. The next few lines open the database transaction and provide messages to notify the user if this was successful or failed. Then an `objectStore` is created into which the new item is added. The `notified` property of the data object indicates that the to-do list item's deadline has not yet come up and been notified - more on this later!
> **Note:** The `db` variable stores a reference to the IndexedDB database instance; we can then use various properties of this variable to manipulate the data.
```js
request.onsuccess = (event) => {
note.innerHTML += '<li>New item added to database.</li>';
title.value = '';
hours.value = null;
minutes.value = null;
day.value = '01';
month.value = 'January';
year.value = 2020;
};
}
```
This next section creates a log message to say the new item addition is successful, and resets the form so it's ready for the next task to be entered.
```js
// update the display of data to show the newly added item, by running displayData() again.
displayData();
};
```
Last of all, we run the `displayData()` function, which updates the display of data in the app to show the new task that was just entered.
### Checking whether a deadline has been reached
At this point our data is in the database; now we want to check whether any of the deadlines have been reached. This is done by our `checkDeadlines()` function:
```js
function checkDeadlines() {
const now = new Date();
```
First we grab the current date and time by creating a blank `Date` object. Easy huh? It's about to get a bit more complex.
```js
const minuteCheck = now.getMinutes();
const hourCheck = now.getHours();
const dayCheck = now.getDate();
const monthCheck = now.getMonth();
const yearCheck = now.getFullYear();
```
The `Date` object has a number of methods to extract various parts of the date and time inside it. Here we fetch the current minutes (gives an easy numerical value), hours (gives an easy numerical value), day of the month (`getDate()` is needed for this, as `getDay()` returns the day of the week, 1-7), month (returns a number from 0-11, see below), and year (`getFullYear()` is needed; `getYear()` is deprecated, and returns a weird value that is not much use to anyone!)
```js
const objectStore = db.transaction(['toDoList'], "readwrite").objectStore('toDoList');
objectStore.openCursor().onsuccess = (event) => {
const cursor = event.target.result;
let monthNumber;
if (cursor) {
```
Next we create another IndexedDB `objectStore`, and use the `openCursor()` method to open a cursor, which is basically a way in IndexedDB to iterate through all the items in the store. We then loop through all the items in the cursor for as long as there is a valid item left in the cursor.
```js
switch (cursor.value.month) {
case "January":
monthNumber = 0;
break;
case "February":
monthNumber = 1;
break;
// other lines removed from listing for brevity
case "December":
monthNumber = 11;
break;
default:
alert("Incorrect month entered in database.");
}
```
The first thing we do is convert the month names we have stored in the database into a month number that JavaScript will understand. As we saw before, the JavaScript `Date` object creates month values as a number between 0 and 11.
```js
if (
Number(cursor.value.hours) === hourCheck &&
Number(cursor.value.minutes) === minuteCheck &&
Number(cursor.value.day) === dayCheck &&
monthNumber === monthCheck &&
cursor.value.year === yearCheck &&
notified === "no"
) {
// If the numbers all do match, run the createNotification()
// function to create a system notification
createNotification(cursor.value.taskTitle);
}
```
With the current time and date segments that we want to check against the IndexedDB stored values all assembled, it is time to perform the checks. We want all the values to match before we show the user some kind of notification to tell them their deadline is up.
The `+` operator in this case converts numbers with leading zeros into their non leading zero equivalents, e.g. 09 -> 9. This is needed because JavaScript `Date` number values never have leading zeros, but our data might.
The `notified === "no"` check is designed to make sure you will only get one notification per to-do item. When a notification is fired for each item object, its `notification` property is set to `"yes"` so this check will not pass on the next iteration, via the following code inside the `createNotification()` function (read [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) for an explanation):
```js
// now we need to update the value of notified to "yes" in this particular data object, so the
// notification won't be set off on it again
// first open up a transaction as usual
const objectStore = db.transaction(['toDoList'], "readwrite").objectStore('toDoList');
// get the to-do list object that has this title as it's title
const request = objectStore.get(title);
request.onsuccess = () => {
// grab the data object returned as the result
const data = request.result;
// update the notified value in the object to "yes"
data.notified = "yes";
// create another request that inserts the item back into the database
const requestUpdate = objectStore.put(data);
// when this new request succeeds, run the displayData() function again to update the display
requestUpdate.onsuccess = () => {
displayData();
}
```
If the checks all match, we then run the `createNotification()` function to provide a notification to the user.
```js
cursor.continue();
}
}
}
```
The last line of the function moves the cursor on, which causes the above deadline checking mechanism to be run for the next task stored in the IndexedDB.
### Keep on checking!
Of course, it is no use to just run the above deadline checking function once! We want to keep constantly checking all the deadlines to see if any of them are being reached. To do this, we are using `setInterval()` to run `checkDeadlines()` once per second:
```js
setInterval(checkDeadlines, 1000);
```
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/iirfilternode/index.md | ---
title: IIRFilterNode
slug: Web/API/IIRFilterNode
page-type: web-api-interface
browser-compat: api.IIRFilterNode
---
{{APIRef("Web Audio API")}}
The **`IIRFilterNode`** interface of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) is a {{domxref("AudioNode")}} processor which implements a general **[infinite impulse response](https://en.wikipedia.org/wiki/Infinite_impulse_response)** (IIR) filter; this type of filter can be used to implement tone control devices and graphic equalizers as well. It lets the parameters of the filter response be specified, so that it can be tuned as needed.
{{InheritanceDiagram}}
<table class="properties">
<tbody>
<tr>
<th scope="row">Number of inputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Number of outputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Channel count mode</th>
<td><code>"max"</code></td>
</tr>
<tr>
<th scope="row">Channel count</th>
<td>Same as on the input</td>
</tr>
<tr>
<th scope="row">Channel interpretation</th>
<td><code>"speakers"</code></td>
</tr>
</tbody>
</table>
Typically, it's best to use the {{domxref("BiquadFilterNode")}} interface to implement higher-order filters. There are several reasons why:
- Biquad filters are typically less sensitive to numeric quirks.
- The filter parameters of biquad filters can be automated.
- All even-ordered IIR filters can be created using {{domxref("BiquadFilterNode")}}.
However, if you need to create an odd-ordered IIR filter, you'll need to use `IIRFilterNode`. You may also find this interface useful if you don't need automation, or for other reasons.
> **Note:** Once the node has been created, you can't change its coefficients.
`IIRFilterNode`s have a tail-time reference; they continue to output non-silent audio with zero input. As an IIR filter, the non-zero input continues forever, but this can be limited after some finite time in practice, when the output has approached zero closely enough. The actual time that takes depends on the filter coefficients provided.
## Constructor
- {{domxref("IIRFilterNode.IIRFilterNode", "IIRFilterNode()")}}
- : Creates a new instance of an IIRFilterNode object.
## Instance properties
_This interface has no properties of its own; however, it inherits properties from its parent, {{domxref("AudioNode")}}_.
## Instance methods
_Inherits methods from its parent, {{domxref("AudioNode")}}. It also has the following additional methods:_
- {{domxref("IIRFilterNode.getFrequencyResponse", "getFrequencyResponse()")}}
- : Uses the filter's current parameter settings to calculate the response for frequencies specified in the provided array of frequencies.
## Examples
You can find a simple IIR filter demo live [on Codepen](https://codepen.io/Rumyra/pen/oPxvYB/). Also see the [source code on GitHub](https://github.com/mdn/webaudio-examples/tree/main/iirfilter-node). It includes some different coefficient values for different lowpass frequencies — you can change the value of the `filterNumber` constant to a value between 0 and 3 to check out the different available effects.
Also see our [Using IIR filters](/en-US/docs/Web/API/Web_Audio_API/Using_IIR_filters) guide for a full explanation.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- {{domxref("AudioNode")}}
- {{domxref("BiquadFilterNode")}}
| 0 |
data/mdn-content/files/en-us/web/api/iirfilternode | data/mdn-content/files/en-us/web/api/iirfilternode/getfrequencyresponse/index.md | ---
title: "IIRFilterNode: getFrequencyResponse() method"
short-title: getFrequencyResponse()
slug: Web/API/IIRFilterNode/getFrequencyResponse
page-type: web-api-instance-method
browser-compat: api.IIRFilterNode.getFrequencyResponse
---
{{ APIRef("Web Audio API") }}
The `getFrequencyResponse()` method of the {{ domxref("IIRFilterNode") }}
interface takes the current filtering algorithm's settings and calculates the
frequency response for frequencies specified in a specified array of frequencies.
The two output arrays, `magResponseOutput` and
`phaseResponseOutput`, must be created before calling this method; they
must be the same size as the array of input frequency values
(`frequencyArray`).
## Syntax
```js-nolint
getFrequencyResponse(frequencyArray, magResponseOutput, phaseResponseOutput)
```
### Parameters
- `frequencyArray`
- : A {{jsxref("Float32Array")}} containing an array of frequencies, specified in Hertz,
which you want to filter.
- `magResponseOutput`
- : A {{jsxref("Float32Array")}} to receive the computed magnitudes of the frequency
response for each frequency value in the `frequencyArray`.
- `phaseResponseOutput`
- : A {{jsxref("Float32Array")}} to receive the computed phase response values in
radians for each frequency value in the input `frequencyArray`.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if the three arrays provided are not all of the same length.
## Examples
In the following example we are using an IIR filter on a media stream (for a complete
full demo, see our [stream-source-buffer demo](https://mdn.github.io/webaudio-examples/stream-source-buffer/) live,
or [read its source](https://github.com/mdn/webaudio-examples/blob/main/stream-source-buffer/index.html)). As part of this demo, we get the frequency responses for this IIR
filter, for five sample frequencies. We first create the {{jsxref("Float32Array")}}
objects we need, one containing the input frequencies, and two to receive the output
magnitude and phase values:
```js
const myFrequencyArray = new Float32Array(5);
myFrequencyArray[0] = 1000;
myFrequencyArray[1] = 2000;
myFrequencyArray[2] = 3000;
myFrequencyArray[3] = 4000;
myFrequencyArray[4] = 5000;
const magResponseOutput = new Float32Array(5);
const phaseResponseOutput = new Float32Array(5);
```
Next we create a {{ htmlelement("ul") }} element in our HTML to contain our results,
and grab a reference to it in our JavaScript:
```html
<p>IIR filter frequency response for:</p>
<ul class="freq-response-output"></ul>
```
```js
const freqResponseOutput = document.querySelector(".freq-response-output");
```
Finally, after creating our filter, we use `getFrequencyResponse()` to
generate the response data and put it in our arrays, then loop through each data set and
output them in a human-readable list at the bottom of the page:
```js
const feedforwardCoefficients = [0.1, 0.2, 0.3, 0.4, 0.5];
const feedbackCoefficients = [0.5, 0.4, 0.3, 0.2, 0.1];
const iirFilter = audioCtx.createIIRFilter(
feedforwardCoefficients,
feedbackCoefficients,
);
// …
function calcFrequencyResponse() {
iirFilter.getFrequencyResponse(
myFrequencyArray,
magResponseOutput,
phaseResponseOutput,
);
for (let i = 0; i < myFrequencyArray.length; i++) {
const listItem = document.createElement("li");
listItem.textContent = `${myFrequencyArray[i]}Hz: Magnitude ${magResponseOutput[i]}, Phase ${phaseResponseOutput[i]} radians.`;
freqResponseOutput.appendChild(listItem);
}
}
calcFrequencyResponse();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- {{domxref("IIRFilterNode")}}
- {{domxref("AudioNode")}}
| 0 |
data/mdn-content/files/en-us/web/api/iirfilternode | data/mdn-content/files/en-us/web/api/iirfilternode/iirfilternode/index.md | ---
title: "IIRFilterNode: IIRFilterNode() constructor"
short-title: IIRFilterNode()
slug: Web/API/IIRFilterNode/IIRFilterNode
page-type: web-api-constructor
browser-compat: api.IIRFilterNode.IIRFilterNode
---
{{APIRef("Web Audio API")}}
The **`IIRFilterNode()`** constructor
of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) creates a new
{{domxref("IIRFilterNode")}} object which an {{domxref("AudioNode")}} processor
which implements a general infinite impulse response filter.
## Syntax
```js-nolint
new IIRFilterNode(context, options)
```
### Parameters
- `context`
- : A reference to an {{domxref("AudioContext")}}.
- `options`
- : Options are as follows:
- `feedforward`
- : A sequence of feedforward coefficients.
- `feedback`
- : A sequence of feedback coefficients.
- `channelCount`
- : Represents an integer used to determine how many channels are used when [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) connections to any inputs to the node. (See
{{domxref("AudioNode.channelCount")}} for more information.) Its usage and precise
definition depend on the value of `channelCountMode`.
- `channelCountMode`
- : Represents an enumerated value describing the way channels must be matched between
the node's inputs and outputs. (See {{domxref("AudioNode.channelCountMode")}} for more
information including default values.)
- `channelInterpretation`
- : Represents an enumerated value describing the meaning of the channels. This
interpretation will define how audio [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) will happen.
The possible values are `"speakers"` or `"discrete"`. (See
{{domxref("AudioNode.channelCountMode")}} for more information including default
values.)
Unlike other nodes in the Web Audio API, the options passed into the IIR
filter upon creation are not optional. The filter needs these values to work and with
the vast range of filters available, there is no default.
### Return value
A new {{domxref("IIRFilterNode")}} object instance.
## Examples
```js
let feedForward = [0.00020298, 0.0004059599, 0.00020298];
let feedBackward = [1.0126964558, -1.9991880801, 0.9873035442];
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
const iirFilter = new IIRFilterNode(audioCtx, {
feedforward: feedForward,
feedback: feedBackward,
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.