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/readablestream | data/mdn-content/files/en-us/web/api/readablestream/cancel/index.md | ---
title: "ReadableStream: cancel() method"
short-title: cancel()
slug: Web/API/ReadableStream/cancel
page-type: web-api-instance-method
browser-compat: api.ReadableStream.cancel
---
{{APIRef("Streams")}}
The **`cancel()`** method of the {{domxref("ReadableStream")}} interface returns a {{jsxref("Promise")}} that resolves when the stream is canceled.
Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read.
That data is lost after cancel is called, and the stream is not readable any more.
To read those chunks still and not completely get rid of the stream, you'd use {{domxref("ReadableStreamDefaultController.close()")}}.
## Syntax
```js-nolint
cancel()
cancel(reason)
```
### Parameters
- `reason` {{optional_inline}}
- : A human-readable reason for the cancellation.
This is passed to the underlying source, which may or may not use it.
### Return value
A {{jsxref("Promise")}}, which fulfills with `undefined` value.
### Exceptions
- {{jsxref("TypeError")}}
- : The stream you are trying to cancel is not a {{domxref("ReadableStream")}}, or it is locked.
## Examples
In Jake Archibald's [cancelling a fetch](https://jsbin.com/gameboy/edit?js,console) example, a stream is used to fetch the WHATWG HTML spec chunk by chunk;
each chunk is searched for the string "service workers". When the search terms is found, `cancel()` is used to cancel the stream — the job is finished so it is no longer needed.
```js
const searchTerm = "service workers";
// Chars to show either side of the result in the match
const contextBefore = 30;
const contextAfter = 30;
const caseInsensitive = true;
const url = "https://html.spec.whatwg.org/";
console.log(`Searching '${url}' for '${searchTerm}'`);
fetch(url)
.then((response) => {
console.log("Received headers");
const decoder = new TextDecoder();
const reader = response.body.getReader();
const toMatch = caseInsensitive ? searchTerm.toLowerCase() : searchTerm;
const bufferSize = Math.max(toMatch.length - 1, contextBefore);
let bytesReceived = 0;
let buffer = "";
let matchFoundAt = -1;
return reader.read().then(function process(result) {
if (result.done) {
console.log("Failed to find match");
return;
}
bytesReceived += result.value.length;
console.log(`Received ${bytesReceived} bytes of data so far`);
buffer += decoder.decode(result.value, { stream: true });
// already found match & just context-gathering?
if (matchFoundAt === -1) {
matchFoundAt = (
caseInsensitive ? buffer.toLowerCase() : buffer
).indexOf(toMatch);
}
if (matchFoundAt === -1) {
buffer = buffer.slice(-bufferSize);
} else if (
buffer.slice(matchFoundAt + toMatch.length).length >= contextAfter
) {
console.log("Here's the match:");
console.log(
buffer.slice(
Math.max(0, matchFoundAt - contextBefore),
matchFoundAt + toMatch.length + contextAfter,
),
);
console.log("Cancelling fetch");
reader.cancel();
return;
} else {
console.log("Found match, but need more context…");
}
// keep reading
return reader.read().then(process);
});
})
.catch((err) => {
console.error(
"Something went wrong. See devtools for details. Does the response lack CORS headers?",
);
throw err;
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor
- [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestream | data/mdn-content/files/en-us/web/api/readablestream/tee/index.md | ---
title: "ReadableStream: tee() method"
short-title: tee()
slug: Web/API/ReadableStream/tee
page-type: web-api-instance-method
browser-compat: api.ReadableStream.tee
---
{{APIRef("Streams")}}
The **`tee()`** method of the
{{domxref("ReadableStream")}} interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a
two-element array containing the two resulting branches as
new {{domxref("ReadableStream")}} instances.
This is useful for allowing two readers to read a stream sequentially or simultaneously,
perhaps at different speeds.
For example, you might do this in a ServiceWorker if you want to fetch
a response from the server and stream it to the browser, but also stream it to the
ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need
two copies to do this.
A teed stream will partially signal backpressure at the rate of the _faster_ consumer
of the two `ReadableStream` branches,
and unread data is enqueued internally on the slower consumed `ReadableStream`
without any limit or backpressure.
That is, when _both_ branches have an unread element in their internal queue,
then the original `ReadableStream`'s controller's internal queue will start to fill up,
and once its {{domxref("ReadableStreamDefaultController.desiredSize", "desiredSize")}} ≤ 0
or byte stream controller {{domxref("ReadableByteStreamController.desiredSize", "desiredSize")}} ≤ 0,
then the controller will stop calling `pull(controller)` on the
underlying source passed to {{domxref("ReadableStream.ReadableStream", "new ReadableStream()")}}.
If only one branch is consumed, then the entire body will be enqueued in memory.
Therefore, you should not use the built-in `tee()` to read very large streams
in parallel at different speeds.
Instead, search for an implementation that fully backpressures
to the speed of the _slower_ consumed branch.
To cancel the stream you then need to cancel both resulting branches. Teeing a stream
will generally lock it for the duration, preventing other readers from locking it.
## Syntax
```js-nolint
tee()
```
### Parameters
None.
### Return value
An {{jsxref("Array")}} containing two {{domxref("ReadableStream")}} instances.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the source stream is not a `ReadableStream`.
## Examples
In the following simple example, a previously-created stream is teed, then both
resulting streams (contained in two members of a generated array) are passed to a
function that reads the data out of the two streams and prints each stream's chunks
sequentially to a different part of the UI. See [Simple tee example](https://mdn.github.io/dom-examples/streams/simple-tee-example/) for the full code.
```js
function teeStream() {
const teedOff = stream.tee();
fetchStream(teedOff[0], list2);
fetchStream(teedOff[1], list3);
}
function fetchStream(stream, list) {
const reader = stream.getReader();
let charsReceived = 0;
// read() returns a promise that resolves
// when a value has been received
reader.read().then(function processText({ done, value }) {
// Result objects contain two properties:
// done - true if the stream has already given you all its data.
// value - some data. Always undefined when done is true.
if (done) {
console.log("Stream complete");
return;
}
// value for fetch streams is a Uint8Array
charsReceived += value.length;
const chunk = value;
let listItem = document.createElement("li");
listItem.textContent = `Read ${charsReceived} characters so far. Current chunk = ${chunk}`;
list.appendChild(listItem);
// Read some more, and call this function again
return reader.read().then(processText);
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor
- [Teeing a stream](/en-US/docs/Web/API/Streams_API/Using_readable_streams#teeing_a_stream)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/fontfacesetloadevent/index.md | ---
title: FontFaceSetLoadEvent
slug: Web/API/FontFaceSetLoadEvent
page-type: web-api-interface
browser-compat: api.FontFaceSetLoadEvent
---
{{APIRef("CSS Font Loading API")}}
The **`FontFaceSetLoadEvent`** interface of the [CSS Font Loading API](/en-US/docs/Web/API/CSS_Font_Loading_API) represents events fired at a {{domxref("FontFaceSet")}} after it starts loading font faces.
Events are fired when font loading starts ([`loading`](/en-US/docs/Web/API/FontFaceSet/loading_event)), loading completes ([`loadingdone`](/en-US/docs/Web/API/FontFaceSet/loadingdone_event)) or there is an error loading one of the fonts ([`loadingerror`](/en-US/docs/Web/API/FontFaceSet/loadingerror_event)).
{{InheritanceDiagram}}
## Constructor
- {{domxref("FontFaceSetLoadEvent.FontFaceSetLoadEvent","FontFaceSetLoadEvent()")}}
- : Creates a new `FontFaceSetLoadEvent` object.
## Instance properties
_Also inherits properties from its parent {{domxref("Event")}}_.
- {{domxref("FontFaceSetLoadEvent.fontfaces")}} {{ReadOnlyInline}}
- : Returns an array of {{domxref("FontFace")}} instances.
Depending on the event, the array will contain font faces that are loading (`loading`), have successfully loaded (`loadingdone`), or have failed to load (`loadingerror`).
## Instance methods
_Inherits methods from its parent, {{domxref("Event")}}_.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Document.fonts")}}
- {{domxref("WorkerGlobalScope.fonts")}}
| 0 |
data/mdn-content/files/en-us/web/api/fontfacesetloadevent | data/mdn-content/files/en-us/web/api/fontfacesetloadevent/fontfaces/index.md | ---
title: "FontFaceSetLoadEvent: fontfaces property"
short-title: fontfaces
slug: Web/API/FontFaceSetLoadEvent/fontfaces
page-type: web-api-instance-property
browser-compat: api.FontFaceSetLoadEvent.fontfaces
---
{{APIRef("CSS Font Loading API")}}
The **`fontfaces`** read-only property of the
{{domxref("FontFaceSetLoadEvent")}} interface returns an array of
{{domxref("FontFace")}} instances, each of which represents a single usable font.
## Value
An array of {{domxref("FontFace")}} instance.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontfacesetloadevent | data/mdn-content/files/en-us/web/api/fontfacesetloadevent/fontfacesetloadevent/index.md | ---
title: "FontFaceSetLoadEvent: FontFaceSetLoadEvent() constructor"
short-title: FontFaceSetLoadEvent()
slug: Web/API/FontFaceSetLoadEvent/FontFaceSetLoadEvent
page-type: web-api-constructor
browser-compat: api.FontFaceSetLoadEvent.FontFaceSetLoadEvent
---
{{APIRef("CSS Font Loading API")}}
The **`FontFaceSetLoadEvent()`** constructor creates a new
{{domxref("FontFaceSetLoadEvent")}} object which is fired whenever a
{{domxref("FontFaceSet")}} loads.
## Syntax
```js-nolint
new FontFaceSetLoadEvent(type)
new FontFaceSetLoadEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `loading`, `loadingdone`, or `loadingerror`.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `fontfaces` {{optional_inline}}
- : An array of {{domxref("FontFace")}} instances. It defaults to the empty array.
### Return value
A new {{domxref("FontFaceSetLoadEvent")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/navigateevent/index.md | ---
title: NavigateEvent
slug: Web/API/NavigateEvent
page-type: web-api-interface
status:
- experimental
browser-compat: api.NavigateEvent
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`NavigateEvent`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} is the event object for the {{domxref("Navigation/navigate_event", "navigate")}} event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated (this includes usage of {{domxref("History API", "History API", "", "nocode")}} features like {{domxref("History.go()")}}). `NavigateEvent` provides access to information about that navigation, and allows developers to intercept and control the navigation handling.
{{InheritanceDiagram}}
## Constructor
- {{domxref("NavigateEvent.NavigateEvent", "NavigateEvent()")}} {{Experimental_Inline}}
- : Creates a new `NavigateEvent` object instance.
## Instance properties
_Inherits properties from its parent, {{DOMxRef("Event")}}._
- {{domxref("NavigateEvent.canIntercept", "canIntercept")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns `true` if the navigation can be intercepted, or `false` otherwise (e.g. you can't intercept a cross-origin navigation).
- {{domxref("NavigateEvent.destination", "destination")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("NavigationDestination")}} object representing the destination being navigated to.
- {{domxref("NavigateEvent.downloadRequest", "downloadRequest")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the filename of the file requested for download, in the case of a download navigation (e.g. an {{htmlelement("a")}} or {{htmlelement("area")}} element with a `download` attribute), or `null` otherwise.
- {{domxref("NavigateEvent.formData", "formData")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the {{domxref("FormData")}} object representing the submitted data in the case of a `POST` form submission, or `null` otherwise.
- {{domxref("NavigateEvent.hashChange", "hashChange")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns `true` if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document), or `false` otherwise.
- {{domxref("NavigateEvent.info", "info")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the `info` data value passed by the initiating navigation operation (e.g. {{domxref("Navigation.back()")}}, or {{domxref("Navigation.navigate()")}}), or `undefined` if no `info` data was passed.
- {{domxref("NavigateEvent.navigationType", "navigationType")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the type of the navigation — `push`, `reload`, `replace`, or `traverse`.
- {{domxref("NavigateEvent.signal", "signal")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns an {{domxref("AbortSignal")}}, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one).
- {{domxref("NavigateEvent.userInitiated", "userInitiated")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns `true` if the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons), or `false` otherwise.
## Instance methods
_Inherits methods from its parent, {{DOMxRef("Event")}}._
- {{domxref("NavigateEvent.intercept", "intercept()")}} {{Experimental_Inline}}
- : Intercepts this navigation, turning it into a same-document navigation to the {{domxref("NavigationDestination.url", "destination")}} URL. It can accept a handler function that defines what the navigation handling behavior should be, plus `focusReset` and `scroll` options to control behavior as desired.
- {{domxref("NavigateEvent.scroll", "scroll()")}} {{Experimental_Inline}}
- : Can be called to manually trigger the browser-driven scrolling behavior that occurs in response to the navigation, if you want it to happen before the navigation handling has completed.
## Examples
### Handling a navigation using `intercept()`
```js
navigation.addEventListener("navigate", (event) => {
// Exit early if this navigation shouldn't be intercepted,
// e.g. if the navigation is cross-origin, or a download request
if (shouldNotIntercept(event)) return;
const url = new URL(event.destination.url);
if (url.pathname.startsWith("/articles/")) {
event.intercept({
async handler() {
// The URL has already changed, so show a placeholder while
// fetching the new content, such as a spinner or loading page
renderArticlePagePlaceholder();
// Fetch the new content and display when ready
const articleContent = await getArticleContent(url.pathname);
renderArticlePage(articleContent);
},
});
}
});
```
> **Note:** Before the Navigation API was available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate {{domxref("History.pushState()")}} call, then set up the page view based on the new URL. And this wouldn't handle all navigations — only user-initiated link clicks.
### Handling scrolling using `scroll()`
In this example of intercepting a navigation, the `handler()` function starts by fetching and rendering some article content, but then fetches and renders some secondary content afterwards. It makes sense to scroll the page to the main article content as soon as it is available so the user can interact with it, rather than waiting until the secondary content is also rendered. To achieve this, we have added a {{domxref("NavigateEvent.scroll", "scroll()")}} call between the two.
```js
navigation.addEventListener("navigate", (event) => {
if (shouldNotIntercept(navigateEvent)) return;
const url = new URL(event.destination.url);
if (url.pathname.startsWith("/articles/")) {
event.intercept({
async handler() {
const articleContent = await getArticleContent(url.pathname);
renderArticlePage(articleContent);
event.scroll();
const secondaryContent = await getSecondaryContent(url.pathname);
addSecondaryContent(secondaryContent);
},
});
}
});
```
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/userinitiated/index.md | ---
title: "NavigateEvent: userInitiated property"
short-title: userInitiated
slug: Web/API/NavigateEvent/userInitiated
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigateEvent.userInitiated
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`userInitiated`** read-only property of the
{{domxref("NavigateEvent")}} interface returns `true` if the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons), or `false` otherwise.
> **Note:** The table found at [Appendix: types of navigations](https://github.com/WICG/navigation-api#appendix-types-of-navigations) shows which navigation types are user-initiated.
## Value
A boolean value—`true` if the navigation is user-initiated, `false` if not.
## Examples
```js
navigation.addEventListener("navigate", (event) => {
console.log(event.userInitiated);
});
```
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/signal/index.md | ---
title: "NavigateEvent: signal property"
short-title: signal
slug: Web/API/NavigateEvent/signal
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigateEvent.signal
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`signal`** read-only property of the
{{domxref("NavigateEvent")}} interface returns an {{domxref("AbortSignal")}}, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one).
## Value
An {{domxref("AbortSignal")}} object.
## Examples
The general idea here is that the `signal` property can be passed to an associated {{domxref("fetch()")}} operation so that if the navigation is cancelled, the `fetch()` operation can be safely aborted, avoiding wasting bandwidth on fetches that are no longer needed.
```js
navigation.addEventListener("navigate", (event) => {
event.intercept({
async handler() {
// ...
await fetch(`/img/some-image.jpg`, { signal: event.signal });
// ...
},
});
});
```
> **Note:** See [Example: next/previous buttons](https://github.com/WICG/navigation-api#example-nextprevious-buttons) for a more detailed example.
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/intercept/index.md | ---
title: "NavigateEvent: intercept() method"
short-title: intercept()
slug: Web/API/NavigateEvent/intercept
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.NavigateEvent.intercept
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`intercept()`** method of the
{{domxref("NavigateEvent")}} interface intercepts this navigation, turning it into a same-document navigation to the {{domxref("NavigationDestination.url", "destination")}} URL.
## Syntax
```js-nolint
intercept()
intercept(options)
```
### Parameters
- `options` {{optional_inline}}
- : An options object containing the following properties:
- `handler` {{optional_inline}}
- : A callback function that defines what the navigation handling behavior should be. This generally handles resource fetching, and returns a promise.
- `focusReset` {{optional_inline}}
- : Defines the navigation's focus behavior. This may take one of the following values:
- `after-transition`
- : Once the promise returned by your handler function resolves, the browser will focus the first element with the [`autofocus`](/en-US/docs/Web/HTML/Global_attributes/autofocus) attribute, or the {{htmlelement("body")}} element if no element has `autofocus` set. This is the default value.
- `manual`
- : Disable the default behavior.
- `scroll` {{optional_inline}}
- : Defines the navigation's scrolling behavior. This may take one of the following values:
- `after-transition`
- : Allow the browser to handle scrolling, for example by scrolling to the relevant fragment identifier if the URL contains a fragment, or restoring the scroll position to the same place as last time if the page is reloaded or a page in the history is revisited. This is the default value.
- `manual`
- : Disable the default behavior.
### Return value
None (`undefined`).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the current {{domxref("Document")}} is not yet active, or if the navigation has been cancelled.
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the event was dispatched by a {{domxref("EventTarget.dispatchEvent", "dispatchEvent()")}} call, rather than the user agent, or if the navigation cannot be intercepted (i.e. {{domxref("NavigateEvent.canIntercept")}} is `false`).
## Examples
### Handling a navigation using `intercept()`
```js
navigation.addEventListener("navigate", (event) => {
// Exit early if this navigation shouldn't be intercepted,
// e.g. if the navigation is cross-origin, or a download request
if (shouldNotIntercept(event)) return;
const url = new URL(event.destination.url);
if (url.pathname.startsWith("/articles/")) {
event.intercept({
async handler() {
// The URL has already changed, so show a placeholder while
// fetching the new content, such as a spinner or loading page
renderArticlePagePlaceholder();
// Fetch the new content and display when ready
const articleContent = await getArticleContent(url.pathname);
renderArticlePage(articleContent);
},
});
}
});
```
### Using `focusReset` and `scroll`
Form submission can be detected by querying for the {{domxref("NavigateEvent.formData")}} property. The following example turns any form submission into one which stays on the current page. In this case, you don't update the DOM, so you can cancel any default reset and scroll behavior using `focusReset` and `scroll`.
```js
navigation.addEventListener("navigate", (event) => {
if (event.formData && event.canIntercept) {
// User submitted a POST form to a same-domain URL
// (If canIntercept is false, the event is just informative:
// you can't intercept this request, although you could
// likely still call .preventDefault() to stop it completely).
event.intercept({
// Since we don't update the DOM in this navigation,
// don't allow focus or scrolling to reset:
focusReset: "manual",
scroll: "manual",
async handler() {
await fetch(event.destination.url, {
method: "POST",
body: event.formData,
});
// You could navigate again with {history: 'replace'} to change the URL here,
// which might indicate "done"
},
});
}
});
```
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/destination/index.md | ---
title: "NavigateEvent: destination property"
short-title: destination
slug: Web/API/NavigateEvent/destination
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigateEvent.destination
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`destination`** read-only property of the
{{domxref("NavigateEvent")}} interface returns a {{domxref("NavigationDestination")}} object representing the destination being navigated to.
## Value
A {{domxref("NavigationDestination")}} object.
## Examples
```js
navigation.addEventListener("navigate", (event) => {
// Exit early if this navigation shouldn't be intercepted,
// e.g. if the navigation is cross-origin, or a download request
if (shouldNotIntercept(event)) {
return;
}
const url = new URL(event.destination.url);
if (url.pathname.startsWith("/articles/")) {
event.intercept({
async handler() {
// The URL has already changed, so show a placeholder while
// fetching the new content, such as a spinner or loading page
renderArticlePagePlaceholder();
// Fetch the new content and display when ready
const articleContent = await getArticleContent(url.pathname);
renderArticlePage(articleContent);
},
});
}
});
```
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/info/index.md | ---
title: "NavigateEvent: info property"
short-title: info
slug: Web/API/NavigateEvent/info
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigateEvent.info
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`info`** read-only property of the
{{domxref("NavigateEvent")}} interface returns the `info` data value passed by the initiating navigation operation (e.g. {{domxref("Navigation.back()")}}, or {{domxref("Navigation.navigate()")}}), or `undefined` if no `info` data was passed.
## Value
The `info` value passed by the initiating navigation operation, or `undefined` if none was passed.
## Examples
One example of how `info` might be used is to trigger different single-page navigation renderings depending on how a certain route was reached. For example, consider a photo gallery app, where you can reach the same photo URL and state via various routes. You might want to use a different animation to show the photo for each route.
```js
navigation.addEventListener("navigate", (event) => {
if (isPhotoNavigation(event)) {
event.intercept({
async handler() {
switch (event.info?.via) {
case "go-left": {
await animateLeft();
break;
}
case "go-right": {
await animateRight();
break;
}
case "gallery": {
await animateZoomFromThumbnail(event.info.thumbnail);
break;
}
}
// TODO: actually load the photo.
},
});
}
});
```
## 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 info to be passed — {{domxref("Navigation.back()")}}, {{domxref("Navigation.forward()")}}, {{domxref("Navigation.navigate()")}}, {{domxref("Navigation.reload()")}}, and {{domxref("Navigation.traverseTo()")}}
| 0 |
data/mdn-content/files/en-us/web/api/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/navigateevent/index.md | ---
title: "NavigateEvent: NavigateEvent() constructor"
short-title: NavigateEvent()
slug: Web/API/NavigateEvent/NavigateEvent
page-type: web-api-constructor
status:
- experimental
browser-compat: api.NavigateEvent.NavigateEvent
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`NavigateEvent()`** constructor creates a new
{{domxref("NavigateEvent")}} object instance.
## Syntax
```js-nolint
new NavigateEvent(type, init)
```
### Parameters
- `type`
- : A string representing the type of event. In the case of `NavigateEvent` this is always `navigate`.
- `init`
- : An object containing the following properties:
- `canIntercept` {{optional_inline}}
- : A boolean defining whether the navigation can be intercepted or not (e.g. you can't intercept a cross-origin navigation). Defaults to `false`.
- `destination`
- : A {{domxref("NavigationDestination")}} object representing the location being navigated to.
- `downloadRequest` {{optional_inline}}
- : The filename of the file requested for download, in the case of a download navigation (e.g. an {{htmlelement("a")}} or {{htmlelement("area")}} element with a `download` attribute). Defaults to `null`.
- `formData` {{optional_inline}}
- : The {{domxref("FormData")}} object representing the submitted data in the case of a `POST` form submission. Defaults to `null`.
- `hashChange` {{optional_inline}}
- : A boolean defining if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document). Defaults to `false`.
- `info` {{optional_inline}}
- : The `info` data value passed by the initiating navigation operation (e.g. {{domxref("Navigation.back()")}}, or {{domxref("Navigation.navigate()")}}).
- `navigationType` {{optional_inline}}
- : The type of the navigation. Possible values — `push`, `reload`, `replace`, and `traverse`. Defaults to `push`.
- `signal`
- : An {{domxref("AbortSignal")}}, which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one).
- `userInitiated` {{optional_inline}}
- : A boolean defining whether the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons). Defaults to `false`.
## Examples
A developer would not use this constructor manually. A new `NavigateEvent` object is constructed when a handler is invoked as a result of the {{domxref("Navigation.navigate_event", "navigate")}} event firing.
```js
navigation.addEventListener("navigate", (event) => {
// Exit early if this navigation shouldn't be intercepted,
// e.g. if the navigation is cross-origin, or a download request
if (shouldNotIntercept(event)) {
return;
}
const url = new URL(event.destination.url);
if (url.pathname.startsWith("/articles/")) {
event.intercept({
async handler() {
// The URL has already changed, so show a placeholder while
// fetching the new content, such as a spinner or loading page
renderArticlePagePlaceholder();
// Fetch the new content and display when ready
const articleContent = await getArticleContent(url.pathname);
renderArticlePage(articleContent);
},
});
}
});
```
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/hashchange/index.md | ---
title: "NavigateEvent: hashChange property"
short-title: hashChange
slug: Web/API/NavigateEvent/hashChange
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigateEvent.hashChange
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`hashChange`** read-only property of the
{{domxref("NavigateEvent")}} interface returns `true` if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document), or `false` otherwise.
## Value
A boolean value—`true` if the navigation is a fragment navigation, `false` if not.
## Examples
```js
navigation.addEventListener("navigate", (event) => {
// Some navigations, e.g. cross-origin navigations, we
// cannot intercept. Let the browser handle those normally.
if (!event.canIntercept) {
return;
}
// Don't intercept fragment navigations or downloads.
if (event.hashChange || event.downloadRequest !== null) {
return;
}
event.intercept({
handler() {
if (event.formData) {
processFormDataAndUpdateUI(event.formData, event.signal);
} else {
doSinglePageAppNav(event.destination, event.signal);
}
},
});
});
```
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/downloadrequest/index.md | ---
title: "NavigateEvent: downloadRequest property"
short-title: downloadRequest
slug: Web/API/NavigateEvent/downloadRequest
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigateEvent.downloadRequest
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`downloadRequest`** read-only property of the
{{domxref("NavigateEvent")}} interface returns the filename of the file requested for download, in the case of a download navigation (e.g. an {{htmlelement("a")}} or {{htmlelement("area")}} element with a `download` attribute), or `null` otherwise.
## Value
A string containing the filename of the file requested for download, or `null`.
## Examples
```js
navigation.addEventListener("navigate", (event) => {
// Some navigations, e.g. cross-origin navigations, we
// cannot intercept. Let the browser handle those normally.
if (!event.canIntercept) {
return;
}
// Don't intercept fragment navigations or downloads.
if (event.hashChange || event.downloadRequest !== null) {
return;
}
event.intercept({
handler() {
if (event.formData) {
processFormDataAndUpdateUI(event.formData, event.signal);
} else {
doSinglePageAppNav(event.destination, event.signal);
}
},
});
});
```
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/canintercept/index.md | ---
title: "NavigateEvent: canIntercept property"
short-title: canIntercept
slug: Web/API/NavigateEvent/canIntercept
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigateEvent.canIntercept
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`canIntercept`** read-only property of the
{{domxref("NavigateEvent")}} interface returns `true` if the navigation can be intercepted and have its URL rewritten, or `false` otherwise
There are several rules around when a navigation can be intercepted. For example:
- You can't intercept cross-origin navigations.
- You can intercept `http` or `https` URLs if only the `path`, `query`, and `fragment` portions of the new URL differ from the current URL.
- You can intercept `file` URLs if only the `query` and `fragment` portions of the new URL differ.
- For other URL types you can intercept the navigation if only the `fragment` portion differs.
See the spec for more explanation on [when a Document can have its URL rewritten](https://html.spec.whatwg.org/multipage/nav-history-apis.html#can-have-its-url-rewritten), including a table of examples.
## Value
A boolean value—`true` if the navigation can be intercepted, `false` if not.
## Examples
```js
navigation.addEventListener("navigate", (event) => {
// Some navigations, e.g. cross-origin navigations, we
// cannot intercept. Let the browser handle those normally.
if (!event.canIntercept) {
return;
}
// Don't intercept fragment navigations or downloads.
if (event.hashChange || event.downloadRequest !== null) {
return;
}
event.intercept({
handler() {
if (event.formData) {
processFormDataAndUpdateUI(event.formData, event.signal);
} else {
doSinglePageAppNav(event.destination, event.signal);
}
},
});
});
```
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/navigationtype/index.md | ---
title: "NavigateEvent: navigationType property"
short-title: navigationType
slug: Web/API/NavigateEvent/navigationType
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigateEvent.navigationType
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`navigationType`** read-only property of the
{{domxref("NavigateEvent")}} interface returns the type of the navigation — `push`, `reload`, `replace`, or `traverse`.
## Value
An enumerated value representing the type of navigation.
The possible values are:
- `push`: A new location is navigated to, causing a new entry to be pushed onto the history list.
- `reload`: The {{domxref("Navigation.currentEntry")}} is reloaded.
- `replace`: The {{domxref("Navigation.currentEntry")}} is replaced with a new history entry. This new entry will reuse the same {{domxref("NavigationHistoryEntry.key", "key")}}, but be assigned a different {{domxref("NavigationHistoryEntry.id", "id")}}.
- `traverse`: The browser navigates from one existing history entry to another existing history entry.
## Examples
### Async transitions with special back/forward handling
Sometimes it's desirable to handle back/forward navigations specially, e.g. reusing cached views by transitioning them onto the screen. This can be done by branching as follows:
```js
navigation.addEventListener("navigate", (event) => {
// Some navigations, e.g. cross-origin navigations, we
// cannot intercept. Let the browser handle those normally.
if (!event.canIntercept) {
return;
}
// Don't intercept fragment navigations or downloads.
if (event.hashChange || event.downloadRequest !== null) {
return;
}
event.intercept({
async handler() {
if (myFramework.currentPage) {
await myFramework.currentPage.transitionOut();
}
let { key } = event.destination;
if (
event.navigationType === "traverse" &&
myFramework.previousPages.has(key)
) {
await myFramework.previousPages.get(key).transitionIn();
} else {
// This will probably result in myFramework storing
// the rendered page in myFramework.previousPages.
await myFramework.renderPage(event.destination);
}
},
});
});
```
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/scroll/index.md | ---
title: "NavigateEvent: scroll() method"
short-title: scroll()
slug: Web/API/NavigateEvent/scroll
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.NavigateEvent.scroll
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`scroll()`** method of the
{{domxref("NavigateEvent")}} interface can be called to manually trigger the browser-driven scrolling behavior that occurs in response to the navigation, if you want it to happen before the navigation handling has completed.
## Syntax
```js-nolint
scroll()
```
### Parameters
None.
### Return value
None (`undefined`).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the current {{domxref("Document")}} is not yet active, or if the navigation has been cancelled.
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the event was dispatched by a {{domxref("EventTarget.dispatchEvent", "dispatchEvent()")}} call, rather than the user agent.
## Examples
### Handling scrolling using `scroll()`
In this example of intercepting a navigation, the `handler()` function starts by fetching and rendering some article content, but then fetches and renders some secondary content afterwards. It makes sense to scroll the page to the main article content as soon as it is available so the user can interact with it, rather than waiting until the secondary content is also rendered. To achieve this, we have added a {{domxref("NavigateEvent.scroll", "scroll()")}} call between the two.
```js
navigation.addEventListener("navigate", (event) => {
if (shouldNotIntercept(navigateEvent)) {
return;
}
const url = new URL(event.destination.url);
if (url.pathname.startsWith("/articles/")) {
event.intercept({
async handler() {
const articleContent = await getArticleContent(url.pathname);
renderArticlePage(articleContent);
event.scroll();
const secondaryContent = await getSecondaryContent(url.pathname);
addSecondaryContent(secondaryContent);
},
});
}
});
```
## 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/navigateevent | data/mdn-content/files/en-us/web/api/navigateevent/formdata/index.md | ---
title: "NavigateEvent: formData property"
short-title: formData
slug: Web/API/NavigateEvent/formData
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigateEvent.formData
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`formData`** read-only property of the
{{domxref("NavigateEvent")}} interface returns the {{domxref("FormData")}} object representing the submitted data in the case of a [`POST`](/en-US/docs/Web/HTTP/Methods/POST) form submission, or `null` otherwise.
## Value
A {{domxref("FormData")}} object, or `null`.
## Examples
```js
navigation.addEventListener("navigate", (event) => {
// Some navigations, e.g. cross-origin navigations, we
// cannot intercept. Let the browser handle those normally.
if (!event.canIntercept) {
return;
}
// Don't intercept fragment navigations or downloads.
if (event.hashChange || event.downloadRequest !== null) {
return;
}
event.intercept({
handler() {
if (event.formData) {
processFormDataAndUpdateUI(event.formData, event.signal);
} else {
doSinglePageAppNav(event.destination, event.signal);
}
},
});
});
```
## 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 | data/mdn-content/files/en-us/web/api/pushmanager/index.md | ---
title: PushManager
slug: Web/API/PushManager
page-type: web-api-interface
browser-compat: api.PushManager
---
{{ApiRef("Push API")}}{{SecureContext_Header}}
The **`PushManager`** interface of the [Push API](/en-US/docs/Web/API/Push_API) provides a way to receive notifications from third-party servers as well as request URLs for push notifications.
This interface is accessed via the {{domxref("ServiceWorkerRegistration.pushManager")}} property.
## Static properties
- [`PushManager.supportedContentEncodings`](/en-US/docs/Web/API/PushManager/supportedContentEncodings_static)
- : Returns an array of supported content codings that can be used to encrypt the payload of a push message.
## Instance methods
- {{domxref("PushManager.getSubscription()")}}
- : Retrieves an existing push subscription. It returns a {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}} object containing details of an existing subscription. If no existing subscription exists, this resolves to a `null` value.
- {{domxref("PushManager.permissionState()")}}
- : Returns a {{jsxref("Promise")}} that resolves to the permission state of the current {{domxref("PushManager")}}, which will be one of `'granted'`, `'denied'`, or `'prompt'`.
- {{domxref("PushManager.subscribe()")}}
- : Subscribes to a push service. It returns a {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}} object containing details of a push subscription. A new push subscription is created if the current service worker does not have an existing subscription.
### Deprecated methods
- {{domxref("PushManager.hasPermission()")}} {{deprecated_inline}}
- : Returns a {{jsxref("Promise")}} that resolves to the `PushPermissionStatus` of the requesting webapp, which will be one of `granted`, `denied`, or `default`. Replaced by {{domxref("PushManager.permissionState()")}}.
- {{domxref("PushManager.register()")}} {{deprecated_inline}}
- : Subscribes to a push subscription. Replaced by {{domxref("PushManager.subscribe()")}}.
- {{domxref("PushManager.registrations()")}} {{deprecated_inline}}
- : Retrieves existing push subscriptions. Replaced by {{domxref("PushManager.getSubscription()")}}.
- {{domxref("PushManager.unregister()")}} {{deprecated_inline}}
- : Unregisters and deletes a specified subscription endpoint. In the updated API, a subscription is unregistered by calling the {{domxref("PushSubscription.unsubscribe()")}} method.
## Example
```js
this.onpush = (event) => {
console.log(event.data);
// From here we can write the data to IndexedDB, send it to any open
// windows, display a notification, etc.
};
navigator.serviceWorker
.register("serviceworker.js")
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.subscribe().then(
(pushSubscription) => {
console.log(pushSubscription.endpoint);
// The push subscription details needed by the application
// server are now available, and can be sent to it using,
// for example, the fetch() API.
},
(error) => {
console.error(error);
},
);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Push API](/en-US/docs/Web/API/Push_API)
- [Service Worker API](/en-US/docs/Web/API/Service_Worker_API)
| 0 |
data/mdn-content/files/en-us/web/api/pushmanager | data/mdn-content/files/en-us/web/api/pushmanager/getsubscription/index.md | ---
title: "PushManager: getSubscription() method"
short-title: getSubscription()
slug: Web/API/PushManager/getSubscription
page-type: web-api-instance-method
browser-compat: api.PushManager.getSubscription
---
{{ApiRef("Push API")}}{{SecureContext_Header}}
The **`PushManager.getSubscription()`** method of the {{domxref("PushManager")}} interface retrieves an existing push subscription.
It returns a {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}} object containing details of an existing subscription. If no existing subscription exists, this resolves to a `null` value.
## Syntax
```js-nolint
getSubscription()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}} object or `null`.
## Examples
This code snippet is taken from a [push messaging and notification sample](https://github.com/GoogleChrome/samples/tree/gh-pages/push-messaging-and-notifications). (No live demo is available.)
```js
// We need the service worker registration to check for a subscription
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
// Do we already have a push message subscription?
serviceWorkerRegistration.pushManager
.getSubscription()
.then((subscription) => {
// Enable any UI which subscribes / unsubscribes from
// push messages.
const pushButton = document.querySelector(".js-push-button");
pushButton.disabled = false;
if (!subscription) {
// We aren't subscribed to push, so set UI
// to allow the user to enable push
return;
}
// Keep your server in sync with the latest subscriptionId
sendSubscriptionToServer(subscription);
showCurlCommand(subscription);
// Set your UI to show they have subscribed for
// push messages
pushButton.textContent = "Disable Push Messages";
isPushEnabled = true;
})
.catch((err) => {
console.error(`Error during getSubscription(): ${err}`);
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/pushmanager | data/mdn-content/files/en-us/web/api/pushmanager/register/index.md | ---
title: "PushManager: register() method"
short-title: register()
slug: Web/API/PushManager/register
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.PushManager.register
---
{{deprecated_header}}{{ApiRef("Push API")}}
The **`register`** method is used to ask the system to request
a new endpoint for notifications.
> **Note:** This method has been superseded by {{domxref("PushManager.subscribe()")}}.
## Syntax
```js-nolint
register()
```
### Parameters
None.
### Return value
A `DOMRequest` object to handle the success or failure of the method call.
If the method call is successful, the request's `result` will be a string,
which is the endpoint URL.
> **Note:** if you do not need the URL any more, please use
> {{domxref("PushManager.unregister()")}} to clean up after yourself.
## Examples
```js
const req = navigator.push.register();
req.onsuccess = (e) => {
const endpoint = req.result;
console.log(`New endpoint: ${endpoint}`);
};
req.onerror = (e) => {
console.error(`Error getting a new endpoint: ${e.error}`);
};
```
## Specifications
This feature is not part of any specification. It is no longer on track to become a standard.
## Browser compatibility
{{Compat}}
## See also
- {{domxref("PushManager")}}
| 0 |
data/mdn-content/files/en-us/web/api/pushmanager | data/mdn-content/files/en-us/web/api/pushmanager/permissionstate/index.md | ---
title: "PushManager: permissionState() method"
short-title: permissionState()
slug: Web/API/PushManager/permissionState
page-type: web-api-instance-method
browser-compat: api.PushManager.permissionState
---
{{ApiRef("Push API")}}{{SecureContext_Header}}
The **`permissionState()`** method of the
{{domxref("PushManager")}} interface returns a {{jsxref("Promise")}} that resolves to a
string indicating the permission state of the push manager. Possible
values are `'prompt'`, `'denied'`, or `'granted'`.
> **Note:** As of Firefox 44, the permissions for [Notifications](/en-US/docs/Web/API/Notifications_API) and [Push](/en-US/docs/Web/API/Push_API) have been merged. If permission is
> granted for notifications, push will also be enabled.
## Syntax
```js-nolint
permissionState()
permissionState(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object containing optional configuration parameters. It can have the following
properties:
- `userVisibleOnly`
- : A boolean indicating that the returned push
subscription will only be used for messages whose effect is made visible to the
user.
- `applicationServerKey`
- : A public key your push server will use to
send messages to client apps via a push server. This value is part of a signing
key pair generated by your application server and usable with elliptic curve
digital signature (ECDSA) over the P-256 curve.
### Return value
A {{jsxref("Promise")}} that resolves to a string with a value of
`'prompt'`, `'denied'`, or `'granted'`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/pushmanager | data/mdn-content/files/en-us/web/api/pushmanager/unregister/index.md | ---
title: "PushManager: unregister() method"
short-title: unregister()
slug: Web/API/PushManager/unregister
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.PushManager.unregister
---
{{deprecated_header}}{{ ApiRef("Push API")}}
The **`unregister()`** method was used to ask the system to
unregister and delete the specified endpoint.
> **Note:** In the updated API, a subscription can be unregistered via the {{domxref("PushSubscription.unsubscribe()")}} method.
## Syntax
```js-nolint
unregister(pushEndpoint)
```
### Parameters
- `pushEndpoint`
- : A pushEndpoint to be unregistered.
### Return value
A `DOMRequest` object to handle the success or failure of the method call.
If the method call is successful, the request's `result` will be a
[PushRegistration](#pushregistration) object representing the endpoint that has been
unregistered.
### PushRegistration
Those objects are anonymous JavaScript objects with the following properties:
- `pushEndpoint`
- : A string representing the URL of the unregistered endpoint.
- `version`
- : `Undefined` when `unregister.onsuccess` is called.
## Examples
```js
const req = navigator.push.unregister(pushEndpoint);
req.onsuccess = (e) => {
const endpoint = req.result;
console.log(`Unregistered endpoint: ${endpoint}`);
};
req.onerror = (e) => {
console.error(`Error unregistering the endpoint: ${e.error}`);
};
```
## Specifications
This feature is not part of any specification anymore. It is no longer on track to become a standard.
## Browser compatibility
{{Compat}}
## See also
- {{domxref("PushManager")}}
| 0 |
data/mdn-content/files/en-us/web/api/pushmanager | data/mdn-content/files/en-us/web/api/pushmanager/registrations/index.md | ---
title: "PushManager: registrations() method"
short-title: registrations()
slug: Web/API/PushManager/registrations
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.PushManager.registrations
---
{{deprecated_header}}{{ApiRef("Push API")}}
The **`registrations`** method is used to ask the system about
existing push endpoint registrations.
> **Note:** This method has been superseded by the {{domxref("PushManager.getSubscription()")}} method.
## Syntax
```js-nolint
registrations()
```
### Parameters
None.
### Return value
A `DOMRequest` object to handle the success or failure of the method call.
If the method call is successful, the request's `result` will be an array of
[PushRegistration](#pushregistration) objects.
### PushRegistration
Those objects are anonymous JavaScript objects with the following properties:
- `pushEndpoint`
- : A string representing the URL of the endpoint.
- `version`
- : The current version that the push endpoint is at.
## Examples
```js
const req = navigator.push.registrations();
req.onsuccess = (e) => {
if (req.result.length > 0) {
req.result.forEach((result) => {
console.log(
`Existing registration ${result.pushEndpoint} ${result.version}`,
);
});
// Reuse existing endpoints.
} else {
// Register for a new endpoint.
const register = navigator.push.register();
register.onsuccess = (e) => {
console.log(`Registered new endpoint: ${register.result}`);
};
}
};
```
## Specifications
This feature is not part of any specification anymore. It is no longer on track to become a standard.
## Browser compatibility
{{Compat}}
## See also
- {{domxref("PushManager")}}
| 0 |
data/mdn-content/files/en-us/web/api/pushmanager | data/mdn-content/files/en-us/web/api/pushmanager/supportedcontentencodings_static/index.md | ---
title: "PushManager: supportedContentEncodings static property"
short-title: supportedContentEncodings
slug: Web/API/PushManager/supportedContentEncodings_static
page-type: web-api-static-property
browser-compat: api.PushManager.supportedContentEncodings_static
---
{{APIRef("Push API")}}{{SecureContext_Header}}
The **`supportedContentEncodings`** read-only static property of the
{{domxref("PushManager")}} interface returns an array of supported content codings that
can be used to encrypt the payload of a push message.
## Value
An array of strings.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/pushmanager | data/mdn-content/files/en-us/web/api/pushmanager/haspermission/index.md | ---
title: "PushManager: hasPermission() method"
short-title: hasPermission()
slug: Web/API/PushManager/hasPermission
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.PushManager.hasPermission
---
{{deprecated_header}}{{ApiRef("Push API")}}
The **`PushManager.hasPermission()`** method of the {{domxref("PushManager")}} interface returns a {{jsxref("Promise")}} that resolves to the `PushPermissionStatus` of the requesting webapp, which will be one of `granted`, `denied`, or `default`.
> **Note:** This feature has been superseded by the {{domxref("PushManager.permissionState()")}} method.
## Syntax
```js-nolint
hasPermission()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves to the `PushPermissionStatus`.
## Examples
```js
// TBD
```
## Specifications
This feature is not part of any specification anymore. It is no longer on track to become a standard.
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/pushmanager | data/mdn-content/files/en-us/web/api/pushmanager/subscribe/index.md | ---
title: "PushManager: subscribe() method"
short-title: subscribe()
slug: Web/API/PushManager/subscribe
page-type: web-api-instance-method
browser-compat: api.PushManager.subscribe
---
{{ApiRef("Push API")}}{{SecureContext_Header}}
The **`subscribe()`** method of the {{domxref("PushManager")}}
interface subscribes to a push service.
It returns a {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}}
object containing details of a push subscription. A new push subscription is created if
the current service worker does not have an existing subscription.
## Syntax
```js-nolint
subscribe(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object containing optional configuration parameters. It can have the following
properties:
- `userVisibleOnly`
- : A boolean indicating that the returned push
subscription will only be used for messages whose effect is made visible to the
user.
- `applicationServerKey`
- : A Base64-encoded string or
{{jsxref("ArrayBuffer")}} containing an [ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm)
P-256 public key that the push server will use to authenticate your application
server. If specified, all messages from your application server must use the [VAPID](https://datatracker.ietf.org/doc/html/rfc8292) authentication scheme, and
include a JWT signed with the corresponding private key. This key **_IS
NOT_** the same ECDH key that you use to encrypt the data. For more
information, see "[Using VAPID with WebPush](https://blog.mozilla.org/services/2016/04/04/using-vapid-with-webpush/)".
> **Note:** This parameter is required in some browsers like
> Chrome and Edge. They will reject the Promise if `userVisibleOnly` is not set to `true`.
### Return value
A {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}} object.
## Examples
```js
this.onpush = (event) => {
console.log(event.data);
// From here we can write the data to IndexedDB, send it to any open
// windows, display a notification, etc.
};
navigator.serviceWorker.register("serviceworker.js");
// Use serviceWorker.ready to ensure that you can subscribe for push
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
const options = {
userVisibleOnly: true,
applicationServerKey,
};
serviceWorkerRegistration.pushManager.subscribe(options).then(
(pushSubscription) => {
console.log(pushSubscription.endpoint);
// The push subscription details needed by the application
// server are now available, and can be sent to it using,
// for example, the fetch() API.
},
(error) => {
// During development it often helps to log errors to the
// console. In a production environment it might make sense to
// also report information about errors back to the
// application server.
console.error(error);
},
);
});
```
### Responding to user gestures
`subscribe()` calls should be done in response to a user gesture, such as
clicking a button, for example:
```js
btn.addEventListener("click", () => {
serviceWorkerRegistration.pushManager
.subscribe(options)
.then((pushSubscription) => {
// handle subscription
});
});
```
This is not only best practice — you should not be spamming users with notifications
they didn't agree to — but going forward browsers will explicitly disallow notifications
not triggered in response to a user gesture. Firefox is already doing this from version
72, for example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrinputsourcearray/index.md | ---
title: XRInputSourceArray
slug: Web/API/XRInputSourceArray
page-type: web-api-interface
status:
- experimental
browser-compat: api.XRInputSourceArray
---
{{APIRef("WebXR Device API")}}{{SecureContext_header}}{{SeeCompatTable}}
The interface **`XRInputSourceArray`** represents a _live_ list of WebXR input sources, and is used as the return value of the {{domxref("XRSession")}} property {{domxref("XRSession.inputSources", "inputSources")}}. Each entry is an {{domxref("XRInputSource")}} representing one input device connected to the WebXR system.
In addition to being able to access the input sources in the list using standard array notation (that is, with index numbers inside square brackets), methods are available to allow the use of iterators and the {{domxref("XRInputSourceArray.forEach", "forEach()")}} method is also available.
## Instance properties
_The following properties are available on `XRInputSourceArray` objects._
- {{domxref("XRInputSourceArray.length", "length")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The number of {{domxref("XRInputSource")}} objects in the list.
## Instance methods
_The following methods are available on `XRInputSourceArray` objects. You may also use the features of the [`Symbol`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) type._
- {{domxref("XRInputSourceArray.entries", "entries()")}} {{Experimental_Inline}}
- : Returns an [`iterator`](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) you can use to walk the list of key/value pairs in the list. Each item returned is an array whose first value is the index and whose second value is the {{domxref("XRInputSource")}} at that index.
- {{domxref("XRInputSourceArray.forEach", "forEach()")}} {{Experimental_Inline}}
- : Iterates over each item in the list, in order from first to last.
- {{domxref("XRInputSourceArray.keys", "keys()")}} {{Experimental_Inline}}
- : A list of the keys corresponding to the entries in the input source list.
- {{domxref("XRInputSourceArray.values", "values()")}} {{Experimental_Inline}}
- : Returns an `iterator` you can use to go through all the values in the list. Each item is a single {{domxref("XRInputSource")}} object.
In addition to these methods, you may use array notation to access items in the list by index For example, the snippet of code below calls a function `handleInput()`, passing into it the first item in the input source list, if the list isn't empty.
```js
let sources = xrSession.inputSources;
if (sources.length > 0) {
handleInput(sources[0]);
}
```
## Examples
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrinputsourcearray | data/mdn-content/files/en-us/web/api/xrinputsourcearray/length/index.md | ---
title: "XRInputSourceArray: length property"
short-title: length
slug: Web/API/XRInputSourceArray/length
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRInputSourceArray.length
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The read-only **`length`** property returns an integer value
indicating the number of items in the input source list represented by
the {{domxref("XRInputSourceArray")}} object.
## Value
An integer value indicating the number of {{domxref("XRInputSource")}} objects
representing WebXR input sources are included in the array.
## Examples
In this example, a game that requires at least one input source
uses `length` to check this before proceeding to allow the user to play the
game.
```js
let sources = xrSession.inputSources;
if (sources.length === 0) {
showAlertDialog(
"You need to have at least one controller to play Super Duper Shark Jump Fest 9000.",
[
{ label: "Shop Now", url: "https://www.example.com/shop/controllers" },
{ label: "Quit", handler: quitGame },
],
);
}
```
Here, if `length` is 0, a
hypothetical `showAlertDialog()` function is called with a prompt string
explaining the need for a controller, and an array of objects, each describing a button
and what should happen when it's clicked. The first takes the user to an Amazon.com
search for VR controllers, and the second calls a `quitGame()` function to
start shutting the game program down.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrinputsourcearray | data/mdn-content/files/en-us/web/api/xrinputsourcearray/keys/index.md | ---
title: "XRInputSourceArray: keys() method"
short-title: keys()
slug: Web/API/XRInputSourceArray/keys
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRInputSourceArray.keys
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}
The **`keys()`** method in the
{{domxref("XRInputSourceArray")}} interface returns a {{Glossary("JavaScript")}}
[`iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)
which can then be used to iterate over the keys used to reference each item in the array
of input sources.
## Syntax
```js-nolint
keys()
```
### Parameters
None.
### Return value
A
JavaScript [`iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that
can be used to walk through the keys for each entry in the list of input sources. The
values returned by the iterator are the indexes of each entry in the list; that is, the
numbers 0, 1, 2, and so forth through the index of the last item in the list.
## Examples
This example snippet gets the list of inputs for a session and tries to handle each
type of input device it supports using.
```js
for (const inputIdx of xrSession.inputSources.keys()) {
/* the keys are the indexes into the list of inputs */
checkInput(xrSession.inputSources[inputIdx]);
}
```
Here,
[`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
is used to iterate over each of the keys. For each key, the input is retrieved using the
index with array notation: `xrSession.inputSources[inputIdx]`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Inputs and input sources](/en-US/docs/Web/API/WebXR_Device_API/Inputs)
- The {{domxref("XRInputSourceArray")}} method {{domxref("XRInputSourceArray.values",
"values()")}}
- The
[`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) method `keys()`
- {{domxref("XRInputSource")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrinputsourcearray | data/mdn-content/files/en-us/web/api/xrinputsourcearray/values/index.md | ---
title: "XRInputSourceArray: values() method"
short-title: values()
slug: Web/API/XRInputSourceArray/values
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRInputSourceArray.values
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}
The {{domxref("XRInputSourceArray")}}
method **`values()`** returns a {{Glossary("JavaScript")}}
[`iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)
that can walk over the list of {{domxref("XRInputSource")}} objects contained in the
array, from first to last.
## Syntax
```js-nolint
values()
```
### Parameters
None.
### Return value
A
JavaScript [`iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that
can be used to walk through the list of {{domxref("XRInputSource")}} objects in the
array, starting with the first entry (at index 0) and proceeding straight through the
list.
## Examples
This example snippet walks through each input and calls the
function `checkInput()` with each returned value.
```js
for (const source of xrSession.inputSources.values()) {
checkInput(source);
}
```
Here,
[`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
is used to iterate over the array's contents. Each pass through the loop,
`source` is the next {{domxref("XRInputSource")}} in the list. The loop exits
once every input has been delivered to `checkInput()`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Inputs and input sources](/en-US/docs/Web/API/WebXR_Device_API/Inputs)
- The {{domxref("XRInputSourceArray")}} method {{domxref("XRInputSourceArray.keys",
"keys()")}}
- The
[`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) method `values()`
- {{domxref("XRInputSource")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrinputsourcearray | data/mdn-content/files/en-us/web/api/xrinputsourcearray/foreach/index.md | ---
title: "XRInputSourceArray: forEach() method"
short-title: forEach()
slug: Web/API/XRInputSourceArray/forEach
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRInputSourceArray.forEach
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}
The {{domxref("XRInputSourceArray")}}
method **`forEach()`** executes the specified callback once for
each input source in the array, starting at index 0 and progressing until the end of the
list.
## Syntax
```js-nolint
forEach(callback)
forEach(callback, thisArg)
```
### Parameters
- `callback`
- : A function to execute once for each entry in the
array `xrInputSourceArray`. The callback accepts up to three parameters:
- `currentValue`
- : A {{domxref("XRInputSource")}} object which is the value of the item from within
the `xrInputSourceArray` which is currently being processed.
- `currentIndex` {{Optional_Inline}}
- : An integer value providing the index into the array at which the element given
by `currentValue` is located. If you don't need to know the index
number, you can omit this.
- `sourceList` {{Optional_Inline}}
- : The {{domxref("XRInputSourceArray")}} object which is being processed. If you
don't need this information, you may omit this.
- `thisArg` {{Optional_Inline}}
- : The value to be used for
[`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this)
while executing the callback. Note that if you use [arrow function notation](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) (`=>`) to provide the callback, you can
omit `thisArg`, since all arrow functions lexically bind `this`.
### Return value
Undefined.
## Examples
This example snippet gets the list of inputs for a session and tries to handle each
type of input device it supports using.
```js
let inputSources = xrSession.inputSources;
inputSources.forEach((input) => {
if (input.gamepad) {
checkGamepad(input.gamepad);
} else if (
input.targetRayMode === "tracked-pointer" &&
input.handedness === player.handedness
) {
/* Handle main hand controller */
handleMainHandInput(input);
} else {
/* Handle other inputs */
}
});
```
For each input in the list, the callback dispatches gamepad inputs to
a `checkGamepad()` with the input's {{domxref("Gamepad")}} object, taken from
its {{domxref("XRInputSource.gamepad", "gamepad")}} property, as an input
For other devices, we look for `tracked-pointer` devices in the player's
main hand, dispatching those to a `handleMainHandInput()` method.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Inputs and input sources](/en-US/docs/Web/API/WebXR_Device_API/Inputs)
- The
[`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) method `forEach()`
- {{domxref("XRInputSource")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrinputsourcearray | data/mdn-content/files/en-us/web/api/xrinputsourcearray/entries/index.md | ---
title: "XRInputSourceArray: entries() method"
short-title: entries()
slug: Web/API/XRInputSourceArray/entries
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRInputSourceArray.entries
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}
The {{domxref("XRInputSourceArray")}} interface's
**`entries()`** method returns a JavaScript
[`iterator`](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
which can then be used to iterate over the key/value pairs in the input source
array. Each item in the array is an {{domxref("XRInputSource")}} object.
Most frequently, you will use this in tandem with statements such as
[`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of).
## Syntax
```js-nolint
entries()
```
### Parameters
None.
### Return value
An [`iterator`](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
which can be used to walk through the list of `XRInputSource` objects
included in the input source array.
## Examples
This example snippet gets the list of inputs for a session and tries to handle each
type of input device it supports using.
```js
let sources = xrSession.inputSources;
for (const input of sources.entries()) {
if (input.gamepad) {
checkGamepad(input.gamepad);
} else if (
input.targetRayMode === "tracked-pointer" &&
input.handedness === player.handedness
) {
/* Handle main hand controller */
handleMainHandInput(input);
} else {
/* Handle other inputs */
}
}
```
For each input in the list, gamepad inputs are dispatched to
a `checkGamepad()` with the input's {{domxref("Gamepad")}} object, taken from
its {{domxref("XRInputSource.gamepad", "gamepad")}} property, as an input
For other devices, we look for `tracked-pointer` devices in the player's
main hand, dispatching those to a `handleMainHandInput()` method.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediastreamtrackgenerator/index.md | ---
title: MediaStreamTrackGenerator
slug: Web/API/MediaStreamTrackGenerator
page-type: web-api-interface
status:
- experimental
- non-standard
browser-compat: api.MediaStreamTrackGenerator
---
{{APIRef("Insertable Streams for MediaStreamTrack API")}}{{SeeCompatTable}}{{Non-standard_Header}}
The **`MediaStreamTrackGenerator`** interface of the {{domxref('Insertable Streams for MediaStreamTrack API')}} creates a {{domxref("WritableStream")}} that acts as a {{domxref("MediaStreamTrack")}} source.
The object consumes a stream of media frames as input, which can be audio or video frames.
## Constructor
- {{domxref("MediaStreamTrackGenerator.MediaStreamTrackGenerator", "MediaStreamTrackGenerator()")}} {{Experimental_Inline}} {{Non-standard_Inline}}
- : Creates a new `MediaStreamTrackGenerator` object which accepts either {{domxref("VideoFrame")}} or {{domxref("AudioData")}} objects.
## Instance properties
_This interface also inherits properties from {{domxref("MediaStreamTrack")}}._
- {{domxref("MediaStreamTrackGenerator.writable")}} {{Experimental_Inline}} {{Non-standard_Inline}}
- : A {{domxref("WritableStream")}}.
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from {{domxref("MediaStreamTrack")}}._
## Examples
The following example is from the article [Insertable streams for MediaStreamTrack](https://developer.chrome.com/docs/capabilities/web-apis/mediastreamtrack-insertable-media-processing), and demonstrates a barcode scanner application, which process barcodes and highlights them before writing the transformed frames to the writable stream of {{domxref("MediaStreamTrackGenerator.writable")}}.
```js
const stream = await getUserMedia({ video: true });
const videoTrack = stream.getVideoTracks()[0];
const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });
const transformer = new TransformStream({
async transform(videoFrame, controller) {
const barcodes = await detectBarcodes(videoFrame);
const newFrame = highlightBarcodes(videoFrame, barcodes);
videoFrame.close();
controller.enqueue(newFrame);
},
});
trackProcessor.readable
.pipeThrough(transformer)
.pipeTo(trackGenerator.writable);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrackgenerator | data/mdn-content/files/en-us/web/api/mediastreamtrackgenerator/mediastreamtrackgenerator/index.md | ---
title: "MediaStreamTrackGenerator: MediaStreamTrackGenerator() constructor"
short-title: MediaStreamTrackGenerator()
slug: Web/API/MediaStreamTrackGenerator/MediaStreamTrackGenerator
page-type: web-api-constructor
status:
- experimental
- non-standard
browser-compat: api.MediaStreamTrackGenerator.MediaStreamTrackGenerator
---
{{APIRef("Insertable Streams for MediaStreamTrack API")}}{{SeeCompatTable}}{{Non-standard_Header}}
The **`MediaStreamTrackGenerator()`** constructor creates a new {{domxref("MediaStreamTrackGenerator")}} object which consumes a stream of media frames and exposes a {{domxref("MediaStreamTrack")}}.
## Syntax
```js-nolint
new MediaStreamTrackGenerator(options)
```
### Parameters
- `options`
- : An object containing the property `kind`, which is one of the following strings:
- `"audio"`
- : Specifies that the stream accepts {{domxref("AudioTrack")}} objects.
- `"video"`
- : Specifies that the stream accepts {{domxref("VideoTrack")}} objects.
## Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `init.kind` is not `"video"` or `"audio"`.
## Examples
In the following example a new video `MediaStreamTrackGenerator` is created.
```js
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Insertable streams for MediaStreamTrack](https://developer.chrome.com/docs/capabilities/web-apis/mediastreamtrack-insertable-media-processing)
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrackgenerator | data/mdn-content/files/en-us/web/api/mediastreamtrackgenerator/writable/index.md | ---
title: "MediaStreamTrackGenerator: writable property"
short-title: writable
slug: Web/API/MediaStreamTrackGenerator/writable
page-type: web-api-instance-property
status:
- experimental
- non-standard
browser-compat: api.MediaStreamTrackGenerator.writable
---
{{APIRef("Insertable Streams for MediaStreamTrack API")}}{{SeeCompatTable}}{{Non-standard_Header}}
The **`writable`** property of the {{domxref("MediaStreamTrackGenerator")}} interface returns a {{domxref("WritableStream")}}. This allows the writing of media frames to the `MediaStreamTrackGenerator`. The frames will be audio or video. The type is dictated by the kind of `MediaStreamTrackGenerator` that was created.
## Value
A {{domxref("WritableStream")}}.
## Examples
In the following example video frames are transformed then written to the {{domxref("WritableStream")}} accessed with `MediaStreamTrackGenerator.writable`.
```js
const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });
/* */
trackProcessor.readable
.pipeThrough(transformer)
.pipeTo(trackGenerator.writable);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgmetadataelement/index.md | ---
title: SVGMetadataElement
slug: Web/API/SVGMetadataElement
page-type: web-api-interface
browser-compat: api.SVGMetadataElement
---
{{APIRef("SVG")}}
The **`SVGMetadataElement`** interface corresponds to the {{SVGElement("metadata")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface doesn't implement any specific properties, but inherits properties from its parent interface, {{domxref("SVGElement")}}._
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssimportrule/index.md | ---
title: CSSImportRule
slug: Web/API/CSSImportRule
page-type: web-api-interface
browser-compat: api.CSSImportRule
---
{{APIRef("CSSOM")}}
The **`CSSImportRule`** interface represents an {{cssxref("@import")}} [at-rule](/en-US/docs/Web/CSS/At-rule).
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its ancestor {{domxref("CSSRule")}}._
- {{domxref("CSSImportRule.href")}} {{ReadOnlyInline}}
- : Returns the URL specified by the {{cssxref("@import")}} rule.
- {{domxref("CSSImportRule.layerName")}} {{ReadOnlyInline}}
- : Returns the name of the [cascade layer](/en-US/docs/Web/CSS/@layer) declared in the {{cssxref("@import")}} rule, the empty string if the layer is anonymous, the or `null` if the rule doesn't declare any.
- {{domxref("CSSImportRule.media")}}
- : Returns the value of the `media` attribute of the associated stylesheet.
- {{domxref("CSSImportRule.styleSheet")}} {{ReadOnlyInline}}
- : Returns the associated stylesheet.
- {{domxref("CSSImportRule.supportsText")}} {{ReadOnlyInline}}
- : Returns the supports condition specified by the {{cssxref("@import")}} rule.
## Instance methods
_Inherits methods from its ancestor {{domxref("CSSRule")}}._
## Examples
The document includes a single stylesheet which contains a single {{cssxref("@import")}} rule. Therefore the first item in the list of CSS rules will be a `CSSImportRule`.
```css
@import url("style.css") screen;
```
```js
const myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); // A CSSImportRule instance object
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssimportrule | data/mdn-content/files/en-us/web/api/cssimportrule/layername/index.md | ---
title: "CSSImportRule: layerName property"
short-title: layerName
slug: Web/API/CSSImportRule/layerName
page-type: web-api-instance-property
browser-compat: api.CSSImportRule.layerName
---
{{APIRef("CSSOM")}}
The read-only **`layerName`** property of the {{domxref("CSSImportRule")}} interface returns the name of the cascade layer created by the {{cssxref("@import")}} [at-rule](/en-US/docs/Web/CSS/At-rule).
If the created layer is anonymous, the string is empty (`""`), if no layer has been
created, it is the `null` object.
## Value
A string, that can be empty, or the `null` object.
## Examples
The document's single stylesheet contains three {{cssxref("@import")}} rules. The first declaration imports a stylesheet into a named layer. The second declaration imports a stylesheet into an anonymous layer. The third declaration imports a stylesheet without a layer declaration.
The `layerName` property returns the name of the layer associated with the imported
stylesheet.
```css
@import url("style1.css") layer(layer-1);
@import url("style2.css") layer;
@import url("style3.css");
```
```js
const myRules = document.styleSheets[0].cssRules;
console.log(myRules[0].layerName); // returns `"layer-1"`
console.log(myRules[1].layerName); // returns `""` (an anonymous layer)
console.log(myRules[2].layerName); // returns `null`
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Learning area : [Cascade layers](/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers)
- {{cssxref("@import")}} and {{cssxref("@layer")}}
| 0 |
data/mdn-content/files/en-us/web/api/cssimportrule | data/mdn-content/files/en-us/web/api/cssimportrule/stylesheet/index.md | ---
title: "CSSImportRule: stylesheet property"
short-title: stylesheet
slug: Web/API/CSSImportRule/stylesheet
page-type: web-api-instance-property
browser-compat: api.CSSImportRule.styleSheet
---
{{APIRef("CSSOM")}}
The read-only **`styleSheet`** property of the
{{domxref("CSSImportRule")}} interface returns the CSS Stylesheet specified by the
{{cssxref("@import")}} [at-rule](/en-US/docs/Web/CSS/At-rule). This will be
in the form of a {{domxref("CSSStyleSheet")}} object.
An {{cssxref("@import")}} [at-rule](/en-US/docs/Web/CSS/At-rule) always has
an associated stylesheet.
## Value
A {{domxref("CSSStyleSheet")}}.
## Examples
The following stylesheet includes a single {{cssxref("@import")}} rule. Therefore the
first item in the list of CSS rules will be a `CSSImportRule`. The
`styleSheet` property returns the imported stylesheet.
```css
@import url("style.css") screen;
```
```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0].styleSheet); //returns a CSSStyleSheet object
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssimportrule | data/mdn-content/files/en-us/web/api/cssimportrule/media/index.md | ---
title: "CSSImportRule: media property"
short-title: media
slug: Web/API/CSSImportRule/media
page-type: web-api-instance-property
browser-compat: api.CSSImportRule.media
---
{{APIRef("CSSOM")}}
The read-only **`media`** property of the
{{domxref("CSSImportRule")}} interface returns a {{domxref("MediaList")}} object,
containing the value of the `media` attribute of the associated stylesheet.
## Value
Returns a {{domxref("MediaList")}} object.
The value of `media` can be set by passing a string containing the `media` attribute; for example `"print"`.
## Examples
### Getting the media property
The following stylesheet includes a single {{cssxref("@import")}} rule. Therefore the
first item in the list of CSS rules will be a `CSSImportRule`. The
`media` property returns a {{domxref("MediaList")}} object. This includes
the `mediaText` property with a value of `screen`.
```css
@import url("style.css") screen;
```
```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0].media); //returns a MediaList
```
### Setting the media property
To change the `media` attribute of the associated stylesheet, set the value of `media` to a string containing the new value.
```js
let myRules = document.styleSheets[0].cssRules;
myRules[0].media = "print";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssimportrule | data/mdn-content/files/en-us/web/api/cssimportrule/supportstext/index.md | ---
title: "CSSImportRule: supportsText property"
short-title: supportsText
slug: Web/API/CSSImportRule/supportsText
page-type: web-api-instance-property
browser-compat: api.CSSImportRule.supportsText
---
{{APIRef("CSSOM")}}
The read-only **`supportsText`** property of the {{domxref("CSSImportRule")}} interface returns the supports condition specified by the {{cssxref("@import")}} [at-rule](/en-US/docs/Web/CSS/At-rule).
## Value
A string, or `null`.
## Examples
The document's single stylesheet contains three {{cssxref("@import")}} rules. The first declaration imports a stylesheet if `display: flex` is supported. The second declaration imports a stylesheet if the `:has` selector is supported. The third declaration imports a stylesheet without a supports condition.
The `supportsText` property returns the import conditions associated with the at-rule.
```css
@import url("style1.css") supports(display: flex);
@import url("style2.css") supports(selector(p:has(a)));
@import url("style3.css");
```
```js
const myRules = document.styleSheets[0].cssRules;
console.log(myRules[0].supportsText); // returns `"display: flex"`
console.log(myRules[1].supportsText); // returns `"selector(p:has(a))"`
console.log(myRules[2].supportsText); // returns `null`
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using feature queries](/en-US/docs/Web/CSS/CSS_conditional_rules/Using_feature_queries)
- {{cssxref("@import")}} and {{cssxref("@supports")}}
| 0 |
data/mdn-content/files/en-us/web/api/cssimportrule | data/mdn-content/files/en-us/web/api/cssimportrule/href/index.md | ---
title: "CSSImportRule: href property"
short-title: href
slug: Web/API/CSSImportRule/href
page-type: web-api-instance-property
browser-compat: api.CSSImportRule.href
---
{{APIRef("CSSOM")}}
The read-only **`href`** property of the
{{domxref("CSSImportRule")}} interface returns the URL specified by the
{{cssxref("@import")}} [at-rule](/en-US/docs/Web/CSS/At-rule).
The resolved URL will be the [`href`](/en-US/docs/Web/HTML/Element/link#href) attribute of the
associated stylesheet.
## Value
A string.
## Examples
The following stylesheet includes a single {{cssxref("@import")}} rule. Therefore the
first item in the list of CSS rules will be a `CSSImportRule`. The
`href` property returns the URL of the imported stylesheet.
```css
@import url("style.css") screen;
```
```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0].href); //returns style.css
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/csspositionvalue/index.md | ---
title: CSSPositionValue
slug: Web/API/CSSPositionValue
page-type: web-api-interface
status:
- deprecated
- non-standard
browser-compat: api.CSSPositionValue
---
{{deprecated_header}}{{APIRef("CSS Typed Object Model API")}}{{Non-standard_header}}
The **`CSSPositionValue`** interface of the [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Object_Model#css_typed_object_model) represents values for properties that take a position, for example {{cssxref('object-position')}}.
## Constructor
- {{domxref("CSSPositionValue.CSSPositionValue", "CSSPositionValue()")}} {{Non-standard_Inline}} {{Deprecated_Inline}}
- : Creates a new `CSSPositionValue` object.
## Instance properties
- {{domxref('CSSPositionValue.x')}} {{Non-standard_Inline}} {{Deprecated_Inline}}
- : Returns the item's position along the web page's horizontal axis.
- {{domxref('CSSPositionValue.y')}} {{Non-standard_Inline}} {{Deprecated_Inline}}
- : Returns the item's position along the vertical axis.
## Instance methods
None.
## Examples
The following example positions a container `<div>` 5 pixels from the top and 10 pixels from the left of the page.
```js
const replacedEl = document.getElementById("image");
const position = new CSSPositionValue(CSS.px(35), CSS.px(40));
replacedEl.attributeStyleMap.set("object-position", position);
console.log(position.x.value, position.y.value);
console.log(replacedEl.computedStyleMap().get("object-position"));
```
We set the {{cssxref('object-position')}} property, then check the values returned.
```css hidden
#image {
width: 300px;
height: 300px;
border: 1px solid black;
background-color: #dededf;
object-fit: none;
}
```
```html hidden
<p>
Check the developer tools to see the log in the console and to inspect the
style attribute on the image.
</p>
<img id="image" src="mdn.svg" alt="MDN Logo" />
```
{{EmbedLiveSample("Examples", 300, 300)}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref('CSSImageValue')}}
- {{domxref('CSSKeywordValue')}}
- {{domxref('CSSNumericValue')}}
- {{domxref('CSSTransformValue')}}
- {{domxref('CSSUnparsedValue')}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/csspositionvalue/mdn.svg | <svg xmlns="http://www.w3.org/2000/svg" height="200" width="226.855"><defs><linearGradient gradientTransform="translate(-353.18 -4908.622) scale(6.99647)" gradientUnits="userSpaceOnUse" id="a" y2="701.6" x2="66.7" y1="730.2" x1="66.7"><stop offset="0" style="stop-color:#2075bc;stop-opacity:1"/><stop offset="1" style="stop-color:#29aae1;stop-opacity:1"/></linearGradient><linearGradient gradientTransform="translate(-353.18 -4908.622) scale(6.99647)" gradientUnits="userSpaceOnUse" id="b" y2="701.6" x2="54.6" y1="730.2" x1="54.6"><stop offset="0" style="stop-color:#0a6aa8;stop-opacity:1"/><stop offset="1" style="stop-color:#1699c8;stop-opacity:1"/></linearGradient><linearGradient gradientTransform="translate(-353.18 -4908.622) scale(6.99647)" gradientUnits="userSpaceOnUse" id="c" y2="701.6" x2="70.7" y1="730.2" x1="70.7"><stop offset="0" style="stop-color:#0a6aa8;stop-opacity:1"/><stop offset="1" style="stop-color:#1699c8;stop-opacity:1"/></linearGradient></defs><path style="fill:url(#a)" d="m56.89 0-.353.354L0 22.969V200l56.537-21.555L113.427 200l56.538-21.555L226.855 200V22.969L169.965.354 169.61 0v.354l-56.183 22.261L56.89.354V0zm43.026 42.215c.968.017 1.938.077 2.91.187 7.067 1.767 13.783 4.595 20.85 6.008 6.36-1.767 14.487-3.533 20.494.707 3.887 3.887 7.773 8.48 6.006 14.487 10.954 12.014 34.983 13.427 41.697 22.615 1.06 1.413.353 11.66 2.473 17.668l.707 2.828c-2.12 4.24-7.068 15.9-5.301 13.426-1.767 2.473-3.534 3.18-8.48 2.12-4.24 2.828-6.714 4.24-11.307 6.714-4.947 1.06-15.9-2.474-20.848-3.534-9.187-1.766-9.894.354-18.021 4.594-12.014 6.007-9.541 20.85-14.135 29.33 0 1.06.354 1.766.707 2.826s.707 1.766.707 2.473c-13.78 1.767-27.209-.352-39.576-6.36-9.54-4.593-17.667-11.661-24.381-20.142 1.413-.707 3.178-1.766 4.592-2.473 1.06-.353 2.121-1.06 2.828-1.414H60.07c-3.18-.706-1.413-.353-3.886-.353 2.826-3.18 6.715-6.006 7.068-6.36l.352-.353c-3.534 1.06-8.834 2.474-11.66 5.3 1.06-4.946 4.594-8.128 6.36-12.015-4.24 2.12-8.481 4.949-12.015 8.13 0-3.888 4.595-7.776 6.715-10.956 1.413-2.12 3.534-3.886 4.594-6.36-4.24 1.414-14.135 6.713-18.022 9.186 1.767-6.007 9.895-15.193 14.488-19.787-4.593.353-14.134 6.007-18.021 8.127 0-.353.353-.707 0-1.06 3.18-4.948 12.72-12.721 17.314-16.608-5.3.707-15.9 6.36-20.847 8.127 4.24-7.774 18.374-17.313 25.088-22.967l-16.254 4.24c-2.474 0-4.595 1.766-6.715 1.413 8.48-8.481 25.796-23.322 37.103-30.39 0 0 13.665-9.626 28.184-9.374z"/><path style="fill:url(#b)" d="M56.89 0 0 22.969V200l56.89-21.555v-37.304a85.988 85.988 0 0 1-2.472-2.979 68.24 68.24 0 0 0 2.473-1.33v-2.936c-.21.011-.344.026-.707.026.226-.255.469-.503.707-.752v-3.707c-1.89.797-3.674 1.773-4.948 3.047.823-3.838 3.128-6.615 4.948-9.48v-1.8c-3.761 2.02-7.461 4.566-10.602 7.393 0-3.887 4.595-7.775 6.715-10.955 1.148-1.722 2.753-3.216 3.887-5.04v-1.05c-4.53 1.687-13.615 6.562-17.315 8.916 1.767-6.007 9.895-15.193 14.488-19.787-4.593.353-14.134 6.007-18.021 8.127 0-.353.353-.707 0-1.06 3.18-4.948 12.72-12.721 17.314-16.608-5.3.707-15.9 6.36-20.847 8.127 4.108-7.531 17.444-16.688 24.38-22.395v-.388l-15.546 4.056c-2.474 0-4.595 1.766-6.715 1.413 5.224-5.225 13.802-12.857 22.262-19.604V0z"/><path style="fill:url(#c)" d="m169.965 0-56.537 22.969v22.627c3.386 1.083 6.775 2.12 10.248 2.814 6.36-1.767 14.487-3.533 20.494.707 3.887 3.887 7.773 8.48 6.006 14.487 4.891 5.364 12.39 8.613 19.789 11.386V0zm-26.397 124.818c-4.455.05-6.377 2.037-12.472 5.217-12.014 6.007-9.541 20.85-14.135 29.33 0 1.06.354 1.766.707 2.826s.707 1.766.707 2.473a74.51 74.51 0 0 1-4.947.465V200l56.537-21.555v-49.47c-4.947 1.06-15.9-2.474-20.848-3.534-2.297-.441-4.063-.64-5.549-.623z"/></svg> | 0 |
data/mdn-content/files/en-us/web/api/csspositionvalue | data/mdn-content/files/en-us/web/api/csspositionvalue/y/index.md | ---
title: "CSSPositionValue: y property"
short-title: "y"
slug: Web/API/CSSPositionValue/y
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.CSSPositionValue.y
---
{{deprecated_header}}{{APIRef("CSS Typed Object Model API")}}{{Non-standard_header}}
The **`y`** property of the
{{domxref("CSSPositionValue")}} interface returns the item's position along the
vertical axis.
## Value
A {{domxref('CSSNumericValue')}}.
## Examples
The following example positions a container `<div>` 5 pixels from the
top and 10 pixels from the left of the page.
```js
let replaceEl = document.getElementById("container");
let position = new CSSPositionValue(CSS.px(5), CSS.px(10));
someDiv.attributeStyleMap.set("object-position", position);
console.log(position.x.value, position.y.value);
```
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CSSPositionValue.CSSPositionValue", "CSSPositionValue()")}}
- {{domxref("CSSPositionValue.x")}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api/csspositionvalue | data/mdn-content/files/en-us/web/api/csspositionvalue/csspositionvalue/index.md | ---
title: "CSSPositionValue: CSSPositionValue() constructor"
short-title: CSSPositionValue()
slug: Web/API/CSSPositionValue/CSSPositionValue
page-type: web-api-constructor
status:
- deprecated
- non-standard
browser-compat: api.CSSPositionValue.CSSPositionValue
---
{{APIRef("CSS Typed Object Model API")}}{{deprecated_header}}{{Non-standard_header}}
The **`CSSPositionValue()`** constructor
creates a new {{domxref("CSSPositionValue")}} object which represents values for
properties that take a position, for example {{cssxref('object-position')}}.
## Syntax
```js-nolint
new CSSPositionValue(x, y)
```
### Parameters
- `x`
- : A position along the web page's horizontal axis.
- `y`
- : A position along the web page's vertical axis.
## Examples
The following example positions a container `<div>` 5 pixels from the
top and 10 pixels from the left of the page.
```js
let someDiv = document.getElementById("container");
let position = new CSSPositionValue(CSS.px(5), CSS.px(10));
someDiv.attributeStyleMap.set("object-position", position);
console.log(position.x.value, position.y.value); // 5 10
```
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CSSPositionValue.x")}}
- {{domxref("CSSPositionValue.y")}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api/csspositionvalue | data/mdn-content/files/en-us/web/api/csspositionvalue/x/index.md | ---
title: "CSSPositionValue: x property"
short-title: x
slug: Web/API/CSSPositionValue/x
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.CSSPositionValue.x
---
{{deprecated_header}}{{APIRef("CSS Typed Object Model API")}}{{Non-standard_header}}
The **`x`** property of the
{{domxref("CSSPositionValue")}} interface returns the item's position along the web
page's horizontal axis.
## Value
A {{domxref('CSSNumericValue')}}.
## Examples
The following example positions a container `<div>` 5 pixels from the
top and 10 pixels from the left of the page.
```js
let someDiv = document.getElementById("container");
let position = new CSSPositionValue(CSS.px(5), CSS.px(10));
someDiv.attributeStyleMap.set("object-position", position);
console.log(position.x.value, position.y.value);
```
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CSSPositionValue.CSSPositionValue", "CSSPositionValue()")}}
- {{domxref("CSSPositionValue.y")}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/ink_api/index.md | ---
title: Ink API
slug: Web/API/Ink_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.Ink
---
{{DefaultAPISidebar("Ink API")}}{{SeeCompatTable}}
The Ink API allows browsers to directly make use of available OS-level compositors when drawing pen strokes in an inking app feature, thereby reducing latency and increasing performance.
## Concepts and usage
Inking on the web refers to app features that involve using [pointer events](/en-US/docs/Web/API/Pointer_events) to draw a smooth pen stroke — for example, a drawing app or document signing feature.
Pointers events are usually sent first to the browser process, which then forwards these events to the JavaScript event loop to execute the associated handler functions and render the result in the app. The time delay between the start and finish of this process can be significant, resulting in latency between the user initiating drawing (for example, with a stylus or mouse), and the stroke showing up on the screen.
The Ink API significantly reduces this latency by allowing browsers to bypass the JavaScript event loop entirely. Where possible, browsers will pass such rendering instructions directly to OS-level compositors. If the underlying operating system does not have a specialized OS-level compositor to use for this purpose, browsers will use their own optimized rendering code. This is not as powerful as a compositor, but it still confers some improvements.
> **Note:** Compositors are part of the rendering machinery that draws the UI to the screen in a browser or operating system. See [Inside look at modern web browser (part 3)](https://developer.chrome.com/blog/inside-browser-part3/) for some interesting insights into how a compositor functions inside a web browser.
The entry point is the {{domxref("Navigator.ink")}} property, which returns an {{domxref("Ink")}} object for the current document. The {{domxref("Ink.requestPresenter","Ink.requestPresenter()")}} method returns a {{jsxref("Promise")}} that fulfills with an {{domxref("InkPresenter")}} object instance. This instructs the OS-level compositor to render ink strokes between pointer event dispatches in the next available frame in each case.
## Interfaces
- {{domxref("Ink")}}
- : Provides access to {{domxref("InkPresenter")}} objects for the application to use to render the strokes.
- {{domxref("InkPresenter")}}
- : Instructs the OS-level compositor to render ink strokes between pointer event dispatches.
### Extensions to other interfaces
- {{domxref("Navigator.ink")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns an {{domxref("Ink")}} object for the current document.
## Examples
### Drawing an ink trail
In this example, we draw a trail onto a 2D canvas. Near the start of the code, we call {{domxref("Ink.requestPresenter()")}}, passing it the canvas as the presentation area for it to take care of and storing the promise it returns in the `presenter` variable.
Later on, in the `pointermove` event listener, the new position of the trailhead is drawn onto the canvas each time the event fires. In addition, the {{domxref("InkPresenter")}} object returned when the `presenter` promise fulfills has its {{domxref("InkPresenter.updateInkTrailStartPoint", "updateInkTrailStartPoint()")}} method invoked; this is passed:
- The last trusted pointer event representing the rendering point for the current frame.
- A `style` object containing color and diameter settings.
The result is that a delegated ink trail is drawn ahead of the default browser rendering on the app's behalf, in the specified style, until the next time it receives a `pointermove` event.
#### HTML
```html
<canvas id="canvas"></canvas>
<div id="div">Delegated ink trail should match the color of this div.</div>
```
#### CSS
```css
div {
background-color: rgb(0 255 0 / 100%);
position: fixed;
top: 1rem;
left: 1rem;
}
```
#### JavaScript
```js
const ctx = canvas.getContext("2d");
const presenter = navigator.ink.requestPresenter({ presentationArea: canvas });
let move_cnt = 0;
let style = { color: "rgb(0 255 0 / 100%)", diameter: 10 };
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
canvas.addEventListener("pointermove", async (evt) => {
const pointSize = 10;
ctx.fillStyle = style.color;
ctx.fillRect(evt.pageX, evt.pageY, pointSize, pointSize);
if (move_cnt == 20) {
const r = getRandomInt(0, 255);
const g = getRandomInt(0, 255);
const b = getRandomInt(0, 255);
style = { color: `rgb(${r} ${g} ${b} / 100%)`, diameter: 10 };
move_cnt = 0;
document.getElementById("div").style.backgroundColor =
`rgb(${r} ${g} ${b} / 60%)`;
}
move_cnt += 1;
await presenter.updateInkTrailStartPoint(evt, style);
});
window.addEventListener("pointerdown", () => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
});
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
```
#### Result
{{EmbedLiveSample("Drawing an ink trail")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Enhancing Inking on the Web](https://blogs.windows.com/msedgedev/2021/08/18/enhancing-inking-on-the-web/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgdefselement/index.md | ---
title: SVGDefsElement
slug: Web/API/SVGDefsElement
page-type: web-api-interface
browser-compat: api.SVGDefsElement
---
{{APIRef("SVG")}}
The **`SVGDefsElement`** interface corresponds to the {{SVGElement("defs")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface doesn't implement any specific properties, but inherits properties from its parent, {{domxref("SVGGraphicsElement")}}._
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent, {{domxref("SVGGraphicsElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/analysernode/index.md | ---
title: AnalyserNode
slug: Web/API/AnalyserNode
page-type: web-api-interface
browser-compat: api.AnalyserNode
---
{{APIRef("Web Audio API")}}
The **`AnalyserNode`** interface represents a node able to provide real-time frequency and time-domain analysis information. It is an {{domxref("AudioNode")}} that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations.
An `AnalyserNode` has exactly one input and one output. The node works even if the output is not connected.
![Without modifying the audio stream, the node allows to get the frequency and time-domain data associated to it, using a FFT.](fttaudiodata_en.svg)
{{InheritanceDiagram}}
<table class="properties">
<tbody>
<tr>
<th scope="row">Number of inputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Number of outputs</th>
<td><code>1</code> (but may be left unconnected)</td>
</tr>
<tr>
<th scope="row">Channel count mode</th>
<td><code>"max"</code></td>
</tr>
<tr>
<th scope="row">Channel count</th>
<td><code>2</code></td>
</tr>
<tr>
<th scope="row">Channel interpretation</th>
<td><code>"speakers"</code></td>
</tr>
</tbody>
</table>
## Constructor
- {{domxref("AnalyserNode.AnalyserNode", "AnalyserNode()")}}
- : Creates a new instance of an `AnalyserNode` object.
## Instance properties
_Inherits properties from its parent, {{domxref("AudioNode")}}_.
- {{domxref("AnalyserNode.fftSize")}}
- : An unsigned long value representing the size of the FFT ([Fast Fourier Transform](https://en.wikipedia.org/wiki/Fast_Fourier_transform)) to be used to determine the frequency domain.
- {{domxref("AnalyserNode.frequencyBinCount")}} {{ReadOnlyInline}}
- : An unsigned long value half that of the FFT size. This generally equates to the number of data values you will have to play with for the visualization.
- {{domxref("AnalyserNode.minDecibels")}}
- : A double value representing the minimum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the minimum value for the range of results when using `getByteFrequencyData()`.
- {{domxref("AnalyserNode.maxDecibels")}}
- : A double value representing the maximum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the maximum value for the range of results when using `getByteFrequencyData()`.
- {{domxref("AnalyserNode.smoothingTimeConstant")}}
- : A double value representing the averaging constant with the last analysis frame — basically, it makes the transition between values over time smoother.
## Instance methods
_Inherits methods from its parent, {{domxref("AudioNode")}}_.
- {{domxref("AnalyserNode.getFloatFrequencyData()")}}
- : Copies the current frequency data into a {{jsxref("Float32Array")}} array passed into it.
- {{domxref("AnalyserNode.getByteFrequencyData()")}}
- : Copies the current frequency data into a {{jsxref("Uint8Array")}} (unsigned byte array) passed into it.
- {{domxref("AnalyserNode.getFloatTimeDomainData()")}}
- : Copies the current waveform, or time-domain, data into a {{jsxref("Float32Array")}} array passed into it.
- {{domxref("AnalyserNode.getByteTimeDomainData()")}}
- : Copies the current waveform, or time-domain, data into a {{jsxref("Uint8Array")}} (unsigned byte array) passed into it.
## Examples
> **Note:** See the guide [Visualizations with Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API) for more information on creating audio visualizations.
### Basic usage
The following example shows basic usage of an {{domxref("AudioContext")}} to create an `AnalyserNode`, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} 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);
// Connect the source to be analysed
source.connect(analyser);
// Get a canvas defined with ID "oscilloscope"
const canvas = document.getElementById("oscilloscope");
const canvasCtx = canvas.getContext("2d");
// draw an oscilloscope of the current audio source
function draw() {
requestAnimationFrame(draw);
analyser.getByteTimeDomainData(dataArray);
canvasCtx.fillStyle = "rgb(200 200 200)";
canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = "rgb(0 0 0)";
canvasCtx.beginPath();
const sliceWidth = (canvas.width * 1.0) / bufferLength;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const v = dataArray[i] / 128.0;
const y = (v * canvas.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 | data/mdn-content/files/en-us/web/api/analysernode/fttaudiodata_en.svg | <svg xmlns="http://www.w3.org/2000/svg" width="692.929" height="206.323"><path fill="none" stroke="#010101" d="M25.556 31.667v59.458"/><path fill="#010101" d="M19.722 32.667l5.834-16.839 5.5 16.839zm210.915 51.914l16.839 5.834-16.839 5.5z"/><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M25.722 53.167h36.667s4.167-14.333 9-11c0 0 2.333.417 7.333 14 0 0 2.917 10.583 8 8.167 0 0 3.333-.417 6.667-14.167 0 0 3.333-11.917 8.5-7.333 0 0 2.667 1.833 6.5 13.333 0 0 4 12 8.5 7.5 0 0 3.333-2.666 6.167-13.5 0 0 3.167-12.667 9-7.667 0 0 2.292.562 5.667 13.5 0 0 4.167 13.083 9.5 7.667 0 0 2.188-1.729 5-13.5 0 0 3.25-12.667 8.5-7.667 0 0 2.938 3.25 6.667 13.667 0 0 5.021 12.333 8.833 7.667 0 0 3.812-4.646 4.667-10.561h30"/><text transform="translate(252.055 94.834)" font-family="'ArialMT'" font-size="14">t</text><text transform="translate(23.222 106.333)"><tspan x="0" y="0" font-family="'ArialMT'" font-size="14">0</tspan><tspan x="7.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="36" y="0" font-family="'ArialMT'" font-size="14">1</tspan><tspan x="43.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="72" y="0" font-family="'ArialMT'" font-size="14">2</tspan><tspan x="79.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="108" y="0" font-family="'ArialMT'" font-size="14">3</tspan><tspan x="115.787" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="144" y="0" font-family="'ArialMT'" font-size="14">4</tspan></text><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M25.556 90.667h205.081"/><path fill="none" stroke="#010101" d="M431.556 31.667v59.458"/><path fill="#010101" d="M425.722 32.667l5.834-16.839 5.5 16.839zm210.914 51.914l16.84 5.834-16.84 5.5z"/><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M431.722 53.167h36.666s4.167-14.333 9-11c0 0 2.334.417 7.334 14 0 0 2.916 10.583 8 8.167 0 0 3.334-.417 6.666-14.167 0 0 3.334-11.917 8.5-7.333 0 0 2.667 1.833 6.5 13.333 0 0 4 12 8.5 7.5 0 0 3.334-2.666 6.168-13.5 0 0 3.166-12.667 9-7.667 0 0 2.291.562 5.666 13.5 0 0 4.167 13.083 9.5 7.667 0 0 2.188-1.729 5-13.5 0 0 3.25-12.667 8.5-7.667 0 0 2.938 3.25 6.667 13.667 0 0 5.021 12.333 8.833 7.667 0 0 3.812-4.646 4.667-10.561h30"/><text transform="translate(658.055 94.834)" font-family="'ArialMT'" font-size="14">t</text><text transform="translate(429.222 106.333)"><tspan x="0" y="0" font-family="'ArialMT'" font-size="14">0</tspan><tspan x="7.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="36" y="0" font-family="'ArialMT'" font-size="14">1</tspan><tspan x="43.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="72" y="0" font-family="'ArialMT'" font-size="14">2</tspan><tspan x="79.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="108" y="0" font-family="'ArialMT'" font-size="14">3</tspan><tspan x="115.787" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="144" y="0" font-family="'ArialMT'" font-size="14">4</tspan></text><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M431.556 90.667h205.08"/><path fill="#010101" d="M401.636 47.489l16.84 5.834-16.84 5.5z"/><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M273.555 53.576h128.081"/><path fill="#010101" d="M347.889 148.454l-5.834 16.84-5.5-16.84z"/><path fill="#719FD0" stroke="#010101" d="M299.222 35h86v96.5h-86z"/><text transform="translate(304.223 56.823)" font-family="'ArialMT'" font-size="11">AnalyserNode</text><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M341.803 118v30.454"/><text transform="translate(331.889 106.333)" font-family="'Arial-BoldMT'" font-size="11">FFT</text><path fill="none" stroke="#2C2C76" stroke-miterlimit="10" d="M321.889 86.667h41l-8 29.333h-25.333z"/><g font-family="'ArialMT'" font-size="11"><text transform="translate(484.89 131.5)">unchanged output</text><text transform="translate(302.223 176.167)">frequency data</text></g></svg> | 0 |
data/mdn-content/files/en-us/web/api/analysernode | data/mdn-content/files/en-us/web/api/analysernode/maxdecibels/index.md | ---
title: "AnalyserNode: maxDecibels property"
short-title: maxDecibels
slug: Web/API/AnalyserNode/maxDecibels
page-type: web-api-instance-property
browser-compat: api.AnalyserNode.maxDecibels
---
{{APIRef("Web Audio API")}}
The **`maxDecibels`** property of the {{domxref("AnalyserNode")}} interface is a double value representing the maximum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the maximum value for the range of results when using `getByteFrequencyData()`.
## Value
A double, representing the maximum [decibel](https://en.wikipedia.org/wiki/Decibel) value for scaling the FFT analysis data, where `0` dB is the loudest possible sound, `-10` dB is a 10th of that, etc. The default value is `-30` dB.
When getting data from `getByteFrequencyData()`, any frequencies with an amplitude of `maxDecibels` or higher will be returned as `255`.
### Exceptions
- `IndexSizeError` {{domxref("DOMException")}}
- : Thrown if a value less than or equal to `AnalyserNode.minDecibels` is set.
## Examples
The following example shows basic usage of an {{domxref("AudioContext")}} to create an `AnalyserNode`, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} to collect frequency data repeatedly and draw a "winamp bar graph style" output of the current audio input.
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 (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
// …
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
const dataArray = new Uint8Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
canvasCtx.fillStyle = "rgb(0 0 0)";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
const barWidth = (WIDTH / bufferLength) * 2.5;
let barHeight;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i];
canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);
x += barWidth + 1;
}
}
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/analysernode | data/mdn-content/files/en-us/web/api/analysernode/getfloatfrequencydata/index.md | ---
title: "AnalyserNode: getFloatFrequencyData() method"
short-title: getFloatFrequencyData()
slug: Web/API/AnalyserNode/getFloatFrequencyData
page-type: web-api-instance-method
browser-compat: api.AnalyserNode.getFloatFrequencyData
---
{{ APIRef("Web Audio API") }}
The **`getFloatFrequencyData()`** method of the {{domxref("AnalyserNode")}} Interface copies the current frequency data into a {{jsxref("Float32Array")}} array passed into it. Each array value is a _sample_, the magnitude of the signal at a particular time.
Each item in the array represents the decibel value for a specific frequency. The frequencies are spread linearly from 0 to 1/2 of the sample rate. For example, for a `48000` Hz sample rate, the last item of the array will represent the decibel value for `24000` Hz.
If you need higher performance and don't care about precision, you can use {{domxref("AnalyserNode.getByteFrequencyData()")}} instead, which works on a {{jsxref("Uint8Array")}}.
## Syntax
```js-nolint
getFloatFrequencyData(array)
```
### Parameters
- `array`
- : The {{jsxref("Float32Array")}} that the frequency domain data will be copied to. For any sample which is silent, the value is `-Infinity`.
If the array has fewer elements than the {{domxref("AnalyserNode.frequencyBinCount")}}, excess elements are dropped. If it has more elements than needed, excess elements are ignored.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
const audioCtx = new AudioContext();
const analyser = audioCtx.createAnalyser();
// Float32Array should be the same length as the frequencyBinCount
const myDataArray = new Float32Array(analyser.frequencyBinCount);
// fill the Float32Array with data returned from getFloatFrequencyData()
analyser.getFloatFrequencyData(myDataArray);
```
### Drawing a spectrum
The following example shows basic usage of an {{domxref("AudioContext")}} to connect a {{domxref("MediaElementAudioSourceNode")}} to an `AnalyserNode`. While the audio is playing, we collect the frequency data repeatedly with {{domxref("window.requestAnimationFrame()","requestAnimationFrame()")}} and draw a "winamp bar graph style" to a {{htmlelement("canvas")}} element.
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).
```html
<!doctype html>
<body>
<script>
const audioCtx = new AudioContext();
//Create audio source
//Here, we use an audio file, but this could also be e.g. microphone input
const audioEle = new Audio();
audioEle.src = "my-audio.mp3"; //insert file name here
audioEle.autoplay = true;
audioEle.preload = "auto";
const audioSourceNode = audioCtx.createMediaElementSource(audioEle);
//Create analyser node
const analyserNode = audioCtx.createAnalyser();
analyserNode.fftSize = 256;
const bufferLength = analyserNode.frequencyBinCount;
const dataArray = new Float32Array(bufferLength);
//Set up audio node network
audioSourceNode.connect(analyserNode);
analyserNode.connect(audioCtx.destination);
//Create 2D canvas
const canvas = document.createElement("canvas");
canvas.style.position = "absolute";
canvas.style.top = "0";
canvas.style.left = "0";
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const canvasCtx = canvas.getContext("2d");
canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
function draw() {
//Schedule next redraw
requestAnimationFrame(draw);
//Get spectrum data
analyserNode.getFloatFrequencyData(dataArray);
//Draw black background
canvasCtx.fillStyle = "rgb(0 0 0)";
canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
//Draw spectrum
const barWidth = (canvas.width / bufferLength) * 2.5;
let posX = 0;
for (let i = 0; i < bufferLength; i++) {
const barHeight = (dataArray[i] + 140) * 2;
canvasCtx.fillStyle = `rgb(${Math.floor(barHeight + 100)} 50 50)`;
canvasCtx.fillRect(
posX,
canvas.height - barHeight / 2,
barWidth,
barHeight / 2,
);
posX += barWidth + 1;
}
}
draw();
</script>
</body>
```
## 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/analysernode | data/mdn-content/files/en-us/web/api/analysernode/analysernode/index.md | ---
title: "AnalyserNode: AnalyserNode() constructor"
short-title: AnalyserNode()
slug: Web/API/AnalyserNode/AnalyserNode
page-type: web-api-constructor
browser-compat: api.AnalyserNode.AnalyserNode
---
{{APIRef("'Web Audio API'")}}
The **`AnalyserNode()`** constructor of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) creates a new {{domxref("AnalyserNode")}} object instance.
## Syntax
```js-nolint
new AnalyserNode(context)
new AnalyserNode(context, options)
```
### Parameters
- `context`
- : A reference to an {{domxref("AudioContext")}} or {{domxref("OfflineAudioContext")}}.
- `options` {{optional_inline}}
- : An object with the following properties, all optional:
- `fftSize`
- : The desired initial size of the [FFT](https://en.wikipedia.org/wiki/Fast_Fourier_transform) for [frequency-domain](https://en.wikipedia.org/wiki/Frequency_domain) analysis.
The default is `2048`.
- `maxDecibels`
- : The desired initial maximum power in [dB](https://en.wikipedia.org/wiki/Decibel) for FFT analysis.
The default is `-30`.
- `minDecibels`
- : The desired initial minimum power in dB for FFT analysis.
The default is `-100`.
- `smoothingTimeConstant`
- : The desired initial smoothing constant for the FFT analysis. The default is `0.8`.
- `channelCount`
- : Represents an integer used to determine how many channels are used when [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) connections to any inputs to the node. (See
{{domxref("AudioNode.channelCount")}} for more information.) Its usage and precise
definition depend on the value of `channelCountMode`.
- `channelCountMode`
- : Represents an [enumerated](/en-US/docs/Glossary/Enumerated) value describing the way channels must be matched between
the node's inputs and outputs. (See {{domxref("AudioNode.channelCountMode")}} for more
information including default values.)
- `channelInterpretation`
- : Represents an enumerated value describing the meaning of the channels. This
interpretation will define how audio [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) will happen.
The possible values are `"speakers"` or `"discrete"`. (See
{{domxref("AudioNode.channelCountMode")}} for more information including default
values.)
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("BaseAudioContext.createAnalyser()")}}, the equivalent factory method
| 0 |
data/mdn-content/files/en-us/web/api/analysernode | data/mdn-content/files/en-us/web/api/analysernode/mindecibels/index.md | ---
title: "AnalyserNode: minDecibels property"
short-title: minDecibels
slug: Web/API/AnalyserNode/minDecibels
page-type: web-api-instance-property
browser-compat: api.AnalyserNode.minDecibels
---
{{ APIRef("Web Audio API") }}
The **`minDecibels`** property of the {{ domxref("AnalyserNode") }} interface is a double value representing the minimum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the minimum value for the range of results when using `getByteFrequencyData()`.
## Value
A double, representing the minimum [decibel](https://en.wikipedia.org/wiki/Decibel) value for scaling the FFT analysis data, where `0` dB is the loudest possible sound, `-10` dB is a 10th of that, etc. The default value is `-100` dB.
When getting data from `getByteFrequencyData()`, any frequencies with an amplitude of `minDecibels` or lower will be returned as `0`.
> **Note:** If a value greater than `AnalyserNode.maxDecibels` is set, an `INDEX_SIZE_ERR` exception is thrown.
## Examples
The following example shows basic usage of an {{domxref("AudioContext")}} to create an `AnalyserNode`, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} to collect frequency data repeatedly and draw a "winamp bar graph style" output of the current audio input.
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 (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
// …
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
const dataArray = new Uint8Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
canvasCtx.fillStyle = "rgb(0 0 0)";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
const barWidth = (WIDTH / bufferLength) * 2.5;
let barHeight;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i];
canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);
x += barWidth + 1;
}
}
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/analysernode | data/mdn-content/files/en-us/web/api/analysernode/getbytefrequencydata/index.md | ---
title: "AnalyserNode: getByteFrequencyData() method"
short-title: getByteFrequencyData()
slug: Web/API/AnalyserNode/getByteFrequencyData
page-type: web-api-instance-method
browser-compat: api.AnalyserNode.getByteFrequencyData
---
{{ APIRef("Web Audio API") }}
The **`getByteFrequencyData()`** method of the {{ domxref("AnalyserNode") }} interface copies the current frequency data into a {{jsxref("Uint8Array")}} (unsigned byte array) passed into it.
The frequency data is composed of integers on a scale from 0 to 255.
Each item in the array represents the decibel value for a specific frequency. The frequencies are spread linearly from 0 to 1/2 of the sample rate. For example, for `48000` sample rate, the last item of the array will represent the decibel value for `24000` Hz.
If the array has fewer elements than the {{domxref("AnalyserNode.frequencyBinCount")}}, excess elements are dropped. If it has more elements than needed, excess elements are ignored.
## Syntax
```js-nolint
getByteFrequencyData(array)
```
### Parameters
- `array`
- : The {{jsxref("Uint8Array")}} that the frequency domain data will be copied to. For any sample which is silent, the value is `-Infinity`.
If the array has fewer elements than the {{domxref("AnalyserNode.frequencyBinCount")}}, excess elements are dropped. If it has more elements than needed, excess elements are ignored.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following example shows basic usage of an {{domxref("AudioContext")}} to create an `AnalyserNode`, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} to collect frequency data repeatedly and draw a "winamp bar graph style" output of the current audio input. 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 (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
// …
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
const dataArray = new Uint8Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
canvasCtx.fillStyle = "rgb(0 0 0)";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
const barWidth = (WIDTH / bufferLength) * 2.5;
let barHeight;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i];
canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);
x += barWidth + 1;
}
}
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/analysernode | data/mdn-content/files/en-us/web/api/analysernode/smoothingtimeconstant/index.md | ---
title: "AnalyserNode: smoothingTimeConstant property"
short-title: smoothingTimeConstant
slug: Web/API/AnalyserNode/smoothingTimeConstant
page-type: web-api-instance-property
browser-compat: api.AnalyserNode.smoothingTimeConstant
---
{{ APIRef("Web Audio API") }}
The **`smoothingTimeConstant`** property of the {{ domxref("AnalyserNode") }} interface is a double value representing the averaging constant with the last analysis frame. It's basically an average between the current buffer and the last buffer the `AnalyserNode` processed, and results in a much smoother set of value changes over time.
## Value
A double within the range `0` to `1` (`0` meaning no time averaging). The default value is `0.8`.
If 0 is set, there is no averaging done, whereas a value of 1 means "overlap the previous and current buffer quite a lot while computing the value", which essentially smooths the changes across {{domxref("AnalyserNode.getFloatFrequencyData")}}/{{domxref("AnalyserNode.getByteFrequencyData")}} calls.
In technical terms, we apply a [Blackman window](https://webaudio.github.io/web-audio-api/#blackman-window) and smooth the values over time. The default value is good enough for most cases.
> **Note:** If a value outside the range 0–1 is set, an `INDEX_SIZE_ERR` exception is thrown.
## Examples
The following example shows basic usage of an {{domxref("AudioContext")}} to create an `AnalyserNode`, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} to collect frequency data repeatedly and draw a "winamp bar graph style" output of the current audio input.
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).
If you are curious about the effect the `smoothingTimeConstant()` has, try cloning the above example and setting `analyser.smoothingTimeConstant = 0;` instead. You'll notice that the value changes are much more jarring.
```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.smoothingTimeConstant = 0.85;
// …
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
const dataArray = new Uint8Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
canvasCtx.fillStyle = "rgb(0 0 0)";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
const barWidth = (WIDTH / bufferLength) * 2.5;
let barHeight;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i];
canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);
x += barWidth + 1;
}
}
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/analysernode | data/mdn-content/files/en-us/web/api/analysernode/getbytetimedomaindata/index.md | ---
title: "AnalyserNode: getByteTimeDomainData() method"
short-title: getByteTimeDomainData()
slug: Web/API/AnalyserNode/getByteTimeDomainData
page-type: web-api-instance-method
browser-compat: api.AnalyserNode.getByteTimeDomainData
---
{{ APIRef("Web Audio API") }}
The **`getByteTimeDomainData()`** method of the {{ domxref("AnalyserNode") }} Interface copies the current waveform, or time-domain, data into a {{jsxref("Uint8Array")}} (unsigned byte array) passed into it.
If the array has fewer elements than the {{domxref("AnalyserNode.fftSize")}}, excess elements are dropped. If it has more elements than needed, excess elements are ignored.
## Syntax
```js-nolint
getByteTimeDomainData(array)
```
### Parameters
- `array`
- : The {{jsxref("Uint8Array")}} that the time domain data will be copied to.
If the array has fewer elements than the {{domxref("AnalyserNode.fftSize")}}, excess elements are dropped. If it has more elements than needed, excess elements are ignored.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following example shows basic usage of an {{domxref("AudioContext")}} to create an `AnalyserNode`, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} 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://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 (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
// …
analyser.fftSize = 2048;
const bufferLength = analyser.fftSize;
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)";
const sliceWidth = (WIDTH * 1.0) / bufferLength;
let x = 0;
canvasCtx.beginPath();
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(WIDTH, 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/analysernode | data/mdn-content/files/en-us/web/api/analysernode/frequencybincount/index.md | ---
title: "AnalyserNode: frequencyBinCount property"
short-title: frequencyBinCount
slug: Web/API/AnalyserNode/frequencyBinCount
page-type: web-api-instance-property
browser-compat: api.AnalyserNode.frequencyBinCount
---
{{APIRef("Web Audio API")}}
The **`frequencyBinCount`** read-only property of the {{domxref("AnalyserNode")}} interface contains the total number of data points available to {{domxref("AudioContext")}} {{domxref("BaseAudioContext.sampleRate", "sampleRate")}}. This is half of the `value` of the {{domxref("AnalyserNode.fftSize")}}. The two methods' indices have a linear relationship with the frequencies they represent, between 0 and the [Nyquist frequency](https://en.wikipedia.org/wiki/Nyquist_frequency).
## Value
An unsigned integer, equal to the number of values that {{domxref("AnalyserNode.getByteFrequencyData()")}} and {{domxref("AnalyserNode.getFloatFrequencyData()")}} copy into the provided `TypedArray`.
For technical reasons related to how the [Fast Fourier transform](https://en.wikipedia.org/wiki/Fast_Fourier_transform) is defined, it is always half the value of {{domxref("AnalyserNode.fftSize")}}. Therefore, it will be one of `16`, `32`, `64`, `128`, `256`, `512`, `1024`, `2048`, `4096`, `8192`, and `16384`.
## Examples
The following example shows basic usage of an {{domxref("AudioContext")}} to create an `AnalyserNode`, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} to collect frequency data repeatedly and draw a "winamp bar graph 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.
```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
// …
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
const dataArray = new Uint8Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
canvasCtx.fillStyle = "rgb(0 0 0)";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
const barWidth = (WIDTH / bufferLength) * 2.5 - 1;
let barHeight;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i];
canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);
x += barWidth;
}
}
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/analysernode | data/mdn-content/files/en-us/web/api/analysernode/getfloattimedomaindata/index.md | ---
title: "AnalyserNode: getFloatTimeDomainData() method"
short-title: getFloatTimeDomainData()
slug: Web/API/AnalyserNode/getFloatTimeDomainData
page-type: web-api-instance-method
browser-compat: api.AnalyserNode.getFloatTimeDomainData
---
{{ APIRef("Web Audio API") }}
The **`getFloatTimeDomainData()`** method of the {{ domxref("AnalyserNode") }} Interface copies the current waveform, or time-domain, data into a {{jsxref("Float32Array")}} array passed into it. Each array value is a _sample_, the magnitude of the signal at a particular time.
## Syntax
```js-nolint
getFloatTimeDomainData(array)
```
### Parameters
- `array`
- : The {{jsxref("Float32Array")}} that the time domain data will be copied to.
If the array has fewer elements than the {{domxref("AnalyserNode.fftSize")}}, excess elements are dropped. If it has more elements than needed, excess elements are ignored.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following example shows basic usage of an {{domxref("AudioContext")}} to create an `AnalyserNode`, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} 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://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 (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
// …
analyser.fftSize = 1024;
const bufferLength = analyser.fftSize;
console.log(bufferLength);
const dataArray = new Float32Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getFloatTimeDomainData(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] * 200.0;
const y = HEIGHT / 2 + v;
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/analysernode | data/mdn-content/files/en-us/web/api/analysernode/fftsize/index.md | ---
title: "AnalyserNode: fftSize property"
short-title: fftSize
slug: Web/API/AnalyserNode/fftSize
page-type: web-api-instance-property
browser-compat: api.AnalyserNode.fftSize
---
{{APIRef("Web Audio API")}}
The **`fftSize`** property of the {{domxref("AnalyserNode")}} interface is an unsigned long value and represents the window size in samples that is used when performing a [Fast Fourier Transform](https://en.wikipedia.org/wiki/Fast_Fourier_transform) (FFT) to get frequency domain data.
## Value
An unsigned integer, representing the window size of the FFT, given in number of samples. A higher value will result in more details in the frequency domain but fewer details in the amplitude domain.
Must be a power of 2 between 2^5 and 2^15, so one of: `32`, `64`, `128`, `256`, `512`, `1024`, `2048`, `4096`, `8192`, `16384`, and `32768`. Defaults to `2048`.
### Exceptions
- `IndexSizeError` {{domxref("DOMException")}}
- : Thrown if the value set is not a power of 2, or is outside the allowed range.
## Examples
The following example shows basic usage of an {{domxref("AudioContext")}} to create an `AnalyserNode`, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} 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://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 (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 | data/mdn-content/files/en-us/web/api/xrinputsourceevent/index.md | ---
title: XRInputSourceEvent
slug: Web/API/XRInputSourceEvent
page-type: web-api-interface
browser-compat: api.XRInputSourceEvent
---
{{APIRef("WebXR Device API")}} {{SecureContext_Header}}
The [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API)'s **`XRInputSourceEvent`** interface describes an event which has occurred on a WebXR user input device such as a hand controller, gaze tracking system, or motion tracking system. More specifically, they represent a change in the state of an {{domxref("XRInputSource")}}.
To learn more about handling inputs in a WebXR project, see the article [Inputs and input sources](/en-US/docs/Web/API/WebXR_Device_API/Inputs).
{{InheritanceDiagram}}
## Constructor
- {{domxref("XRInputSourceEvent.XRInputSourceEvent", "XRInputSourceEvent()")}}
- : Creates and returns a new `XRInputSourceEvent` object whose properties match those provided in the `eventInitDict` dictionary provided.
## Instance properties
- {{domxref("XRInputSourceEvent.frame", "frame")}} {{ReadOnlyInline}}
- : An {{domxref("XRFrame")}} object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an _event_ frame, not an _animation_ frame, you cannot call the {{domxref("XRFrame")}} method {{domxref("XRFrame.getViewerPose", "getViewerPose()")}} on it; instead, use {{domxref("XRFrame.getPose", "getPose()")}}.
- {{domxref("XRInputSourceEvent.inputSource", "inputSource")}} {{ReadOnlyInline}}
- : An {{domxref("XRInputSource")}} object indicating which input source generated the input event.
## Instance methods
_The `XRInputSourceEvent` interface doesn't define any methods; however, several methods are inherited from the parent interface, {{domxref("Event")}}._
## Event types
- {{domxref("XRSession.select_event", "select")}}
- : Sent to an {{domxref("XRSession")}} when the sending input source has fully completed a [primary action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_actions).
- {{domxref("XRSession.selectend_event", "selectend")}}
- : Sent to an {{domxref("XRSession")}} when an ongoing [primary action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_actions) ends, or when an input source with an ongoing primary action has been disconnected from the system.
- {{domxref("XRSession.selectstart_event", "selectstart")}}
- : Sent to an {{domxref("XRSession")}} when an input source begins its [primary action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_actions), indicating that the user has begun a command-like input, such as pressing a trigger or button, issuing a spoken command, tapping on a touchpad, or the like.
- {{domxref("XRSession.squeeze_event", "squeeze")}}
- : Sent to an {{domxref("XRSession")}} when the sending input source has fully completed a [primary squeeze action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_squeeze_actions).
- {{domxref("XRSession.squeezeend_event", "squeezeend")}}
- : Sent to an {{domxref("XRSession")}} when an ongoing [primary squeeze action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_squeeze_actions) ends or when an input source with an ongoing primary squeeze action is disconnected.
- {{domxref("XRSession.squeezestart_event", "squeezestart")}}
- : Sent to an {{domxref("XRSession")}} when an input source begins its [primary squeeze action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_squeeze_actions), indicating that the user has begun to grab, squeeze, or grip the controller.
## Examples
The code below sets up handlers for primary action events in order to determine when the user clicks on (shoots at/pokes at/whatever) objects in the scene.
```js
xrSession.addEventListener("select", (event) => {
let targetRayPose = event.frame.getPose(
event.inputSource.targetRaySpace,
myRefSpace,
);
if (targetRayPose) {
let hit = myHitTest(targetRayPose.transform);
if (hit) {
/* handle the hit */
}
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrinputsourceevent | data/mdn-content/files/en-us/web/api/xrinputsourceevent/inputsource/index.md | ---
title: "XRInputSourceEvent: inputSource property"
short-title: inputSource
slug: Web/API/XRInputSourceEvent/inputSource
page-type: web-api-instance-property
browser-compat: api.XRInputSourceEvent.inputSource
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The {{domxref("XRInputSourceEvent")}} interface's read-only
**`inputSource`** property specifies the
{{domxref("XRInputSource")}} which generated the input event. This information
lets you handle the event appropriately given the particulars of the user input device
being manipulated.
## Value
An {{domxref("XRInputSource")}} object identifying the source of the user input event.
This event indicates an action the user has taken using a WebXR input controller, such
as a hand controller, motion sensing device, or other input apparatus.
## Examples
The snippet below shows a handler for the {{domxref("XRSession.select_event",
"select")}} event which looks specifically for events which happen on `gaze`
input devices. The device type is identified by looking at the
{{domxref("XRInputSource")}} in `inputSource` and its
{{domxref("XRInputSource.targetRayMode", "targetRayMode")}} property.
```js
xrSession.onselect = (event) => {
let source = event.inputSource;
if (source.targetRayMode === "gaze") {
/* handle selection using a gaze input */
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrinputsourceevent | data/mdn-content/files/en-us/web/api/xrinputsourceevent/frame/index.md | ---
title: "XRInputSourceEvent: frame property"
short-title: frame
slug: Web/API/XRInputSourceEvent/frame
page-type: web-api-instance-property
browser-compat: api.XRInputSourceEvent.frame
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The read-only {{domxref("XRInputSourceEvent")}} property
**`frame`** specifies an {{domxref("XRFrame")}} object
representing the event frame during which a [WebXR](/en-US/docs/Web/API/WebXR_Device_API) user input occurred.
This may thus be an event which occurred in the past rather than a current or impending
event.
## Value
An {{domxref("XRFrame")}} indicating the event frame at which the user input event
described by the object took place.
## Usage notes
The event frame does not correspond to a visual frame as is delivered to the frame
rendering callback function (see [Rendering and the WebXR frame rendering callback](/en-US/docs/Web/API/WebXR_Device_API/Rendering) for details on the callback). Instead, the `XRFrame`
specified by the `frame` property is a method to provide access to the
{{domxref("XRFrame.getPose", "getPose()")}} method, which you can use to get the
relative positions of the objects in the scene at the time the event occurred.
However, since the event frame isn't an animation frame, there is no viewer pose
available to represent the viewer's current point of view; the results of calling
{{domxref("XRFrame.getViewerPose", "getViewerPose()")}} will be an
{{domxref("XRViewerPose")}} with an empty {{domxref("XRViewerPose.views", "views")}}
list.
## Examples
This code shows a handler for the {{domxref("XRSession.selectstart_event",
"selectstart")}} event which gets the target ray's pose from the frame, mapping the pose
representing the ray (`event.inputSource.targetRaySpace`) to the overall
reference space `myRefSpace`.
Then, if the result isn't `null`, the target ray pose's transform is passed
into a function called `myCheckAndHandleHit()` to see if the ray was pointing
at anything when the select was triggered.
```js
xrSession.onselectstart = (event) => {
let targetRayPose = event.frame.getPose(
event.inputSource.targetRaySpace,
myRefSpace,
);
if (targetRayPose) {
checkAndHandleHit(targetRayPose.transform);
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrinputsourceevent | data/mdn-content/files/en-us/web/api/xrinputsourceevent/xrinputsourceevent/index.md | ---
title: "XRInputSourceEvent: XRInputSourceEvent() constructor"
short-title: XRInputSourceEvent()
slug: Web/API/XRInputSourceEvent/XRInputSourceEvent
page-type: web-api-constructor
browser-compat: api.XRInputSourceEvent.XRInputSourceEvent
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}
The **`XRInputSourceEvent()`**
constructor creates and returns a new {{domxref("XRInputSourceEvent")}} object
describing an event (state change) which has occurred on a WebXR user input device
represented by an {{domxref("XRInputSource")}}.
## Syntax
```js-nolint
new XRInputSourceEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers set it to `select`, `selectend`, `selectstart`, `squeeze`, `squeezeend`, `squeezestart`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `frame`
- : An {{domxref("XRFrame")}} object representing the event frame during which the event took place.
This event is _not_ associated with the animation process, and has no viewer information contained within it.
- `inputSource`
- : An {{domxref("XRInputSource")}} object representing the input device from which the event is being sent.
### Return value
A new {{domxref("XRInputSourceEvent")}} object representing the event described by the
given `type` and `eventInitDict`.
## Examples
This example creates a new {{domxref("XRSession.select_event", "select")}} event and
sends it to the {{domxref("XRSession")}}.
```js
let event = new XRInputSourceEvent("select", {
frame: eventFrame,
inputSource: source,
});
if (event) {
xrSession.dispatchEvent(event);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpupipelineerror/index.md | ---
title: GPUPipelineError
slug: Web/API/GPUPipelineError
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPUPipelineError
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUPipelineError`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} describes a pipeline failure. This is the value received when a {{jsxref("Promise")}} returned by a {{domxref("GPUDevice.createComputePipelineAsync()")}} or {{domxref("GPUDevice.createRenderPipelineAsync()")}} call rejects.
{{InheritanceDiagram}}
## Constructor
- {{domxref("GPUPipelineError.GPUPipelineError", "GPUPipelineError()")}} {{Experimental_Inline}}
- : Creates a new `GPUPipelineError` object instance.
## Instance properties
_Inherits properties from its parent, {{domxref("DOMException")}}._
- {{domxref("GPUPipelineError.reason", "reason")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : An enumerated value that defines the reason the pipeline creation failed in a machine-readable way.
## Examples
In the following snippet we are attempting to create a {{domxref("GPUComputePipeline")}} using {{domxref("GPUDevice.createComputePipelineAsync()")}}. However, we have misspelt our compute pipeline `entryPoint` as `"maijn"` (it should be `"main"`), therefore pipeline creation fails, and our `catch` block prints the resulting reason and error message to the console.
```js
// ...
let computePipeline;
try {
computePipeline = await device.createComputePipelineAsync({
layout: device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout],
}),
compute: {
module: shaderModule,
entryPoint: "maijn",
},
});
} catch (error) {
// error is a GPUPipelineError object instance
console.error(error.reason);
console.error(`Pipeline creation failed: ${error.message}`);
}
// ...
```
In this case, the given `reason` is `"Validation"`, and the `message` is `"Entry point "maijn" doesn't exist in the shader module [ShaderModule]."`
## 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/gpupipelineerror | data/mdn-content/files/en-us/web/api/gpupipelineerror/gpupipelineerror/index.md | ---
title: "GPUPipelineError: GPUPipelineError() constructor"
short-title: GPUPipelineError()
slug: Web/API/GPUPipelineError/GPUPipelineError
page-type: web-api-constructor
status:
- experimental
browser-compat: api.GPUPipelineError.GPUPipelineError
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUPipelineError()`** constructor creates a new
{{domxref("GPUPipelineError")}} object instance.
## Syntax
```js-nolint
new GPUPipelineError(message, options)
```
### Parameters
- `message` {{optional_inline}}
- : A string providing a human-readable message that explains why the error occurred. If not specified, `message` defaults to an empty string (`""`).
- `options`
- : An object, which can contain the following properties:
- `reason`
- : An enumerated value that defines the reason the pipeline creation failed in a machine-readable way. The value can be one of:
- `"internal"`: Pipeline creation failed because of an internal error (see {{domxref("GPUInternalError")}} for more information about these kinds of error).
- `"validation"`: Pipeline creation failed because of a validation error (see {{domxref("GPUValidationError")}} for more information about these kinds of error).
## Examples
A developer would not manually use the constructor to create a `GPUPipelineError` object. The user agent uses this constructor to create an appropriate object when a {{jsxref("Promise")}} returned by a {{domxref("GPUDevice.createComputePipelineAsync()")}} or {{domxref("GPUDevice.createRenderPipelineAsync()")}} call rejects, signalling a pipeline failure.
See the main [`GPUPipelineError`](/en-US/docs/Web/API/GPUPipelineError#examples) page for an example involving a `GPUPipelineError` 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/gpupipelineerror | data/mdn-content/files/en-us/web/api/gpupipelineerror/reason/index.md | ---
title: "GPUPipelineError: reason property"
short-title: reason
slug: Web/API/GPUPipelineError/reason
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUPipelineError.reason
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`reason`** read-only property of the
{{domxref("GPUPipelineError")}} interface defines the reason the pipeline creation failed in a machine-readable way.
## Value
An enumerated value that can be one of:
- `"internal"`
- : Pipeline creation failed because of an internal error (see {{domxref("GPUInternalError")}} for more information about these kinds of error.)
- `"validation"`
- : Pipeline creation failed because of a validation error (see {{domxref("GPUValidationError")}} for more information about these kinds of error.)
## Examples
See the main [`GPUPipelineError`](/en-US/docs/Web/API/GPUPipelineError#examples) page for an example involving a `GPUPipelineError` object instance.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svganimatemotionelement/index.md | ---
title: SVGAnimateMotionElement
slug: Web/API/SVGAnimateMotionElement
page-type: web-api-interface
browser-compat: api.SVGAnimateMotionElement
---
{{APIRef("SVG")}}
The **`SVGAnimateMotionElement`** interface corresponds to the {{SVGElement("animateMotion")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface has no properties but inherits properties from its parent, {{domxref("SVGAnimationElement")}}._
## Instance methods
_This interface has no methods but inherits methods from its parent, {{domxref("SVGAnimationElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webkitpoint/index.md | ---
title: Point
slug: Web/API/WebKitPoint
page-type: web-api-interface
status:
- deprecated
- non-standard
browser-compat: api.WebKitPoint
---
{{APIRef("CSS3 Transforms")}}{{Deprecated_Header}}{{Non-standard_Header}}
**`Point`** is an interface which represents a point in 2-dimensional space. It is non-standard, not broadly compatible, and should not be used.
> **Note:** Although it is not directly related to this defunct interface, you are probably looking for {{domxref("DOMPoint")}}.
## Instance properties
- `x` {{Deprecated_Inline}} {{Non-standard_Inline}}
- : A floating-point value specifying the point's position with respect to the X (horizontal) axis.
- `y` {{Deprecated_Inline}} {{Non-standard_Inline}}
- : A floating-point value specifying the point's position with respect to the Y (vertical) axis.
## Specifications
This class was specified in [the defunct 20 March 2009 Working Draft of CSS 2D Transforms Module Level 3](https://www.w3.org/TR/2009/WD-css3-2d-transforms-20090320/). It is not present in any current specification.
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Window.webkitConvertPointFromNodeToPage()")}}
- {{domxref("Window.webkitConvertPointFromPageToNode()")}}
- [`WebKitPoint` documentation at the IE Dev Center](<https://msdn.microsoft.com/library/ie/dn760730(v=vs.85).aspx>) {{deprecated_inline}} {{non-standard_inline}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/sharedworker/index.md | ---
title: SharedWorker
slug: Web/API/SharedWorker
page-type: web-api-interface
browser-compat: api.SharedWorker
---
{{APIRef("Web Workers API")}}
The **`SharedWorker`** interface represents a specific kind of worker that can be _accessed_ from several browsing contexts, such as several windows, iframes or even workers. They implement an interface different than dedicated workers and have a different global scope, {{domxref("SharedWorkerGlobalScope")}}.
> **Note:** If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host and port).
{{InheritanceDiagram}}
## Constructors
- {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}
- : Creates a shared web worker that executes the script at the specified URL.
## Instance properties
_Inherits properties from its parent, {{domxref("EventTarget")}}._
- {{domxref("SharedWorker.port")}} {{ReadOnlyInline}}
- : Returns a {{domxref("MessagePort")}} object used to communicate with and control the shared worker.
## Events
- {{domxref("SharedWorker.error_event", "error")}}
- : Fires when an error occurs in the shared worker.
## Instance methods
_Inherits methods from its parent, {{domxref("EventTarget")}}._
## Example
In our [Basic shared worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker) ([run shared worker](https://mdn.github.io/dom-examples/web-workers/simple-shared-worker/)), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.
The following code snippet shows creation of a `SharedWorker` object using the {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor. Both scripts contain this:
```js
const myWorker = new SharedWorker("worker.js");
```
> **Note:** Once a shared worker is created, any script running in the same origin can obtain a reference to that worker and communicate with it. The shared worker will be alive as long as its global scope's owner set (a set of `Document` and `WorkerGlobalScope` objects) is not empty (for example, if there is any live page holding a reference to it, maybe through `new SharedWorker()`). To read more about shared worker lifetime, see [The worker's lifetime](https://html.spec.whatwg.org/multipage/workers.html#the-worker's-lifetime) section of the HTML specification.
Both scripts then access the worker through a {{domxref("MessagePort")}} object created using the {{domxref("SharedWorker.port")}} property. If the onmessage event is attached using addEventListener, the port is manually started using its `start()` method:
```js
myWorker.port.start();
```
When the port is started, both scripts post messages to the worker and handle messages sent from it using `port.postMessage()` and `port.onmessage`, respectively:
> **Note:** You can use browser devtools to debug your SharedWorker, by entering a URL in your browser address bar to access the devtools workers inspector; for example, in Chrome, the URL `chrome://inspect/#workers`, and in FireFox, the URL `about:debugging#workers`.
```js
first.onchange = () => {
myWorker.port.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
second.onchange = () => {
myWorker.port.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
myWorker.port.onmessage = (e) => {
result1.textContent = e.data;
console.log("Message received from worker");
};
```
Inside the worker we use the {{domxref("SharedWorkerGlobalScope.connect_event", "onconnect")}} handler to connect to the same port discussed above. The ports associated with that worker are accessible in the {{domxref("SharedWorkerGlobalScope/connect_event", "connect")}} event's `ports` property — we then use {{domxref("MessagePort")}} `start()` method to start the port, and the `onmessage` handler to deal with messages sent from the main threads.
```js
onconnect = (e) => {
const port = e.ports[0];
port.addEventListener("message", (e) => {
const workerResult = `Result: ${e.data[0] * e.data[1]}`;
port.postMessage(workerResult);
});
port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Worker")}}
| 0 |
data/mdn-content/files/en-us/web/api/sharedworker | data/mdn-content/files/en-us/web/api/sharedworker/port/index.md | ---
title: "SharedWorker: port property"
short-title: port
slug: Web/API/SharedWorker/port
page-type: web-api-instance-property
browser-compat: api.SharedWorker.port
---
{{APIRef("Web Workers API")}}
The **`port`** property of the {{domxref("SharedWorker")}}
interface returns a {{domxref("MessagePort")}} object used to communicate and control
the shared worker.
## Value
A {{domxref("MessagePort")}} object.
## Examples
The following code snippet shows creation of a `SharedWorker` object using
the {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor. Multiple
scripts can then access the worker through a {{domxref("MessagePort")}} object accessed
using the `SharedWorker.port` property — the port is started using its
`start()` method:
```js
const myWorker = new SharedWorker("worker.js");
myWorker.port.start();
```
For a full example, see our [Basic shared worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker) ([run shared worker](https://mdn.github.io/dom-examples/web-workers/simple-shared-worker/).)
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("SharedWorker")}}
| 0 |
data/mdn-content/files/en-us/web/api/sharedworker | data/mdn-content/files/en-us/web/api/sharedworker/sharedworker/index.md | ---
title: "SharedWorker: SharedWorker() constructor"
short-title: SharedWorker()
slug: Web/API/SharedWorker/SharedWorker
page-type: web-api-constructor
browser-compat: api.SharedWorker.SharedWorker
---
{{APIRef("Web Workers API")}}
The **`SharedWorker()`** constructor creates a
{{domxref("SharedWorker")}} object that executes the script at the specified URL. This
script must obey the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy).
> **Note:** there is disagreement among browser manufacturers about
> whether a data URL is of the same origin or not. Although Firefox 10.0
> and later accept data URLs, that's not the case in all other
> browsers.
## Syntax
```js-nolint
new SharedWorker(aURL)
new SharedWorker(aURL, name)
new SharedWorker(aURL, options)
```
### Parameters
- `aURL`
- : A string representing the URL of the script the worker will
execute. It must obey the same-origin policy.
- `name` {{optional_inline}}
- : A string specifying an identifying name for the
{{domxref("SharedWorkerGlobalScope")}} representing the scope of the worker, which is useful for creating new instances of the same SharedWorker and debugging.
- `options` {{optional_inline}}
- : An object containing option properties that can set when creating the object
instance. Available properties are as follows:
- `type`
- : A string specifying the type of worker to
create. The value can be `classic` or `module`. If not
specified, the default used is `classic`.
- `credentials`
- : A string specifying the type of
credentials to use for the worker. The value can be `omit`,
`same-origin`, or _`include`. If not
specified, or if type is `classic`, the default used is
`omit` (no credentials required)._
- `name`
- : A string specifying an
identifying name for the {{domxref("SharedWorkerGlobalScope")}} representing the
scope of the worker, which is mainly useful for debugging purposes.
### Exceptions
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the document is not allowed to start workers, for example if the URL has an invalid syntax or if the same-origin policy is violated.
- `NetworkError` {{domxref("DOMException")}}
- : Thrown if the MIME type of the worker script is incorrect. It should _always_ be `text/javascript` (for historical reasons [other JavaScript MIME types](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#textjavascript) may be accepted).
- `SyntaxError` {{domxref("DOMException")}}
- : Thrown if `aURL` cannot be parsed.
## Examples
The following code snippet shows creation of a {{domxref("SharedWorker")}} object using
the `SharedWorker()` constructor and subsequent usage of the object:
```js
const myWorker = new SharedWorker("worker.js");
myWorker.port.start();
first.onchange = () => {
myWorker.port.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
second.onchange = () => {
myWorker.port.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
myWorker.port.onmessage = (e) => {
result1.textContent = e.data;
console.log("Message received from worker");
};
```
For a full example, see our [Basic shared worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker) ([run shared worker](https://mdn.github.io/dom-examples/web-workers/simple-shared-worker/).)
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("SharedWorker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/sharedworker | data/mdn-content/files/en-us/web/api/sharedworker/error_event/index.md | ---
title: "SharedWorker: error event"
short-title: error
slug: Web/API/SharedWorker/error_event
page-type: web-api-event
browser-compat: api.SharedWorker.error_event
---
{{APIRef("Web Workers API")}}
The **`error`** event of the {{domxref("SharedWorker")}} interface fires when an error occurs in the worker.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("error", (event) => {});
onerror = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Example
The following code snippet creates a {{domxref("SharedWorker")}} object using the {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor and sets up an `onerror` handler on the resulting object:
```js
const mySharedWorker = new SharedWorker("shared-worker.js");
mySharedWorker.onerror = (event) => {
console.error("There is an error with your worker!");
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpuerror/index.md | ---
title: GPUError
slug: Web/API/GPUError
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPUError
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUError`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} is the base interface for errors surfaced by {{domxref("GPUDevice.popErrorScope")}} and the {{domxref("GPUDevice.uncapturederror_event", "uncapturederror")}} event.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("GPUError.message", "message")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : A string providing a human-readable message that explains why the error occurred.
## Examples
For usage examples of error objects based on `GPUError`, see:
- [`GPUDevice.popErrorScope`](/en-US/docs/Web/API/GPUDevice/popErrorScope#examples)
- [The `GPUDevice uncapturederror` event](/en-US/docs/Web/API/GPUDevice/uncapturederror_event#examples)
- {{domxref("GPUInternalError")}}, {{domxref("GPUOutOfMemoryError")}}, and {{domxref("GPUValidationError")}}
## 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/gpuerror | data/mdn-content/files/en-us/web/api/gpuerror/message/index.md | ---
title: "GPUError: message property"
short-title: message
slug: Web/API/GPUError/message
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUError.message
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`message`** read-only property of the
{{domxref("GPUError")}} interface provides a human-readable message that explains why the error occurred.
## Value
A string.
## Examples
For usage examples of error objects based on `GPUError`, see:
- [`GPUDevice.popErrorScope`](/en-US/docs/Web/API/GPUDevice/popErrorScope#examples)
- [The `GPUDevice uncapturederror` event](/en-US/docs/Web/API/GPUDevice/uncapturederror_event#examples)
- {{domxref("GPUInternalError")}}, {{domxref("GPUOutOfMemoryError")}}, and {{domxref("GPUValidationError")}}
## 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/pannernode/index.md | ---
title: PannerNode
slug: Web/API/PannerNode
page-type: web-api-interface
browser-compat: api.PannerNode
---
{{ APIRef("Web Audio API") }}
The `PannerNode` interface defines an audio-processing object that represents the location, direction, and behavior of an audio source signal in a simulated physical space. This {{domxref("AudioNode")}} uses right-hand Cartesian coordinates to describe the source's _position_ as a vector and its _orientation_ as a 3D directional cone.
A `PannerNode` always has exactly one input and one output: the input can be _mono_ or _stereo_ but the output is always _stereo_ (2 channels); you can't have panning effects without at least two audio channels!
![The PannerNode defines a spatial position and direction for a given signal.](webaudiopannernode.png)
{{InheritanceDiagram}}
<table class="properties">
<tbody>
<tr>
<th scope="row">Number of inputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Number of outputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Channel count mode</th>
<td><code>"clamped-max"</code></td>
</tr>
<tr>
<th scope="row">Channel count</th>
<td><code>2</code></td>
</tr>
<tr>
<th scope="row">Channel interpretation</th>
<td><code>"speakers"</code></td>
</tr>
</tbody>
</table>
## Constructor
- {{domxref("PannerNode.PannerNode", "PannerNode()")}}
- : Creates a new `PannerNode` object instance.
## Instance properties
_Inherits properties from its parent, {{domxref("AudioNode")}}_.
> **Note:** The orientation and position value are set and retrieved using different syntaxes, since they're stored as {{domxref("AudioParam")}} values. Retrieval is done by accessing, for example, `PannerNode.positionX`. While setting the same property is done with `PannerNode.positionX.value`. This is why these values are not marked read only, which is how they appear in the WebIDL.
- {{domxref("PannerNode.coneInnerAngle")}}
- : A double value describing the angle, in degrees, of a cone inside of which there will be no volume reduction.
- {{domxref("PannerNode.coneOuterAngle")}}
- : A double value describing the angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` property.
- {{domxref("PannerNode.coneOuterGain")}}
- : A double value describing the amount of volume reduction outside the cone defined by the `coneOuterAngle` attribute. Its default value is `0`, meaning that no sound can be heard.
- {{domxref("PannerNode.distanceModel")}}
- : An enumerated value determining which algorithm to use to reduce the volume of the audio source as it moves away from the listener. Possible values are `"linear"`, `"inverse"` and `"exponential"`. The default value is `"inverse"`.
- {{domxref("PannerNode.maxDistance")}}
- : A double value representing the maximum distance between the audio source and the listener, after which the volume is not reduced any further.
- {{domxref("PannerNode.orientationX")}}
- : Represents the horizontal position of the audio source's vector in a right-hand Cartesian coordinate system. While this {{domxref("AudioParam")}} cannot be directly changed, its value can be altered using its {{domxref("AudioParam.value", "value")}} property. The default is value is 1.
- {{domxref("PannerNode.orientationY")}}
- : Represents the vertical position of the audio source's vector in a right-hand Cartesian coordinate system. The default is 0. While this {{domxref("AudioParam")}} cannot be directly changed, its value can be altered using its {{domxref("AudioParam.value", "value")}} property. The default is value is 0.
- {{domxref("PannerNode.orientationZ")}}
- : Represents the longitudinal (back and forth) position of the audio source's vector in a right-hand Cartesian coordinate system. The default is 0. While this {{domxref("AudioParam")}} cannot be directly changed, its value can be altered using its {{domxref("AudioParam.value", "value")}} property. The default is value is 0.
- {{domxref("PannerNode.panningModel")}}
- : An enumerated value determining which spatialization algorithm to use to position the audio in 3D space.
- {{domxref("PannerNode.positionX")}}
- : Represents the horizontal position of the audio in a right-hand Cartesian coordinate system. The default is 0. While this {{domxref("AudioParam")}} cannot be directly changed, its value can be altered using its {{domxref("AudioParam.value", "value")}} property. The default is value is 0.
- {{domxref("PannerNode.positionY")}}
- : Represents the vertical position of the audio in a right-hand Cartesian coordinate system. The default is 0. While this {{domxref("AudioParam")}} cannot be directly changed, its value can be altered using its {{domxref("AudioParam.value", "value")}} property. The default is value is 0.
- {{domxref("PannerNode.positionZ")}}
- : Represents the longitudinal (back and forth) position of the audio in a right-hand Cartesian coordinate system. The default is 0. While this {{domxref("AudioParam")}} cannot be directly changed, its value can be altered using its {{domxref("AudioParam.value", "value")}} property. The default is value is 0.
- {{domxref("PannerNode.refDistance")}}
- : A double value representing the reference distance for reducing volume as the audio source moves further from the listener. For distances greater than this the volume will be reduced based on `rolloffFactor` and `distanceModel`.
- {{domxref("PannerNode.rolloffFactor")}}
- : A double value describing how quickly the volume is reduced as the source moves away from the listener. This value is used by all distance models.
## Instance methods
_Inherits methods from its parent, {{domxref("AudioNode")}}_.
- {{domxref("PannerNode.setPosition()")}} {{deprecated_inline}}
- : Defines the position of the audio source relative to the listener (represented by an {{domxref("AudioListener")}} object stored in the {{domxref("BaseAudioContext.listener")}} attribute.)
- {{domxref("PannerNode.setOrientation()")}} {{deprecated_inline}}
- : Defines the direction the audio source is playing in.
## Examples
See [`BaseAudioContext.createPanner()`](/en-US/docs/Web/API/BaseAudioContext/createPanner#examples) for example code.
## 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/pannernode | data/mdn-content/files/en-us/web/api/pannernode/setorientation/index.md | ---
title: "PannerNode: setOrientation() method"
short-title: setOrientation()
slug: Web/API/PannerNode/setOrientation
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.PannerNode.setOrientation
---
{{APIRef("Web Audio API")}}{{Deprecated_Header}}
> **Note:** The suggested replacement for this deprecated method is to instead set the [`orientationX`](/en-US/docs/Web/API/PannerNode/orientationX), [`orientationY`](/en-US/docs/Web/API/PannerNode/orientationY), and [`orientationZ`](/en-US/docs/Web/API/PannerNode/orientationZ) attributes directly.
The `setOrientation()` method of the {{ domxref("PannerNode") }} Interface defines the direction the audio source is playing in.
This can have a big effect if the sound is very directional — controlled by the three cone-related attributes {{domxref("PannerNode.coneInnerAngle")}}, {{domxref("PannerNode.coneOuterAngle")}}, and {{domxref("PannerNode.coneOuterGain")}}. In such a case, a sound pointing away from the listener can be very quiet or even silent.
The three parameters `x`, `y` and `z` are unitless and describe a direction vector in 3D space using the right-hand Cartesian coordinate system. The default value of the direction vector is `(1, 0, 0)`.
## Syntax
```js-nolint
setOrientation(x, y, z)
```
### Parameters
- `x`
- : The x value of the panner's direction vector in 3D space.
- `y`
- : The y value of the panner's direction vector in 3D space.
- `z`
- : The z value of the panner's direction vector in 3D space.
### Return value
None ({{jsxref("undefined")}}).
## Examples
See [`BaseAudioContext.createPanner()`](/en-US/docs/Web/API/BaseAudioContext/createPanner#examples) for example code.
## 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/pannernode | data/mdn-content/files/en-us/web/api/pannernode/distancemodel/index.md | ---
title: "PannerNode: distanceModel property"
short-title: distanceModel
slug: Web/API/PannerNode/distanceModel
page-type: web-api-instance-property
browser-compat: api.PannerNode.distanceModel
---
{{ APIRef("Web Audio API") }}
The `distanceModel` property of the {{ domxref("PannerNode") }} interface is an enumerated value determining which algorithm to use to reduce the volume of the audio source as it moves away from the listener.
The possible values are:
- `linear`: A _linear distance model_ calculating the gain induced by the distance according to:
`1 - rolloffFactor * (distance - refDistance) / (maxDistance - refDistance)`
- `inverse`: An _inverse distance model_ calculating the gain induced by the distance according to:
`refDistance / (refDistance + rolloffFactor * (Math.max(distance, refDistance) - refDistance))`
- `exponential`: An _exponential distance model_ calculating the gain induced by the distance according to:
`pow((Math.max(distance, refDistance) / refDistance, -rolloffFactor)`.
`inverse` is the default value of `distanceModel`.
## Value
An enum — see [`DistanceModelType`](https://webaudio.github.io/web-audio-api/#idl-def-DistanceModelType).
## Examples
See [`BaseAudioContext.createPanner()`](/en-US/docs/Web/API/BaseAudioContext/createPanner#examples) for example code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/refdistance/index.md | ---
title: "PannerNode: refDistance property"
short-title: refDistance
slug: Web/API/PannerNode/refDistance
page-type: web-api-instance-property
browser-compat: api.PannerNode.refDistance
---
{{ APIRef("Web Audio API") }}
The `refDistance` property of the {{ domxref("PannerNode") }} interface is a double value representing the reference distance for reducing volume as the audio source moves further from the listener – i.e. the distance at which the volume reduction starts taking effect. This value is used by all distance models.
The `refDistance` property's default value is `1`.
## Value
A non-negative number. If the value is set to less than 0, a {{jsxref("RangeError")}} is thrown.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the property has been given a value that is outside the accepted range.
## Examples
This example demonstrates how different values of {{ domxref("PannerNode.refDistance", "refDistance") }} affect how the volume of a sound decays as it moves away from the listener. Unlike {{ domxref("PannerNode.rolloffFactor", "rolloffFactor") }}, changing this value also _delays_ the volume decay until the sound moves past the reference point.
```js
const context = new AudioContext();
// all our test tones will last this many seconds
const NOTE_LENGTH = 6;
// this is how far we'll move the sound
const Z_DISTANCE = 20;
// this function creates a graph for the test tone with a given refDistance
// and schedules it to move away from the listener along the Z (depth-wise) axis
// at the given start time, resulting in a decrease in volume (decay)
const scheduleTestTone = (refDistance, startTime) => {
const osc = new OscillatorNode(context);
const panner = new PannerNode(context);
panner.refDistance = refDistance;
// set the initial Z position, then schedule the ramp
panner.positionZ.setValueAtTime(0, startTime);
panner.positionZ.linearRampToValueAtTime(Z_DISTANCE, startTime + NOTE_LENGTH);
osc.connect(panner).connect(context.destination);
osc.start(startTime);
osc.stop(startTime + NOTE_LENGTH);
};
// this tone should decay immediately and fairly quickly
scheduleTestTone(1, context.currentTime);
// this tone should decay slower and later than the previous one
scheduleTestTone(4, context.currentTime + NOTE_LENGTH);
// this tone should decay only slightly, and only start decaying fairly late
scheduleTestTone(7, context.currentTime + NOTE_LENGTH * 2);
```
After running this code, the resulting waveforms should look something like this:
![A waveform visualization of three oscillator tones produced in Web Audio. Each oscillator moves away from the listener at the same speed, but with different refDistances affecting the resulting volume decay.](screen_shot_2018-10-11_at_23.14.32.png)
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/coneoutergain/index.md | ---
title: "PannerNode: coneOuterGain property"
short-title: coneOuterGain
slug: Web/API/PannerNode/coneOuterGain
page-type: web-api-instance-property
browser-compat: api.PannerNode.coneOuterGain
---
{{ APIRef("Web Audio API") }}
The `coneOuterGain` property of the {{ domxref("PannerNode") }} interface is a double value, describing the amount of volume reduction outside the cone, defined by the {{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}} attribute.
The `coneOuterGain` property's default value is `0`, meaning that no sound can be heard outside the cone.
## Value
A double. The default is `0`, and its value can be in the range 0–1.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the property has been given a value outside the accepted range (0–1).
## Examples
See [`PannerNode.orientationX`](/en-US/docs/Web/API/PannerNode/orientationX#example) for example code that demonstrates how changing the {{domxref("PannerNode")}} orientation parameters in combination with {{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}} and {{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}} affects volume.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/maxdistance/index.md | ---
title: "PannerNode: maxDistance property"
short-title: maxDistance
slug: Web/API/PannerNode/maxDistance
page-type: web-api-instance-property
browser-compat: api.PannerNode.maxDistance
---
{{ APIRef("Web Audio API") }}
The `maxDistance` property of the {{ domxref("PannerNode") }} interface is a double value representing the maximum distance between the audio source and the listener, after which the volume is not reduced any further. This value is used only by the `linear` distance model.
The `maxDistance` property's default value is `10000`.
## Value
A double. The default is `10000`, and non-positive values are not allowed.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the property has been given a value that is outside the accepted range.
## Examples
See [`BaseAudioContext.createPanner()`](/en-US/docs/Web/API/BaseAudioContext/createPanner#examples) for example code.
## 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/pannernode | data/mdn-content/files/en-us/web/api/pannernode/setposition/index.md | ---
title: "PannerNode: setPosition() method"
short-title: setPosition()
slug: Web/API/PannerNode/setPosition
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.PannerNode.setPosition
---
{{APIRef("Web Audio API")}}{{Deprecated_Header}}
> **Note:** The suggested replacement for this deprecated method is to instead set the [`positionX`](/en-US/docs/Web/API/PannerNode/positionX), [`positionY`](/en-US/docs/Web/API/PannerNode/positionY), and [`positionZ`](/en-US/docs/Web/API/PannerNode/positionZ) attributes directly.
The `setPosition()` method of the {{ domxref("PannerNode") }} Interface defines the position of the audio source relative to the listener (represented by an {{domxref("AudioListener")}} object stored in the {{domxref("BaseAudioContext.listener")}} attribute.) The three parameters `x`, `y` and `z` are unitless and describe the source's position in 3D space using the right-hand Cartesian coordinate system.
The `setPosition()` method's default value of the position is `(0, 0, 0)`.
## Syntax
```js-nolint
setPosition(x, y, z)
```
### Parameters
- `x`
- : The x position of the panner in 3D space.
- `y`
- : The y position of the panner in 3D space.
- `z`
- : The z position of the panner in 3D space.
### Return value
None ({{jsxref("undefined")}}).
## Examples
See [`BaseAudioContext.createPanner()`](/en-US/docs/Web/API/BaseAudioContext/createPanner#examples) for example code.
## 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/pannernode | data/mdn-content/files/en-us/web/api/pannernode/positionz/index.md | ---
title: "PannerNode: positionZ property"
short-title: positionZ
slug: Web/API/PannerNode/positionZ
page-type: web-api-instance-property
browser-compat: api.PannerNode.positionZ
---
{{ APIRef("Web Audio API") }}
The **`positionZ`** property of the {{ domxref("PannerNode") }} interface specifies the Z coordinate of the audio source's position in 3D Cartesian
coordinates, corresponding to the _depth_ axis (behind-in front of the
listener). The complete vector is defined by the position of the audio source, given
as ({{domxref("PannerNode.positionX", "positionX")}},
{{domxref("PannerNode.positionY", "positionY")}}, {{domxref("PannerNode.positionZ",
"positionZ")}}), and the orientation of the audio source (that is, the direction in
which it's facing), given as ({{domxref("PannerNode.orientationX", "orientationX")}},
{{domxref("PannerNode.orientationY", "orientationY")}},
{{domxref("PannerNode.orientationZ", "orientationZ")}}).
Depending on the directionality of the sound (as specified using the attributes
{{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}},
{{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}}, and
{{domxref("PannerNode.coneOuterGain", "codeOuterGain")}}), the orientation of the
sound may alter the perceived volume of the sound as it's being played. If the sound
is pointing toward the listener, it will be louder than if the sound is pointed away
from the listener.
The {{domxref("AudioParam")}} contained by this property is read only; however, you
can still change the value of the parameter by assigning a new value to its
{{domxref("AudioParam.value")}} property.
## Value
An {{domxref("AudioParam")}} whose `value` is the Z coordinate of the audio
source's position, in 3D Cartesian coordinates.
## Examples
The following example starts an oscillator and moves it in front of the listener after
1 second, behind the listener after 2 seconds, and back to the listener's position after
3 seconds. Note that in this case, the change will mainly affect the timbre and
perceived volume of the sound.
```js
const context = new AudioContext();
const osc = new OscillatorNode(context);
const panner = new PannerNode(context);
panner.panningModel = "HRTF";
panner.positionZ.setValueAtTime(1, context.currentTime + 1);
panner.positionZ.setValueAtTime(-1, context.currentTime + 2);
panner.positionZ.setValueAtTime(0, context.currentTime + 3);
osc.connect(panner).connect(context.destination);
osc.start(0);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
- {{domxref("PannerNode")}}
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/pannernode/index.md | ---
title: "PannerNode: PannerNode() constructor"
short-title: PannerNode()
slug: Web/API/PannerNode/PannerNode
page-type: web-api-constructor
browser-compat: api.PannerNode.PannerNode
---
{{APIRef("Web Audio API")}}
The **`PannerNode()`** constructor of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) creates a new {{domxref("PannerNode")}} object instance.
## Syntax
```js-nolint
new PannerNode(context)
new PannerNode(context, options)
```
### Parameters
- `context`
- : A {{domxref("BaseAudioContext")}} representing the audio context you want the node to be associated with.
- `options` {{optional_inline}}
- : A [`PannerOptions`](https://webaudio.github.io/web-audio-api/#idl-def-PannerOptions) dictionary object defining the properties you want the `PannerNode` to have:
- `panningModel`
- : The {{domxref("PannerNode.panningModel")}} you want the {{domxref("PannerNode")}} to have (the default is `equalpower`.)
- `distanceModel`
- : The {{domxref("PannerNode.distanceModel")}} you want the {{domxref("PannerNode")}} to have (the default is `inverse`.)
- `positionX`
- : The {{domxref("PannerNode.positionX")}} you want the {{domxref("PannerNode")}} to have (the default is `0`.)
- `positionY`
- : The {{domxref("PannerNode.positionY")}} you want the {{domxref("PannerNode")}} to have (the default is `0`.)
- `positionZ`
- : The {{domxref("PannerNode.positionZ")}} you want the {{domxref("PannerNode")}} to have (the default is `0`.)
- `orientationX`
- : The {{domxref("PannerNode.orientationX")}} you want the {{domxref("PannerNode")}} to have (the default is `1`.)
- `orientationY`
- : The {{domxref("PannerNode.orientationY")}} you want the {{domxref("PannerNode")}} to have (the default is `0`.)
- `orientationZ`
- : The {{domxref("PannerNode.orientationZ")}} you want the {{domxref("PannerNode")}} to have (the default is `0`.)
- `refDistance`
- : The {{domxref("PannerNode.refDistance")}} you want the {{domxref("PannerNode")}} to have. The default is `1`, and negative values are not allowed.
- `maxDistance`
- : The {{domxref("PannerNode.maxDistance")}} you want the {{domxref("PannerNode")}} to have. The default is `10000`, and non-positive values are not allowed.
- `rolloffFactor`
- : The {{domxref("PannerNode.rolloffFactor")}} you want the {{domxref("PannerNode")}} to have. The default is `1`, and negative values are not allowed.
- `coneInnerAngle`
- : The {{domxref("PannerNode.coneInnerAngle")}} you want the {{domxref("PannerNode")}} to have (the default is `360`.)
- `coneOuterAngle`
- : The {{domxref("PannerNode.coneOuterAngle")}} you want the {{domxref("PannerNode")}} to have (the default is `360`.)
- `coneOuterGain`
- : The {{domxref("PannerNode.coneOuterGain")}} you want the {{domxref("PannerNode")}} to have. The default is `0`, and its value can be in the range 0–1.
- `channelCount`
- : Represents an integer used to determine how many channels are used when [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) connections to any inputs to the node. (See
{{domxref("AudioNode.channelCount")}} for more information.) Its usage and precise
definition depend on the value of `channelCountMode`.
- `channelCountMode`
- : Represents an enumerated value describing the way channels must be matched between
the node's inputs and outputs. (See {{domxref("AudioNode.channelCountMode")}} for more
information including default values.)
- `channelInterpretation`
- : Represents an enumerated value describing the meaning of the channels. This
interpretation will define how audio [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) will happen.
The possible values are `"speakers"` or `"discrete"`. (See
{{domxref("AudioNode.channelCountMode")}} for more information including default
values.)
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the `refDistance`, `maxDistance`, or `rolloffFactor` properties have been given a value that is outside the accepted range.
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the `coneOuterGain` property has been given a value outside the accepted range (0–1).
## Examples
```js
const ctx = new AudioContext();
const options = {
positionX: 1,
maxDistance: 5000,
};
const myPanner = new PannerNode(ctx, options);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/orientationz/index.md | ---
title: "PannerNode: orientationZ property"
short-title: orientationZ
slug: Web/API/PannerNode/orientationZ
page-type: web-api-instance-property
browser-compat: api.PannerNode.orientationZ
---
{{ APIRef("Web Audio API") }}
The **`orientationZ`** property of the {{ domxref("PannerNode") }} interface
indicates the Z (depth) component of the direction the audio source is facing, in 3D Cartesian coordinate space.
The complete vector is defined by the position of the audio source, given as
({{domxref("PannerNode.positionX", "positionX")}}, {{domxref("PannerNode.positionY",
"positionY")}}, {{domxref("PannerNode.positionZ", "positionZ")}}), and the orientation
of the audio source (that is, the direction in which it's facing), given as
({{domxref("PannerNode.orientationX", "orientationX")}},
{{domxref("PannerNode.orientationY", "orientationY")}},
{{domxref("PannerNode.orientationZ", "orientationZ")}}).
Depending on the directionality of the sound (as specified using the attributes
{{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}},
{{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}}, and
{{domxref("PannerNode.coneOuterGain", "codeOuterGain")}}), the orientation of the
sound may alter the perceived volume of the sound as it's being played. If the sound
is pointing toward the listener, it will be louder than if the sound is pointed away
from the listener.
The {{domxref("AudioParam")}} contained by this property is read only; however, you
can still change the value of the parameter by assigning a new value to its
{{domxref("AudioParam.value")}} property.
## Value
An {{domxref("AudioParam")}} whose `value` is the Z component of the
direction the audio source is facing, in 3D Cartesian coordinate space.
## Example
See [`PannerNode.orientationX`](/en-US/docs/Web/API/PannerNode/orientationX#example) for example code that demonstrates the effect on volume of changing the {{domxref("PannerNode")}} orientation parameters in combination with {{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}} and {{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
- {{domxref("PannerNode")}}
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/rollofffactor/index.md | ---
title: "PannerNode: rolloffFactor property"
short-title: rolloffFactor
slug: Web/API/PannerNode/rolloffFactor
page-type: web-api-instance-property
browser-compat: api.PannerNode.rolloffFactor
---
{{ APIRef("Web Audio API") }}
The `rolloffFactor` property of the {{ domxref("PannerNode") }} interface is a double value describing how quickly the volume is reduced as the source moves away from the listener. This value is used by all distance models. The `rolloffFactor` property's default value is `1`.
## Value
A number whose range depends on the {{ domxref("PannerNode.distanceModel", "distanceModel") }} of the panner as follows (negative values are not allowed):
- "`linear`"
- : The range is 0 to 1.
- "`inverse`"
- : The range is 0 to `Infinity`.
- "`exponential`"
- : The range is 0 to `Infinity`.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the property has been given a value that is outside the accepted range.
## Examples
This example demonstrates how different {{ domxref("PannerNode.rolloffFactor", "rolloffFactor") }} values affect how the volume of the test tone decreases with increasing distance from the listener:
```js
const context = new AudioContext();
// all our test tones will last this many seconds
const NOTE_LENGTH = 4;
// this is how far we'll move the sound
const Z_DISTANCE = 20;
// this function creates a graph for the test tone with a given rolloffFactor
// and schedules it to move away from the listener along the Z (depth-wise) axis
// at the given start time, resulting in a decrease in volume (decay)
const scheduleTestTone = (rolloffFactor, startTime) => {
const osc = new OscillatorNode(context);
const panner = new PannerNode(context);
panner.rolloffFactor = rolloffFactor;
// set the initial Z position, then schedule the ramp
panner.positionZ.setValueAtTime(0, startTime);
panner.positionZ.linearRampToValueAtTime(Z_DISTANCE, startTime + NOTE_LENGTH);
osc.connect(panner).connect(context.destination);
osc.start(startTime);
osc.stop(startTime + NOTE_LENGTH);
};
// this tone should decay fairly quickly
scheduleTestTone(1, context.currentTime);
// this tone should decay slower than the previous one
scheduleTestTone(0.5, context.currentTime + NOTE_LENGTH);
// this tone should decay only slightly
scheduleTestTone(0.1, context.currentTime + NOTE_LENGTH * 2);
```
After running this code, the resulting waveforms should look something like this:
![A waveform visualization of three oscillator tones produced in Web Audio. Each oscillator moves away from the listener at the same speed, but with different rolloffFactors affecting the resulting volume decay.](screen_shot_2018-10-11_at_23.22.37.png)
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/panningmodel/index.md | ---
title: "PannerNode: panningModel property"
short-title: panningModel
slug: Web/API/PannerNode/panningModel
page-type: web-api-instance-property
browser-compat: api.PannerNode.panningModel
---
{{ APIRef("Web Audio API") }}
The `panningModel` property of the {{ domxref("PannerNode") }} interface is an enumerated value determining which spatialization algorithm to use to position the audio in 3D space.
The possible values are:
- `equalpower`: Represents the equal-power panning algorithm, generally regarded as simple and efficient. `equalpower` is the default value.
- `HRTF`: Renders a stereo output of higher quality than `equalpower` — it uses a convolution with measured impulse responses from human subjects.
## Value
An enum — see [`PanningModelType`](https://webaudio.github.io/web-audio-api/#idl-def-PanningModelType).
## Examples
See [`BaseAudioContext.createPanner()`](/en-US/docs/Web/API/BaseAudioContext/createPanner#examples) for example code.
## 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/pannernode | data/mdn-content/files/en-us/web/api/pannernode/coneouterangle/index.md | ---
title: "PannerNode: coneOuterAngle property"
short-title: coneOuterAngle
slug: Web/API/PannerNode/coneOuterAngle
page-type: web-api-instance-property
browser-compat: api.PannerNode.coneOuterAngle
---
{{ APIRef("Web Audio API") }}
The `coneOuterAngle` property of the {{ domxref("PannerNode") }} interface is a double value describing the angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the {{domxref("PannerNode.coneOuterGain","coneOuterGain")}} property.
The `coneOuterAngle` property's default value is `0`.
## Value
A double.
## Examples
See [`PannerNode.orientationX`](/en-US/docs/Web/API/PannerNode/orientationX#example) for example code that demonstrates the effect on volume of changing the {{domxref("PannerNode")}} orientation parameters in combination with {{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}} and {{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/coneinnerangle/index.md | ---
title: "PannerNode: coneInnerAngle property"
short-title: coneInnerAngle
slug: Web/API/PannerNode/coneInnerAngle
page-type: web-api-instance-property
browser-compat: api.PannerNode.coneInnerAngle
---
{{ APIRef("Web Audio API") }}
The `coneInnerAngle` property of the {{ domxref("PannerNode") }} interface is a double value describing the angle, in degrees, of a cone inside of which there will be no volume reduction.
The `coneInnerAngle` property's default value is `360`, suitable for a non-directional source.
## Value
A double.
## Examples
See [`PannerNode.orientationX`](/en-US/docs/Web/API/PannerNode/orientationX#example) for example code that demonstrates the effect on volume of changing the {{domxref("PannerNode")}} orientation parameters in combination with {{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}} and {{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/positionx/index.md | ---
title: "PannerNode: positionX property"
short-title: positionX
slug: Web/API/PannerNode/positionX
page-type: web-api-instance-property
browser-compat: api.PannerNode.positionX
---
{{ APIRef("Web Audio API") }}
The **`positionX`** property of the {{ domxref("PannerNode")
}} interface specifies the X coordinate of the audio source's position in 3D Cartesian
coordinates, corresponding to the _horizontal_ axis (left-right).
The complete vector is defined by the position of the audio source, given as
({{domxref("PannerNode.positionX", "positionX")}}, {{domxref("PannerNode.positionY",
"positionY")}}, {{domxref("PannerNode.positionZ", "positionZ")}}), and the orientation
of the audio source (that is, the direction in which it's facing), given as
({{domxref("PannerNode.orientationX", "orientationX")}},
{{domxref("PannerNode.orientationY", "orientationY")}},
{{domxref("PannerNode.orientationZ", "orientationZ")}}).
Depending on the directionality of the sound (as specified using the attributes
{{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}},
{{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}}, and
{{domxref("PannerNode.coneOuterGain", "codeOuterGain")}}), the orientation of the
sound may alter the perceived volume of the sound as it's being played. If the sound
is pointing toward the listener, it will be louder than if the sound is pointed away
from the listener.
The {{domxref("AudioParam")}} contained by this property is read only; however, you
can still change the value of the parameter by assigning a new value to its
{{domxref("AudioParam.value")}} property.
## Value
An {{domxref("AudioParam")}} whose `value` is the X coordinate of the audio
source's position, in 3D Cartesian coordinates. The default value is 0.
## Examples
The following example starts an oscillator, and pans it to the left after 1 second, to
the right after 2 seconds, and back to the center after 3 seconds.
```js
const context = new AudioContext();
const osc = new OscillatorNode(context);
const panner = new PannerNode(context);
panner.positionX.setValueAtTime(-1, context.currentTime + 1);
panner.positionX.setValueAtTime(1, context.currentTime + 2);
panner.positionX.setValueAtTime(0, context.currentTime + 3);
osc.connect(panner).connect(context.destination);
osc.start(0);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
- {{domxref("PannerNode")}}
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/orientationx/index.md | ---
title: "PannerNode: orientationX property"
short-title: orientationX
slug: Web/API/PannerNode/orientationX
page-type: web-api-instance-property
browser-compat: api.PannerNode.orientationX
---
{{ APIRef("Web Audio API") }}
The **`orientationX`** property of the {{
domxref("PannerNode") }} interface indicates the X (horizontal) component of the
direction in which the audio source is facing, in a 3D Cartesian coordinate space.
The complete vector is defined by the position of the audio source, given as
({{domxref("PannerNode.positionX", "positionX")}}, {{domxref("PannerNode.positionY",
"positionY")}}, {{domxref("PannerNode.positionZ", "positionZ")}}), and the orientation
of the audio source (that is, the direction in which it's facing), given as
({{domxref("PannerNode.orientationX", "orientationX")}},
{{domxref("PannerNode.orientationY", "orientationY")}},
{{domxref("PannerNode.orientationZ", "orientationZ")}}).
Depending on the directionality of the sound (as specified using the attributes
{{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}},
{{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}}, and
{{domxref("PannerNode.coneOuterGain", "coneOuterGain")}}), the orientation of the
sound may alter the perceived volume of the sound as it's being played. If the sound
is pointing toward the listener, it will be louder than if the sound is pointed away
from the listener.
The {{domxref("AudioParam")}} contained by this property is read only; however, you
can still change the value of the parameter by assigning a new value to its
{{domxref("AudioParam.value")}} property.
## Value
An {{domxref("AudioParam")}} whose `value` is the X component of the
direction in which the audio source is facing, in 3D Cartesian coordinate space.
## Example
In this example, we'll demonstrate how changing the orientation parameters of a {{
domxref("PannerNode") }} in combination with {{domxref("PannerNode.coneInnerAngle",
"coneInnerAngle")}} and {{domxref("PannerNode.coneOuterAngle",
"coneOuterAngle")}} affects volume. To help us visualize how the orientation vector
affects, we can use the [Right-hand rule](https://en.wikipedia.org/wiki/Right-hand_rule):
![This chart visualizes how the PannerNode orientation vectors affect the direction of the sound cone.](pannernode-orientation.png)
First, let's start by writing a utility function to figure out our _orientation vector._
The X and Z components are always at a 90° to each other, so we can
use the sine and cosine functions, which are offset by the same amount in radians.
However, normally this would mean the {{ domxref("PannerNode") }} points to
the **left** of the listener at 0° rotation – since `x = cos(0) = 1` and `z = sin(0) = 0`.
It's more useful to offset the angle by -90°, which means the {{domxref("PannerNode")}} will point **directly at the listener** at 0° rotation.
```js
// this utility converts amount of rotation around the Y axis
// (i.e. rotation in the 'horizontal plane') to an orientation vector
const yRotationToVector = (degrees) => {
// convert degrees to radians and offset the angle so 0 points towards the listener
const radians = (degrees - 90) * (Math.PI / 180);
// using cosine and sine here ensures the output values are always normalized
// i.e. they range between -1 and 1
const x = Math.cos(radians);
const z = Math.sin(radians);
// we hard-code the Y component to 0, as Y is the axis of rotation
return [x, 0, z];
};
```
Now we can create our {{ domxref("AudioContext") }}, an oscillator and a {{
domxref("PannerNode") }}:
```js
const context = new AudioContext();
const osc = new OscillatorNode(context);
osc.type = "sawtooth";
const panner = new PannerNode(context);
panner.panningModel = "HRTF";
```
Next, we set up the _cone_ of our spatialized sound, determining the area in
which it can be heard:
```js
// this value determines the size of the area in which the sound volume is constant
// if coneInnerAngle === 30, it means that when the sound is rotated
// by at most 15 (30/2) degrees either direction, the volume won't change
panner.coneInnerAngle = 30;
// this value determines the size of the area in which the sound volume decreases gradually
// if coneOuterAngle === 45 and coneInnerAngle === 30, it means that when the sound is rotated
// by between 15 (30/2) and 22.5 (45/2) degrees either direction,
// the volume will decrease gradually
panner.coneOuterAngle = 45;
// this value determines the volume of the sound outside of both inner and outer cone
// setting it to 0 means there is no sound, so we can clearly hear when we leave the cone
// 0 is also the default
panner.coneOuterGain = 0;
// increase the Z position to ensure the cone has an effect
// (otherwise the sound is located at the same position as the listener)
panner.positionZ.setValueAtTime(1, context.currentTime);
```
Having set up the {{ domxref("PannerNode") }}, we can now schedule some updates to its
Y-axis rotation:
```js
// calculate the vector for no rotation
// this means the sound will play at full volume
const [x1, y1, z1] = yRotationToVector(0);
// schedule the no-rotation vector immediately
panner.orientationX.setValueAtTime(x1, context.currentTime);
panner.orientationY.setValueAtTime(y1, context.currentTime);
panner.orientationZ.setValueAtTime(z1, context.currentTime);
// calculate the vector for -22.4 degrees
// since our coneOuterAngle is 45, this will just about make the sound audible
// if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive
const [x2, y2, z2] = yRotationToVector(-22.4);
panner.orientationX.setValueAtTime(x2, context.currentTime + 2);
panner.orientationY.setValueAtTime(y2, context.currentTime + 2);
panner.orientationZ.setValueAtTime(z2, context.currentTime + 2);
```
Finally, let's connect all our nodes and start the oscillator!
```js
osc.connect(panner).connect(context.destination);
osc.start(0);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
- {{domxref("PannerNode")}}
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/orientationy/index.md | ---
title: "PannerNode: orientationY property"
short-title: orientationY
slug: Web/API/PannerNode/orientationY
page-type: web-api-instance-property
browser-compat: api.PannerNode.orientationY
---
{{ APIRef("Web Audio API") }}
The **`orientationY`** property of the {{ domxref("PannerNode") }} interface
indicates the Y (vertical) component of the direction the audio source is facing, in 3D Cartesian coordinate space.
The complete vector is defined by the position of the audio source, given as
({{domxref("PannerNode.positionX", "positionX")}}, {{domxref("PannerNode.positionY",
"positionY")}}, {{domxref("PannerNode.positionZ", "positionZ")}}), and the orientation
of the audio source (that is, the direction in which it's facing), given as
({{domxref("PannerNode.orientationX", "orientationX")}},
{{domxref("PannerNode.orientationY", "orientationY")}},
{{domxref("PannerNode.orientationZ", "orientationZ")}}).
Depending on the directionality of the sound (as specified using the attributes
{{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}},
{{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}}, and
{{domxref("PannerNode.coneOuterGain", "codeOuterGain")}}), the orientation of the
sound may alter the perceived volume of the sound as it's being played. If the sound
is pointing toward the listener, it will be louder than if the sound is pointed away
from the listener.
The {{domxref("AudioParam")}} contained by this property is read only; however, you
can still change the value of the parameter by assigning a new value to its
{{domxref("AudioParam.value")}} property.
## Value
An {{domxref("AudioParam")}} whose `value` is the Y component of the
direction the audio source is facing, in 3D Cartesian coordinate space.
## Examples
See [`PannerNode.orientationX`](/en-US/docs/Web/API/PannerNode/orientationX#example) for example code that demonstrates the effect on volume of changing the {{domxref("PannerNode")}} orientation parameters in combination with {{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}} and {{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
- {{domxref("PannerNode")}}
| 0 |
data/mdn-content/files/en-us/web/api/pannernode | data/mdn-content/files/en-us/web/api/pannernode/positiony/index.md | ---
title: "PannerNode: positionY property"
short-title: positionY
slug: Web/API/PannerNode/positionY
page-type: web-api-instance-property
browser-compat: api.PannerNode.positionY
---
{{ APIRef("Web Audio API") }}
The **`positionY`** property of the {{ domxref("PannerNode") }} interface specifies the Y coordinate of the audio source's position in 3D Cartesian
coordinates, corresponding to the _vertical_ axis (top-bottom). The complete
vector is defined by the position of the audio source, given as
({{domxref("PannerNode.positionX", "positionX")}}, {{domxref("PannerNode.positionY", "positionY")}}, {{domxref("PannerNode.positionZ", "positionZ")}}), and the orientation
of the audio source (that is, the direction in which it's facing), given as
({{domxref("PannerNode.orientationX", "orientationX")}},
{{domxref("PannerNode.orientationY", "orientationY")}},
{{domxref("PannerNode.orientationZ", "orientationZ")}}).
Depending on the directionality of the sound (as specified using the attributes
{{domxref("PannerNode.coneInnerAngle", "coneInnerAngle")}},
{{domxref("PannerNode.coneOuterAngle", "coneOuterAngle")}}, and
{{domxref("PannerNode.coneOuterGain", "codeOuterGain")}}), the orientation of the
sound may alter the perceived volume of the sound as it's being played. If the sound
is pointing toward the listener, it will be louder than if the sound is pointed away
from the listener.
The {{domxref("AudioParam")}} contained by this property is read only; however, you
can still change the value of the parameter by assigning a new value to its
{{domxref("AudioParam.value")}} property.
## Value
An {{domxref("AudioParam")}} whose `value` is the Y coordinate of the audio
source's position, in 3D Cartesian coordinates.
## Examples
The following example starts an oscillator and pans it above the listener after 1
second, below the listener after 2 seconds, and back to the center after 3 seconds. Note
that in this case, the change will mainly affect the timbre of the oscillator, as it's a
simple mono wave.
```js
const context = new AudioContext();
const osc = new OscillatorNode(context);
const panner = new PannerNode(context);
panner.panningModel = "HRTF";
panner.positionY.setValueAtTime(1, context.currentTime + 1);
panner.positionY.setValueAtTime(-1, context.currentTime + 2);
panner.positionY.setValueAtTime(0, context.currentTime + 3);
osc.connect(panner).connect(context.destination);
osc.start(0);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Web Audio spatialization basics](/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics)
- {{domxref("PannerNode")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/devicemotioneventrotationrate/index.md | ---
title: DeviceMotionEventRotationRate
slug: Web/API/DeviceMotionEventRotationRate
page-type: web-api-interface
browser-compat: api.DeviceMotionEventRotationRate
---
{{APIRef("Device Orientation Events")}}{{securecontext_header}}
A **`DeviceMotionEventRotationRate`** interface of the {{domxref("Device Orientation Events", "", "", "nocode")}} provides information about the rate at which the device is rotating around all three axes.
## Instance properties
- {{ domxref("DeviceMotionEventRotationRate.alpha") }} {{ReadOnlyInline}}
- : The amount of rotation around the Z axis, in degrees per second.
- {{ domxref("DeviceMotionEventRotationRate.beta") }} {{ReadOnlyInline}}
- : The amount of rotation around the X axis, in degrees per second.
- {{ domxref("DeviceMotionEventRotationRate.gamma") }} {{ReadOnlyInline}}
- : The amount of rotation around the Y axis, in degrees per second.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/devicemotioneventrotationrate | data/mdn-content/files/en-us/web/api/devicemotioneventrotationrate/gamma/index.md | ---
title: "DeviceMotionEventRotationRate: gamma property"
short-title: gamma
slug: Web/API/DeviceMotionEventRotationRate/gamma
page-type: web-api-instance-property
browser-compat: api.DeviceMotionEventRotationRate.gamma
---
{{APIRef("Device Orientation Events")}}{{securecontext_header}}
The **`gamma`** read-only property of the {{domxref("DeviceMotionEventRotationRate")}} interface indicates the rate of rotation around the Y axis, in degrees per second.
## Value
A `double` indicating the rate of rotation around the Y axis, in degrees per second.
See [Accelerometer values explained](/en-US/docs/Web/API/Device_orientation_events/Detecting_device_orientation#accelerometer_values_explained) for details.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/devicemotioneventrotationrate | data/mdn-content/files/en-us/web/api/devicemotioneventrotationrate/beta/index.md | ---
title: "DeviceMotionEventRotationRate: beta property"
short-title: beta
slug: Web/API/DeviceMotionEventRotationRate/beta
page-type: web-api-instance-property
browser-compat: api.DeviceMotionEventRotationRate.beta
---
{{APIRef("Device Orientation Events")}}{{securecontext_header}}
The **`beta`** read-only property of the {{domxref("DeviceMotionEventRotationRate")}} interface indicates the rate of rotation around the X axis, in degrees per second.
## Value
A `double` indicating the rate of rotation around the X axis, in degrees per second.
See [Accelerometer values explained](/en-US/docs/Web/API/Device_orientation_events/Detecting_device_orientation#accelerometer_values_explained) for details.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/devicemotioneventrotationrate | data/mdn-content/files/en-us/web/api/devicemotioneventrotationrate/alpha/index.md | ---
title: "DeviceMotionEventRotationRate: alpha property"
short-title: alpha
slug: Web/API/DeviceMotionEventRotationRate/alpha
page-type: web-api-instance-property
browser-compat: api.DeviceMotionEventRotationRate.alpha
---
{{APIRef("Device Orientation Events")}}{{securecontext_header}}
The **`alpha`** read-only property of the {{domxref("DeviceMotionEventRotationRate")}} interface indicates the rate of rotation around the Z axis, in degrees per second.
## Value
A `double` indicating the rate of rotation around the Z axis, in degrees per second.
See [Accelerometer values explained](/en-US/docs/Web/API/Device_orientation_events/Detecting_device_orientation#accelerometer_values_explained) for details.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/abstractrange/index.md | ---
title: AbstractRange
slug: Web/API/AbstractRange
page-type: web-api-interface
browser-compat: api.AbstractRange
---
{{APIRef("DOM")}}
The **`AbstractRange`** abstract interface is the base class upon which all {{Glossary("DOM")}} range types are defined. A **range** is an object that indicates the start and end points of a section of content within the document.
> **Note:** As an abstract interface, you will not directly instantiate an object of type `AbstractRange`. Instead, you will use the {{domxref("Range")}} or {{domxref("StaticRange")}} interfaces. To understand the difference between those two interfaces, and how to choose which is appropriate for your needs, consult each interface's documentation.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("AbstractRange.collapsed", "collapsed")}} {{ReadOnlyInline}}
- : A Boolean value which is `true` if the range is _collapsed_. A collapsed range is a range whose start position and end position are the same, resulting in a zero-character-long range.
- {{domxref("AbstractRange.endContainer", "endContainer")}} {{ReadOnlyInline}}
- : The {{domxref("Node")}} object in which the end of the range, as specified by the `endOffset` property, is located.
- {{domxref("AbstractRange.endOffset", "endOffset")}} {{ReadOnlyInline}}
- : An integer value indicating the offset, in characters, from the beginning of the node's contents to the last character of the range represented by the range object. This value must be less than the length of the `endContainer` node.
- {{domxref("AbstractRange.startContainer", "startContainer")}} {{ReadOnlyInline}}
- : The DOM {{domxref("Node")}} in which the beginning of the range, as specified by the `startOffset` property, is located.
- {{domxref("AbstractRange.startOffset", "startOffset")}} {{ReadOnlyInline}}
- : An integer value indicating the offset, in characters, from the beginning of the node's contents to the first character of the contents referred to by the range object. This value must be less than the length of the node indicated in `startContainer`.
## Instance methods
_The `AbstractRange` interface doesn't provide any methods._
## Usage notes
### Range types
All ranges of content within a {{domxref("Document", "document")}} are described using instances of interfaces based on `AbstractRange`. There are two such interfaces:
- {{domxref("Range")}}
- : The `Range` interface has been around for a long time and has only recently been redefined to be based upon `AbstractRange` as the need arose to define other forms of range data. `Range` provides methods that allow you to alter the range's endpoints, as well as methods to compare ranges, detect intersections between ranges, and so forth.
- {{domxref("StaticRange")}}
- : A `StaticRange` is a basic range which cannot be changed once it's been created. Specifically, as the node tree mutates and changes, the range does not. This is useful when you need to specify a range that will only be used once, since it avoids the performance and resource impact of the more complex {{domxref("Range")}} interface.
### Contents of elements
When trying to access the contents of an element, keep in mind that the element itself is a node, but so is any text inside it. In order to set a range endpoint within the text of an element, be sure to find the text node inside the element:
```js
const startElem = document.querySelector("p");
const endElem = startElem.querySelector("span");
const range = document.createRange();
range.setStart(startElem, 0);
range.setEnd(endElem, endElem.childNodes[0].length / 2);
const contents = range.cloneContents();
document.body.appendChild(contents);
```
This example creates a new range, `range`, and sets its starting point to the third child node of the first element whose class is `elementclass`. The end point is set to be the middle of the first child of the span, and then the range is used to copy the contents of the range.
### Ranges and the hierarchy of the DOM
In order to define a range of characters within a document in a way that is able to span across zero or more node boundaries, and which is as resilient as possible to changes to the DOM, you can't specify the offset to the first and last characters in the {{Glossary("HTML")}}. There are a few good reasons for that.
First, after your page is loaded, the browser isn't thinking in terms of HTML. Once it's been loaded, the page is a tree of DOM {{domxref("Node")}} objects, so you need to specify the beginning and ending locations of a range in terms of nodes and positions within nodes.
Second, in order to support the mutability of the DOM tree as much as possible, you need a way to represent positions relative to nodes in the tree, rather than global positions within the entire document. By defining points within the document as offsets within a given node, those positions remain consistent with the content even as nodes are added to, removed from, or moved around within the DOM tree—within reason. There are fairly obvious limitations (such as if a node is moved to be after the endpoint of a range, or if the content of a node is heavily altered), but it's far better than nothing.
Third, using node-relative positions to define the start and end positions will generally be easier to make perform well. Rather than having to negotiate the DOM figuring out what your global offset refers to, the {{Glossary("user agent")}} (browser) can instead go directly to the node indicated by the starting position and start from there, working its way forward until it reaches the given offset into the ending node.
To illustrate this, consider the HTML below:
```html
<div class="container">
<div class="header">
<img src="" class="sitelogo" />
<h1>The Ultimate Website</h1>
</div>
<article>
<section class="entry" id="entry1">
<h2>Section 1: An interesting thing…</h2>
<p>A <em>very</em> interesting thing happened on the way to the forum…</p>
<aside class="callout">
<h2>Aside</h2>
<p>An interesting aside to share with you…</p>
</aside>
</section>
</article>
<pre id="log"></pre>
</div>
```
After loading the HTML and constructing the DOM representation of the document, the resulting DOM tree looks like this:
[![Diagram of the DOM for a simple web page](simpledom.svg)](simpledom.svg)
In this diagram, the nodes representing HTML elements are shown in green. Each row beneath them shows the next layer of depth into the DOM tree. Blue nodes are text nodes, containing the text that gets shown onscreen. Each element's contents are linked below it in the tree, potentially spawning a series of branches below as elements include other elements and text nodes.
If you want to create a range that incorporates the contents of the {{HTMLElement("p")}} element whose contents are `"A <em>very</em> interesting thing happened on the way to the forum…"`, you can do so like this:
```js
const pRange = document.createRange();
pRange.selectNodeContents(document.querySelector("#entry1 p"));
```
Since we wish to select the entire contents of the `<p>` element, including its descendants, this works perfectly.
If we wish to instead copy the text "An interesting thing…" from the {{HTMLElement("section")}}'s heading (an {{HTMLElement("Heading_Elements", "h2")}} element) through the end of the letters "ve" in the {{HTMLElement("em")}} within the paragraph below it, the following code would work:
```js
const range = document.createRange();
const startNode = document.querySelector("section h2").childNodes[0];
range.setStart(startNode, 11);
const endNode = document.querySelector("#entry1 p em").childNodes[0];
range.setEnd(endNode, 2);
const fragment = range.cloneContents();
```
Here an interesting problem arises—we are capturing content from multiple nodes located at different levels of the DOM hierarchy, and then only part of one of them. What should the result look like?
As it turns out, the DOM specification fortunately addresses this exact issue. For example, in this case, we're calling {{domxref("Range.cloneContents", "cloneContents()")}} on the range to create a new {{domxref("DocumentFragment")}} object providing a DOM subtree which replicates the contents of the specified range. To do this, `cloneContents()` constructs all the nodes needed to preserve the structure of the indicated range, but no more than necessary.
In this example, the start of the specified range is found within the text node below the section's heading, which means that the new `DocumentFragment` will need to contain an {{HTMLElement("Heading_Elements", "h2")}} and, below it, a text node.
The range's end is located below the {{HTMLElement("p")}} element, so that will be needed within the new fragment. So will the text node containing the word "A", since that's included in the range. Finally, an `<em>` and a text node below it will be added below the `<p>` as well.
The contents of the text nodes are then determined by the offsets into those text nodes given when calling {{domxref("Range.setStart", "setStart()")}} and {{domxref("Range.setEnd", "setEnd()")}}. Given the offset of 11 into the heading's text, that node will contain "An interesting thing…". Similarly, the last text node will contain "ve", given the request for the first two characters of the ending node.
The resulting document fragment looks like this:
![A DocumentFragment representing the cloned content](dom-fragment.svg)
Notice especially that the contents of this fragment are all _below_ the shared common parent of the topmost nodes within it. The parent `<section>` is not needed to replicate the cloned content, so it isn't included.
## Example
Consider this simple HTML fragment of HTML.
```html
<p><strong>This</strong> is a paragraph.</p>
```
Imagine using a {{domxref("Range")}} to extract the word "paragraph" from this. The code to do that looks like the following:
```js
const paraNode = document.querySelector("p");
const paraTextNode = paraNode.childNodes[1];
const range = document.createRange();
range.setStart(paraTextNode, 6);
range.setEnd(paraTextNode, paraTextNode.length - 1);
const fragment = range.cloneContents();
document.body.appendChild(fragment);
```
First we get references to the paragraph node itself as well as to the _second_ child node within the paragraph. The first child is the {{HTMLElement("strong")}} element. The second child is the text node " is a paragraph.".
With the text node reference in hand, we create a new `Range` object by calling {{domxref("Document.createRange", "createRange()")}} on the `Document` itself. We set the starting position of the range to the sixth character of the text node's string, and the end position to the length of the text node's string minus one. This sets the range to encompass the word "paragraph".
We then finish up by calling {{domxref("Range.cloneContents", "cloneContents()")}} on the `Range` to create a new {{domxref("DocumentFragment")}} object which contains the portion of the document encompassed by the range. After that, we use {{domxref("Node.appendChild", "appendChild()")}} to add that fragment at the end of the document's body, as obtained from {{domxref("document.body")}}.
The result looks like this:
{{EmbedLiveSample("Example", 600, 80)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |