repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/navigationhistoryentry/index.md | ---
title: NavigationHistoryEntry
slug: Web/API/NavigationHistoryEntry
page-type: web-api-interface
status:
- experimental
browser-compat: api.NavigationHistoryEntry
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`NavigationHistoryEntry`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} represents a single navigation history entry.
These objects are commonly accessed via the {{domxref("Navigation.currentEntry")}} property and {{domxref("Navigation.entries()")}} method.
The Navigation API only exposes history entries created in the current browsing context that have the same origin as the current page (e.g. not navigations inside embedded {{htmlelement("iframe")}}s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than with the older {{domxref("History API", "History API", "", "nocode")}}.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{DOMxRef("EventTarget")}}._
- {{domxref("NavigationHistoryEntry.id", "id")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the `id` of the history entry. This is a unique, UA-generated value that always represents a specific history entry, useful to correlate it with an external resource such as a storage cache.
- {{domxref("NavigationHistoryEntry.index", "index")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the index of the history entry in the history entries list (that is, the list returned by {{domxref("Navigation.entries()")}}), or `-1` if the entry does not appear in the list.
- {{domxref("NavigationHistoryEntry.key", "key")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the `key` of the history entry. This is a unique, UA-generated value that represents the history entry's slot in the entries list rather than the entry itself. It is used to navigate that particular slot via {{domxref("Navigation.traverseTo()")}}. The `key` will be reused by other entries that replace the entry in the list (that is, if the {{domxref("NavigateEvent.navigationType")}} is `replace`).
- {{domxref("NavigationHistoryEntry.sameDocument", "sameDocument")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns `true` if this history entry is for the same `document` as the current {{domxref("Document")}} value, or `false` otherwise.
- {{domxref("NavigationHistoryEntry.url", "url")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the absolute URL of this history entry. If the entry corresponds to a different document than the current one (like `sameDocument` property is `false`), and that document was fetched with a {{httpheader("Referrer-Policy", "referrer policy")}} header set to `no-referrer` or `origin`, the property returns `null`.
## Instance methods
_Inherits methods from its parent, {{DOMxRef("EventTarget")}}._
- {{domxref("NavigationHistoryEntry.getState", "getState()")}} {{Experimental_Inline}}
- : Returns a clone of the available state associated with this history entry.
## Events
- {{domxref("NavigationHistoryEntry/dispose_event", "dispose")}} {{Experimental_Inline}}
- : Fires when the entry is no longer part of the history entry list.
## Examples
```js
function initHomeBtn() {
// Get the key of the first loaded entry
// so the user can always go back to this view.
const { key } = navigation.currentEntry;
backToHomeButton.onclick = () => {
navigation.traverseTo(key);
};
}
// Intercept navigate events, such as link clicks, and
// replace them with single-page navigations
navigation.addEventListener("navigate", (event) => {
event.intercept({
async handler() {
// Navigate to a different view,
// but the "home" button will always work.
},
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api/navigationhistoryentry | data/mdn-content/files/en-us/web/api/navigationhistoryentry/url/index.md | ---
title: "NavigationHistoryEntry: url property"
short-title: url
slug: Web/API/NavigationHistoryEntry/url
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigationHistoryEntry.url
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`url`** read-only property of the {{domxref("NavigationHistoryEntry")}} interface returns the absolute URL of this history entry. If the entry corresponds to a different Document than the current one (like `sameDocument` property is `false`), and that Document was fetched with a {{httpheader("Referrer-Policy", "referrer policy")}} header set to `no-referrer` or `origin`, the property returns `null`. If current document is not fully active, it returns an empty string.
## Value
A string representing the URL or `null`.
## Examples
```js
const current = navigation.currentEntry;
console.log(current.url);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api/navigationhistoryentry | data/mdn-content/files/en-us/web/api/navigationhistoryentry/dispose_event/index.md | ---
title: "NavigationHistoryEntry: dispose event"
short-title: dispose
slug: Web/API/NavigationHistoryEntry/dispose_event
page-type: web-api-event
status:
- experimental
browser-compat: api.NavigationHistoryEntry.dispose_event
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`dispose`** event of the {{domxref("NavigationHistoryEntry")}} interface is fired when the entry is no longer part of the history entry list.
Disposal occurs when:
- Forward history entries are cleared. See the example at [Notifications on entry disposal](https://github.com/wicg/navigation-api#notifications-on-entry-disposal) for more information.
- The user clears their browser history using settings or provided UI controls.
- The history limit is exceeded. This is not specified anywhere, but browsers tend to have a history limit of 50 pages.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("dispose", (event) => {});
ondispose = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
```js
navigation.addEventListener("currententrychange", () => {
navigation.currentEntry.addEventListener("dispose", disposeHandler);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api/navigationhistoryentry | data/mdn-content/files/en-us/web/api/navigationhistoryentry/id/index.md | ---
title: "NavigationHistoryEntry: id property"
short-title: id
slug: Web/API/NavigationHistoryEntry/id
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigationHistoryEntry.id
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`id`** read-only property of the {{domxref("NavigationHistoryEntry")}} interface returns the `id` of the history entry, or an empty string if current document is not fully active. This is a unique, UA-generated value that always represents a specific history entry, useful to correlate it with an external resource such as a storage cache.
This differs from the {{domxref("NavigationHistoryEntry.key", "key")}} of a history entry. The `key` is a unique, UA-generated value that represents the history entry's slot in the entries list rather than the entry itself. It is used to navigate that particular slot via {{domxref("Navigation.traverseTo()")}}. The `key` will be reused by other entries that replace the entry in the list (that is, if the {{domxref("NavigateEvent.navigationType")}} is `replace`).
## Value
A string representing the `id` of the {{domxref("NavigationHistoryEntry")}}.
## Examples
```js
const current = navigation.currentEntry;
console.log(current.id);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api/navigationhistoryentry | data/mdn-content/files/en-us/web/api/navigationhistoryentry/samedocument/index.md | ---
title: "NavigationHistoryEntry: sameDocument property"
short-title: sameDocument
slug: Web/API/NavigationHistoryEntry/sameDocument
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigationHistoryEntry.sameDocument
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`sameDocument`** read-only property of the {{domxref("NavigationHistoryEntry")}} interface returns `true` if this history entry is for the same `document` as the current {{domxref("Document")}} value and current document is fully active, or `false` otherwise.
## Value
A boolean.
## Examples
```js
const current = navigation.currentEntry;
console.log(current.sameDocument);
// Will always return true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api/navigationhistoryentry | data/mdn-content/files/en-us/web/api/navigationhistoryentry/key/index.md | ---
title: "NavigationHistoryEntry: key property"
short-title: key
slug: Web/API/NavigationHistoryEntry/key
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigationHistoryEntry.key
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`key`** read-only property of the {{domxref("NavigationHistoryEntry")}} interface returns the `key` of the history entry, or an empty string if current document is not fully active. This is a unique, UA-generated value that represents the history entry's slot in the entries list. It is used to navigate that particular slot via {{domxref("Navigation.traverseTo()")}}. The `key` will be reused by other entries that replace the entry in the list (that is, if the {{domxref("NavigateEvent.navigationType")}} is `replace`).
This differs from the {{domxref("NavigationHistoryEntry.id", "id")}} of a history entry. The `id` is a unique, UA-generated value that always represents a specific history entry rather than its slot in the entries list. This is useful to correlate it with an external resource such as a storage cache.
## Value
A string representing the `key` of the {{domxref("NavigationHistoryEntry")}}.
## Examples
### Basic usage
```js
const current = navigation.currentEntry;
console.log(current.key);
```
### Set up a home button
```js
function initHomeBtn() {
// Get the key of the first loaded entry
// so the user can always go back to this view.
const { key } = navigation.currentEntry;
backToHomeButton.onclick = () => {
navigation.traverseTo(key);
};
}
// Intercept navigate events, such as link clicks, and
// replace them with single-page navigations
navigation.addEventListener("navigate", (event) => {
event.intercept({
async handler() {
// Navigate to a different view,
// but the "home" button will always work.
},
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api/navigationhistoryentry | data/mdn-content/files/en-us/web/api/navigationhistoryentry/index/index.md | ---
title: "NavigationHistoryEntry: index property"
short-title: index
slug: Web/API/NavigationHistoryEntry/index
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigationHistoryEntry.index
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`index`** read-only property of the {{domxref("NavigationHistoryEntry")}} interface returns the index of the history entry in the history entries list (that is, the list returned by {{domxref("Navigation.entries()")}}), or `-1` if the entry does not appear in the list or if current document is not fully active.
## Value
A number representing the `index` of the entry in the history entries list, or `-1` if this item does not appear in the list.
## Examples
```js
const current = navigation.currentEntry;
console.log(current.index);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api/navigationhistoryentry | data/mdn-content/files/en-us/web/api/navigationhistoryentry/getstate/index.md | ---
title: "NavigationHistoryEntry: getState() method"
short-title: getState()
slug: Web/API/NavigationHistoryEntry/getState
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.NavigationHistoryEntry.getState
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`getState()`** method of the {{domxref("NavigationHistoryEntry")}} interface returns a clone of the developer-supplied state associated with this history entry.
## Syntax
```js-nolint
getState()
```
### Parameters
None.
### Return value
A value representing the state. This can be any [structured-cloneable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) data type.
If no state is defined or if current document is not fully active, it returns `undefined`.
### Exceptions
None.
## Examples
```js
async function handleReload() {
// Update existing state via reload()
await navigation.reload({
state: { ...navigation.currentEntry.getState(), newState: 3 },
});
// Print current state to the console
const current = navigation.currentEntry;
console.log(current.getState());
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
- Methods that allow state to be updated — {{domxref("Navigation.navigate()")}}, {{domxref("Navigation.reload()")}}, and {{domxref("Navigation.updateCurrentEntry()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/layoutshiftattribution/index.md | ---
title: LayoutShiftAttribution
slug: Web/API/LayoutShiftAttribution
page-type: web-api-interface
status:
- experimental
browser-compat: api.LayoutShiftAttribution
---
{{APIRef("Performance API")}}{{SeeCompatTable}}
The `LayoutShiftAttribution` interface provides debugging information about elements which have shifted.
Instances of `LayoutShiftAttribution` are returned in an array by calling {{domxref("LayoutShift.sources")}}.
## Instance properties
- {{domxref("LayoutShiftAttribution.node")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the element that has shifted (null if it has been removed).
- {{domxref("LayoutShiftAttribution.previousRect")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("DOMRectReadOnly")}} object representing the position of the element before the shift.
- {{domxref("LayoutShiftAttribution.currentRect")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("DOMRectReadOnly")}} object representing the position of the element after the shift.
## Instance methods
- {{domxref("LayoutShiftAttribution.toJSON()")}} {{Experimental_Inline}}
- : Returns a JSON representation of the `LayoutShiftAttribution` object.
## Examples
The following example finds the element with the highest layout shift score, and returns the element in that entry with the largest size prior to the shift (`previousRect`). For more detail on this see [Debug Web Vitals in the field](https://web.dev/articles/debug-performance-in-the-field).
```js
function getCLSDebugTarget(entries) {
const largestEntry = entries.reduce((a, b) =>
a && a.value > b.value ? a : b,
);
if (largestEntry?.sources?.length) {
const largestSource = largestEntry.sources.reduce((a, b) => {
const area = (el) => el.previousRect.width * el.previousRect.height;
return a.node && area(a) > area(b) ? a : b;
});
if (largestSource) {
return largestSource.node;
}
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Debug layout shifts](https://web.dev/articles/debug-layout-shifts)
- [Debug Web Vitals in the field](https://web.dev/articles/debug-performance-in-the-field)
| 0 |
data/mdn-content/files/en-us/web/api/layoutshiftattribution | data/mdn-content/files/en-us/web/api/layoutshiftattribution/currentrect/index.md | ---
title: "LayoutShiftAttribution: currentRect property"
short-title: currentRect
slug: Web/API/LayoutShiftAttribution/currentRect
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.LayoutShiftAttribution.currentRect
---
{{APIRef("Performance API")}}{{SeeCompatTable}}
The **`currentRect`** read-only property of the {{domxref("LayoutShiftAttribution")}} interface returns a {{domxref("DOMRectReadOnly")}} object representing the position of the element after the shift.
## Value
A {{domxref("DOMRectReadOnly")}} object.
## Examples
The following example prints the `currentRect` of the first item in {{domxref("LayoutShift.sources")}} to the console.
```js
new PerformanceObserver((list) => {
for (const { sources } of list.getEntries()) {
if (sources) {
console.log(sources[0].currentRect);
}
}
}).observe({ type: "layout-shift", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/layoutshiftattribution | data/mdn-content/files/en-us/web/api/layoutshiftattribution/previousrect/index.md | ---
title: "LayoutShiftAttribution: previousRect property"
short-title: previousRect
slug: Web/API/LayoutShiftAttribution/previousRect
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.LayoutShiftAttribution.previousRect
---
{{APIRef("Performance API")}}{{SeeCompatTable}}
The **`previousRect`** read-only property of the {{domxref("LayoutShiftAttribution")}} interface returns a {{domxref("DOMRectReadOnly")}} object representing the position of the element before the shift.
## Value
A {{domxref("DOMRectReadOnly")}} object.
## Examples
The following example prints the `previousRect` of the first item in {{domxref("LayoutShift.sources")}} to the console.
```js
new PerformanceObserver((list) => {
for (const { sources } of list.getEntries()) {
if (sources) {
console.log(sources[0].previousRect);
}
}
}).observe({ type: "layout-shift", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/layoutshiftattribution | data/mdn-content/files/en-us/web/api/layoutshiftattribution/node/index.md | ---
title: "LayoutShiftAttribution: node property"
short-title: node
slug: Web/API/LayoutShiftAttribution/node
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.LayoutShiftAttribution.node
---
{{APIRef("Performance API")}}{{SeeCompatTable}}
The **`node`** read-only property of the {{domxref("LayoutShiftAttribution")}} interface returns a {{domxref("Node")}} representing the object that has shifted.
## Value
A {{domxref("Node")}}.
## Examples
The following example prints the `node` of the first item in {{domxref("LayoutShift.sources")}} to the console.
```js
new PerformanceObserver((list) => {
for (const { sources } of list.getEntries()) {
if (sources) {
console.log(sources[0].node);
}
}
}).observe({ type: "layout-shift", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/layoutshiftattribution | data/mdn-content/files/en-us/web/api/layoutshiftattribution/tojson/index.md | ---
title: "LayoutShiftAttribution: toJSON() method"
short-title: toJSON()
slug: Web/API/LayoutShiftAttribution/toJSON
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.LayoutShiftAttribution.toJSON
---
{{APIRef("Performance API")}}{{SeeCompatTable}}
The **`toJSON()`** method of the {{domxref("LayoutShiftAttribution")}} interface is a _serializer_ that returns a JSON representation of the `LayoutShiftAttribution` object.
## Syntax
```js-nolint
toJSON()
```
### Parameters
None.
### Return value
A JSON object that is the serialization of the {{domxref("LayoutShiftAttribution")}} object.
## Examples
The following example prints a JSON representation of the first item in {{domxref("LayoutShift.sources")}} to the console.
```js
new PerformanceObserver((list) => {
for (const { sources } of list.getEntries()) {
if (sources) {
console.log(sources[0].toJSON());
}
}
}).observe({ type: "layout-shift", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/web_bluetooth_api/index.md | ---
title: Web Bluetooth API
slug: Web/API/Web_Bluetooth_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.Bluetooth
---
{{DefaultAPISidebar("Bluetooth API")}}{{SeeCompatTable}}
The Web Bluetooth API provides the ability to connect and interact with Bluetooth Low Energy peripherals.
> **Note:** This API is _not available_ in [Web Workers](/en-US/docs/Web/API/Web_Workers_API) (not exposed via {{domxref("WorkerNavigator")}}).
## Interfaces
- {{DOMxRef("Bluetooth")}}
- : Returns a {{jsxref("Promise")}} to a {{DOMxRef("BluetoothDevice")}} object with the specified options.
- {{DOMxRef("BluetoothCharacteristicProperties")}}
- : Provides properties of a particular `BluetoothRemoteGATTCharacteristic`.
- {{DOMxRef("BluetoothDevice")}}
- : Represents a Bluetooth device inside a particular script execution environment.
- {{DOMxRef("BluetoothRemoteGATTCharacteristic")}}
- : Represents a GATT Characteristic, which is a basic data element that provides further information about a peripheral's service.
- {{DOMxRef("BluetoothRemoteGATTDescriptor")}}
- : Represents a GATT Descriptor, which provides further information about a characteristic's value.
- {{DOMxRef("BluetoothRemoteGATTServer")}}
- : Represents a GATT Server on a remote device.
- {{DOMxRef("BluetoothRemoteGATTService")}}
- : Represents a service provided by a GATT server, including a device, a list of referenced services, and a list of the characteristics of this service.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediaerror/index.md | ---
title: MediaError
slug: Web/API/MediaError
page-type: web-api-interface
browser-compat: api.MediaError
---
{{APIRef("HTML DOM")}}
The **`MediaError`** interface represents an error which occurred while handling media in an HTML media element based on {{domxref("HTMLMediaElement")}}, such as {{HTMLElement("audio")}} or {{HTMLElement("video")}}.
A `MediaError` object describes the error in general terms using a numeric `code` categorizing the kind of error, and a `message`, which provides specific diagnostics about what went wrong.
## Instance properties
_This interface doesn't inherit any properties._
- {{domxref("MediaError.code")}}
- : A number which represents [the general type of error that occurred](/en-US/docs/Web/API/MediaError/code#media_error_code_constants).
- {{domxref("MediaError.message")}}
- : A human-readable string which provides _specific diagnostic information_ to help the reader understand the error condition which occurred; specifically, it isn't a summary of what the error code means, but actual diagnostic information to help in understanding what exactly went wrong. This text and its format is not defined by the specification and will vary from one {{Glossary("user agent")}} to another. If no diagnostics are available, or no explanation can be provided, this value is an empty string (`""`).
## Instance methods
_This interface doesn't implement or inherit any methods, and has none of its own._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLMediaElement.error")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediaerror | data/mdn-content/files/en-us/web/api/mediaerror/message/index.md | ---
title: "MediaError: message property"
short-title: message
slug: Web/API/MediaError/message
page-type: web-api-instance-property
browser-compat: api.MediaError.message
---
{{APIRef("HTML DOM")}}
The read-only property **`MediaError.message`** returns a
human-readable string offering specific
diagnostic details related to the error described by the `MediaError` object,
or an empty string (`""`) if no diagnostic information can be determined or
provided.
## Value
A string providing a detailed, specific explanation of what went
wrong and possibly how it might be fixed. This is _not_ a generic description of
the {{domxref("MediaError.code")}} property's value, but instead goes deeper into the
specifics of this particular error and its circumstances. If no specific details are
available, this string is empty.
## Examples
This example creates a {{HTMLElement("audio")}} element, establishes an error handler
for it, then lets the user click buttons to choose whether to assign a valid audio file
or a missing file to the element's [`src`](/en-US/docs/Web/HTML/Element/audio#src) attribute. The error
handler outputs a message to a box onscreen describing the error, including both the
`code` and the `message`.
Only the relevant parts of the code are displayed; you can [see the complete source code here](https://github.com/mdn/dom-examples/tree/main/media/mediaerror).
The example creates an {{HTMLElement("audio")}} element and lets the user assign either
a valid music file to it, or a link to a file which doesn't exist. This lets us see the
behavior of the {{domxref("HTMLMediaElement/error_event", "error")}} event handler, which is received by an event handler
we add to the `<audio>` element itself.
The error handler looks like this:
```js
audioElement.onerror = () => {
let s = "";
const err = audioElement.error;
switch (err.code) {
case MediaError.MEDIA_ERR_ABORTED:
s += "The user canceled the audio.";
break;
case MediaError.MEDIA_ERR_NETWORK:
s += "A network error occurred while fetching the audio.";
break;
case MediaError.MEDIA_ERR_DECODE:
s += "An error occurred while decoding the audio.";
break;
case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
s +=
"The audio is missing or is in a format not supported by your browser.";
break;
default:
s += "An unknown error occurred.";
break;
}
const message = err.message;
if (message?.length > 0) {
s += ` ${message}`;
}
displayErrorMessage(`<strong>Error ${err.code}:</strong> ${s}<br>`);
};
```
This gets the {{domxref("MediaError")}} object describing the error from the
{{domxref("HTMLMediaElement.error", "error")}} property on the
{{domxref("HTMLAudioElement")}} representing the audio player. The error's
{{domxref("MediaError.code", "code")}} attribute is checked to determine a generic error
message to display, and, if `message` is not empty, it's appended to provide
additional details. Then the resulting text is output to the log.
### Result
You can try out this example below, and can [see the example in action outside this page here](https://mdn.github.io/dom-examples/media/mediaerror/).
{{ EmbedGHLiveSample('dom-examples/media/mediaerror', 650, 200) }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaError")}}: Interface used to define the `MediaError.message` property
- {{HTMLElement("audio")}}, {{HTMLElement("video")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediaerror | data/mdn-content/files/en-us/web/api/mediaerror/code/index.md | ---
title: "MediaError: code property"
short-title: code
slug: Web/API/MediaError/code
page-type: web-api-instance-property
browser-compat: api.MediaError.code
---
{{APIRef("HTML DOM")}}
The read-only property **`MediaError.code`** returns a numeric
value which represents the kind of error that occurred on a media element. To get a text
string with specific diagnostic information, see {{domxref("MediaError.message")}}.
## Value
A numeric value indicating the general type of error which occurred. The possible
values are described below, in [Media error code constants](#media_error_code_constants).
### Media error code constants
<table class="no-markdown">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Value</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>MEDIA_ERR_ABORTED</code></td>
<td><code>1</code></td>
<td>
The fetching of the associated resource was aborted by the user's
request.
</td>
</tr>
<tr>
<td><code>MEDIA_ERR_NETWORK</code></td>
<td><code>2</code></td>
<td>
Some kind of network error occurred which prevented the media from being
successfully fetched, despite having previously been available.
</td>
</tr>
<tr>
<td><code>MEDIA_ERR_DECODE</code></td>
<td><code>3</code></td>
<td>
Despite having previously been determined to be usable, an error
occurred while trying to decode the media resource, resulting in an
error.
</td>
</tr>
<tr>
<td><code>MEDIA_ERR_SRC_NOT_SUPPORTED</code></td>
<td><code>4</code></td>
<td>
The associated resource or media provider object (such as a
{{domxref("MediaStream")}}) has been found to be unsuitable.
</td>
</tr>
</tbody>
</table>
## Examples
This example creates a {{HTMLElement("video")}} element, establishes an error handler
for it, and then sets the element's [`src`](/en-US/docs/Web/HTML/Element/video#src) attribute to the
video resource to present in the element. The error handler outputs a message
```js
const obj = document.createElement("video");
obj.onerror = () => {
console.error(`Error with media: ${obj.error.code}`);
};
obj.src = "https://example.com/blahblah.mp4";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaError")}}: Interface used to define the `MediaError.code` property
| 0 |
data/mdn-content/files/en-us/web/api/mediaerror | data/mdn-content/files/en-us/web/api/mediaerror/msextendedcode/index.md | ---
title: "MediaError: msExtendedCode property"
short-title: msExtendedCode
slug: Web/API/MediaError/msExtendedCode
page-type: web-api-instance-property
---
{{APIRef("DOM")}}{{Non-standard_header}}
In the event of an error, the media element's error event will be fired. The element's error property will then contain an **`msExtendedCode`** read-only property with platform-specific error code information.
**`msExtendedCode`** is a read-only proprietary property specific to Internet Explorer and Microsoft Edge.
## Value
Type: **long**; The platform specific error code.
## Example
```js
const video1 = object.getElementById("video1");
video1.addEventListener(
"error",
() => {
const error = video1.error.msExtendedCode;
//…
},
false,
);
video.addEventListener(
"canplay",
() => {
video1.play();
},
false,
);
```
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpuinternalerror/index.md | ---
title: GPUInternalError
slug: Web/API/GPUInternalError
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPUInternalError
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUInternalError`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} describes an application error indicating that an operation did not pass the WebGPU API's validation constraints.
It represents one of the types of errors surfaced by {{domxref("GPUDevice.popErrorScope")}} and the {{domxref("GPUDevice.uncapturederror_event", "uncapturederror")}} event.
Internal errors occur when something happens in the WebGPU implementation that wasn't caught by validation and wasn't clearly identifiable as an out-of-memory error. It generally means that an operation your code performed hit a system limit in a way that was difficult to express with WebGPU's [supported limits](/en-US/docs/Web/API/GPUSupportedLimits). The same operation might succeed on a different device. These can only be raised by pipeline creation, usually if the shader is too complex for the device.
{{InheritanceDiagram}}
## Constructor
- {{domxref("GPUInternalError.GPUInternalError", "GPUInternalError()")}} {{Experimental_Inline}}
- : Creates a new `GPUInternalError` object instance.
## Instance properties
The `message` property is inherited from its parent, {{domxref("GPUError")}}:
- {{domxref("GPUError.message", "message")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : A string providing a human-readable message that explains why the error occurred.
## Examples
The following example uses an error scope to capture a suspected validation error, logging it to the console.
```js
device.pushErrorScope("internal");
const module = device.createShaderModule({
code: shader, // REALLY complex shader
});
device.popErrorScope().then((error) => {
if (error) {
// error is a GPUInternalError object instance
module = null;
console.error(`An error occurred while creating shader: ${error.message}`);
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
- [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)
| 0 |
data/mdn-content/files/en-us/web/api/gpuinternalerror | data/mdn-content/files/en-us/web/api/gpuinternalerror/gpuinternalerror/index.md | ---
title: "GPUInternalError: GPUInternalError() constructor"
short-title: GPUInternalError()
slug: Web/API/GPUInternalError/GPUInternalError
page-type: web-api-constructor
status:
- experimental
browser-compat: api.GPUInternalError.GPUInternalError
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUInternalError()`** constructor creates a new
{{domxref("GPUInternalError")}} object instance.
## Syntax
```js-nolint
new GPUInternalError(message)
```
### Parameters
- `message`
- : A string providing a human-readable message that explains why the error occurred.
## Examples
A developer would not manually use the constructor to create a `GPUInternalError` object. The user agent uses this constructor to create an appropriate object when an internal error is surfaced by {{domxref("GPUDevice.popErrorScope")}} or the {{domxref("GPUDevice.uncapturederror_event", "uncapturederror")}} event.
See the main [`GPUInternalError`](/en-US/docs/Web/API/GPUInternalError#examples) page for an example involving a `GPUInternalError` object instance.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
- [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/readablestreambyobreader/index.md | ---
title: ReadableStreamBYOBReader
slug: Web/API/ReadableStreamBYOBReader
page-type: web-api-interface
browser-compat: api.ReadableStreamBYOBReader
---
{{APIRef("Streams")}}
The `ReadableStreamBYOBReader` interface of the [Streams API](/en-US/docs/Web/API/Streams_API) defines a reader for a {{domxref("ReadableStream")}} that supports zero-copy reading from an underlying byte source.
It is used for efficient copying from underlying sources where the data is delivered as an "anonymous" sequence of bytes, such as files.
An instance of this reader type should usually be obtained by calling {{domxref("ReadableStream.getReader()")}} on the stream, specifying `mode: "byob"` in the options parameter.
The readable stream must have an _underlying byte source_. In other words, it must have been [constructed](/en-US/docs/Web/API/ReadableStream/ReadableStream) specifying an underlying source with [`type: "bytes"`](/en-US/docs/Web/API/ReadableStream/ReadableStream#type)).
Using this kind of reader, a [`read()`](#readablestreambyobreader.read) request when the readable stream's internal queues are empty will result in a zero copy transfer from the underlying source (bypassing the stream's internal queues).
If the internal queues are not empty, a `read()` will satisfy the request from the buffered data.
Note that the methods and properties are similar to those for the default reader ({{domxref("ReadableStreamDefaultReader")}}).
The `read()` method differs in that it provide a view into which data should be written.
## Constructor
- {{domxref("ReadableStreamBYOBReader.ReadableStreamBYOBReader", "ReadableStreamBYOBReader()")}}
- : Creates and returns a `ReadableStreamBYOBReader` object instance.
## Instance properties
- {{domxref("ReadableStreamBYOBReader.closed")}} {{ReadOnlyInline}}
- : Returns a {{jsxref("Promise")}} that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process.
## Instance methods
- {{domxref("ReadableStreamBYOBReader.cancel()")}}
- : Returns a {{jsxref("Promise")}} that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. The supplied `reason` argument will be given to the underlying source, which may or may not use it.
- {{domxref("ReadableStreamBYOBReader.read()")}}
- : Passes a view into which data must be written, and returns a {{jsxref("Promise")}} that resolves with the next chunk in the stream or rejects with an indication that the stream is closed or has errored.
- {{domxref("ReadableStreamBYOBReader.releaseLock()")}}
- : Releases the reader's lock on the stream.
## Examples
The example below is taken from the live examples in [Using readable byte streams](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams#examples).
First create the reader using {{domxref("ReadableStream.getReader()")}} on the stream, specifying `mode: "byob"` in the options parameter.
As this is a "Bring Your Own Buffer" reader, we also need to create an `ArrayBuffer` to read into.
```js
const reader = stream.getReader({ mode: "byob" });
let buffer = new ArrayBuffer(200);
```
A function that uses the reader is shown below.
This calls the `read()` method recursively to read data into the buffer.
The method takes a [`Uint8Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) [typed array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) which is a view over the part of the original array buffer that has not yet been written.
The parameters of the view are calculated from the data that was received in previous calls, which define an offset into the original array buffer.
```js
readStream(reader);
function readStream(reader) {
let bytesReceived = 0;
let offset = 0;
// read() returns a promise that resolves when a value has been received
reader
.read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
.then(function processText({ done, value }) {
// Result objects contain two properties:
// done - true if the stream has already given all its data.
// value - some data. Always undefined when done is true.
if (done) {
logConsumer(`readStream() complete. Total bytes: ${bytesReceived}`);
return;
}
buffer = value.buffer;
offset += value.byteLength;
bytesReceived += value.byteLength;
logConsumer(
`Read ${value.byteLength} (${bytesReceived}) bytes: ${value}`,
);
result += value;
// Read some more, and call this function again
return reader
.read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
.then(processText);
});
}
```
When there is no more data in the stream, the `read()` method resolves with an object with the property `done` set to `true`, and the function returns.
The {{domxref("ReadableStreamBYOBReader.closed")}} property returns a promise that can be used to monitor for the stream being closed or errored, or the reader lock being released.
```js
reader.closed
.then(() => {
// Resolved - code to handle stream closing
})
.catch(() => {
// Rejected - code to handle error
});
```
To cancel the stream call {{domxref("ReadableStreamBYOBReader.cancel()")}}, optionally specifying a _reason_.
This returns a promise that will resolve when the stream has been cancelled.
When the stream is cancelled the controller will in turn call `cancel()` on the underlying source, passing in the optional reason.
The example code in [Using readable byte streams](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams#examples) calls the cancel method when a button is pressed, as shown:
```js
button.addEventListener("click", () => {
reader.cancel("user choice").then(() => console.log("cancel complete"));
});
```
The consumer can also call `releaseLock()` to release the reader's hold on the stream, but only when no read is pending:
```js
reader.releaseLock();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Streams API concepts](/en-US/docs/Web/API/Streams_API)
- [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
- {{domxref("ReadableStream")}}
- [WHATWG Stream Visualizer](https://whatwg-stream-visualizer.glitch.me/), for a basic visualization of readable, writable, and transform streams.
- [Web-streams-polyfill](https://github.com/MattiasBuelens/web-streams-polyfill) or [sd-streams](https://github.com/stardazed/sd-streams) - polyfills
| 0 |
data/mdn-content/files/en-us/web/api/readablestreambyobreader | data/mdn-content/files/en-us/web/api/readablestreambyobreader/closed/index.md | ---
title: "ReadableStreamBYOBReader: closed property"
short-title: closed
slug: Web/API/ReadableStreamBYOBReader/closed
page-type: web-api-instance-property
browser-compat: api.ReadableStreamBYOBReader.closed
---
{{APIRef("Streams")}}
The **`closed`** read-only property of the {{domxref("ReadableStreamBYOBReader")}} interface returns a {{jsxref("Promise")}} that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released.
This property enables you to write code that responds to an end to the streaming process.
## Value
A {{jsxref("Promise")}}.
## Examples
The code below shows the pattern for handling the closed/error state of a BYOBReader.
```js
const reader = stream.getReader({ mode: "byob" });
reader.closed
.then(() => {
// Resolved - code to handle stream closing
})
.catch(() => {
// Rejected - code to handle error
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStreamBYOBReader.ReadableStreamBYOBReader", "ReadableStreamBYOBReader()")}} constructor
- [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestreambyobreader | data/mdn-content/files/en-us/web/api/readablestreambyobreader/readablestreambyobreader/index.md | ---
title: "ReadableStreamBYOBReader: ReadableStreamBYOBReader() constructor"
short-title: ReadableStreamBYOBReader()
slug: Web/API/ReadableStreamBYOBReader/ReadableStreamBYOBReader
page-type: web-api-constructor
browser-compat: api.ReadableStreamBYOBReader.ReadableStreamBYOBReader
---
{{APIRef("Streams")}}
The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance.
> **Note:** You generally wouldn't use this constructor manually;
> instead, you'd use the {{domxref("ReadableStream.getReader()")}} method with the argument `"byob"`.
## Syntax
```js-nolint
new ReadableStreamBYOBReader(stream)
```
### Parameters
- `stream`
- : The {{domxref("ReadableStream")}} to be read.
### Return value
An instance of the {{domxref("ReadableStreamBYOBReader")}} object.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the supplied `stream` parameter is not a {{domxref("ReadableStream")}}, or it is already locked for reading by another reader, or its stream controller is not a {{domxref("ReadableByteStreamController")}}.
## Examples
The constructor is rarely called directly.
Instead call {{domxref("ReadableStream.getReader()")}} as shown:
```js
const reader = stream.getReader({ mode: "byob" });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStreamBYOBReader")}}
- [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestreambyobreader | data/mdn-content/files/en-us/web/api/readablestreambyobreader/read/index.md | ---
title: "ReadableStreamBYOBReader: read() method"
short-title: read()
slug: Web/API/ReadableStreamBYOBReader/read
page-type: web-api-instance-method
browser-compat: api.ReadableStreamBYOBReader.read
---
{{APIRef("Streams")}}
The **`read()`** method of the {{domxref("ReadableStreamBYOBReader")}} interface is used to read data into a view on a user-supplied buffer from an associated [readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams).
A request for data will be satisfied from the stream's internal queues if there is any data present.
If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source.
The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a {{jsxref("Promise")}}.
The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled.
If the stream is errored, the promise will be rejected with the relevant error object.
If a chunk of data is supplied, the `value` property will contain a new view.
This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data.
Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable.
The promise will fulfill with a `value: undefined` if the stream has been cancelled.
In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost).
The `done` property indicates whether or not more data is expected.
The value is set `true` if the stream is closed or cancelled, and `false` otherwise.
## Syntax
```js-nolint
read(view)
```
### Parameters
- `view`
- : The view that data is to be read into.
### Return value
A {{jsxref("Promise")}}, which fulfills/rejects with a result depending on the state of the stream.
The following are possible:
- If a chunk is available and the stream is still active, the promise fulfills with an object of the form:
```js
{ value: theChunk, done: false }
```
`theChunk` is a view containing the new data.
This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method.
The original `view` will be detached and no longer usable.
- If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above):
```js
{ value: theChunk, done: true }
```
- If the stream is cancelled, the promise fulfills with an object of the form:
```js
{ value: undefined, done: true }
```
In this case the backing memory is discarded.
- If the stream throws an error, the promise rejects with the relevant error.
### Exceptions
- {{jsxref("TypeError")}}
- : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or {{domxref("ReadableStreamBYOBReader.releaseLock()")}} is called (when there's is a pending read request).
## Examples
The example code here is taken from the live examples in [Using readable byte streams](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams#examples).
First we create the reader using {{domxref("ReadableStream.getReader()")}} on the stream, specifying `mode: "byob"` in the options parameter.
We also need create an `ArrayBuffer`, which is the "backing memory" of the views that we will write into.
```js
const reader = stream.getReader({ mode: "byob" });
let buffer = new ArrayBuffer(4000);
```
A function that uses the reader is shown below.
This calls the `read()` method recursively to read data into the buffer.
The method takes a [`Uint8Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) [typed array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) which is a view over the part of the original array buffer that has not yet been written.
The parameters of the view are calculated from the data that was received in previous calls, which define an offset into the original array buffer.
```js
readStream(reader);
function readStream(reader) {
let bytesReceived = 0;
let offset = 0;
while (offset < buffer.byteLength) {
// read() returns a promise that fulfills when a value has been received
reader
.read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
.then(function processBytes({ done, value }) {
// Result objects contain two properties:
// done - true if the stream has already given all its data.
// value - some data. 'undefined' if the reader is canceled.
if (done) {
// There is no more data in the stream
return;
}
buffer = value.buffer;
offset += value.byteLength;
bytesReceived += value.byteLength;
// Read some more, and call this function again
// Note that here we create a new view over the original buffer.
return reader
.read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
.then(processBytes);
});
}
}
```
When there is no more data in the stream, the `read()` method fulfills with an object with the property `done` set to `true`, and the function returns.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStreamBYOBReader.ReadableStreamBYOBReader", "ReadableStreamBYOBReader()")}} constructor
- [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestreambyobreader | data/mdn-content/files/en-us/web/api/readablestreambyobreader/cancel/index.md | ---
title: "ReadableStreamBYOBReader: cancel() method"
short-title: cancel()
slug: Web/API/ReadableStreamBYOBReader/cancel
page-type: web-api-instance-method
browser-compat: api.ReadableStreamBYOBReader.cancel
---
{{APIRef("Streams")}}
The **`cancel()`** method of the {{domxref("ReadableStreamBYOBReader")}} interface returns a {{jsxref("Promise")}} that resolves when the stream is canceled.
Calling this method signals a loss of interest in the stream by a consumer.
> **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream ({{domxref("ReadableStream.cancel()")}}).
## Syntax
```js-nolint
cancel()
cancel(reason)
```
### Parameters
- `reason` {{optional_inline}}
- : A human-readable reason for the cancellation. The underlying source may or may not use it.
### Return value
A {{jsxref("Promise")}}, which fulfills with the value given in the `reason` parameter.
### Exceptions
- {{jsxref("TypeError")}}
- : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner.
## Examples
This example code calls the `cancel()` method when a button is pressed, passing the string "user choice" as a reason.
The promise resolves when cancellation completes.
```js
button.addEventListener("click", () => {
reader.cancel("user choice").then(() => console.log(`cancel complete`));
});
```
Note that this code can be seen running in the [Using readable byte streams](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams#result) example code (press the **Cancel stream** button).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStreamBYOBReader.ReadableStreamBYOBReader", "ReadableStreamBYOBReader()")}} constructor
- [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestreambyobreader | data/mdn-content/files/en-us/web/api/readablestreambyobreader/releaselock/index.md | ---
title: "ReadableStreamBYOBReader: releaseLock() method"
short-title: releaseLock()
slug: Web/API/ReadableStreamBYOBReader/releaseLock
page-type: web-api-instance-method
browser-compat: api.ReadableStreamBYOBReader.releaseLock
---
{{APIRef("Streams")}}
The **`releaseLock()`** method of the {{domxref("ReadableStreamBYOBReader")}} interface releases the reader's lock on the stream.
After the lock is released, the reader is no longer active.
The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed.
If the reader's lock is released while it still has pending read requests then the promises returned by the reader's {{domxref("ReadableStreamBYOBReader.read()")}} method are immediately rejected with a `TypeError`.
Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader.
## Syntax
```js-nolint
releaseLock()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the source object is not a `ReadableStreamBYOBReader`.
## Examples
A trivial examples is shown below.
A lock is created as soon as the reader is created on the stream.
```js
const reader = stream.getReader({ mode: "byob" });
reader.releaseLock();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStreamBYOBReader.ReadableStreamBYOBReader", "ReadableStreamBYOBReader()")}} constructor
- [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/videotrack/index.md | ---
title: VideoTrack
slug: Web/API/VideoTrack
page-type: web-api-interface
browser-compat: api.VideoTrack
---
{{APIRef("HTML DOM")}}
The {{domxref("VideoTrack")}} interface represents a single video track from a {{HTMLElement("video")}} element.
The most common use for accessing a `VideoTrack` object is to toggle its {{domxref("VideoTrack.selected", "selected")}} property in order to make it the active video track for its {{HTMLElement("video")}} element.
## Instance properties
- {{domxref("VideoTrack.selected", "selected")}}
- : A Boolean value which controls whether or not the video track is active. Only a single video track can be active at any given time, so setting this property to `true` for one track while another track is active will make that other track inactive.
- {{domxref("VideoTrack.id", "id")}} {{ReadOnlyInline}}
- : A string which uniquely identifies the track within the media. This ID can be used to locate a specific track within a video track list by calling {{domxref("VideoTrackList.getTrackById()")}}. The ID can also be used as the fragment part of the URL if the media supports seeking by media fragment per the [Media Fragments URI specification](https://www.w3.org/TR/media-frags/).
- {{domxref("VideoTrack.kind", "kind")}} {{ReadOnlyInline}}
- : A string specifying the category into which the track falls. For example, the main video track would have a `kind` of `"main"`.
- {{domxref("VideoTrack.label", "label")}} {{ReadOnlyInline}}
- : A string providing a human-readable label for the track. For example, a track whose `kind` is `"sign"` might have a `label` of `"A sign-language interpretation"`. This string is empty if no label is provided.
- {{domxref("VideoTrack.language", "language")}} {{ReadOnlyInline}}
- : A string specifying the video track's primary language, or an empty string if unknown. The language is specified as a BCP 47 ({{RFC(5646)}}) language code, such as `"en-US"` or `"pt-BR"`.
- {{domxref("VideoTrack.sourceBuffer", "sourceBuffer")}} {{ReadOnlyInline}}
- : The {{domxref("SourceBuffer")}} that created the track. Returns null if the track was not created by a {{domxref("SourceBuffer")}} or the {{domxref("SourceBuffer")}} has been removed from the {{domxref("MediaSource.sourceBuffers")}} attribute of its parent media source.
## Usage notes
To get a `VideoTrack` for a given media element, use the element's {{domxref("HTMLMediaElement.videoTracks", "videoTracks")}} property, which returns a {{domxref("VideoTrackList")}} object from which you can get the individual tracks contained in the media:
```js
const el = document.querySelector("video");
const tracks = el.videoTracks;
```
You can then access the media's individual tracks using either array syntax or functions such as {{jsxref("Array.forEach", "forEach()")}}.
This first example gets the first video track on the media:
```js
const firstTrack = tracks[0];
```
The next example scans through all of the media's video tracks, activating the first video track that is in the user's preferred language (taken from a variable `userLanguage`).
```js
for (const track of tracks) {
if (track.language === userLanguage) {
track.selected = true;
break;
}
}
```
The {{domxref("VideoTrack.language", "language")}} is in standard ({{RFC(5646)}}) format. For US English, this would be `"en-US"`, for example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/videotrack | data/mdn-content/files/en-us/web/api/videotrack/selected/index.md | ---
title: "VideoTrack: selected property"
short-title: selected
slug: Web/API/VideoTrack/selected
page-type: web-api-instance-property
browser-compat: api.VideoTrack.selected
---
{{APIRef("HTML DOM")}}
The **{{domxref("VideoTrack")}}** property
**`selected`** controls whether or not a particular video
track is active.
## Value
The `selected` property is a Boolean whose value is `true` if the
track is active. Only a single video track can be active at any given time, so setting
this property to `true` for one track while another track is active will make
that other track inactive.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/videotrack | data/mdn-content/files/en-us/web/api/videotrack/language/index.md | ---
title: "VideoTrack: language property"
short-title: language
slug: Web/API/VideoTrack/language
page-type: web-api-instance-property
browser-compat: api.VideoTrack.language
---
{{APIRef("HTML DOM")}}
The read-only **{{domxref("VideoTrack")}}**
property **`language`** returns a string identifying the
language used in the video track.
For tracks that include multiple languages
(such as a movie in English in which a few lines are spoken in other languages), this
should be the video's primary language.
## Value
A string specifying the BCP 47 ({{RFC(5646)}}) format language tag of
the primary language used in the video track, or an empty string (`""`) if
the language is not specified or known, or if the track doesn't contain speech.
For example, if the primary language used in the track is United States English, this
value would be `"en-US"`. For Brazilian Portuguese, the value would be
`"pt-BR"`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/videotrack | data/mdn-content/files/en-us/web/api/videotrack/id/index.md | ---
title: "VideoTrack: id property"
short-title: id
slug: Web/API/VideoTrack/id
page-type: web-api-instance-property
browser-compat: api.VideoTrack.id
---
{{APIRef("HTML DOM")}}
The **`id`** property contains a
string which uniquely identifies the track represented by the
**{{domxref("VideoTrack")}}**.
This ID can be used with the
{{domxref("VideoTrackList.getTrackById()")}} method to locate a specific track within
the media associated with a media element.
The track ID can also be used as the fragment of a URL that loads the specific track
(if the media supports media fragments).
## Value
A string which identifies the track, suitable for use when calling
{{domxref("VideoTrackList.getTrackById", "getTrackById()")}} on an
{{domxref("VideoTrackList")}} such as the one specified by a media element's
{{domxref("HTMLMediaElement.videoTracks", "videoTracks")}} property.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/videotrack | data/mdn-content/files/en-us/web/api/videotrack/label/index.md | ---
title: "VideoTrack: label property"
short-title: label
slug: Web/API/VideoTrack/label
page-type: web-api-instance-property
browser-compat: api.VideoTrack.label
---
{{APIRef("HTML DOM")}}
The read-only **{{domxref("VideoTrack")}}**
property **`label`** returns a string specifying the video
track's human-readable label, if one is available; otherwise, it returns an empty
string.
## Value
A string specifying the track's human-readable label, if one is
available in the track metadata. Otherwise, an empty string (`""`) is
returned.
For example, a track whose {{domxref("VideoTrack.kind", "kind")}} is
`"sign"` might have a `label` such as
`"A sign-language interpretation."`.
## Examples
This example returns an array of track kinds and labels for potential use in a user
interface to select video tracks for a specified media element. The list is filtered to
only allow certain track kinds through.
```js
function getTrackList(el) {
const trackList = [];
const wantedKinds = ["main", "alternative", "commentary"];
el.videoTracks.forEach((track) => {
if (wantedKinds.includes(track.kind)) {
trackList.push({
id: track.id,
kind: track.kind,
label: track.label,
});
}
});
return trackList;
}
```
The resulting `trackList` contains an array of video tracks whose
`kind` is one of those in the array `wantedKinds`, with each entry
providing the track's {{domxref("VideoTrack.id", "id")}}, {{domxref("VideoTrack.kind",
"kind")}}, and {{domxref("VideoTrack.label", "label")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/videotrack | data/mdn-content/files/en-us/web/api/videotrack/kind/index.md | ---
title: "VideoTrack: kind property"
short-title: kind
slug: Web/API/VideoTrack/kind
page-type: web-api-instance-property
browser-compat: api.VideoTrack.kind
---
{{APIRef("HTML DOM")}}
The **`kind`** property contains a
string indicating the category of video contained in the
**{{domxref("VideoTrack")}}**.
The `kind` can be used
to determine the scenarios in which specific tracks should be enabled or disabled. See
[Video track kind strings](#video_track_kind_strings) for a list of the kinds available for video tracks.
## Value
A string specifying the type of content the media represents. The
string is one of those found in [Video track kind strings](#video_track_kind_strings) below.
## Video track kind strings
The kinds available for video tracks are:
- `"alternative"`
- : A potential alternative to the main track, such as a different video take or a
version of the soundtrack with only the music and no dialogue.
- `"captions"`
- : A version of the main video track with captions burnt in.
- `"main"`
- : The primary video track.
- `"sign"`
- : A sign-language interpretation of an audio track.
- `"subtitles"`
- : A version of the main video track with subtitles burnt in.
- `"commentary"`
- : A video track containing a commentary. This might be used to contain the director's
commentary track on a movie, for example.
- `""` (empty string)
- : The track doesn't have an explicit kind, or the kind provided by the track's
metadata isn't recognized by the {{Glossary("user agent")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/videotrack | data/mdn-content/files/en-us/web/api/videotrack/sourcebuffer/index.md | ---
title: "VideoTrack: sourceBuffer property"
short-title: sourceBuffer
slug: Web/API/VideoTrack/sourceBuffer
page-type: web-api-instance-property
browser-compat: api.VideoTrack.sourceBuffer
---
{{APIRef("HTML DOM")}}
The read-only **{{domxref("VideoTrack")}}**
property **`sourceBuffer`** returns the
{{domxref("SourceBuffer")}} that created the track, or null if the track was not
created by a {{domxref("SourceBuffer")}} or the {{domxref("SourceBuffer")}} has been
removed from the {{domxref("MediaSource.sourceBuffers")}} attribute of its parent
media source.
## Value
A {{domxref("SourceBuffer")}} or null.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/baseaudiocontext/index.md | ---
title: BaseAudioContext
slug: Web/API/BaseAudioContext
page-type: web-api-interface
browser-compat: api.BaseAudioContext
---
{{APIRef("Web Audio API")}}
The `BaseAudioContext` interface of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) acts as a base definition for online and offline audio-processing graphs, as represented by {{domxref("AudioContext")}} and {{domxref("OfflineAudioContext")}} respectively. You wouldn't use `BaseAudioContext` directly — you'd use its features via one of these two inheriting interfaces.
A `BaseAudioContext` can be a target of events, therefore it implements the {{domxref("EventTarget")}} interface.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("BaseAudioContext.audioWorklet")}} {{ReadOnlyInline}} {{securecontext_inline}}
- : Returns the {{domxref("AudioWorklet")}} object, which can be used to create and manage {{domxref("AudioNode")}}s in which JavaScript code implementing the {{domxref("AudioWorkletProcessor")}} interface are run in the background to process audio data.
- {{domxref("BaseAudioContext.currentTime")}} {{ReadOnlyInline}}
- : Returns a double representing an ever-increasing hardware time in seconds used for scheduling. It starts at `0`.
- {{domxref("BaseAudioContext.destination")}} {{ReadOnlyInline}}
- : Returns an {{domxref("AudioDestinationNode")}} representing the final destination of all audio in the context. It can be thought of as the audio-rendering device.
- {{domxref("BaseAudioContext.listener")}} {{ReadOnlyInline}}
- : Returns the {{domxref("AudioListener")}} object, used for 3D spatialization.
- {{domxref("BaseAudioContext.sampleRate")}} {{ReadOnlyInline}}
- : Returns a float representing the sample rate (in samples per second) used by all nodes in this context. The sample-rate of an {{domxref("AudioContext")}} cannot be changed.
- {{domxref("BaseAudioContext.state")}} {{ReadOnlyInline}}
- : Returns the current state of the `AudioContext`.
## Instance methods
_Also implements methods from the interface_ {{domxref("EventTarget")}}.
- {{domxref("BaseAudioContext.createAnalyser()")}}
- : Creates an {{domxref("AnalyserNode")}}, which can be used to expose audio time and frequency data and for example to create data visualizations.
- {{domxref("BaseAudioContext.createBiquadFilter()")}}
- : Creates a {{domxref("BiquadFilterNode")}}, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc
- {{domxref("BaseAudioContext.createBuffer()")}}
- : Creates a new, empty {{ domxref("AudioBuffer") }} object, which can then be populated by data and played via an {{ domxref("AudioBufferSourceNode") }}.
- {{domxref("BaseAudioContext.createBufferSource()")}}
- : Creates an {{domxref("AudioBufferSourceNode")}}, which can be used to play and manipulate audio data contained within an {{ domxref("AudioBuffer") }} object. {{ domxref("AudioBuffer") }}s are created using {{domxref("BaseAudioContext/createBuffer", "AudioContext.createBuffer()")}} or returned by {{domxref("BaseAudioContext/decodeAudioData", "AudioContext.decodeAudioData()")}} when it successfully decodes an audio track.
- {{domxref("BaseAudioContext.createConstantSource()")}}
- : Creates a {{domxref("ConstantSourceNode")}} object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value.
- {{domxref("BaseAudioContext.createChannelMerger()")}}
- : Creates a {{domxref("ChannelMergerNode")}}, which is used to combine channels from multiple audio streams into a single audio stream.
- {{domxref("BaseAudioContext.createChannelSplitter()")}}
- : Creates a {{domxref("ChannelSplitterNode")}}, which is used to access the individual channels of an audio stream and process them separately.
- {{domxref("BaseAudioContext.createConvolver()")}}
- : Creates a {{domxref("ConvolverNode")}}, which can be used to apply convolution effects to your audio graph, for example a reverberation effect.
- {{domxref("BaseAudioContext.createDelay()")}}
- : Creates a {{domxref("DelayNode")}}, which is used to delay the incoming audio signal by a certain amount. This node is also useful to create feedback loops in a Web Audio API graph.
- {{domxref("BaseAudioContext.createDynamicsCompressor()")}}
- : Creates a {{domxref("DynamicsCompressorNode")}}, which can be used to apply acoustic compression to an audio signal.
- {{domxref("BaseAudioContext.createGain()")}}
- : Creates a {{domxref("GainNode")}}, which can be used to control the overall volume of the audio graph.
- {{domxref("BaseAudioContext.createIIRFilter()")}}
- : Creates an {{domxref("IIRFilterNode")}}, which represents a second order filter configurable as several different common filter types.
- {{domxref("BaseAudioContext.createOscillator()")}}
- : Creates an {{domxref("OscillatorNode")}}, a source representing a periodic waveform. It basically generates a tone.
- {{domxref("BaseAudioContext.createPanner()")}}
- : Creates a {{domxref("PannerNode")}}, which is used to spatialize an incoming audio stream in 3D space.
- {{domxref("BaseAudioContext.createPeriodicWave()")}}
- : Creates a {{domxref("PeriodicWave")}}, used to define a periodic waveform that can be used to determine the output of an {{ domxref("OscillatorNode") }}.
- {{domxref("BaseAudioContext.createScriptProcessor()")}} {{deprecated_inline}}
- : Creates a {{domxref("ScriptProcessorNode")}}, which can be used for direct audio processing via JavaScript.
- {{domxref("BaseAudioContext.createStereoPanner()")}}
- : Creates a {{domxref("StereoPannerNode")}}, which can be used to apply stereo panning to an audio source.
- {{domxref("BaseAudioContext.createWaveShaper()")}}
- : Creates a {{domxref("WaveShaperNode")}}, which is used to implement non-linear distortion effects.
- {{domxref("BaseAudioContext.decodeAudioData()")}}
- : Asynchronously decodes audio file data contained in an {{jsxref("ArrayBuffer")}}. In this case, the `ArrayBuffer` is usually loaded from an {{domxref("XMLHttpRequest")}}'s `response` attribute after setting the `responseType` to `arraybuffer`. This method only works on complete files, not fragments of audio files.
## Events
- {{domxref("BaseAudioContext.statechange_event", "statechange")}}
- : Fired when the `AudioContext`'s state changes due to the calling of one of the state change methods ({{domxref("AudioContext.suspend")}}, {{domxref("AudioContext.resume")}}, or {{domxref("AudioContext.close")}}).
## Examples
Basic audio context declaration:
```js
const audioContext = new AudioContext();
```
Cross browser variant:
```js
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioContext = new AudioContext();
const oscillatorNode = audioContext.createOscillator();
const gainNode = audioContext.createGain();
const finish = audioContext.destination;
```
## 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("AudioContext")}}
- {{domxref("OfflineAudioContext")}}
| 0 |
data/mdn-content/files/en-us/web/api/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createstereopanner/index.md | ---
title: "BaseAudioContext: createStereoPanner() method"
short-title: createStereoPanner()
slug: Web/API/BaseAudioContext/createStereoPanner
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createStereoPanner
---
{{ APIRef("Web Audio API") }}
The `createStereoPanner()` method of the {{ domxref("BaseAudioContext") }} interface creates a {{ domxref("StereoPannerNode") }}, which can be used to apply
stereo panning to an audio source.
It positions an incoming audio stream in a stereo image using a [low-cost panning algorithm](https://webaudio.github.io/web-audio-api/#stereopanner-algorithm).
> **Note:** The {{domxref("StereoPannerNode.StereoPannerNode", "StereoPannerNode()")}}
> constructor is the recommended way to create a {{domxref("StereoPannerNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createStereoPanner()
```
### Parameters
None.
### Return value
A {{domxref("StereoPannerNode")}}.
## Examples
In our [StereoPannerNode example](https://mdn.github.io/webaudio-examples/stereo-panner-node/) ([see source code](https://github.com/mdn/webaudio-examples/tree/main/stereo-panner-node)) HTML we have a simple {{htmlelement("audio")}} element along with a
slider {{HTMLElement("input")}} to increase and decrease pan value. In the JavaScript we
create a {{domxref("MediaElementAudioSourceNode")}} and a
{{domxref("StereoPannerNode")}}, and connect the two together using the
`connect()` method. We then use an `oninput` event handler to
change the value of the {{domxref("StereoPannerNode.pan")}} parameter and update the pan
value display when the slider is moved.
Moving the slider left and right while the music is playing pans the music across to
the left and right speakers of the output, respectively.
```js
const audioCtx = new AudioContext();
const myAudio = document.querySelector("audio");
const panControl = document.querySelector(".panning-control");
const panValue = document.querySelector(".panning-value");
// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);
// Create a stereo panner
const panNode = audioCtx.createStereoPanner();
// Event handler function to increase panning to the right and left
// when the slider is moved
panControl.oninput = () => {
panNode.pan.setValueAtTime(panControl.value, audioCtx.currentTime);
panValue.innerHTML = panControl.value;
};
// connect the MediaElementAudioSourceNode to the panNode
// and the panNode to the destination, so we can play the
// music and adjust the panning using the controls
source.connect(panNode);
panNode.connect(audioCtx.destination);
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createconstantsource/index.md | ---
title: "BaseAudioContext: createConstantSource() method"
short-title: createConstantSource()
slug: Web/API/BaseAudioContext/createConstantSource
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createConstantSource
---
{{APIRef("Web Audio API")}}
The **`createConstantSource()`**
property of the {{domxref("BaseAudioContext")}} interface creates a
{{domxref("ConstantSourceNode")}} object, which is an audio source that continuously
outputs a monaural (one-channel) sound signal whose samples all have the same
value.
> **Note:** The {{domxref("ConstantSourceNode.ConstantSourceNode", "ConstantSourceNode()")}}
> constructor is the recommended way to create a {{domxref("ConstantSourceNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createConstantSource()
```
### Parameters
None.
### Return value
A {{domxref('ConstantSourceNode')}} instance.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createwaveshaper/index.md | ---
title: "BaseAudioContext: createWaveShaper() method"
short-title: createWaveShaper()
slug: Web/API/BaseAudioContext/createWaveShaper
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createWaveShaper
---
{{ APIRef("Web Audio API") }}
The `createWaveShaper()` method of the {{ domxref("BaseAudioContext") }}
interface creates a {{ domxref("WaveShaperNode") }}, which represents a non-linear
distortion. It is used to apply distortion effects to your audio.
> **Note:** The {{domxref("WaveShaperNode.WaveShaperNode", "WaveShaperNode()")}}
> constructor is the recommended way to create a {{domxref("WaveShaperNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createWaveShaper()
```
### Parameters
None.
### Return value
A {{domxref("WaveShaperNode")}}.
## Examples
The following example shows basic usage of an AudioContext to create a wave shaper node.
For more complete applied examples/information, check out our [Voice-change-O-matic](https://github.com/mdn/webaudio-examples/tree/main/voice-change-o-matic) demo (see [app.js lines 108–193](https://github.com/mdn/webaudio-examples/blob/main/voice-change-o-matic/scripts/app.js#L108-L193) for relevant code).
> **Note:** Sigmoid functions are commonly used for distortion curves
> because of their natural properties. Their S-shape, for instance, helps create a
> smoother sounding result. We found the below distortion curve code on [Stack Overflow](https://stackoverflow.com/questions/22312841/waveshaper-node-in-webaudio-how-to-emulate-distortion).
```js
const audioCtx = new AudioContext();
const distortion = audioCtx.createWaveShaper();
// …
function makeDistortionCurve(amount) {
const k = typeof amount === "number" ? amount : 50;
const n_samples = 44100;
const curve = new Float32Array(n_samples);
const deg = Math.PI / 180;
for (let i = 0; i < n_samples; i++) {
const x = (i * 2) / n_samples - 1;
curve[i] = ((3 + k) * x * 20 * deg) / (Math.PI + k * Math.abs(x));
}
return curve;
}
// …
distortion.curve = makeDistortionCurve(400);
distortion.oversample = "4x";
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/currenttime/index.md | ---
title: "BaseAudioContext: currentTime property"
short-title: currentTime
slug: Web/API/BaseAudioContext/currentTime
page-type: web-api-instance-property
browser-compat: api.BaseAudioContext.currentTime
---
{{ APIRef("Web Audio API") }}
The `currentTime` read-only property of the {{ domxref("BaseAudioContext") }}
interface returns a double representing an ever-increasing hardware timestamp in seconds that
can be used for scheduling audio playback, visualizing timelines, etc. It starts at 0.
## Value
A floating point number.
## Examples
```js
const audioCtx = new AudioContext();
// Older webkit/blink browsers require a prefix
// …
console.log(audioCtx.currentTime);
```
## Reduced time precision
To offer protection against timing attacks and [fingerprinting](/en-US/docs/Glossary/Fingerprinting), the precision of
`audioCtx.currentTime` 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
audioCtx.currentTime;
// 23.404
// 24.192
// 25.514
// …
// reduced time precision with `privacy.resistFingerprinting` enabled
audioCtx.currentTime;
// 49.8
// 50.6
// 51.7
// …
```
In Firefox, you can also enabled `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
- [Using Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createbuffer/index.md | ---
title: "BaseAudioContext: createBuffer() method"
short-title: createBuffer()
slug: Web/API/BaseAudioContext/createBuffer
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createBuffer
---
{{ APIRef("Web Audio API") }}
The `createBuffer()` method of the {{ domxref("BaseAudioContext") }}
Interface is used to create a new, empty {{ domxref("AudioBuffer") }} object, which
can then be populated by data, and played via an {{ domxref("AudioBufferSourceNode")
}}
For more details about audio buffers, check out the {{ domxref("AudioBuffer") }}
reference page.
> **Note:** `createBuffer()` used to be able to take compressed
> data and give back decoded samples, but this ability was removed from the specification,
> because all the decoding was done on the main thread, so
> `createBuffer()` was blocking other code execution. The asynchronous method
> `decodeAudioData()` does the same thing — takes compressed audio, such as an
> MP3 file, and directly gives you back an {{ domxref("AudioBuffer") }} that you can
> then play via an {{ domxref("AudioBufferSourceNode") }}. For simple use cases
> like playing an MP3, `decodeAudioData()` is what you should be using.
## Syntax
```js-nolint
createBuffer(numOfChannels, length, sampleRate)
```
### Parameters
> **Note:** For an in-depth explanation of how audio buffers work, and
> what these parameters mean, read [Audio buffers: frames, samples and channels](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#audio_buffers.3a_frames.2c_samples_and_channels) from our Basic concepts guide.
- `numOfChannels`
- : An integer representing the number of channels this buffer should have. The default
value is 1, and all user agents must support at least 32 channels.
- `length`
- : An integer representing the size of the buffer in sample-frames (where each
sample-frame is the size of a sample in bytes multiplied by
`numOfChannels`). To determine the `length` to use for a
specific number of seconds of audio, use `numSeconds * sampleRate`.
- `sampleRate`
- : The sample rate of the linear audio data in sample-frames per second. All browsers
must support sample rates in at least the range 8,000 Hz to 96,000 Hz.
### Return value
An {{domxref("AudioBuffer")}} configured based on the specified options.
### Exceptions
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if one or more of the options are negative or otherwise has an invalid value (such as
`numberOfChannels` being higher than supported, or a
`sampleRate` outside the nominal range).
- {{jsxref("RangeError")}}
- : Thrown if there isn't enough memory available to allocate the buffer.
## Examples
First, a couple of simple trivial examples, to help explain how the parameters are
used:
```js
const audioCtx = new AudioContext();
const buffer = audioCtx.createBuffer(2, 22050, 44100);
```
If you use this call, you will get a stereo buffer (two channels), that, when played
back on an AudioContext running at 44100Hz (very common, most normal sound cards run at
this rate), will last for 0.5 seconds: 22050 frames / 44100Hz = 0.5 seconds.
```js
const audioCtx = new AudioContext();
const buffer = audioCtx.createBuffer(1, 22050, 22050);
```
If you use this call, you will get a mono buffer (one channel), that, when played back
on an `AudioContext` running at 44100Hz, will be automatically \*resampled\* to
44100Hz (and therefore yield 44100 frames), and last for 1.0 second: 44100 frames /
44100Hz = 1 second.
> **Note:** audio resampling is very similar to image resizing: say you've
> got a 16 x 16 image, but you want it to fill a 32x32 area: you resize (resample) it.
> the result has less quality (it can be blurry or edgy, depending on the resizing
> algorithm), but it works, and the resized image takes up less space. Resampled audio
> is exactly the same — you save space, but in practice you will be unable to properly
> reproduce high frequency content (treble sound).
Now let's look at a more complex `createBuffer()` example, in which we
create a three-second buffer, fill it with white noise, and then play it via an {{
domxref("AudioBufferSourceNode") }}. The comment should clearly explain what is going
on. You can also [run the code live](https://mdn.github.io/webaudio-examples/audio-buffer/), or [view the source](https://github.com/mdn/webaudio-examples/blob/main/audio-buffer/index.html).
```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
// Create an empty three-second stereo buffer at the sample rate of the AudioContext
const myArrayBuffer = audioCtx.createBuffer(
2,
audioCtx.sampleRate * 3,
audioCtx.sampleRate,
);
// Fill the buffer with white noise;
// just random values between -1.0 and 1.0
for (let channel = 0; channel < myArrayBuffer.numberOfChannels; channel++) {
// This gives us the actual ArrayBuffer that contains the data
const nowBuffering = myArrayBuffer.getChannelData(channel);
for (let i = 0; i < myArrayBuffer.length; i++) {
// Math.random() is in [0; 1.0]
// audio needs to be in [-1.0; 1.0]
nowBuffering[i] = Math.random() * 2 - 1;
}
}
// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
const source = audioCtx.createBufferSource();
// set the buffer in the AudioBufferSourceNode
source.buffer = myArrayBuffer;
// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioCtx.destination);
// start the source playing
source.start();
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createscriptprocessor/index.md | ---
title: "BaseAudioContext: createScriptProcessor() method"
short-title: createScriptProcessor()
slug: Web/API/BaseAudioContext/createScriptProcessor
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.BaseAudioContext.createScriptProcessor
---
{{APIRef("Web Audio API")}}{{deprecated_header}}
The `createScriptProcessor()` method of the {{domxref("BaseAudioContext")}} interface
creates a {{domxref("ScriptProcessorNode")}} used for direct audio processing.
> **Note:** This feature was replaced by [AudioWorklets](/en-US/docs/Web/API/AudioWorklet) and the {{domxref("AudioWorkletNode")}} interface.
## Syntax
```js-nolint
createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels)
```
### Parameters
- `bufferSize`
- : The buffer size in units of sample-frames. If specified, the bufferSize must be one
of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. If it's not passed
in, or if the value is 0, then the implementation will choose the best buffer size for
the given environment, which will be a constant power of 2 throughout the lifetime of
the node.
This value controls how frequently the `audioprocess` event is dispatched
and how many sample-frames need to be processed each call. Lower values for
`bufferSize` will result in a lower (better) latency. Higher values will be
necessary to avoid audio breakup and glitches. It is recommended for authors to not
specify this buffer size and allow the implementation to pick a good buffer size to
balance between latency and audio quality.
- `numberOfInputChannels`
- : Integer specifying the number of channels for this node's input, defaults to 2.
Values of up to 32 are supported.
- `numberOfOutputChannels`
- : Integer specifying the number of channels for this node's output, defaults to 2.
Values of up to 32 are supported.
> **Warning:** Webkit currently (version 31) requires that a valid
> `bufferSize` be passed when calling this method.
> **Note:** It is invalid for both `numberOfInputChannels` and
> `numberOfOutputChannels` to be zero.
### Return value
A {{domxref("ScriptProcessorNode")}}.
## Examples
### Adding white noise using a script processor
The following example shows how to use a `ScriptProcessorNode` to take a track loaded via {{domxref("BaseAudioContext/decodeAudioData", "AudioContext.decodeAudioData()")}}, process it, adding a bit of white noise to each audio sample of the input track, and play it through the {{domxref("AudioDestinationNode")}}.
For each channel and each sample frame, the script node's {{domxref("ScriptProcessorNode.audioprocess_event", "audioprocess")}} event handler uses the associated `audioProcessingEvent` to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case.
> **Note:** You can [run the full example live](https://mdn.github.io/webaudio-examples/script-processor-node/), or [view the source](https://github.com/mdn/webaudio-examples/blob/main/script-processor-node/).
```js
const myScript = document.querySelector("script");
const myPre = document.querySelector("pre");
const playButton = document.querySelector("button");
// Create AudioContext and buffer source
let audioCtx;
async function init() {
audioCtx = new AudioContext();
const source = audioCtx.createBufferSource();
// Create a ScriptProcessorNode with a bufferSize of 4096 and
// a single input and output channel
const scriptNode = audioCtx.createScriptProcessor(4096, 1, 1);
// Load in an audio track using fetch() and decodeAudioData()
try {
const response = await fetch("viper.ogg");
const arrayBuffer = await response.arrayBuffer();
source.buffer = await audioCtx.decodeAudioData(arrayBuffer);
} catch (err) {
console.error(
`Unable to fetch the audio file: ${name} Error: ${err.message}`,
);
}
// Give the node a function to process audio events
scriptNode.addEventListener("audioprocess", (audioProcessingEvent) => {
// The input buffer is the song we loaded earlier
let inputBuffer = audioProcessingEvent.inputBuffer;
// The output buffer contains the samples that will be modified and played
let outputBuffer = audioProcessingEvent.outputBuffer;
// Loop through the output channels (in this case there is only one)
for (let channel = 0; channel < outputBuffer.numberOfChannels; channel++) {
let inputData = inputBuffer.getChannelData(channel);
let outputData = outputBuffer.getChannelData(channel);
// Loop through the 4096 samples
for (let sample = 0; sample < inputBuffer.length; sample++) {
// make output equal to the same as the input
outputData[sample] = inputData[sample];
// add noise to each output sample
outputData[sample] += (Math.random() * 2 - 1) * 0.1;
}
}
});
source.connect(scriptNode);
scriptNode.connect(audioCtx.destination);
source.start();
// When the buffer source stops playing, disconnect everything
source.addEventListener("ended", () => {
source.disconnect(scriptNode);
scriptNode.disconnect(audioCtx.destination);
});
}
// wire up play button
playButton.addEventListener("click", () => {
if (!audioCtx) {
init();
}
});
```
## Specifications
Since the August 29 2014 [Web Audio API specification](https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createscriptprocessor) publication, this feature has been deprecated. It is no longer on track to become a standard.
It was replaced by [AudioWorklets](/en-US/docs/Web/API/AudioWorklet) and the {{domxref("AudioWorkletNode")}} interface.
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createbiquadfilter/index.md | ---
title: "BaseAudioContext: createBiquadFilter() method"
short-title: createBiquadFilter()
slug: Web/API/BaseAudioContext/createBiquadFilter
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createBiquadFilter
---
{{ APIRef("Web Audio API") }}
The `createBiquadFilter()` method of the {{ domxref("BaseAudioContext") }}
interface creates a {{ domxref("BiquadFilterNode") }}, which represents a second order
filter configurable as several different common filter types.
> **Note:** The {{domxref("BiquadFilterNode.BiquadFilterNode", "BiquadFilterNode()")}} constructor is the
> recommended way to create a {{domxref("BiquadFilterNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createBiquadFilter()
```
### Parameters
None.
### Return value
A {{domxref("BiquadFilterNode")}}.
## Examples
The following example shows basic usage of an AudioContext to create a Biquad filter node.
For more complete applied examples/information, check out our [Voice-change-O-matic](https://github.com/mdn/webaudio-examples/tree/main/voice-change-o-matic) demo (see [app.js lines 108–193](https://github.com/mdn/webaudio-examples/blob/main/voice-change-o-matic/scripts/app.js#L108-L193) for relevant code).
```js
const audioCtx = new AudioContext();
//set up the different audio nodes we will use for the app
const analyser = audioCtx.createAnalyser();
const distortion = audioCtx.createWaveShaper();
const gainNode = audioCtx.createGain();
const biquadFilter = audioCtx.createBiquadFilter();
const convolver = audioCtx.createConvolver();
// connect the nodes together
source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);
analyser.connect(distortion);
distortion.connect(biquadFilter);
biquadFilter.connect(convolver);
convolver.connect(gainNode);
gainNode.connect(audioCtx.destination);
// Manipulate the Biquad filter
biquadFilter.type = "lowshelf";
biquadFilter.frequency.setValueAtTime(1000, audioCtx.currentTime);
biquadFilter.gain.setValueAtTime(25, audioCtx.currentTime);
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createchannelmerger/index.md | ---
title: "BaseAudioContext: createChannelMerger() method"
short-title: createChannelMerger()
slug: Web/API/BaseAudioContext/createChannelMerger
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createChannelMerger
---
{{ APIRef("Web Audio API") }}
The `createChannelMerger()` method of the {{domxref("BaseAudioContext")}} interface creates a {{domxref("ChannelMergerNode")}},
which combines channels from multiple audio streams into a single audio stream.
> **Note:** The {{domxref("ChannelMergerNode.ChannelMergerNode", "ChannelMergerNode()")}} constructor is the
> recommended way to create a {{domxref("ChannelMergerNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createChannelMerger(numberOfInputs)
```
### Parameters
- `numberOfInputs`
- : The number of channels in the input audio streams, which the output stream will
contain; the default is 6 if this parameter is not specified.
### Return value
A {{domxref("ChannelMergerNode")}}.
## Examples
The following example shows how you could separate a stereo track (say, a piece of
music), and process the left and right channel differently. To use them, you need to use
the second and third parameters of the {{domxref("AudioNode/connect", "AudioNode.connect(AudioNode)")}}
method, which allow you to specify both the index of the channel to connect from and the
index of the channel to connect to.
```js
const ac = new AudioContext();
ac.decodeAudioData(someStereoBuffer, (data) => {
const source = ac.createBufferSource();
source.buffer = data;
const splitter = ac.createChannelSplitter(2);
source.connect(splitter);
const merger = ac.createChannelMerger(2);
// Reduce the volume of the left channel only
const gainNode = ac.createGain();
gainNode.gain.setValueAtTime(0.5, ac.currentTime);
splitter.connect(gainNode, 0);
// Connect the splitter back to the second input of the merger: we
// effectively swap the channels, here, reversing the stereo image.
gainNode.connect(merger, 0, 1);
splitter.connect(merger, 1, 0);
const dest = ac.createMediaStreamDestination();
// Because we have used a ChannelMergerNode, we now have a stereo
// MediaStream we can use to pipe the Web Audio graph to WebRTC,
// MediaRecorder, etc.
merger.connect(dest);
});
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/destination/index.md | ---
title: "BaseAudioContext: destination property"
short-title: destination
slug: Web/API/BaseAudioContext/destination
page-type: web-api-instance-property
browser-compat: api.BaseAudioContext.destination
---
{{ APIRef("Web Audio API") }}
The `destination` property of the {{ domxref("BaseAudioContext") }}
interface returns an {{ domxref("AudioDestinationNode") }} representing the final
destination of all audio in the context. It often represents an actual audio-rendering
device such as your device's speakers.
## Value
An {{ domxref("AudioDestinationNode") }}.
## Examples
> **Note:** For more complete applied examples/information, check out our [Voice-change-O-matic](https://github.com/mdn/webaudio-examples/tree/main/voice-change-o-matic) demo (see [app.js lines 108–193](https://github.com/mdn/webaudio-examples/blob/main/voice-change-o-matic/scripts/app.js#L108-L193) for relevant code).
```js
const audioCtx = new AudioContext();
// Older webkit/blink browsers require a prefix
const oscillatorNode = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillatorNode.connect(gainNode);
gainNode.connect(audioCtx.destination);
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createoscillator/index.md | ---
title: "BaseAudioContext: createOscillator() method"
short-title: createOscillator()
slug: Web/API/BaseAudioContext/createOscillator
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createOscillator
---
{{APIRef("Web Audio API")}}
The `createOscillator()` method of the {{domxref("BaseAudioContext")}}
interface creates an {{domxref("OscillatorNode")}}, a source representing a periodic
waveform. It basically generates a constant tone.
> **Note:** The {{domxref("OscillatorNode.OscillatorNode", "OscillatorNode()")}}
> constructor is the recommended way to create a {{domxref("OscillatorNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createOscillator()
```
### Parameters
None.
### Return value
An {{domxref("OscillatorNode")}}.
## Examples
The following example shows basic usage of an AudioContext to create an oscillator
node. For applied examples/information, check out our [Violent Theremin demo](https://mdn.github.io/webaudio-examples/violent-theremin/) ([see app.js](https://github.com/mdn/webaudio-examples/blob/main/violent-theremin/scripts/app.js) for relevant code); also see our {{domxref("OscillatorNode")}} page for
more information.
```js
// create web audio api context
const audioCtx = new AudioContext();
// create Oscillator node
const oscillator = audioCtx.createOscillator();
oscillator.type = "square";
oscillator.frequency.setValueAtTime(3000, audioCtx.currentTime); // value in hertz
oscillator.connect(audioCtx.destination);
oscillator.start();
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createiirfilter/index.md | ---
title: "BaseAudioContext: createIIRFilter() method"
short-title: createIIRFilter()
slug: Web/API/BaseAudioContext/createIIRFilter
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createIIRFilter
---
{{ APIRef("Web Audio API") }}
The **`createIIRFilter()`** method of the {{
domxref("BaseAudioContext") }} interface creates an {{ domxref("IIRFilterNode") }},
which represents a general **[infinite impulse response](https://en.wikipedia.org/wiki/Infinite_impulse_response)** (IIR) filter which can be configured to serve as various types
of filter.
> **Note:** The {{domxref("IIRFilterNode.IIRFilterNode", "IIRFilterNode()")}}
> constructor is the recommended way to create a {{domxref("IIRFilterNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createIIRFilter(feedforward, feedback)
```
### Parameters
- `feedforward`
- : An array of floating-point values specifying the feedforward (numerator)
coefficients for the transfer function of the IIR filter. The maximum length of this
array is 20, and at least one value must be nonzero.
- `feedback`
- : An array of floating-point values specifying the feedback (denominator) coefficients
for the transfer function of the IIR filter. This array may have up to 20 members, the
first of which must not be zero.
### Return value
An {{domxref("IIRFilterNode")}} implementing the filter with the specified feedback and
feedforward coefficient arrays.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if all of the `feedforward` coefficients are 0, or if the first
`feedback` coefficient is 0.
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if one or both of the input arrays exceeds 20 members.
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createdynamicscompressor/index.md | ---
title: "BaseAudioContext: createDynamicsCompressor() method"
short-title: createDynamicsCompressor()
slug: Web/API/BaseAudioContext/createDynamicsCompressor
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createDynamicsCompressor
---
{{ APIRef("Web Audio API") }}
The `createDynamicsCompressor()` method of the {{
domxref("BaseAudioContext") }} Interface is used to create a
{{domxref("DynamicsCompressorNode")}}, which can be used to apply compression to an
audio signal.
Compression lowers the volume of the loudest parts of the signal and raises the volume
of the softest parts. Overall, a louder, richer, and fuller sound can be achieved. It is
especially important in games and musical applications where large numbers of individual
sounds are played simultaneously, where you want to control the overall signal level and
help avoid clipping (distorting) of the audio output.
> **Note:** The {{domxref("DynamicsCompressorNode.DynamicsCompressorNode", "DynamicsCompressorNode()")}}
> constructor is the recommended way to create a {{domxref("DynamicsCompressorNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createDynamicsCompressor()
```
### Parameters
None.
### Return value
A {{domxref("DynamicsCompressorNode")}}.
## Examples
The code below demonstrates a simple usage of `createDynamicsCompressor()`
to add compression to an audio track. For a more complete example, have a look at our [basic Compressor example](https://mdn.github.io/webaudio-examples/compressor-example/) ([view the source code](https://github.com/mdn/webaudio-examples/tree/main/compressor-example)).
```js
// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);
// Create a compressor node
const compressor = audioCtx.createDynamicsCompressor();
compressor.threshold.setValueAtTime(-50, audioCtx.currentTime);
compressor.knee.setValueAtTime(40, audioCtx.currentTime);
compressor.ratio.setValueAtTime(12, audioCtx.currentTime);
compressor.attack.setValueAtTime(0, audioCtx.currentTime);
compressor.release.setValueAtTime(0.25, audioCtx.currentTime);
// connect the AudioBufferSourceNode to the destination
source.connect(audioCtx.destination);
button.onclick = () => {
const active = button.getAttribute("data-active");
if (active === "false") {
button.setAttribute("data-active", "true");
button.textContent = "Remove compression";
source.disconnect(audioCtx.destination);
source.connect(compressor);
compressor.connect(audioCtx.destination);
} else if (active === "true") {
button.setAttribute("data-active", "false");
button.textContent = "Add compression";
source.disconnect(compressor);
compressor.disconnect(audioCtx.destination);
source.connect(audioCtx.destination);
}
};
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createpanner/index.md | ---
title: "BaseAudioContext: createPanner() method"
short-title: createPanner()
slug: Web/API/BaseAudioContext/createPanner
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createPanner
---
{{ APIRef("Web Audio API") }}
The `createPanner()` method of the {{ domxref("BaseAudioContext") }}
Interface is used to create a new {{domxref("PannerNode")}}, which is used to
spatialize an incoming audio stream in 3D space.
The panner node is spatialized in relation to the AudioContext's
{{domxref("AudioListener") }} (defined by the {{domxref("BaseAudioContext/listener", "AudioContext.listener")}}
attribute), which represents the position and orientation of the person listening to the
audio.
> **Note:** The {{domxref("PannerNode.PannerNode", "PannerNode()")}}
> constructor is the recommended way to create a {{domxref("PannerNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createPanner()
```
### Parameters
None.
### Return value
A {{domxref("PannerNode")}}.
## Examples
In the following example, you can see an example of how the `createPanner()`
method, {{domxref("AudioListener")}} and {{domxref("PannerNode")}} would be used to
control audio spatialization. Generally you will define the position in 3D space that
your audio listener and panner (source) occupy initially, and then update the position
of one or both of these as the application is used. You might be moving a character
around inside a game world for example, and wanting delivery of audio to change
realistically as your character moves closer to or further away from a music player such
as a stereo. In the example you can see this being controlled by the functions
`moveRight()`, `moveLeft()`, etc., which set new values for the
panner position via the `PositionPanner()` function.
To see a complete implementation, check out our [panner-node example](https://mdn.github.io/webaudio-examples/panner-node/)
([view the source code](https://github.com/mdn/webaudio-examples/tree/main/panner-node)) — this demo transports you to the 2.5D "Room of metal", where you can
play a track on a boom box and then walk around the boom box to see how the sound
changes!
Note how we have used some feature detection to either give the browser the newer
property values (like {{domxref("AudioListener.forwardX")}}) for setting position, etc.
if it supports those, or older methods (like
{{domxref("AudioListener.setOrientation()")}}) if it still supports those but not the
new properties.
```js
// set up listener and panner position information
const WIDTH = window.innerWidth;
const HEIGHT = window.innerHeight;
const xPos = Math.floor(WIDTH / 2);
const yPos = Math.floor(HEIGHT / 2);
const zPos = 295;
// define other variables
const audioCtx = new AudioContext();
const panner = audioCtx.createPanner();
panner.panningModel = "HRTF";
panner.distanceModel = "inverse";
panner.refDistance = 1;
panner.maxDistance = 10000;
panner.rolloffFactor = 1;
panner.coneInnerAngle = 360;
panner.coneOuterAngle = 0;
panner.coneOuterGain = 0;
if (panner.orientationX) {
panner.orientationX.setValueAtTime(1, audioCtx.currentTime);
panner.orientationY.setValueAtTime(0, audioCtx.currentTime);
panner.orientationZ.setValueAtTime(0, audioCtx.currentTime);
} else {
panner.setOrientation(1, 0, 0);
}
const listener = audioCtx.listener;
if (listener.forwardX) {
listener.forwardX.setValueAtTime(0, audioCtx.currentTime);
listener.forwardY.setValueAtTime(0, audioCtx.currentTime);
listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime);
listener.upX.setValueAtTime(0, audioCtx.currentTime);
listener.upY.setValueAtTime(1, audioCtx.currentTime);
listener.upZ.setValueAtTime(0, audioCtx.currentTime);
} else {
listener.setOrientation(0, 0, -1, 0, 1, 0);
}
let source;
const play = document.querySelector(".play");
const stop = document.querySelector(".stop");
const boomBox = document.querySelector(".boom-box");
const listenerData = document.querySelector(".listener-data");
const pannerData = document.querySelector(".panner-data");
leftBound = -xPos + 50;
rightBound = xPos - 50;
xIterator = WIDTH / 150;
// listener will always be in the same place for this demo
if (listener.positionX) {
listener.positionX.setValueAtTime(xPos, audioCtx.currentTime);
listener.positionY.setValueAtTime(yPos, audioCtx.currentTime);
listener.positionZ.setValueAtTime(300, audioCtx.currentTime);
} else {
listener.setPosition(xPos, yPos, 300);
}
listenerData.textContent = `Listener data: X ${xPos} Y ${yPos} Z 300`;
// panner will move as the boombox graphic moves around on the screen
function positionPanner() {
if (panner.positionX) {
panner.positionX.setValueAtTime(xPos, audioCtx.currentTime);
panner.positionY.setValueAtTime(yPos, audioCtx.currentTime);
panner.positionZ.setValueAtTime(zPos, audioCtx.currentTime);
} else {
panner.setPosition(xPos, yPos, zPos);
}
pannerData.textContent = `Panner data: X ${xPos} Y ${yPos} Z ${zPos}`;
}
```
> **Note:** In terms of working out what position values to apply to the
> listener and panner, to make the sound appropriate to what the visuals are doing on
> screen, there is quite a bit of math involved, but you will soon get used to it with a
> bit of experimentation.
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/creategain/index.md | ---
title: "BaseAudioContext: createGain() method"
short-title: createGain()
slug: Web/API/BaseAudioContext/createGain
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createGain
---
{{ APIRef("Web Audio API") }}
The `createGain()` method of the {{ domxref("BaseAudioContext") }}
interface creates a {{ domxref("GainNode") }}, which can be used to control the
overall gain (or volume) of the audio graph.
> **Note:** The {{domxref("GainNode.GainNode", "GainNode()")}}
> constructor is the recommended way to create a {{domxref("GainNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createGain()
```
### Parameters
None.
### Return value
A {{domxref("GainNode")}} which takes as input one or more audio sources and outputs
audio whose volume has been adjusted in gain (volume) to a level specified by the node's
{{domxref("GainNode.gain")}} [a-rate](/en-US/docs/Web/API/AudioParam#a-rate)
parameter.
## Examples
The following example shows basic usage of an {{domxref("AudioContext")}} to create a
`GainNode`, which is then used to mute and unmute the audio when a Mute
button is clicked by changing the `gain` property value.
The below snippet wouldn't work as is — for a complete working example, check out our
[Voice-change-O-matic](https://mdn.github.io/webaudio-examples/voice-change-o-matic/) demo ([view source](https://github.com/mdn/webaudio-examples/tree/main/voice-change-o-matic/scripts/app.js).)
```html
<div>
<button class="mute">Mute button</button>
</div>
```
```js
const audioCtx = new AudioContext();
const gainNode = audioCtx.createGain();
const mute = document.querySelector(".mute");
let source;
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(
// constraints - only audio needed for this app
{
audio: true,
},
// Success callback
(stream) => {
source = audioCtx.createMediaStreamSource(stream);
},
// Error callback
(err) => {
console.error(`The following gUM error occurred: ${err}`);
},
);
} else {
console.error("getUserMedia not supported on your browser!");
}
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
// …
mute.onclick = () => {
if (mute.id === "") {
// 0 means mute. If you still hear something, make sure you haven't
// connected your source into the output in addition to using the GainNode.
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
mute.id = "activated";
mute.textContent = "Unmute";
} else {
gainNode.gain.setValueAtTime(1, audioCtx.currentTime);
mute.id = "";
mute.textContent = "Mute";
}
};
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createchannelsplitter/index.md | ---
title: "BaseAudioContext: createChannelSplitter() method"
short-title: createChannelSplitter()
slug: Web/API/BaseAudioContext/createChannelSplitter
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createChannelSplitter
---
{{ APIRef("Web Audio API") }}
The `createChannelSplitter()` method of the {{domxref("BaseAudioContext")}} Interface is used to create a {{domxref("ChannelSplitterNode")}},
which is used to access the individual channels of an audio stream and process them separately.
> **Note:** The {{domxref("ChannelSplitterNode.ChannelSplitterNode", "ChannelSplitterNode()")}}
> constructor is the recommended way to create a {{domxref("ChannelSplitterNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createChannelSplitter(numberOfOutputs)
```
### Parameters
- `numberOfOutputs`
- : The number of channels in the input audio stream that you want to output separately;
the default is 6 if this parameter is not specified.
### Return value
A {{domxref("ChannelSplitterNode")}}.
## Examples
The following simple example shows how you could separate a stereo track (say, a piece
of music), and process the left and right channel differently. To use them, you need to
use the second and third parameters of the {{domxref("AudioNode/connect", "AudioNode.connect(AudioNode)")}}
method, which allow you to specify the index of the channel to connect from and the
index of the channel to connect to.
```js
const ac = new AudioContext();
ac.decodeAudioData(someStereoBuffer, (data) => {
const source = ac.createBufferSource();
source.buffer = data;
const splitter = ac.createChannelSplitter(2);
source.connect(splitter);
const merger = ac.createChannelMerger(2);
// Reduce the volume of the left channel only
const gainNode = ac.createGain();
gainNode.gain.setValueAtTime(0.5, ac.currentTime);
splitter.connect(gainNode, 0);
// Connect the splitter back to the second input of the merger: we
// effectively swap the channels, here, reversing the stereo image.
gainNode.connect(merger, 0, 1);
splitter.connect(merger, 1, 0);
const dest = ac.createMediaStreamDestination();
// Because we have used a ChannelMergerNode, we now have a stereo
// MediaStream we can use to pipe the Web Audio graph to WebRTC,
// MediaRecorder, etc.
merger.connect(dest);
});
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createdelay/index.md | ---
title: "BaseAudioContext: createDelay() method"
short-title: createDelay()
slug: Web/API/BaseAudioContext/createDelay
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createDelay
---
{{APIRef("Web Audio API")}}
The `createDelay()` method of the
{{domxref("BaseAudioContext")}} Interface is used to create a {{domxref("DelayNode")}},
which is used to delay the incoming audio signal by a certain amount of time.
> **Note:** The {{domxref("DelayNode.DelayNode", "DelayNode()")}}
> constructor is the recommended way to create a {{domxref("DelayNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createDelay(maxDelayTime)
```
### Parameters
- `maxDelayTime` {{optional_inline}}
- : The maximum amount of time, in seconds, that the audio signal can be delayed by.
Must be less than 180 seconds, and defaults to 1 second if not specified.
### Return value
A {{domxref("DelayNode")}}. The default {{domxref("DelayNode.delayTime")}} is 0
seconds.
## Examples
We have created a simple example that allows you to play three different samples on a
constant loop — see [create-delay](https://chrisdavidmills.github.io/create-delay/) (you can also
[view the source code](https://github.com/chrisdavidmills/create-delay)). If
you just press the play buttons, the loops will start immediately; if you slide the
sliders up to the right, then press the play buttons, a delay will be introduced, so the
looping sounds don't start playing for a short amount of time.
```js
const audioCtx = new AudioContext();
const synthDelay = audioCtx.createDelay(5.0);
// …
let synthSource;
playSynth.onclick = () => {
synthSource = audioCtx.createBufferSource();
synthSource.buffer = buffers[2];
synthSource.loop = true;
synthSource.start();
synthSource.connect(synthDelay);
synthDelay.connect(destination);
this.setAttribute("disabled", "disabled");
};
stopSynth.onclick = () => {
synthSource.disconnect(synthDelay);
synthDelay.disconnect(destination);
synthSource.stop();
playSynth.removeAttribute("disabled");
};
// …
let delay1;
rangeSynth.oninput = () => {
delay1 = rangeSynth.value;
synthDelay.delayTime.setValueAtTime(delay1, audioCtx.currentTime);
};
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/statechange_event/index.md | ---
title: "BaseAudioContext: statechange event"
short-title: statechange
slug: Web/API/BaseAudioContext/statechange_event
page-type: web-api-event
browser-compat: api.BaseAudioContext.statechange_event
---
{{APIRef("Web Audio API")}}
A `statechange` event is fired at a {{DOMxRef("BaseAudioContext")}} object when its {{domxref("BaseAudioContext.state", "state")}} member changes.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js-nolint
addEventListener("statechange", (event) => { })
onstatechange = (event) => { }
```
## Event type
A generic {{domxref("Event")}}.
## Examples
The following snippet is taken from our [AudioContext states demo](https://github.com/mdn/webaudio-examples) ([see it running live](https://mdn.github.io/webaudio-examples/audiocontext-states/).) The `onstatechange` handler is used to log the current
{{domxref("BaseAudioContext.state", "state")}} to the console every time it changes.
```js
audioCtx.onstatechange = () => {
console.log(audioCtx.state);
};
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/audioworklet/index.md | ---
title: "BaseAudioContext: audioWorklet property"
short-title: audioWorklet
slug: Web/API/BaseAudioContext/audioWorklet
page-type: web-api-instance-property
browser-compat: api.BaseAudioContext.audioWorklet
---
{{ APIRef("Web Audio API") }}{{securecontext_header}}
The `audioWorklet` read-only property of the
{{domxref("BaseAudioContext")}} interface returns an instance of
{{domxref("AudioWorklet")}} that can be used for adding
{{domxref("AudioWorkletProcessor")}}-derived classes which implement custom audio
processing.
## Value
An {{domxref("AudioWorklet")}} instance.
## Examples
_For a complete example demonstrating user-defined audio processing, see the
{{domxref("AudioWorkletNode")}} page._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- {{domxref("AudioWorkletNode")}}
| 0 |
data/mdn-content/files/en-us/web/api/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/listener/index.md | ---
title: "BaseAudioContext: listener property"
short-title: listener
slug: Web/API/BaseAudioContext/listener
page-type: web-api-instance-property
browser-compat: api.BaseAudioContext.listener
---
{{ APIRef("Web Audio API") }}
The `listener` property of the {{ domxref("BaseAudioContext") }} interface
returns an {{ domxref("AudioListener") }} object that can then be used for
implementing 3D audio spatialization.
## Value
An {{ domxref("AudioListener") }} object.
## Examples
> **Note:** for a full Web Audio spatialization example, see our [panner-node](https://github.com/mdn/webaudio-examples/tree/main/panner-node) demo.
```js
const audioCtx = new AudioContext();
// Older webkit/blink browsers require a prefix
// …
const myListener = audioCtx.listener;
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createperiodicwave/index.md | ---
title: "BaseAudioContext: createPeriodicWave() method"
short-title: createPeriodicWave()
slug: Web/API/BaseAudioContext/createPeriodicWave
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createPeriodicWave
---
{{ APIRef("Web Audio API") }}
The `createPeriodicWave()` method of the {{ domxref("BaseAudioContext") }} Interface
is used to create a {{domxref("PeriodicWave")}}, which is used to define a periodic waveform
that can be used to shape the output of an {{ domxref("OscillatorNode") }}.
## Syntax
```js-nolint
createPeriodicWave(real, imag)
createPeriodicWave(real, imag, constraints)
```
### Parameters
- `real`
- : An array of cosine terms (traditionally the A terms).
- `imag`
- : An array of sine terms (traditionally the B terms).
The `real` and `imag` arrays have to have the same length,
otherwise an error is thrown.
- `constraints` {{optional_inline}}
- : An dictionary object that specifies whether normalization should be disabled (if
not specified, normalization is enabled by default.) It takes one property:
- `disableNormalization`
- : If set to `true`,
normalization is disabled for the periodic wave. The default is
`false`.
> **Note:** If normalized, the resulting wave will have a maximum absolute peak value of 1.
### Return value
A {{domxref("PeriodicWave")}}.
## Examples
The following example illustrates simple usage of `createPeriodicWave()`, to
create a {{domxref("PeriodicWave")}} object containing a simple sine wave.
```js
const real = new Float32Array(2);
const imag = new Float32Array(2);
const ac = new AudioContext();
const osc = ac.createOscillator();
real[0] = 0;
imag[0] = 0;
real[1] = 1;
imag[1] = 0;
const wave = ac.createPeriodicWave(real, imag, { disableNormalization: true });
osc.setPeriodicWave(wave);
osc.connect(ac.destination);
osc.start();
osc.stop(2);
```
This works because a sound that contains only a fundamental tone is by definition a
sine wave
Here, we create a `PeriodicWave` with two values. The first value is the DC
offset, which is the value at which the oscillator starts. 0 is good here, because we
want to start the curve at the middle of the \[-1.0; 1.0] range.
The second and subsequent values are sine and cosine components. You can think of it as
the result of a Fourier transform, where you get frequency domain values from time
domain value. Here, with `createPeriodicWave()`, you specify the
frequencies, and the browser performs an inverse Fourier transform to get a time
domain buffer for the frequency of the oscillator. Here, we only set one component at
full volume (1.0) on the fundamental tone, so we get a sine wave. Bear in mind the
fundamental tone is the oscillator's frequency (which, by default, is 440 Hz).
Thus, by altering the oscillator's frequency we are in effect shifting the frequency
of this periodic wave along with it.
The coefficients of the Fourier transform should be given in _ascending_ order
(i.e. <math>
<semantics><mrow><mrow><mo>(</mo>
<mrow><mi>a</mi>
<mo>+</mo>
<mi>b</mi>
<mi>i</mi>
</mrow><mo>)</mo>
</mrow><msup><mi>e</mi>
<mi>i</mi>
</msup><mo>,</mo>
<mrow><mo>(</mo>
<mrow><mi>c</mi>
<mo>+</mo>
<mi>d</mi>
<mi>i</mi>
</mrow><mo>)</mo>
</mrow><msup><mi>e</mi>
<mrow><mn>2</mn>
<mi>i</mi>
</mrow></msup><mo>,</mo>
<mrow><mo>(</mo>
<mrow><mi>f</mi>
<mo>+</mo>
<mi>g</mi>
<mi>i</mi>
</mrow><mo>)</mo>
</mrow><msup><mi>e</mi>
<mrow><mn>3</mn>
<mi>i</mi>
</mrow></msup></mrow><annotation encoding="TeX">\left(a+bi\right)e^{i} , \left(c+di\right)e^{2i} ,
\left(f+gi\right)e^{3i} </annotation>
</semantics></math>etc.) and can be positive or negative. A simple way of manually obtaining such
coefficients (though not the best) is to use a graphing calculator.
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/state/index.md | ---
title: "BaseAudioContext: state property"
short-title: state
slug: Web/API/BaseAudioContext/state
page-type: web-api-instance-property
browser-compat: api.BaseAudioContext.state
---
{{ APIRef("Web Audio API") }}
The `state` read-only property of the {{ domxref("BaseAudioContext") }}
interface returns the current state of the `AudioContext`.
## Value
A string. Possible values are:
- `suspended`
- : The audio context has been suspended (with the
{{domxref("AudioContext.suspend()")}} method.)
- `running`
- : The audio context is running normally.
- `closed`
- : The audio context has been closed (with the
{{domxref("AudioContext.close()")}} method.)
## Examples
### Handling state changes
The following snippet is taken from our [AudioContext states demo](https://github.com/mdn/webaudio-examples) ([see it running live](https://mdn.github.io/webaudio-examples/audiocontext-states/).) The {{domxref("BaseAudioContext.statechange_event", "onstatechange")}} handler is used to log the
current state to the console every time it changes.
```js
audioCtx.onstatechange = () => {
console.log(audioCtx.state);
};
```
### Resuming interrupted play states in iOS Safari
In iOS Safari, when a user leaves the page (e.g. switches tabs, minimizes the browser, or
turns off the screen)
the audio context's state changes to "interrupted" and needs to be resumed. For example:
```js
function play() {
if (audioCtx.state === "interrupted") {
audioCtx.resume().then(() => play());
return;
}
// rest of the play() function
}
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/decodeaudiodata/index.md | ---
title: "BaseAudioContext: decodeAudioData() method"
short-title: decodeAudioData()
slug: Web/API/BaseAudioContext/decodeAudioData
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.decodeAudioData
---
{{ APIRef("Web Audio API") }}
The `decodeAudioData()` method of the {{ domxref("BaseAudioContext") }}
Interface is used to asynchronously decode audio file data contained in an
{{jsxref("ArrayBuffer")}} that is loaded from {{domxref("fetch()")}},
{{domxref("XMLHttpRequest")}}, or {{domxref("FileReader")}}. The decoded
{{domxref("AudioBuffer")}} is resampled to the {{domxref("AudioContext")}}'s sampling
rate, then passed to a callback or promise.
This is the preferred method of creating an audio source for Web Audio API from an
audio track. This method only works on complete file data, not fragments of audio file
data.
This function implements two alternative ways to asynchronously return the audio data or error messages: it returns a {{jsxref("Promise")}} that fulfills with the audio data, and also accepts callback arguments to handle success or failure. The primary method of interfacing with this function is via its Promise return value, and the callback parameters are provided for legacy reasons.
## Syntax
```js-nolint
// Promise-based syntax returns a Promise:
decodeAudioData(arrayBuffer)
// Callback syntax has no return value:
decodeAudioData(arrayBuffer, successCallback)
decodeAudioData(arrayBuffer, successCallback, errorCallback)
```
### Parameters
- `arrayBuffer`
- : An ArrayBuffer containing the audio data to be decoded, usually grabbed from
{{domxref("fetch()")}}, {{domxref("XMLHttpRequest")}} or {{domxref("FileReader")}}.
- `successCallback` {{optional_inline}}
- : A callback function to be invoked when the decoding successfully finishes. The
single argument to this callback is an {{domxref("AudioBuffer")}} representing the
_decodedData_ (the decoded PCM audio data). Usually you'll want to put the
decoded data into an {{domxref("AudioBufferSourceNode")}}, from which it can be played
and manipulated how you want.
- `errorCallback` {{optional_inline}}
- : An optional error callback, to be invoked if an error occurs when the audio data is
being decoded.
### Return value
A {{jsxref("Promise") }} object that fulfills with the _decodedData_. If you are using the
XHR syntax you will ignore this return value and use a callback function instead.
## Examples
In this section we will first cover the promise-based syntax and then the callback syntax.
### Promise-based syntax
In this example `loadAudio()` uses {{domxref("fetch()")}} to retrieve an audio file and decodes it into an {{domxref("AudioBuffer")}}. It then caches the `audioBuffer` in the global `buffer` variable for later playback.
> **Note:** You can [run the full example live](https://mdn.github.io/webaudio-examples/decode-audio-data/promise/), or [view the source](https://github.com/mdn/webaudio-examples/blob/main/decode-audio-data/promise/).
```js
let audioCtx;
let buffer;
let source;
async function loadAudio() {
try {
// Load an audio file
const response = await fetch("viper.mp3");
// Decode it
buffer = await audioCtx.decodeAudioData(await response.arrayBuffer());
} catch (err) {
console.error(`Unable to fetch the audio file. Error: ${err.message}`);
}
}
```
### Callback syntax
In this example `loadAudio()` uses {{domxref("fetch()")}} to retrieve an audio
file and decodes it into an {{domxref("AudioBuffer")}} using the callback-based version of `decodeAudioData()`. In the callback, it plays the decoded buffer.
> **Note:** You can [run the full example live](https://mdn.github.io/webaudio-examples/decode-audio-data/callback/), or [view the source](https://github.com/mdn/webaudio-examples/blob/main/decode-audio-data/callback/).
```js
let audioCtx;
let source;
function playBuffer(buffer) {
source = audioCtx.createBufferSource();
source.buffer = buffer;
source.connect(audioCtx.destination);
source.loop = true;
source.start();
}
async function loadAudio() {
try {
// Load an audio file
const response = await fetch("viper.mp3");
// Decode it
audioCtx.decodeAudioData(await response.arrayBuffer(), playBuffer);
} catch (err) {
console.error(`Unable to fetch the audio file. Error: ${err.message}`);
}
}
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createconvolver/index.md | ---
title: "BaseAudioContext: createConvolver() method"
short-title: createConvolver()
slug: Web/API/BaseAudioContext/createConvolver
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createConvolver
---
{{ APIRef("Web Audio API") }}
The `createConvolver()` method of the {{ domxref("BaseAudioContext") }}
interface creates a {{ domxref("ConvolverNode") }}, which is commonly used to apply
reverb effects to your audio. See the [spec definition of Convolution](https://webaudio.github.io/web-audio-api/#background-3) for more information.
> **Note:** The {{domxref("ConvolverNode.ConvolverNode", "ConvolverNode()")}}
> constructor is the recommended way to create a {{domxref("ConvolverNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createConvolver()
```
### Parameters
None.
### Return value
A {{domxref("ConvolverNode")}}.
## Examples
### Creating a convolver node
The following example shows how to use an AudioContext to create a convolver node.
You create an {{domxref("AudioBuffer")}} containing a sound sample to be used
as an ambience to shape the convolution (called the _impulse response_) and
apply that to the convolver. The example below uses a short sample of a concert hall
crowd, so the reverb effect applied is really deep and echoey.
For more complete applied examples/information, check out our [Voice-change-O-matic](https://mdn.github.io/webaudio-examples/voice-change-o-matic/) demo (see [app.js](https://github.com/mdn/webaudio-examples/blob/main/voice-change-o-matic/scripts/app.js) for the code that is excerpted below).
```js
const audioCtx = new AudioContext();
// ...
const convolver = audioCtx.createConvolver();
// ...
// Grab audio track via fetch() for convolver node
try {
const response = await fetch(
"https://mdn.github.io/voice-change-o-matic/audio/concert-crowd.ogg",
);
const arrayBuffer = await response.arrayBuffer();
const decodedAudio = await audioCtx.decodeAudioData(arrayBuffer);
convolver.buffer = decodedAudio;
} catch (error) {
console.error(
`Unable to fetch the audio file: ${name} Error: ${err.message}`,
);
}
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createanalyser/index.md | ---
title: "BaseAudioContext: createAnalyser() method"
short-title: createAnalyser()
slug: Web/API/BaseAudioContext/createAnalyser
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createAnalyser
---
{{APIRef("Web Audio API")}}
The `createAnalyser()` method of the
{{domxref("BaseAudioContext")}} interface creates an {{domxref("AnalyserNode")}}, which
can be used to expose audio time and frequency data and create data visualizations.
> **Note:** The {{domxref("AnalyserNode.AnalyserNode", "AnalyserNode()")}} constructor is the
> recommended way to create an {{domxref("AnalyserNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
> **Note:** For more on using this node, see the
> {{domxref("AnalyserNode")}} page.
## Syntax
```js-nolint
createAnalyser()
```
### Parameters
None.
### Return value
An {{domxref("AnalyserNode")}}.
## Examples
The following example shows basic usage of an AudioContext to create an Analyser node,
then use requestAnimationFrame() to collect time domain data repeatedly and draw an
"oscilloscope style" output of the current audio input. For more complete applied
examples/information, check out our [Voice-change-O-matic](https://mdn.github.io/webaudio-examples/voice-change-o-matic/) demo (see
[app.js lines 108-193](https://github.com/mdn/webaudio-examples/tree/main/voice-change-o-matic/scripts/app.js#L108-L193) for relevant code).
```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
// …
analyser.fftSize = 2048;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);
// draw an oscilloscope of the current audio source
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteTimeDomainData(dataArray);
canvasCtx.fillStyle = "rgb(200 200 200)";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = "rgb(0 0 0)";
canvasCtx.beginPath();
const sliceWidth = (WIDTH * 1.0) / bufferLength;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const v = dataArray[i] / 128.0;
const y = (v * HEIGHT) / 2;
if (i === 0) {
canvasCtx.moveTo(x, y);
} else {
canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
canvasCtx.lineTo(canvas.width, canvas.height / 2);
canvasCtx.stroke();
}
draw();
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/samplerate/index.md | ---
title: "BaseAudioContext: sampleRate property"
short-title: sampleRate
slug: Web/API/BaseAudioContext/sampleRate
page-type: web-api-instance-property
browser-compat: api.BaseAudioContext.sampleRate
---
{{ APIRef("Web Audio API") }}
The `sampleRate` property of the {{
domxref("BaseAudioContext") }} interface returns a floating point number representing
the sample rate, in samples per second, used by all nodes in this audio
context. This limitation means that sample-rate converters are not supported.
## Value
A floating point number indicating the audio context's sample rate, in samples per
second.
## Examples
> **Note:** for a full Web Audio example implementation, see one of our
> Web Audio Demos on the [MDN GitHub repo](https://github.com/mdn/webaudio-examples). Try entering
> `audioCtx.sampleRate` into your browser console.
```js
const audioCtx = new AudioContext();
// Older webkit/blink browsers require a prefix
// …
console.log(audioCtx.sampleRate);
```
## 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/baseaudiocontext | data/mdn-content/files/en-us/web/api/baseaudiocontext/createbuffersource/index.md | ---
title: "BaseAudioContext: createBufferSource() method"
short-title: createBufferSource()
slug: Web/API/BaseAudioContext/createBufferSource
page-type: web-api-instance-method
browser-compat: api.BaseAudioContext.createBufferSource
---
{{ APIRef("Web Audio API") }}
The `createBufferSource()` method of the {{ domxref("BaseAudioContext") }}
Interface is used to create a new {{ domxref("AudioBufferSourceNode") }}, which can be
used to play audio data contained within an {{ domxref("AudioBuffer") }} object. {{
domxref("AudioBuffer") }}s are created using
{{domxref("BaseAudioContext.createBuffer")}} or returned by
{{domxref("BaseAudioContext.decodeAudioData")}} when it successfully decodes an audio
track.
> **Note:** The {{domxref("AudioBufferSourceNode.AudioBufferSourceNode", "AudioBufferSourceNode()")}}
> constructor is the recommended way to create a {{domxref("AudioBufferSourceNode")}}; see
> [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Syntax
```js-nolint
createBufferSource()
```
### Parameters
None.
### Return value
An {{domxref("AudioBufferSourceNode")}}.
## Examples
In this example, we create a two second buffer, fill it with white noise, and then play
it via an {{ domxref("AudioBufferSourceNode") }}. The comments should clearly explain
what is going on.
> **Note:** You can also [run the code live](https://mdn.github.io/webaudio-examples/audio-buffer/),
> or [view the source](https://github.com/mdn/webaudio-examples/blob/main/audio-buffer/index.html).
```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const button = document.querySelector("button");
const pre = document.querySelector("pre");
const myScript = document.querySelector("script");
pre.innerHTML = myScript.innerHTML;
// Stereo
const channels = 2;
// Create an empty two second stereo buffer at the
// sample rate of the AudioContext
const frameCount = audioCtx.sampleRate * 2.0;
const myArrayBuffer = audioCtx.createBuffer(
channels,
frameCount,
audioCtx.sampleRate,
);
button.onclick = () => {
// Fill the buffer with white noise;
//just random values between -1.0 and 1.0
for (let channel = 0; channel < channels; channel++) {
// This gives us the actual ArrayBuffer that contains the data
const nowBuffering = myArrayBuffer.getChannelData(channel);
for (let i = 0; i < frameCount; i++) {
// Math.random() is in [0; 1.0]
// audio needs to be in [-1.0; 1.0]
nowBuffering[i] = Math.random() * 2 - 1;
}
}
// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
const source = audioCtx.createBufferSource();
// set the buffer in the AudioBufferSourceNode
source.buffer = myArrayBuffer;
// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioCtx.destination);
// start the source playing
source.start();
};
```
## 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/contentvisibilityautostatechangeevent/index.md | ---
title: ContentVisibilityAutoStateChangeEvent
slug: Web/API/ContentVisibilityAutoStateChangeEvent
page-type: web-api-interface
status:
- experimental
browser-compat: api.ContentVisibilityAutoStateChangeEvent
---
{{APIRef("CSS Containment")}}{{SeeCompatTable}}
The **`ContentVisibilityAutoStateChangeEvent`** interface is the event object for the {{domxref("element/contentvisibilityautostatechange_event", "contentvisibilityautostatechange")}} event, which fires on any element with {{cssxref("content-visibility", "content-visibility: auto")}} set on it when it starts or stops being [relevant to the user](/en-US/docs/Web/CSS/CSS_containment#relevant_to_the_user) and [skipping its contents](/en-US/docs/Web/CSS/CSS_containment#skips_its_contents).
While the element is not relevant (between the start and end events), the user agent skips an element's rendering, including layout and painting.
This can significantly improve page rendering speed.
The {{domxref("element/contentvisibilityautostatechange_event", "contentvisibilityautostatechange")}} event provides a way for an app's code to also start or stop rendering processes (e.g. drawing on a {{htmlelement("canvas")}}) when they are not needed, thereby conserving processing power.
Note that even when hidden from view, element contents will remain semantically relevant (e.g. to assistive technology users), so this signal should not be used to skip significant semantic DOM updates.
{{InheritanceDiagram}}
## Constructor
- {{domxref("ContentVisibilityAutoStateChangeEvent.ContentVisibilityAutoStateChangeEvent", "ContentVisibilityAutoStateChangeEvent()")}}
- : Creates a new `ContentVisibilityAutoStateChangeEvent` object instance.
## Instance properties
_Inherits properties from its parent, {{DOMxRef("Event")}}._
- {{domxref("ContentVisibilityAutoStateChangeEvent.skipped", "skipped")}} {{ReadOnlyInline}}
- : Returns `true` if the user agent is skipping the element's rendering, or `false` otherwise.
## Examples
```js
const canvasElem = document.querySelector("canvas");
canvasElem.addEventListener("contentvisibilityautostatechange", stateChanged);
canvasElem.style.contentVisibility = "auto";
function stateChanged(event) {
if (event.skipped) {
stopCanvasUpdates(canvasElem);
} else {
startCanvasUpdates(canvasElem);
}
}
// Call this when the canvas updates need to start.
function startCanvasUpdates(canvas) {
// …
}
// Call this when the canvas updates need to stop.
function stopCanvasUpdates(canvas) {
// …
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("element/contentvisibilityautostatechange_event", "contentvisibilityautostatechange")}} event
- [CSS Containment](/en-US/docs/Web/CSS/CSS_containment)
- The {{cssxref("content-visibility")}} property
- The {{cssxref("contain")}} property
| 0 |
data/mdn-content/files/en-us/web/api/contentvisibilityautostatechangeevent | data/mdn-content/files/en-us/web/api/contentvisibilityautostatechangeevent/contentvisibilityautostatechangeevent/index.md | ---
title: "ContentVisibilityAutoStateChangeEvent: ContentVisibilityAutoStateChangeEvent() constructor"
short-title: ContentVisibilityAutoStateChangeEvent()
slug: Web/API/ContentVisibilityAutoStateChangeEvent/ContentVisibilityAutoStateChangeEvent
page-type: web-api-constructor
browser-compat: api.ContentVisibilityAutoStateChangeEvent.ContentVisibilityAutoStateChangeEvent
---
{{APIRef("CSS Containment")}}
The **`ContentVisibilityAutoStateChangeEvent()`** constructor creates a new {{domxref("ContentVisibilityAutoStateChangeEvent")}} object instance.
## Syntax
```js-nolint
new ContentVisibilityAutoStateChangeEvent(type, options)
```
### Parameters
- `type`
- : A string representing the type of event. In the case of `ContentVisibilityAutoStateChangeEvent` this is always `event`.
- `options` {{optional_inline}}
- : An object that contains the following properties:
- `skipped`
- : A boolean, which is set to `true` if the user agent [skips the element's contents](/en-US/docs/Web/CSS/CSS_containment#skips_its_contents), or `false` otherwise.
## Examples
A developer would not use this constructor manually. A new `ContentVisibilityAutoStateChangeEvent` object is constructed when a handler is invoked as a result of the {{domxref("element/contentvisibilityautostatechange_event", "contentvisibilityautostatechange")}} event firing.
```js
canvasElem.addEventListener("contentvisibilityautostatechange", (event) => {
// …
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("element/contentvisibilityautostatechange_event", "contentvisibilityautostatechange")}} event
- [CSS Containment](/en-US/docs/Web/CSS/CSS_containment)
- The {{cssxref("content-visibility")}} property
- The {{cssxref("contain")}} property
| 0 |
data/mdn-content/files/en-us/web/api/contentvisibilityautostatechangeevent | data/mdn-content/files/en-us/web/api/contentvisibilityautostatechangeevent/skipped/index.md | ---
title: "ContentVisibilityAutoStateChangeEvent: skipped property"
short-title: skipped
slug: Web/API/ContentVisibilityAutoStateChangeEvent/skipped
page-type: web-api-instance-property
browser-compat: api.ContentVisibilityAutoStateChangeEvent.skipped
---
{{APIRef("CSS Containment")}}
The `skipped` read-only property of the {{ domxref("ContentVisibilityAutoStateChangeEvent") }} interface returns `true` if the user agent [skips the element's contents](/en-US/docs/Web/CSS/CSS_containment#skips_its_contents), or `false` otherwise.
## Value
A boolean. Returns `true` if the user agent skips the element's contents, or `false` otherwise.
## Examples
```js
const canvasElem = document.querySelector("canvas");
canvasElem.addEventListener("contentvisibilityautostatechange", stateChanged);
canvasElem.style.contentVisibility = "auto";
function stateChanged(event) {
if (event.skipped) {
stopCanvasUpdates(canvasElem);
} else {
startCanvasUpdates(canvasElem);
}
}
// Call this when the canvas updates need to start.
function startCanvasUpdates(canvas) {
// …
}
// Call this when the canvas updates need to stop.
function stopCanvasUpdates(canvas) {
// …
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("element/contentvisibilityautostatechange_event", "contentvisibilityautostatechange")}} event
- [CSS Containment](/en-US/docs/Web/CSS/CSS_containment)
- The {{cssxref("content-visibility")}} property
- The {{cssxref("contain")}} property
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/filesystemdirectoryreader/index.md | ---
title: FileSystemDirectoryReader
slug: Web/API/FileSystemDirectoryReader
page-type: web-api-interface
browser-compat: api.FileSystemDirectoryReader
---
{{APIRef("File and Directory Entries API")}}
The `FileSystemDirectoryReader` interface of the [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API) lets you access the {{domxref("FileSystemFileEntry")}}-based objects (generally {{domxref("FileSystemFileEntry")}} or {{domxref("FileSystemDirectoryEntry")}}) representing each entry in a directory.
## Instance methods
- {{domxref("FileSystemDirectoryReader.readEntries", "readEntries()")}}
- : Returns an array containing some number of the directory's entries. Each item in the array is an object based on {{domxref("FileSystemEntry")}}—typically either {{domxref("FileSystemFileEntry")}} or {{domxref("FileSystemDirectoryEntry")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemDirectoryEntry")}}
- {{domxref("FileSystem")}}
| 0 |
data/mdn-content/files/en-us/web/api/filesystemdirectoryreader | data/mdn-content/files/en-us/web/api/filesystemdirectoryreader/readentries/index.md | ---
title: "FileSystemDirectoryReader: readEntries() method"
short-title: readEntries()
slug: Web/API/FileSystemDirectoryReader/readEntries
page-type: web-api-instance-method
browser-compat: api.FileSystemDirectoryReader.readEntries
---
{{APIRef("File and Directory Entries API")}}
The {{domxref("FileSystemDirectoryReader")}} interface's **`readEntries()`** method retrieves the directory entries
within the directory being read and delivers them in an array to a provided callback function.
The objects in the array are all based upon {{domxref("FileSystemEntry")}}.
Generally, they are either {{domxref("FileSystemFileEntry")}} objects, which represent standard files, or {{domxref("FileSystemDirectoryEntry")}} objects, which represent directories.
## Syntax
```js-nolint
readEntries(successCallback)
readEntries(successCallback, errorCallback)
```
### Parameters
- `successCallback`
- : A function which is called when the directory's contents have been retrieved. The
function receives a single input parameter: an array of file system entry objects,
each based on {{domxref("FileSystemEntry")}}. Generally, they are either
{{domxref("FileSystemFileEntry")}} objects, which represent standard files, or
{{domxref("FileSystemDirectoryEntry")}} objects, which represent directories. If there
are no files left, or you've already called `readEntries()` on this
{{domxref("FileSystemDirectoryReader")}}, the array is empty.
- `errorCallback` {{optional_inline}}
- : A callback function which is called if an error occurs while reading from the
directory. It receives one input parameter: a {{domxref("DOMException")}} object
describing the error which occurred.
### Return value
None ({{jsxref("undefined")}}).
## Examples
See [`DataTransferItem.webkitGetAsEntry()`](/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry#examples) for example code that uses this method.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
On Chrome 77, `readEntries()` will only return the first 100 `FileSystemEntry` instances. In order to obtain all of the
instances, `readEntries()` must be called multiple times.
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemDirectoryEntry")}}
- {{domxref("FileSystem")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfefuncbelement/index.md | ---
title: SVGFEFuncBElement
slug: Web/API/SVGFEFuncBElement
page-type: web-api-interface
browser-compat: api.SVGFEFuncBElement
---
{{APIRef("SVG")}}
The **`SVGFEFuncBElement`** interface corresponds to the {{SVGElement("feFuncB")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface not provide any specific properties, but inherits properties from its parent interface, {{domxref("SVGComponentTransferFunctionElement")}}._
## Instance methods
_This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGComponentTransferFunctionElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("feFuncB")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/notifications_api/index.md | ---
title: Notifications API
slug: Web/API/Notifications_API
page-type: web-api-overview
browser-compat:
- api.Notification
- api.ServiceWorkerRegistration.showNotification
- api.ServiceWorkerRegistration.getNotifications
spec-urls: https://notifications.spec.whatwg.org/
---
{{DefaultAPISidebar("Web Notifications")}}{{securecontext_header}}
The Notifications API allows web pages to control the display of system notifications to the end user. These are outside the top-level browsing context viewport, so therefore can be displayed even when the user has switched tabs or moved to a different app. The API is designed to be compatible with existing notification systems, across different platforms.
{{AvailableInWorkers}}
## Concepts and usage
On supported platforms, showing a system notification generally involves two things. First, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initializes, using the {{domxref("Notification.requestPermission_static", "Notification.requestPermission()")}} method. This should be done in response to a user gesture, such as clicking a button, for example:
```js
btn.addEventListener("click", () => {
let promise = Notification.requestPermission();
// wait for permission
});
```
This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example.
This will spawn a request dialog, along the following lines:

From here the user can choose to allow notifications from this origin, or block them. Once a choice has been made, the setting will generally persist for the current session.
> **Note:** As of Firefox 44, the permissions for Notifications and [Push](/en-US/docs/Web/API/Push_API) have been merged. If permission is granted for notifications, push will also be enabled.
Next, a new notification is created using the {{domxref("Notification.Notification","Notification()")}} constructor. This must be passed a title argument, and can optionally be passed an options object to specify options, such as text direction, body text, icon to display, notification sound to play, and more.
In addition, the Notifications API spec specifies a number of additions to the [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API), to allow service workers to fire notifications.
> **Note:** To find out more about using notifications in your own app, read [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API).
## Interfaces
- {{domxref("Notification")}}
- : Defines a notification object.
- {{domxref("NotificationEvent")}}
- : Represents a notification event dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}.
### Extensions to other interfaces
- {{domxref("ServiceWorkerGlobalScope/notificationclick_event", "notificationclick")}} event
- : Occurs when a user clicks on a displayed notification.
- {{domxref("ServiceWorkerGlobalScope/notificationclose_event", "notificationclose")}} event
- : Occurs when a user closes a displayed notification.
- {{domxref("ServiceWorkerRegistration.getNotifications()")}}
- : Returns a list of the notifications in the order that they were created from the current origin via the current service worker registration.
- {{domxref("ServiceWorkerRegistration.showNotification()")}}
- : Displays the notification with the requested title.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Notifications API](/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
| 0 |
data/mdn-content/files/en-us/web/api/notifications_api | data/mdn-content/files/en-us/web/api/notifications_api/using_the_notifications_api/index.md | ---
title: Using the Notifications API
slug: Web/API/Notifications_API/Using_the_Notifications_API
page-type: guide
---
{{DefaultAPISidebar("Web Notifications")}}{{securecontext_header}}
The [Notifications API](/en-US/docs/Web/API/Notifications_API) lets a web page or app send notifications that are displayed outside the page at the system level; this lets web apps send information to a user even if the application is idle or in the background. This article looks at the basics of using this API in your own apps.
Typically, system notifications refer to the operating system's standard notification mechanism: think for example of how a typical desktop system or mobile device broadcasts notifications.

The system notification system will vary of course by platform and browser, but this is OK, and the Notifications API is written to be general enough for compatibility with most system notification systems.
{{AvailableInWorkers}}
## Examples
One of the most obvious use cases for web notifications is a web-based mail or IRC application that needs to notify the user when a new message is received, even if the user is doing something else with another application. Many examples of this now exist, such as [Slack](https://slack.com/).
We've written a real-world example — a to-do list app — to give more of an idea of how web notifications can be used. It stores data locally using [IndexedDB](/en-US/docs/Web/API/IndexedDB_API) and notifies users when tasks are due using system notifications. [Download the To-do list code](https://github.com/mdn/dom-examples/tree/main/to-do-notifications), or [view the app running live](https://mdn.github.io/dom-examples/to-do-notifications/).
## Requesting permission
Before an app can send a notification, the user must grant the application the right to do so. This is a common requirement when an API tries to interact with something outside a web page — at least once, the user needs to specifically grant that application permission to present notifications, thereby letting the user control which apps/sites are allowed to display notifications.
Because of abuses of push notifications in the past, web browsers and developers have begun to implement strategies to help mitigate this problem. You should only request consent to display notifications in response to a user gesture (e.g. clicking a button). This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notification permission requests not triggered in response to a user gesture. Firefox is already doing this from version 72, for example, and Safari has done it for some time.
In addition, In Chrome and Firefox you cannot request notifications at all unless the site is a secure context (i.e. HTTPS), and you can no longer allow notification permissions to be requested from cross-origin {{htmlelement("iframe")}}s.
### Checking current permission status
You can check to see if you already have permission by checking the value of the {{domxref("Notification.permission_static", "Notification.permission")}} read only property. It can have one of three possible values:
- `default`
- : The user hasn't been asked for permission yet, so notifications won't be displayed.
- `granted`
- : The user has granted permission to display notifications, after having been asked previously.
- `denied`
- : The user has explicitly declined permission to show notifications.
### Getting permission
If permission to display notifications hasn't been granted yet, the application needs to use the {{domxref("Notification.requestPermission_static", "Notification.requestPermission()")}} method to request this from the user. In its simplest form, we just include the following:
```js
Notification.requestPermission().then((result) => {
console.log(result);
});
```
This uses the promise-based version of the method. If you want to support older versions, you might have to use the older callback version, which looks like this:
```js
Notification.requestPermission((result) => {
console.log(result);
});
```
The callback version optionally accepts a callback function that is called once the user has responded to the request to display permissions.
> **Note:** There's no way to reliably feature-test whether `Notification.requestPermission` supports the promise-based version. If you need to support older browsers, just use the callback-based version—although this is deprecated, it still works in new browsers. Check the [browser compatibility table](/en-US/docs/Web/API/Notification/requestPermission_static#browser_compatibility) for more information.
### Example
In our todo list demo, we include an "Enable notifications" button that, when pressed, requests notification permissions for the app.
```html
<button id="enable">Enable notifications</button>
```
Clicking this calls the `askNotificationPermission()` function:
```js
function askNotificationPermission() {
// Check if the browser supports notifications
if (!("Notification" in window)) {
console.log("This browser does not support notifications.");
return;
}
Notification.requestPermission().then((permission) => {
// set the button to shown or hidden, depending on what the user answers
notificationBtn.style.display = permission === "granted" ? "none" : "block";
});
}
```
Looking at the second main block first, you'll see that we first check to see if Notifications are supported. If they are, we run the promise-based version of `Notification.requestPermission()`, and if not, we log a message to the console.
Inside the promise resolution handler passed to `then`, we show or hide the button depending on what the user chose in the permission dialog. We don't want to show it if permission has already been granted, but if the user chose to deny permission, we want to give them the chance to change their mind later on.
## Creating a notification
Creating a notification is easy; just use the {{domxref("Notification")}} constructor. This constructor expects a title to display within the notification and some options to enhance the notification such as an {{domxref("Notification.icon","icon")}} or a text {{domxref("Notification.body","body")}}.
For example, in the to-do-list example we use the following snippet to create a notification when required (found inside the `createNotification()` function):
```js
const img = "/to-do-notifications/img/icon-128.png";
const text = `HEY! Your task "${title}" is now overdue.`;
const notification = new Notification("To do list", { body: text, icon: img });
```
## Closing notifications
Use {{domxref("Notification.close","close()")}} to remove a notification that is no longer relevant to the user (e.g. the user already read the notification on the webpage, in the case of a messaging app, or the following song is already playing in a music app to notifies upon song changes). Most modern browsers dismiss notifications automatically after a few moments (around four seconds) but this isn't something you should generally be concerned about as it's up to the user and user agent. The dismissal may also happen at the operating system level and users should remain in control of this. Old versions of Chrome didn't remove notifications automatically so you can do so after a {{domxref("setTimeout()")}} only for those legacy versions in order to not remove notifications from notification trays on other browsers.
```js
const n = new Notification("My Great Song");
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
// The tab has become visible so clear the now-stale Notification.
n.close();
}
});
```
> **Note:** This API shouldn't be used just to have the notification removed from the screen after a fixed delay (on modern browsers) since this method will also remove the notification from any notification tray, preventing users from interacting with it after it was initially shown.
> **Note:** When you receive a "close" event, there is no guarantee that it's the user who closed the notification. This is in line with the specification, which states: "When a notification is closed, either by the underlying notifications platform or by the user, the close steps for it must be run."
## Notification events
There are four events that are triggered on the {{domxref("Notification")}} instance:
- `click`
- : Triggered when the user clicks on the notification.
- `close`
- : Triggered once the notification is closed.
- `error`
- : Triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason.
- `show`
- : Triggered when the notification is displayed to the user.
These events can be tracked using the {{domxref("Notification.click_event","onclick")}}, {{domxref("Notification.close_event","onclose")}}, {{domxref("Notification.error_event","onerror")}}, and {{domxref("Notification.show_event","onshow")}} handlers. Because {{domxref("Notification")}} also inherits from {{domxref("EventTarget")}}, it's possible to use the {{domxref("EventTarget.addEventListener","addEventListener()")}} method on it.
## Replacing existing notifications
It is usually undesirable for a user to receive a lot of notifications in a short space of time — for example, what if a messenger application notified a user for each incoming message, and they were being sent a lot? To avoid spamming the user with too many notifications, it's possible to modify the pending notifications queue, replacing single or multiple pending notifications with a new one.
To do this, it's possible to add a tag to any new notification. If a notification already has the same tag and has not been displayed yet, the new notification replaces that previous notification. If the notification with the same tag has already been displayed, the previous notification is closed and the new one is displayed.
### Tag example
Assume the following basic HTML:
```html
<button>Notify me!</button>
```
It's possible to handle multiple notifications this way:
```js
window.addEventListener("load", () => {
const button = document.querySelector("button");
if (window.self !== window.top) {
// Ensure that if our document is in a frame, we get the user
// to first open it in its own tab or window. Otherwise, it
// won't be able to request permission to send notifications.
button.textContent = "View live result of the example code above";
button.addEventListener("click", () => window.open(location.href));
return;
}
button.addEventListener("click", () => {
if (Notification?.permission === "granted") {
// If the user agreed to get notified
// Let's try to send ten notifications
let i = 0;
// Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time.
const interval = setInterval(() => {
// Thanks to the tag, we should only see the "Hi! 9" notification
const n = new Notification(`Hi! ${i}`, { tag: "soManyNotification" });
if (i === 9) {
clearInterval(interval);
}
i++;
}, 200);
} else if (Notification && Notification.permission !== "denied") {
// If the user hasn't told if they want to be notified or not
// Note: because of Chrome, we are not sure the permission property
// is set, therefore it's unsafe to check for the "default" value.
Notification.requestPermission().then((status) => {
// If the user said okay
if (status === "granted") {
let i = 0;
// Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time.
const interval = setInterval(() => {
// Thanks to the tag, we should only see the "Hi! 9" notification
const n = new Notification(`Hi! ${i}`, {
tag: "soManyNotification",
});
if (i === 9) {
clearInterval(interval);
}
i++;
}, 200);
} else {
// Otherwise, we can fallback to a regular modal alert
alert("Hi!");
}
});
} else {
// If the user refuses to get notified, we can fallback to a regular modal alert
alert("Hi!");
}
});
});
```
### Result
{{ EmbedLiveSample('Tag_example', '100%', 30) }}
## See also
- {{ domxref("Notification") }}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rsaoaepparams/index.md | ---
title: RsaOaepParams
slug: Web/API/RsaOaepParams
page-type: web-api-interface
spec-urls: https://w3c.github.io/webcrypto/#dfn-RsaOaepParams
---
{{ APIRef("Web Crypto API") }}
The **`RsaOaepParams`** dictionary of the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) represents the object that should be passed as the `algorithm` parameter into {{domxref("SubtleCrypto.encrypt()")}}, {{domxref("SubtleCrypto.decrypt()")}}, {{domxref("SubtleCrypto.wrapKey()")}}, or {{domxref("SubtleCrypto.unwrapKey()")}}, when using the [RSA_OAEP](/en-US/docs/Web/API/SubtleCrypto/encrypt#rsa-oaep) algorithm.
## Instance properties
- `name`
- : A string. This should be set to `RSA-OAEP`.
- `label` {{optional_inline}}
- : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}} — an array of bytes that does not itself need to be encrypted but which should be bound to the ciphertext. A digest of the label is part of the input to the encryption operation.
Unless your application calls for a label, you can just omit this argument and it will not affect the security of the encryption operation.
## Examples
See the examples for {{domxref("SubtleCrypto.encrypt()")}} and {{domxref("SubtleCrypto.decrypt()")}}.
## Specifications
{{Specifications}}
## Browser compatibility
Browsers that support the "RSA-OAEP" algorithm for the {{domxref("SubtleCrypto.encrypt()")}}, {{domxref("SubtleCrypto.decrypt()")}}, {{domxref("SubtleCrypto.wrapKey()")}}, or {{domxref("SubtleCrypto.unwrapKey()")}} methods will support this type.
## See also
- {{domxref("SubtleCrypto.encrypt()")}}.
- {{domxref("SubtleCrypto.decrypt()")}}.
- {{domxref("SubtleCrypto.wrapKey()")}}.
- {{domxref("SubtleCrypto.unwrapKey()")}}.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/screenorientation/index.md | ---
title: ScreenOrientation
slug: Web/API/ScreenOrientation
page-type: web-api-interface
browser-compat: api.ScreenOrientation
---
{{APIRef("Screen Orientation API")}}
The **`ScreenOrientation`** interface of the [Screen Orientation API](/en-US/docs/Web/API/Screen_Orientation_API) provides information about the current orientation of the document.
A **`ScreenOrientation`** instance object can be retrieved using the {{domxref("screen.orientation")}} property.
{{InheritanceDiagram}}
## Instance properties
- {{DOMxRef("ScreenOrientation.type")}} {{ReadOnlyInline}}
- : Returns the document's current orientation type, one of `portrait-primary`, `portrait-secondary`, `landscape-primary`, or `landscape-secondary`.
- {{DOMxRef("ScreenOrientation.angle")}} {{ReadOnlyInline}}
- : Returns the document's current orientation angle.
## Instance methods
- {{DOMxRef("ScreenOrientation.lock()")}}
- : Locks the orientation of the containing document to its default orientation and returns a {{JSxRef("Promise")}}.
- {{DOMxRef("ScreenOrientation.unlock()")}}
- : Unlocks the orientation of the containing document from its default orientation.
## Events
Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.
- {{DOMxRef("ScreenOrientation.change_event", "change")}}
- : Fired whenever the screen changes orientation.
## Example
In the following example, we listen for an orientation {{DOMxRef("ScreenOrientation.change_event", "change")}} event and log the new {{DOMxRef("ScreenOrientation.type", "screen orientation type", "", "nocode")}} and {{DOMxRef("ScreenOrientation.angle", "angle", "", "nocode")}}.
```js
screen.orientation.addEventListener("change", (event) => {
const type = event.target.type;
const angle = event.target.angle;
console.log(`ScreenOrientation change: ${type}, ${angle} degrees.`);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/screenorientation | data/mdn-content/files/en-us/web/api/screenorientation/unlock/index.md | ---
title: "ScreenOrientation: unlock() method"
short-title: unlock()
slug: Web/API/ScreenOrientation/unlock
page-type: web-api-instance-method
browser-compat: api.ScreenOrientation.unlock
---
{{APIRef("Screen Orientation")}}
The **`unlock()`** property of the
{{domxref("ScreenOrientation")}} interface unlocks the orientation of the containing
document from its default orientation.
## Syntax
```js-nolint
unlock()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
The promise may be rejected with the following exceptions:
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the document is not fully active.
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the document's visibility state is hidden or if the document is forbidden to use the feature (for example, by omitting the keyword `allow-orientation-lock` of the `sandbox` attribute of the `iframe` element).
- `AbortError` {{domxref("DOMException")}}
- : Thrown if there is any other `lock()` method invoking.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/screenorientation | data/mdn-content/files/en-us/web/api/screenorientation/change_event/index.md | ---
title: "ScreenOrientation: change event"
short-title: change
slug: Web/API/ScreenOrientation/change_event
page-type: web-api-event
browser-compat: api.ScreenOrientation.change_event
---
{{APIRef("Screen Orientation API")}}
The **`change`** event of the {{domxref("ScreenOrientation")}} interface fires when the orientation of the screen has changed, for example when a user rotates their mobile phone.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("change", (event) => {});
onchange = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Example
In the following example, the `change` callback prints the new {{DOMxRef("ScreenOrientation.type", "screen orientation type", "", "nocode")}} and {{DOMxRef("ScreenOrientation.angle", "angle", "", "nocode")}}.
```js
screen.orientation.addEventListener("change", (event) => {
const type = event.target.type;
const angle = event.target.angle;
console.log(`ScreenOrientation change: ${type}, ${angle} degrees.`);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/screenorientation | data/mdn-content/files/en-us/web/api/screenorientation/type/index.md | ---
title: "ScreenOrientation: type property"
short-title: type
slug: Web/API/ScreenOrientation/type
page-type: web-api-instance-property
browser-compat: api.ScreenOrientation.type
---
{{APIRef("Screen Orientation")}}
The **`type`** read-only property of the
{{domxref("ScreenOrientation")}} interface returns the document's current orientation
type, one of `portrait-primary`, `portrait-secondary`, `landscape-primary`, or
`landscape-secondary`.
## Value
A {{jsxref("String")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/screenorientation | data/mdn-content/files/en-us/web/api/screenorientation/angle/index.md | ---
title: "ScreenOrientation: angle property"
short-title: angle
slug: Web/API/ScreenOrientation/angle
page-type: web-api-instance-property
browser-compat: api.ScreenOrientation.angle
---
{{APIRef("Screen Orientation")}}
The **`angle`** read-only property of the
{{domxref("ScreenOrientation")}} interface returns the document's current orientation
angle.
## Value
An unsigned short integer.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/screenorientation | data/mdn-content/files/en-us/web/api/screenorientation/lock/index.md | ---
title: "ScreenOrientation: lock() method"
short-title: lock()
slug: Web/API/ScreenOrientation/lock
page-type: web-api-instance-method
browser-compat: api.ScreenOrientation.lock
---
{{APIRef("Screen Orientation")}}
The **`lock()`** property of the {{domxref("ScreenOrientation")}} interface locks the orientation of the containing document to the specified orientation.
Typically orientation locking is only enabled on mobile devices, and when the browser context is full screen.
If locking is supported, then it must work for all the parameter values listed below.
## Syntax
```js-nolint
lock(orientation)
```
### Parameters
- `orientation`
- : An orientation lock type. One of the following:
- `"any"`
- : Any of `portrait-primary`, `portrait-secondary`, `landscape-primary` or `landscape-secondary`.
- `"natural"`
- : The natural orientation of the screen from the underlying operating system: either `portrait-primary` or `landscape-primary`.
- `"landscape"`
- : An orientation where screen width is greater than the screen height.
Depending on the platform convention, this may be `landscape-primary`, `landscape-secondary`, or both.
- `"portrait"`
- : An orientation where screen height is greater than the screen width.
Depending on the platform convention, this may be `portrait-primary`, `portrait-secondary`, or both.
- `"portrait-primary"`
- : The "primary" portrait mode.
If the natural orientation is a portrait mode (screen height is greater than width), this will be the same as the natural orientation, and correspond to an angle of 0 degrees.
If the natural orientation is a landscape mode, then the user agent can choose either portrait orientation as the `portrait-primary` and `portrait-secondary`; one of those will be assigned the angle of 90 degrees and the other will have an angle of 270 degrees.
- `"portrait-secondary"`
- : The secondary portrait orientation.
If the natural orientation is a portrait mode, this will have an angle of 180 degrees (in other words, the device is upside down relative to its natural orientation).
If the natural orientation is a landscape mode, this can be either orientation as selected by the user agent: whichever was not selected for `portrait-primary`.
- `"landscape-primary"`
- : The "primary" landscape mode.
If the natural orientation is a landscape mode (screen width is greater than height), this will be the same as the natural orientation, and correspond to an angle of 0 degrees.
If the natural orientation is a portrait mode, then the user agent can choose either landscape orientation as the `landscape-primary` with an angle of either 90 or 270 degrees (`landscape-secondary` will be the other orientation and angle).
- `"landscape-secondary"`
- : The secondary landscape mode.
If the natural orientation is a landscape mode, this orientation is upside down relative to the natural orientation, and will have an angle of 180 degrees.
If the natural orientation is a portrait mode, this can be either orientation as selected by the user agent: whichever was not selected for `landscape-primary`.
### Return value
A {{jsxref("Promise")}} that resolves after locking succeeds.
### Exceptions
The promise may be rejected with the following exceptions:
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the document is not fully active.
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the document's visibility state is hidden or if the document is forbidden to use the feature (for example, by omitting the keyword `allow-orientation-lock` of the `sandbox` attribute of the `iframe` element).
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if the user agent does not support locking the screen orientation of the specific orientation.
- `AbortError` {{domxref("DOMException")}}
- : Thrown if there is any other `lock()` method invoking.
## Examples
This example shows how to lock the screen to the opposite orientation of the current one.
Note that this example will only work on mobile devices and other devices that support orientation changes.
```html
<div id="example_container">
<button id="fullscreen_button">Fullscreen</button>
<button id="lock_button">Lock</button>
<button id="unlock_button">Unlock</button>
<textarea id="log" rows="7" cols="85"></textarea>
</div>
```
```js
const log = document.getElementById("log");
// Lock button: Lock the screen to the other orientation (rotated by 90 degrees)
const rotate_btn = document.querySelector("#lock_button");
rotate_btn.addEventListener("click", () => {
log.textContent += `Lock pressed \n`;
const oppositeOrientation = screen.orientation.type.startsWith("portrait")
? "landscape"
: "portrait";
screen.orientation
.lock(oppositeOrientation)
.then(() => {
log.textContent = `Locked to ${oppositeOrientation}\n`;
})
.catch((error) => {
log.textContent += `${error}\n`;
});
});
// Unlock button: Unlock the screen orientation (if locked)
const unlock_btn = document.querySelector("#unlock_button");
unlock_btn.addEventListener("click", () => {
log.textContent += "Unlock pressed \n";
screen.orientation.unlock();
});
// Full screen button: Set the example to fullscreen.
const fullscreen_btn = document.querySelector("#fullscreen_button");
fullscreen_btn.addEventListener("click", () => {
log.textContent += "Fullscreen pressed \n";
const container = document.querySelector("#example_container");
container.requestFullscreen().catch((error) => {
log.textContent += `${error}\n`;
});
});
```
To test the example, first press the Fullscreen button.
Once the example is full screen, press the Lock button to switch the orientation, and Unlock to return to the natural orientation.
{{EmbedLiveSample('Examples')}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssanimation/index.md | ---
title: CSSAnimation
slug: Web/API/CSSAnimation
page-type: web-api-interface
browser-compat: api.CSSAnimation
---
{{APIRef("Web Animations")}}
The **`CSSAnimation`** interface of the {{domxref('Web Animations API','','',' ')}} represents an {{domxref("Animation")}} object.
{{InheritanceDiagram}}
## Instance properties
_This interface inherits properties from its parent, {{domxref("Animation")}}._
- {{domxref("CSSAnimation.animationName")}} {{ReadOnlyInline}}
- : Returns the animation name as a string.
## Instance methods
_This interface inherits methods from its parent, {{domxref("Animation")}}._
## Examples
### Inspecting the returned CSSAnimation
The animation in the following example is defined in CSS with the name `slide-in`. Calling {{domxref("Element.getAnimations()")}} returns an array of all {{domxref("Animation")}} objects. In our case this returns a `CSSAnimation` object, representing the animation created in CSS.
```css
.animate {
animation: slide-in 0.7s both;
}
@keyframes slide-in {
0% {
transform: translateY(-1000px);
}
100% {
transform: translateY(0);
}
}
```
```js
let animations = document.querySelector(".animate").getAnimations();
console.log(animations[0]);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssanimation | data/mdn-content/files/en-us/web/api/cssanimation/animationname/index.md | ---
title: "CSSAnimation: animationName property"
short-title: animationName
slug: Web/API/CSSAnimation/animationName
page-type: web-api-instance-property
browser-compat: api.CSSAnimation.animationName
---
{{APIRef("Web Animations")}}
The **`animationName`** property of the
{{domxref("CSSAnimation")}} interface returns the {{CSSXref("animation-name")}}. This
specifies one or more keyframe at-rules which describe the animation applied to the
element.
## Value
A string.
## Examples
### Returning the animationName
The animation in the following example is defined in CSS with the name
`slide-in`. Calling {{domxref("Element.getAnimations()")}} returns an array
of all {{domxref("Animation")}} objects. The `animationName` property returns
the name given to the animation, in our case `slide-in`.
```css
.animate {
animation: slide-in 0.7s both;
}
@keyframes slide-in {
0% {
transform: translateY(-1000px);
}
100% {
transform: translateY(0);
}
}
```
```js
let animations = document.querySelector(".animate").getAnimations();
console.log(animations[0].animationName);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediatrackconstraints/index.md | ---
title: MediaTrackConstraints
slug: Web/API/MediaTrackConstraints
page-type: web-api-interface
browser-compat: api.MediaTrackConstraints
---
{{APIRef("Media Capture and Streams")}}
The **`MediaTrackConstraints`** dictionary is used to describe a set of capabilities and the value or values each can take on. A constraints dictionary is passed into {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}} to allow a script to establish a set of exact (required) values or ranges and/or preferred values or ranges of values for the track, and the most recently-requested set of custom constraints can be retrieved by calling {{domxref("MediaStreamTrack.getConstraints", "getConstraints()")}}.
## Constraints
The following types are used to specify a constraint for a property. They allow you to specify one or more `exact` values from which one must be the parameter's value, or a set of `ideal` values which should be used if possible. You can also specify a single value (or an array of values) which the user agent will do its best to match once all more stringent constraints have been applied.
To learn more about how constraints work, see [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints).
> **Note:** `min` and `exact` values are not permitted in constraints used in {{domxref("MediaDevices.getDisplayMedia()")}} calls — they produce a `TypeError` — but they are allowed in constraints used in {{domxref("MediaStreamTrack.applyConstraints()")}} calls.
### ConstrainBoolean
The `ConstrainBoolean` constraint type is used to specify a constraint for a property whose value is a Boolean value. Its value may either be set to a Boolean (`true` or `false`) or an object containing the following properties:
- `exact`
- : A Boolean which must be the value of the property. If the property can't be set to this value, matching will fail.
- `ideal`
- : A Boolean specifying an ideal value for the property. If possible, this value will be used, but if it's not possible, the user agent will use the closest possible match.
### ConstrainDouble
The `ConstrainDouble` constraint type is used to specify a constraint for a property whose value is a double-precision floating-point number. Its value may either be set to a number or an object containing the following properties:
- `max`
- : A decimal number specifying the largest permissible value of the property it describes. If the value cannot remain equal to or less than this value, matching will fail.
- `min`
- : A decimal number specifying the smallest permissible value of the property it describes. If the value cannot remain equal to or greater than this value, matching will fail.
- `exact`
- : A decimal number specifying a specific, required, value the property must have to be considered acceptable.
- `ideal`
- : A decimal number specifying an ideal value for the property. If possible, this value will be used, but if it's not possible, the user agent will use the closest possible match.
### ConstrainDOMString
The `ConstrainDOMString` constraint type is used to specify a constraint for a property whose value is a string. Its value may either be set to a string, an array of strings, or an object containing the following properties:
- `exact`
- : A string or an array of strings, one of which must be the value of the property. If the property can't be set to one of the listed values, matching will fail.
- `ideal`
- : A string or an array of strings, specifying ideal values for the property. If possible, one of the listed values will be used, but if it's not possible, the user agent will use the closest possible match.
### ConstrainULong
The `ConstrainULong` constraint type is used to specify a constraint for a property whose value is an integer. Its value may either be set to a number or an object containing the following properties:
- `max`
- : An integer specifying the largest permissible value of the property it describes. If the value cannot remain equal to or less than this value, matching will fail.
- `min`
- : An integer specifying the smallest permissible value of the property it describes. If the value cannot remain equal to or greater than this value, matching will fail.
- `exact`
- : An integer specifying a specific, required, value the property must have to be considered acceptable.
- `ideal`
- : An integer specifying an ideal value for the property. If possible, this value will be used, but if it's not possible, the user agent will use the closest possible match.
## Instance properties
Some combination—but not necessarily all—of the following properties will exist on the object. This may be because a given browser doesn't support the property, or because it doesn't apply. For example, because {{Glossary("RTP")}} doesn't provide some of these values during negotiation of a WebRTC connection, a track associated with a {{domxref("RTCPeerConnection")}} will not include certain values, such as {{domxref("MediaTrackConstraints.facingMode", "facingMode")}} or {{domxref("MediaTrackConstraints.groupId", "groupId")}}.
### Instance properties of all media tracks
- {{domxref("MediaTrackConstraints.deviceId", "deviceId")}}
- : A [`ConstrainDOMString`](#constraindomstring) object specifying a device ID or an array of device IDs which are acceptable and/or required.
- {{domxref("MediaTrackConstraints.groupId", "groupId")}}
- : A [`ConstrainDOMString`](#constraindomstring) object specifying a group ID or an array of group IDs which are acceptable and/or required.
### Instance properties of audio tracks
- {{domxref("MediaTrackConstraints.autoGainControl", "autoGainControl")}}
- : A [`ConstrainBoolean`](#constrainboolean) object which specifies whether automatic gain control is preferred and/or required.
- {{domxref("MediaTrackConstraints.channelCount", "channelCount")}}
- : A [`ConstrainULong`](#constrainulong) specifying the channel count or range of channel counts which are acceptable and/or required.
- {{domxref("MediaTrackConstraints.echoCancellation", "echoCancellation")}}
- : A [`ConstrainBoolean`](#constrainboolean) object specifying whether or not echo cancellation is preferred and/or required.
- {{domxref("MediaTrackConstraints.latency", "latency")}}
- : A [`ConstrainDouble`](#constraindouble) specifying the latency or range of latencies which are acceptable and/or required.
- {{domxref("MediaTrackConstraints.noiseSuppression", "noiseSuppression")}}
- : A [`ConstrainBoolean`](#constrainboolean) which specifies whether noise suppression is preferred and/or required.
- {{domxref("MediaTrackConstraints.sampleRate", "sampleRate")}}
- : A [`ConstrainULong`](#constrainulong) specifying the sample rate or range of sample rates which are acceptable and/or required.
- {{domxref("MediaTrackConstraints.sampleSize", "sampleSize")}}
- : A [`ConstrainULong`](#constrainulong) specifying the sample size or range of sample sizes which are acceptable and/or required.
- {{domxref("MediaTrackConstraints.volume", "volume")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : A [`ConstrainDouble`](#constraindouble) specifying the volume or range of volumes which are acceptable and/or required.
### Instance properties of image tracks
- whiteBalanceMode
- : A {{jsxref("String")}} specifying one of `"none"`, `"manual"`, `"single-shot"`, or `"continuous"`.
- exposureMode
- : A {{jsxref("String")}} specifying one of `"none"`, `"manual"`, `"single-shot"`, or `"continuous"`.
- focusMode
- : A {{jsxref("String")}} specifying one of `"none"`, `"manual"`, `"single-shot"`, or `"continuous"`.
- pointsOfInterest
- : The pixel coordinates on the sensor of one or more points of interest. This is either an object in the form { x:_value_, y:_value_ } or an array of such objects, where _value_ is a double-precision integer.
- exposureCompensation
- : A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying f-stop adjustment by up to ±3.
- colorTemperature
- : A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying a desired color temperature in degrees kelvin.
- iso
- : A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying a desired iso setting.
- brightness
- : A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying a desired brightness setting.
- contrast
- : A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying the degree of difference between light and dark.
- saturation
- : A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying the degree of color intensity.
- sharpness
- : A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying the intensity of edges.
- focusDistance
- : A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying distance to a focused object.
- zoom
- : A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying the desired focal length.
- torch
- : A boolean value defining whether the fill light is continuously connected, meaning it stays on as long as the track is active.
### Instance properties of video tracks
- {{domxref("MediaTrackConstraints.aspectRatio", "aspectRatio")}}
- : A [`ConstrainDouble`](#constraindouble) specifying the video aspect ratio or range of aspect ratios which are acceptable and/or required.
- {{domxref("MediaTrackConstraints.facingMode", "facingMode")}}
- : A [`ConstrainDOMString`](#constraindomstring) object specifying a facing or an array of facings which are acceptable and/or required.
- {{domxref("MediaTrackConstraints.frameRate", "frameRate")}}
- : A [`ConstrainDouble`](#constraindouble) specifying the frame rate or range of frame rates which are acceptable and/or required.
- {{domxref("MediaTrackConstraints.height", "height")}}
- : A [`ConstrainULong`](#constrainulong) specifying the video height or range of heights which are acceptable and/or required.
- {{domxref("MediaTrackConstraints.width", "width")}}
- : A [`ConstrainULong`](#constrainulong) specifying the video width or range of widths which are acceptable and/or required.
- resizeMode
- : A [`ConstrainDOMString`](#constraindomstring) object specifying a mode or an array of modes the UA can use to derive the resolution of a video track. Allowed values are `none` and `crop-and-scale`. `none` means that the user agent uses the resolution provided by the camera, its driver or the OS. `crop-and-scale` means that the user agent can use cropping and downscaling on the camera output in order to satisfy other constraints that affect the resolution.
### Instance properties of shared screen tracks
These constraints apply to the `video` property of the object passed into {{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}} to obtain a stream for screen sharing.
- {{domxref("MediaTrackConstraints.displaySurface", "displaySurface")}}
- : A [`ConstrainDOMString`](#constraindomstring) which specifies the types of display surface that may be selected by the user. This may be a single one of the following strings, or a list of them to allow multiple source surfaces:
- `browser`
- : The stream contains the contents of a single browser tab selected by the user.
- `monitor`
- : The stream's video track contains the entire contents of one or more of the user's screens.
- `window`
- : The stream contains a single window selected by the user for sharing.
- {{domxref("MediaTrackConstraints.logicalSurface", "logicalSurface")}}
- : A [`ConstrainBoolean`](#constrainboolean) value which may contain a single Boolean value or a set of them, indicating whether or not to allow the user to choose source surfaces which do not directly correspond to display areas. These may include backing buffers for windows to allow capture of window contents that are hidden by other windows in front of them, or buffers containing larger documents that need to be scrolled through to see the entire contents in their windows.
- {{domxref("MediaTrackConstraints.suppressLocalAudioPlayback", "suppressLocalAudioPlayback")}} {{Experimental_Inline}}
- : A [`ConstrainBoolean`](#constrainboolean) value describing the requested or mandatory constraints placed upon the value of the {{domxref("MediaTrackSettings.suppressLocalAudioPlayback","suppressLocalAudioPlayback")}} constrainable property. This property controls whether the audio playing in a tab will continue to be played out of a user's local speakers when the tab is captured.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- [Screen Capture API](/en-US/docs/Web/API/Screen_Capture_API)
- [Using the Screen Capture API](/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture)
- {{domxref("MediaDevices.getUserMedia()")}}
- {{domxref("MediaStreamTrack.getConstraints()")}}
- {{domxref("MediaStreamTrack.applyConstraints()")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack.getSettings()")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/noisesuppression/index.md | ---
title: "MediaTrackConstraints: noiseSuppression property"
short-title: noiseSuppression
slug: Web/API/MediaTrackConstraints/noiseSuppression
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.noiseSuppression
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's **`noiseSuppression`** property is a [`ConstrainBoolean`](/en-US/docs/Web/API/MediaTrackConstraints#constrainboolean) describing the requested or mandatory constraints placed upon the value of the {{domxref("MediaTrackSettings.noiseSuppression","noiseSuppression")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.noiseSuppression")}} as returned
by a call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically
this is unnecessary since browsers will ignore any constraints they're unfamiliar with.
Noise suppression is typically provided by microphones, although it can be provided by
other input sources as well.
## Value
If this value is a simple `true` or `false`, the user agent will
attempt to obtain media with noise suppression enabled or disabled as specified, if
possible, but will not fail if this can't be done. If, instead, the value is given as an
object with an `exact` field, that field's Boolean value indicates a required
setting for the noise suppression feature; if it can't be met, then the request will
result in an error.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/samplesize/index.md | ---
title: "MediaTrackConstraints: sampleSize property"
short-title: sampleSize
slug: Web/API/MediaTrackConstraints/sampleSize
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.sampleSize
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`sampleSize`** property is a [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.sampleSize", "sampleSize")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.sampleSize")}} as returned by a
call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this
is unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
If this value is a number, the user agent will attempt to obtain media whose sample
size (in bits per linear sample) is as close as possible to this number given the
capabilities of the hardware and the other constraints specified. Otherwise, the value
of this [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong) will guide the user agent in its efforts to provide
an exact match to the required sample size (if `exact` is specified or both
`min` and `max` are provided and have the same value) or to a
best-possible value.
> **Note:** Since this property can only represent linear sample sizes, this constraint can only
> be met by devices that can produce audio with linear samples.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/echocancellation/index.md | ---
title: "MediaTrackConstraints: echoCancellation property"
short-title: echoCancellation
slug: Web/API/MediaTrackConstraints/echoCancellation
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.echoCancellation
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`echoCancellation`** property is a
[`ConstrainBoolean`](/en-US/docs/Web/API/MediaTrackConstraints#constrainboolean) describing the requested or mandatory constraints placed
upon the value of the {{domxref("MediaTrackSettings.echoCancellation",
"echoCancellation")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.echoCancellation")}} as returned
by a call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically
this is unnecessary since browsers will ignore any constraints they're unfamiliar with.
Because {{Glossary("RTP")}} doesn't include this information, tracks associated with a
[WebRTC](/en-US/docs/Web/API/WebRTC_API) {{domxref("RTCPeerConnection")}}
will never include this property.
## Value
If this value is a simple `true` or `false`, the user agent will
attempt to obtain media with echo cancellation enabled or disabled as specified, if
possible, but will not fail if this can't be done. If, instead, the value is given as an
object with an `exact` field, that field's Boolean value indicates a required
setting for the echo cancellation feature; if it can't be met, then the request will
result in an error.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/volume/index.md | ---
title: "MediaTrackConstraints: volume property"
short-title: volume
slug: Web/API/MediaTrackConstraints/volume
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.MediaTrackConstraints.volume
---
{{APIRef("Media Capture and Streams")}}{{Deprecated_Header}}{{Non-standard_Header}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`volume`** property is a [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.volume", "volume")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.volume")}} as returned by a call
to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this is
unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
A [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) describing the acceptable or required value(s) for an
audio track's volume, on a linear scale where 0.0 means silence and 1.0 is the highest
supported volume.
If this value is a number, the user agent will attempt to obtain media whose volume is
as close as possible to this number given the capabilities of the hardware and the other
constraints specified. Otherwise, the value of this [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) will
guide the user agent in its efforts to provide an exact match to the required volume (if
`exact` is specified or both `min` and `max` are
provided and have the same value) or to a best-possible value.
Any constraint set which only permits values outside the range 0.0 to 1.0 cannot be
satisfied and will result in failure.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/logicalsurface/index.md | ---
title: "MediaTrackConstraints: logicalSurface property"
short-title: logicalSurface
slug: Web/API/MediaTrackConstraints/logicalSurface
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.logicalSurface
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's **`logicalSurface`** property is a [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring) describing the requested or mandatory constraints placed upon the value of the {{domxref("MediaTrackSettings.logicalSurface","logicalSurface")}} constrainable property.
This is used to specify whether or
not {{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}} should allow the
user to choose display surfaces which are not necessarily fully visible on the screen,
such as occluded windows or the complete content of windows which are large enough to
require scrolling to see their entire contents.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.logicalSurface")}} as returned by
a call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this
is unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
A [`ConstrainBoolean`](/en-US/docs/Web/API/MediaTrackConstraints#constrainboolean) which is `true` if logical surfaces should be permitted among the selections available to the user.
See [how constraints are defined](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#how_constraints_are_defined).
## Usage notes
You can check the setting selected by the user agent after the display media has been
created by {{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}} by calling
{{domxref("MediaStreamTrack.getSettings", "getSettings()")}} on the display media's
video {{domxref("MediaStreamTrack")}}, then checking the value of the returned
{{domxref("MediaTrackSettings")}} object's
{{domxref("MediaTrackSettings.logicalSurface", "logicalSurface")}} object.
For example, if your app needs to know if the selected display surface is a logical
one:
```js
let isLogicalSurface = displayStream
.getVideoTracks()[0]
.getSettings().logicalSurface;
```
Following this code, `isLogicalSurface` is `true` if the display
surface contained in the stream is a logical surface; that is, one which may not be
entirely onscreen, or may even be entirely offscreen.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Screen Capture API](/en-US/docs/Web/API/Screen_Capture_API)
- [Using the Screen Capture API](/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/framerate/index.md | ---
title: "MediaTrackConstraints: frameRate property"
short-title: frameRate
slug: Web/API/MediaTrackConstraints/frameRate
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.frameRate
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`frameRate`** property is a [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.frameRate", "frameRate")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.frameRate")}} as returned by a
call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this
is unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
A [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) describing the acceptable or required value(s) for a
video track's frame rate, in frames per second.
If this value is a number, the user agent will attempt to obtain media whose frame rate
is as close as possible to this number given the capabilities of the hardware and the
other constraints specified. Otherwise, the value of this [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble)
will guide the user agent in its efforts to provide an exact match to the required frame
rate (if `exact` is specified or both `min` and `max`
are provided and have the same value) or to a best-possible value.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/autogaincontrol/index.md | ---
title: "MediaTrackConstraints: autoGainControl property"
short-title: autoGainControl
slug: Web/API/MediaTrackConstraints/autoGainControl
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.autoGainControl
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's **`autoGainControl`** property is a [`ConstrainBoolean`](/en-US/docs/Web/API/MediaTrackConstraints#constrainboolean) describing the requested or mandatory constraints placed
upon the value of the {{domxref("MediaTrackSettings.autoGainControl", "autoGainControl")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.autoGainControl")}} as returned
by a call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically
this is unnecessary since browsers will ignore any constraints they're unfamiliar with.
Automatic gain control is typically a feature provided by microphones, although it can
be provided by other input sources as well.
## Value
If this value is a simple `true` or `false`, the user agent will
attempt to obtain media with automatic gain control enabled or disabled as specified, if
possible, but will not fail if this can't be done. If, instead, the value is given as an
object with an `exact` field, that field's Boolean value indicates a required
setting for the automatic gain control feature; if it can't be met, then the request
will result in an error.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/suppresslocalaudioplayback/index.md | ---
title: "MediaTrackConstraints: suppressLocalAudioPlayback property"
short-title: suppressLocalAudioPlayback
slug: Web/API/MediaTrackConstraints/suppressLocalAudioPlayback
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.MediaTrackConstraints.suppressLocalAudioPlayback
---
{{APIRef("Media Capture and Streams")}}{{SeeCompatTable}}
The {{domxref("MediaTrackConstraints")}} dictionary's **`suppressLocalAudioPlayback`** property is a [`ConstrainBoolean`](/en-US/docs/Web/API/MediaTrackConstraints#constrainboolean) describing the requested or mandatory constraints placed upon the value of the {{domxref("MediaTrackSettings.suppressLocalAudioPlayback","suppressLocalAudioPlayback")}} constrainable property. This property controls whether the audio playing in a tab will continue to be played out of a user's local speakers when the tab is captured.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.suppressLocalAudioPlayback")}} as returned
by a call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically
this is unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
A [`ConstrainBoolean`](/en-US/docs/Web/API/MediaTrackConstraints#constrainboolean) value.
If this value is a simple `true` or `false`, the user agent will
attempt to obtain media with local audio playback enabled or disabled as specified, if
possible, but will not fail if this can't be done.
If the value is given as `ideal`, that field's boolean value indicates an ideal
setting for the local audio playback suppression feature; if it can't be met, then the request will
result in an error.
## Examples
```js
let isLocalAudioSuppressed = displayStream
.getVideoTracks()[0]
.getSettings().suppressLocalAudioPlayback;
```
The [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example shows how to use media track constraints.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/latency/index.md | ---
title: "MediaTrackConstraints: latency property"
short-title: latency
slug: Web/API/MediaTrackConstraints/latency
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.latency
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`latency`** property is a [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.latency", "latency")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.latency")}} as returned by a call
to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this is
unnecessary since browsers will ignore any constraints they're unfamiliar with.
Because {{Glossary("RTP")}} doesn't include this information, tracks associated with a
[WebRTC](/en-US/docs/Web/API/WebRTC_API) {{domxref("RTCPeerConnection")}}
will never include this property.
## Value
A [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) describing the acceptable or required value(s) for an
audio track's latency, with values specified in seconds. In audio processing, latency is
the time between the start of processing (when sound occurs in the real world, or is
generated by a hardware device) and the data being made available to the next step in
the audio input or output process. In most cases, low latency is desirable for
performance and user experience purposes, but when power consumption is a concern, or
delays are otherwise acceptable, higher latency might be acceptable.
If this property's value is a number, the user agent will attempt to obtain media whose
latency tends to be as close as possible to this number given the capabilities of the
hardware and the other constraints specified. Otherwise, the value of this
[`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) will guide the user agent in its efforts to provide an
exact match to the required latency (if `exact` is specified or both
`min` and `max` are provided and have the same value) or to a
best-possible value.
> **Note:** Latency is always prone to some variation due to hardware usage demands, network
> constraints, and so forth, so even in an "exact" match, some variation should be
> expected.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/channelcount/index.md | ---
title: "MediaTrackConstraints: channelCount property"
short-title: channelCount
slug: Web/API/MediaTrackConstraints/channelCount
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.channelCount
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`channelCount`** property is a [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.channelCount", "channelCount")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.channelCount")}} as returned by a
call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this
is unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
If this value is a number, the user agent will attempt to obtain media whose channel
count is as close as possible to this number given the capabilities of the hardware and
the other constraints specified. Otherwise, the value of this
[`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong) will guide the user agent in its efforts to provide an
exact match to the required channel count (if `exact` is specified or both
`min` and `max` are provided and have the same value) or to a
best-possible value.
The channel count is 1 for monaural sound, 2 for stereo, and so forth.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/facingmode/index.md | ---
title: "MediaTrackConstraints: facingMode property"
short-title: facingMode
slug: Web/API/MediaTrackConstraints/facingMode
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.facingMode
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`facingMode`** property is a [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.facingMode", "facingMode")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.facingMode")}} as returned by a
call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this
is unnecessary since browsers will ignore any constraints they're unfamiliar with.
Because {{Glossary("RTP")}} doesn't include this information, tracks associated with a
[WebRTC](/en-US/docs/Web/API/WebRTC_API) {{domxref("RTCPeerConnection")}}
will never include this property.
## Value
An object based on [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring) specifying one or more acceptable,
ideal, and/or exact (mandatory) facing modes are acceptable for a video track.
An `exact` value in this case indicates that the specified facing mode is
specifically required; for example:
```js
const constraints = {
facingMode: { exact: "user" },
};
```
This indicates that only a user-facing camera is acceptable; if there is no user-facing
camera, or the user declines permission to use that camera, the media request will fail.
The following strings are permitted values for the facing mode. These may represent
separate cameras, or they may represent directions in which an adjustable camera can be
pointed.
- `"user"`
- : The video source is facing toward the user; this includes, for example, the
front-facing camera on a smartphone.
- `"environment"`
- : The video source is facing away from the user, thereby viewing their environment.
This is the back camera on a smartphone.
- `"left"`
- : The video source is facing toward the user but to their left, such as a camera aimed
toward the user but over their left shoulder.
- `"right"`
- : The video source is facing toward the user but to their right, such as a camera
aimed toward the user but over their right shoulder.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/width/index.md | ---
title: "MediaTrackConstraints: width property"
short-title: width
slug: Web/API/MediaTrackConstraints/width
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.width
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`width`** property is a [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.width", "width")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.width")}} as returned by a call
to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this is
unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
If this value is a number, the user agent will attempt to obtain media whose width is
as close as possible to this number given the capabilities of the hardware and the other
constraints specified. Otherwise, the value of this [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong) will
guide the user agent in its efforts to provide an exact match to the required width (if
`exact` is specified or both `min` and `max` are
provided and have the same value) or to a best-possible value.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/height/index.md | ---
title: "MediaTrackConstraints: height property"
short-title: height
slug: Web/API/MediaTrackConstraints/height
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.height
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`height`** property is a [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.height", "height")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.height")}} as returned by a call
to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this is
unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
If this value is a number, the user agent will attempt to obtain media whose height is
as close as possible to this number given the capabilities of the hardware and the other
constraints specified. Otherwise, the value of this [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong) will
guide the user agent in its efforts to provide an exact match to the required height (if
`exact` is specified or both `min` and `max` are
provided and have the same value) or to a best-possible value.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/deviceid/index.md | ---
title: "MediaTrackConstraints: deviceId property"
short-title: deviceId
slug: Web/API/MediaTrackConstraints/deviceId
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.deviceId
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`deviceId`** property is a [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.deviceId", "deviceId")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.deviceId")}} as returned by a
call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this
is unnecessary since browsers will ignore any constraints they're unfamiliar with.
Because {{Glossary("RTP")}} doesn't include this information, tracks associated with a
[WebRTC](/en-US/docs/Web/API/WebRTC_API) {{domxref("RTCPeerConnection")}}
will never include this property.
## Value
An object based on [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring) specifying one or more acceptable,
ideal, and/or exact (mandatory) device IDs which are acceptable as the source of media
content.
Device IDs are unique for a given origin, and are guaranteed to be the same across
browsing sessions on the same origin. However, the value of the `deviceId` is
determined by the source of the track's content, and there's no particular format
mandated by the specification (although some kind of GUID is recommended). That means
that a given track will only return one value for the `deviceId` when you
call {{domxref("MediaStreamTrack.getCapabilities", "getCapabilities()")}}.
Because of this, there's no use for the device ID when calling
{{domxref("MediaStreamTrack.applyConstraints()")}}, since there is only one possible
value; however, you can record a `deviceId` and use it to ensure that you get
the same source for multiple calls to {{domxref("MediaDevices.getUserMedia",
"getUserMedia()")}}.
> **Note:** An exception to the rule that device IDs are the same across browsing sessions:
> private browsing mode will use a different ID, and will change it each browsing
> session.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/displaysurface/index.md | ---
title: "MediaTrackConstraints: displaySurface property"
short-title: displaySurface
slug: Web/API/MediaTrackConstraints/displaySurface
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.displaySurface
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's **`displaySurface`** property is a [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring) describing the preferred value for the {{domxref("MediaTrackSettings.displaySurface","displaySurface")}} constrainable property.
This is set by the application to identify to the user agent the type of display surface (`window`, `browser`, or `monitor`) preferred by the application. It has no effect on what the user can choose to share, but may be used to present the options in a different order.
If needed, you can determine whether or not this constraint is supported by checking the value of {{domxref("MediaTrackSupportedConstraints.displaySurface")}} as returned by a call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this is unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
A [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring) which specifies the type of display surface preferred by the application.
This value _does not_ add or remove display sources in the browser's user interface, but may reorder them. You can't use this property to limit the user to a subset of the three display-surface values `window`, `browser`, and `monitor` — but, as you will see below, you can see what was chosen, and reject it.
See [how constraints are defined](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#how_constraints_are_defined).
> **Note:** You cannot set [`monitorTypeSurfaces: "exclude"`](/en-US/docs/Web/API/MediaDevices/getDisplayMedia#monitortypesurfaces) at the same time as `displaySurface: "monitor"` as the two settings are contradictory. Trying to do so will result in the associated `getDisplayMedia()` call failing with a `TypeError`.
## Usage notes
You can check the setting selected by the user agent after the display media has been
created by {{domxref("MediaDevices.getDisplayMedia", "getDisplayMedia()")}} by calling
{{domxref("MediaStreamTrack.getSettings", "getSettings()")}} on the display media's
video {{domxref("MediaStreamTrack")}}, then checking the value of the returned
{{domxref("MediaTrackSettings")}} object's
{{domxref("MediaTrackSettings.displaySurface", "displaySurface")}} object.
For example, if your app prefers not to share a monitor — meaning that there's possibly a non-content backdrop being captured — it can use code similar
to this:
```js
let mayHaveBackdropFlag = false;
let displaySurface = displayStream
.getVideoTracks()[0]
.getSettings().displaySurface;
if (displaySurface === "monitor") {
mayHaveBackdropFlag = true;
}
```
Following this code, `mayHaveBackdrop` is `true` if the display
surface contained in the stream is of type `monitor`.
Later code can use this flag to determine whether or not to perform special processing,
such as to remove or replace the backdrop, or to "cut" the individual display areas out
of the received frames of video.
## Examples
Here are some example constraints objects for `getDisplayMedia()` that make
use of the `displaySurface` property.
```js
dsConstraints = { displaySurface: "window" }; // 'browser' and 'monitor' are also possible
applyConstraints(dsConstraints);
// The user still may choose to share the monitor or the browser,
// but we indicated that a window is preferred.
```
In addition, see the
[Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example
that demonstrates how constraints are used.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Screen Capture API](/en-US/docs/Web/API/Screen_Capture_API)
- [Using the Screen Capture API](/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/groupid/index.md | ---
title: "MediaTrackConstraints: groupId property"
short-title: groupId
slug: Web/API/MediaTrackConstraints/groupId
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.groupId
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`groupId`** property is a [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.groupId", "groupId")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.groupId")}} as returned by a call
to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this is
unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
An object based on [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring) specifying one or more acceptable,
ideal, and/or exact (mandatory) group IDs which are acceptable as the source of media
content.
Group IDs are unique for a given origin for the duration of a single browsing session,
and are shared by all media sources that come from the same physical device. For
example, the microphone and speaker on the same headset would share a group ID. This
makes it possible to use the group ID to ensure that the audio and input devices are on
the same headset by retrieving the group ID of the input device and specifying it when
asking for an output device, perhaps.
However, the value of the `groupId` is determined by the source of the
track's content, and there's no particular format mandated by the specification
(although some kind of GUID is recommended). That means that a given track will only
return one value for the `groupId` when you call
{{domxref("MediaStreamTrack.getCapabilities", "getCapabilities()")}}, and keep in mind
that this value will change for each browsing session.
Because of this, there's no use for the group ID when calling
{{domxref("MediaStreamTrack.applyConstraints()")}}, since there is only one possible
value, and you can't use it to ensure the same group is used across multiple browsing
sessions when calling `getUserMedia()`.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/samplerate/index.md | ---
title: "MediaTrackConstraints: sampleRate property"
short-title: sampleRate
slug: Web/API/MediaTrackConstraints/sampleRate
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.sampleRate
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's
**`sampleRate`** property is a [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong)
describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.sampleRate", "sampleRate")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.sampleRate")}} as returned by a
call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this
is unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
If this value is a number, the user agent will attempt to obtain media whose sample
rate is as close as possible to this number given the capabilities of the hardware and
the other constraints specified. Otherwise, the value of this
[`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong) will guide the user agent in its efforts to provide an
exact match to the required sample rate (if `exact` is specified or both
`min` and `max` are provided and have the same value) or to a
best-possible value.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediatrackconstraints | data/mdn-content/files/en-us/web/api/mediatrackconstraints/aspectratio/index.md | ---
title: "MediaTrackConstraints: aspectRatio property"
short-title: aspectRatio
slug: Web/API/MediaTrackConstraints/aspectRatio
page-type: web-api-instance-property
browser-compat: api.MediaTrackConstraints.aspectRatio
---
{{APIRef("Media Capture and Streams")}}
The {{domxref("MediaTrackConstraints")}} dictionary's **`aspectRatio`** property is a [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) describing the requested or mandatory constraints placed upon the value of the
{{domxref("MediaTrackSettings.aspectRatio", "aspectRatio")}} constrainable property.
If needed, you can determine whether or not this constraint is supported by checking
the value of {{domxref("MediaTrackSupportedConstraints.aspectRatio")}} as returned by a
call to {{domxref("MediaDevices.getSupportedConstraints()")}}. However, typically this
is unnecessary since browsers will ignore any constraints they're unfamiliar with.
## Value
A [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) describing the acceptable or required value(s) for a
video track's aspect ratio. The value is the width divided by the height and is rounded
to ten decimal places. For example, the standard high-definition video aspect ratio of
16:9 can be computed as 1920/1080, or 1.7777777778.
If this value is a number, the user agent will attempt to obtain media whose aspect
ratio is as close as possible to this number given the capabilities of the hardware and
the other constraints specified. Otherwise, the value of this
[`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) will guide the user agent in its efforts to provide an
exact match to the required aspect ratio (if `exact` is specified or both
`min` and `max` are provided and have the same value) or to a
best-possible value.
## Examples
See the [Constraint exerciser](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#example_constraint_exerciser) example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints)
- {{domxref("MediaTrackConstraints")}}
- {{domxref("MediaDevices.getSupportedConstraints()")}}
- {{domxref("MediaTrackSupportedConstraints")}}
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/serviceworkercontainer/index.md | ---
title: ServiceWorkerContainer
slug: Web/API/ServiceWorkerContainer
page-type: web-api-interface
browser-compat: api.ServiceWorkerContainer
---
{{APIRef("Service Workers API")}}{{SecureContext_Header}}
The **`ServiceWorkerContainer`** interface of the [Service Worker API](/en-US/docs/Web/API/Service_Worker_API) provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.
Most importantly, it exposes the {{domxref("ServiceWorkerContainer.register()")}} method used to register service workers, and the {{domxref("ServiceWorkerContainer.controller")}} property used to determine whether or not the current page is actively controlled.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("ServiceWorkerContainer.controller")}} {{ReadOnlyInline}}
- : Returns a {{domxref("ServiceWorker")}} object if its state is `activating` or `activated` (the same object returned by {{domxref("ServiceWorkerRegistration.active")}}). This property returns `null` during a force-refresh request (_Shift_ + refresh) or if there is no active worker.
- {{domxref("ServiceWorkerContainer.ready")}} {{ReadOnlyInline}}
- : Provides a way of delaying code execution until a service worker is active. It returns a {{jsxref("Promise")}} that will never reject, and which waits indefinitely until the {{domxref("ServiceWorkerRegistration")}} associated with the current page has an {{domxref("ServiceWorkerRegistration.active")}} worker. Once that condition is met, it resolves with the {{domxref("ServiceWorkerRegistration")}}.
## Instance methods
- {{domxref("ServiceWorkerContainer.getRegistration()")}}
- : Gets a {{domxref("ServiceWorkerRegistration")}} object whose scope matches the provided document URL. The method returns a {{jsxref("Promise")}} that resolves to a {{domxref("ServiceWorkerRegistration")}} or `undefined`.
- {{domxref("ServiceWorkerContainer.getRegistrations()")}}
- : Returns all {{domxref("ServiceWorkerRegistration")}} objects associated with a `ServiceWorkerContainer` in an array. The method returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("ServiceWorkerRegistration")}}.
- {{domxref("ServiceWorkerContainer.register()")}}
- : Creates or updates a {{domxref("ServiceWorkerRegistration")}} for the given `scriptURL`.
- {{domxref("ServiceWorkerContainer.startMessages()")}}
- : explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via {{domxref("Client.postMessage()")}}). This can be used to react to sent messages earlier, even before that page's content has finished loading.
## Events
- {{domxref("ServiceWorkerContainer/controllerchange_event", "controllerchange")}}
- : Occurs when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active","active")}} worker.
- {{domxref("ServiceWorkerContainer/error_event", "error")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Fired whenever an error occurs in the associated service workers.
- {{domxref("ServiceWorkerContainer/message_event", "message")}}
- : Occurs when incoming messages are received by the {{domxref("ServiceWorkerContainer")}} object (e.g. via a {{domxref("MessagePort.postMessage()")}} call).
- {{domxref("ServiceWorkerContainer/messageerror_event", "messageerror")}}
- : Occurs when incoming messages can not deserialized by the {{domxref("ServiceWorkerContainer")}} object (e.g. via a {{domxref("MessagePort.postMessage()")}} call).
## Examples
The example below first checks to see if the browser supports service workers. If supported, the code registers the service worker and determines if the page is actively controlled by the service worker. If it isn't, it prompts the user to reload the page so the service worker can take control. The code also reports any registration failures.
```js
if ("serviceWorker" in navigator) {
// Register a service worker hosted at the root of the
// site using the default scope.
navigator.serviceWorker
.register("/sw.js")
.then((registration) => {
console.log("Service worker registration succeeded:", registration);
// At this point, you can optionally do something
// with registration. See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
})
.catch((error) => {
console.error(`Service worker registration failed: ${error}`);
});
// Independent of the registration, let's also display
// information about whether the current page is controlled
// by an existing service worker, and when that
// controller changes.
// First, do a one-off check if there's currently a
// service worker in control.
if (navigator.serviceWorker.controller) {
console.log(
"This page is currently controlled by:",
navigator.serviceWorker.controller,
);
}
// Then, register a handler to detect when a new or
// updated service worker takes control.
navigator.serviceWorker.oncontrollerchange = () => {
console.log(
"This page is now controlled by",
navigator.serviceWorker.controller,
);
};
} else {
console.log("Service workers are not supported.");
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
- [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
- [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
| 0 |
data/mdn-content/files/en-us/web/api/serviceworkercontainer | data/mdn-content/files/en-us/web/api/serviceworkercontainer/register/index.md | ---
title: "ServiceWorkerContainer: register() method"
short-title: register()
slug: Web/API/ServiceWorkerContainer/register
page-type: web-api-instance-method
browser-compat: api.ServiceWorkerContainer.register
---
{{APIRef("Service Workers API")}}{{SecureContext_Header}}
The **`register()`** method of the
{{domxref("ServiceWorkerContainer")}} interface creates or updates a
{{domxref("ServiceWorkerRegistration")}} for the given `scriptURL`.
If successful, a service worker registration ties the provided script URL to a
_scope_, which is subsequently used for navigation matching. You can call this
method unconditionally from the controlled page. I.e., you don't need to first check
whether there's an active registration.
There is frequent confusion surrounding the meaning and use of _scope_. Since a
service worker can't have a scope broader than its own location, only use the
`scope` option when you need a scope that is narrower than the default.
## Syntax
```js-nolint
register(scriptURL)
register(scriptURL, options)
```
### Parameters
- `scriptURL`
- : The URL of the service worker script. The registered service worker file needs to
have a valid [JavaScript MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#textjavascript).
- `options` {{optional_inline}}
- : An object containing registration options. Currently available options are:
- `scope`
- : A string representing a URL that defines a
service worker's registration scope; that is, what range of URLs a service worker
can control. This is usually a relative URL. It is relative to the base URL of the
application. By default, the `scope` value for a service worker
registration is set to the directory where the service worker script is located.
See the [Examples](#examples) section for more information on how it
works.
- `type`
- : A string
specifying the type of worker to create. Valid values are:
- `'classic'`
- : The loaded service worker is in a standard script. This is the default.
- `'module'`
- : The loaded service worker is in an
[ES module](/en-US/docs/Web/JavaScript/Guide/Modules)
and the import statement is available on
worker contexts. For ES module compatibility info, see the [browser compatibility data table for the `ServiceWorker` interface](/en-US/docs/Web/API/ServiceWorker#browser_compatibility).
- `updateViaCache`
- : A string indicating how the HTTP cache is used for service worker scripts resources during updates. Note: This only refers to the service worker script and its imports, not other resources fetched by these scripts.
- `'all'`
- : The HTTP cache will be queried for the main script, and all imported scripts. If no fresh entry is found in the HTTP cache, then the scripts are fetched from the network.
- `'imports'`
- : The HTTP cache will be queried for imports, but the main script will always be updated from the network. If no fresh entry is found in the HTTP cache for the imports, they're fetched from the network.
- `'none'`
- : The HTTP cache will not be used for the main script or its imports. All service worker script resources will be updated from the network.
### Return value
A {{jsxref("Promise")}} that resolves with a {{domxref("ServiceWorkerRegistration")}}
object.
## Examples
The examples described here should be taken together to get a better understanding of
how service workers scope applies to a page.
The following example uses the default value of `scope` (by omitting it).
The service worker code in this case, if
included in `example.com/index.html`, will
control `example.com/index.html`, as well as pages underneath it, like
`example.com/product/description.html`.
```js
if ("serviceWorker" in navigator) {
// Register a service worker hosted at the root of the
// site using the default scope.
navigator.serviceWorker.register("/sw.js").then(
(registration) => {
console.log("Service worker registration succeeded:", registration);
},
(error) => {
console.error(`Service worker registration failed: ${error}`);
},
);
} else {
console.error("Service workers are not supported.");
}
```
The following code, if included in `example.com/index.html`, at the root of
a site, would apply to exactly the same pages as the example above. Remember the scope,
when included, uses the page's location as its base.
Alternatively, if this code were included in a page at
`example.com/product/description.html`, with the JavaScript file residing
at `example.com/product/sw.js`, then the service worker would only apply to
resources under `example.com/product`.
```js
if ("serviceWorker" in navigator) {
// declaring scope manually
navigator.serviceWorker.register("/sw.js", { scope: "./" }).then(
(registration) => {
console.log("Service worker registration succeeded:", registration);
},
(error) => {
console.error(`Service worker registration failed: ${error}`);
},
);
} else {
console.error("Service workers are not supported.");
}
```
There is frequent confusion surrounding the meaning and use of _scope_. Since a
service worker can't have a scope broader than its own location, only use the
`scope` option when you need a scope that is narrower than the default.
The following code, if included in `example.com/index.html`, at the root of
a site, would only apply to resources under `example.com/product`.
```js
if ("serviceWorker" in navigator) {
// declaring scope manually
navigator.serviceWorker.register("/sw.js", { scope: "/product/" }).then(
(registration) => {
console.log("Service worker registration succeeded:", registration);
},
(error) => {
console.error(`Service worker registration failed: ${error}`);
},
);
} else {
console.error("Service workers are not supported.");
}
```
However, servers can remove this restriction by setting a [Service-Worker-Allowed](https://w3c.github.io/ServiceWorker/#service-worker-allowed) header on the service
worker script, and then you can specify a max scope for that service worker above the
service worker's location.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorkerRegistration: `unregister()` method](/en-US/docs/Web/API/ServiceWorkerRegistration/unregister)
- [Service worker API](/en-US/docs/Web/API/Service_Worker_API)
- [Using service workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
| 0 |
data/mdn-content/files/en-us/web/api/serviceworkercontainer | data/mdn-content/files/en-us/web/api/serviceworkercontainer/messageerror_event/index.md | ---
title: "ServiceWorkerContainer: messageerror event"
short-title: messageerror
slug: Web/API/ServiceWorkerContainer/messageerror_event
page-type: web-api-event
browser-compat: api.ServiceWorkerContainer.messageerror_event
---
{{APIRef("Service Workers API")}}{{SecureContext_Header}}
The **`messageerror`** event is fired to the {{domxref("ServiceWorkerContainer")}} when an incoming message sent to the associated worker can't be deserialized.
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener()", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("messageerror", (event) => {});
onmessageerror = (event) => {};
```
## Event type
A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MessageEvent")}}
## Event properties
_This interface also inherits properties from its parent, {{domxref("Event")}}._
- {{domxref("MessageEvent.data")}} {{ReadOnlyInline}}
- : The data sent by the message emitter.
- {{domxref("MessageEvent.origin")}} {{ReadOnlyInline}}
- : A string representing the origin of the message emitter.
- {{domxref("MessageEvent.lastEventId")}} {{ReadOnlyInline}}
- : A string representing a unique ID for the event.
- {{domxref("MessageEvent.source")}} {{ReadOnlyInline}}
- : A `MessageEventSource` (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter.
- {{domxref("MessageEvent.ports")}} {{ReadOnlyInline}}
- : An array of {{domxref("MessagePort")}} objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).
## Examples
In this example the service worker get the client's ID from a {{domxref("ServiceWorkerGlobalScope/fetch_event", "fetch")}} event and then sends it a message using {{domxref("Client.postMessage")}}:
```js
// service-worker.js
async function messageClient(clientId) {
const client = await self.clients.get(clientId);
client.postMessage("Hi client!");
}
self.addEventListener("fetch", (event) => {
messageClient(event.clientId);
event.respondWith(() => {
// …
});
});
```
The service worker can listen for the message deserialization error by listening to the `messageerror` event:
```js
// main.js
navigator.serviceWorker.addEventListener("messageerror", (event) => {
console.error("Receive message from service worker failed!");
});
```
Alternatively, the script can listen for the message deserialization error using `onmessageerror`:
```js
// main.js
navigator.serviceWorker.onmessageerror = (event) => {
console.error("Receive message from service worker failed!");
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ServiceWorkerContainer/message_event", "message")}}
- {{domxref("Client.postMessage()")}}
- [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
- [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
- [Using Web Workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
| 0 |
data/mdn-content/files/en-us/web/api/serviceworkercontainer | data/mdn-content/files/en-us/web/api/serviceworkercontainer/controllerchange_event/index.md | ---
title: "ServiceWorkerContainer: controllerchange event"
short-title: controllerchange
slug: Web/API/ServiceWorkerContainer/controllerchange_event
page-type: web-api-event
browser-compat: api.ServiceWorkerContainer.controllerchange_event
---
{{APIRef("Service Workers API")}}{{SecureContext_Header}}
The **`controllerchange`** event of the {{domxref("ServiceWorkerContainer")}} interface fires when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active","active")}} worker.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("controllerchange", (event) => {});
oncontrollerchange = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Example
```js
navigator.serviceWorker.addEventListener("controllerchange", () => {
console.log("The controller of current browsing context has changed.");
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.